From 22273ae8c60ba7ee1260e61755546b383391e08c Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 23:54:59 -0800 Subject: [PATCH 1/4] test(cloud): PAIRED-HELD-ACTIVE the other-workspace test proves the guard (no activation is even asked for) --- .../src/lib/orca-cloud/github-cloud-first-agent.ts | 1 + .../src/lib/orca-cloud/github-cloud-first-tab.test.ts | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts b/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts index 4ed25f8549d..bc0b8d97c69 100644 --- a/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts +++ b/src/renderer/src/lib/orca-cloud/github-cloud-first-agent.ts @@ -149,6 +149,7 @@ function seederShellInFront( const active = state.activeTabId const tabs = state.tabsByWorktree[worktreeId] ?? [] return ( + // Belt-and-braces: a tab from another workspace is never this one's newest tab either. state.activeWorktreeId === worktreeId && active !== null && active !== heldTabId && diff --git a/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts b/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts index dcaf8b630d2..1d0685ac0b7 100644 --- a/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts +++ b/src/renderer/src/lib/orca-cloud/github-cloud-first-tab.test.ts @@ -187,6 +187,11 @@ describe('PAIRED-HELD-ACTIVE: the held placeholder is in front after a GitHub-on await create() await vi.waitFor(() => expect(tabIds()).toEqual([HELD()])) useAppStore.setState({ activeWorktreeId: 'wt-2', activeTabId: 'web-terminal-elsewhere' }) + // The store's setActiveTab already ignores a tab outside the active workspace, so the end state + // alone can't show the guard: it must not even ask to activate the held tab. + const realSetActiveTab = useAppStore.getState().setActiveTab + const setActiveTab = vi.fn(realSetActiveTab) + useAppStore.setState({ setActiveTab }) // Fake time from here: the settle's recheck after the seeder's shell runs on a timer. vi.useFakeTimers() try { @@ -194,7 +199,9 @@ describe('PAIRED-HELD-ACTIVE: the held placeholder is in front after a GitHub-on await vi.advanceTimersByTimeAsync(600) } finally { vi.useRealTimers() + useAppStore.setState({ setActiveTab: realSetActiveTab }) } + expect(setActiveTab).not.toHaveBeenCalled() expect(useAppStore.getState()).toMatchObject({ activeWorktreeId: 'wt-2', activeTabId: 'web-terminal-elsewhere' From 4d774310ef609bbee646eea4e3cf359077dc3fe7 Mon Sep 17 00:00:00 2001 From: Neil Date: Fri, 13 Nov 2026 02:15:47 -0800 Subject: [PATCH 2/4] fix(lint): split the repo-write check out of use-secret-request-card (max-lines) cloud/integration fails oxlint max-lines on use-secret-request-card.ts (303 counted lines, limit 300) since #637, which fails every premerge that merges integration. Moves canWriteRepo and its cache to secret-request-repo-write.ts; no behaviour change. --- .../agent-pane/secret-request-repo-write.ts | 29 ++++++++++++ .../agent-pane/use-secret-request-card.ts | 45 +++++++------------ 2 files changed, 45 insertions(+), 29 deletions(-) create mode 100644 src/renderer/src/components/agent-pane/secret-request-repo-write.ts diff --git a/src/renderer/src/components/agent-pane/secret-request-repo-write.ts b/src/renderer/src/components/agent-pane/secret-request-repo-write.ts new file mode 100644 index 00000000000..7ea5e0db8bb --- /dev/null +++ b/src/renderer/src/components/agent-pane/secret-request-repo-write.ts @@ -0,0 +1,29 @@ +// Repo-scope write check for the S4-b secret request card (use-secret-request-card.ts), split out to keep that +// hook under the file-length limit. +/** Whether this person can write the workspace repo's scope; asked once per repo per session. */ +const repoWriteCache = new Map>() + +export function canWriteRepo(repoKey: string): Promise { + let pending = repoWriteCache.get(repoKey) + if (!pending) { + const api = window.api.cloudSecrets + pending = api + ? api.effective({ repo: repoKey }).then( + (result) => result.ok && result.value.caller.canWrite.repo, + () => false + ) + : Promise.resolve(false) + // A failed read is retried next time rather than cached as "no". + void pending.then((value) => { + if (!value) { + repoWriteCache.delete(repoKey) + } + }) + repoWriteCache.set(repoKey, pending) + } + return pending +} + +export function resetSecretRequestCardCachesForTests(): void { + repoWriteCache.clear() +} diff --git a/src/renderer/src/components/agent-pane/use-secret-request-card.ts b/src/renderer/src/components/agent-pane/use-secret-request-card.ts index 9c944273351..c5b23277ad7 100644 --- a/src/renderer/src/components/agent-pane/use-secret-request-card.ts +++ b/src/renderer/src/components/agent-pane/use-secret-request-card.ts @@ -29,6 +29,7 @@ import { } from '../../../../shared/secret-request-contract' import { cloudWorkspaceSecretsMode } from '@/lib/orca-cloud/cloud-workspace-secrets-mode' import type { CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire' +import { canWriteRepo } from './secret-request-repo-write' import type { SecretRequestCardActions, SecretRequestCardModel, @@ -46,33 +47,7 @@ const TRANSPORT_FAILURES: ReadonlySet = new Set([ 'unknown' ]) -/** Whether this person can write the workspace repo's scope; asked once per repo per session. */ -const repoWriteCache = new Map>() - -function canWriteRepo(repoKey: string): Promise { - let pending = repoWriteCache.get(repoKey) - if (!pending) { - const api = window.api.cloudSecrets - pending = api - ? api.effective({ repo: repoKey }).then( - (result) => result.ok && result.value.caller.canWrite.repo, - () => false - ) - : Promise.resolve(false) - // A failed read is retried next time rather than cached as "no". - void pending.then((value) => { - if (!value) { - repoWriteCache.delete(repoKey) - } - }) - repoWriteCache.set(repoKey, pending) - } - return pending -} - -export function resetSecretRequestCardCachesForTests(): void { - repoWriteCache.clear() -} +export { resetSecretRequestCardCachesForTests } from './secret-request-repo-write' function useWorkspaceRepoKey(worktreeId: string | null): string | null { return useAppStore((state) => { @@ -220,7 +195,9 @@ export function useSecretRequestCard(args: { : repoScope ? ['personal', 'repo'] : ['personal'] - const effectiveScope: SecretRequestScope = scopes.includes(scope) ? scope : (scopes[0] ?? 'personal') + const effectiveScope: SecretRequestScope = scopes.includes(scope) + ? scope + : (scopes[0] ?? 'personal') const add = useCallback(async () => { const api = window.api.cloudSecrets @@ -259,7 +236,17 @@ export function useSecretRequestCard(args: { requestId, outcome === 'provided' ? 'saved' : 'savedAfterExpiry' ) - }, [value, local, scopes.length, environmentId, requestId, effectiveScope, repoKey, event.name, t]) + }, [ + value, + local, + scopes.length, + environmentId, + requestId, + effectiveScope, + repoKey, + event.name, + t + ]) const phase: SecretRequestCardPhase = local === 'saving' From 2642b3e4d09f1037cda891da96612ec5b386557e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:17:45 -0800 Subject: [PATCH 3/4] feat(cloud): PARITY-FOLLOW follow endpoint: workspace_follows (0055), PUT/DELETE /v1/team/workspaces/:id/follow, followers in workspace views (#654) --- .../migrations/0055_workspace_follows.sql | 12 +++ cloud/apps/sandbox-control/src/index.ts | 11 ++- cloud/apps/sandbox-control/src/lifecycle.ts | 3 + .../sandbox-control/src/member-removal.ts | 3 + .../sandbox-control/src/workspace-follows.ts | 80 ++++++++++++++++ cloud/apps/sandbox-control/src/workspaces.ts | 14 ++- .../test/workspace-follows.test.ts | 93 +++++++++++++++++++ .../cloud-workspaces/cloud-workspaces-wire.ts | 6 +- 8 files changed, 217 insertions(+), 5 deletions(-) create mode 100644 cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql create mode 100644 cloud/apps/sandbox-control/src/workspace-follows.ts create mode 100644 cloud/apps/sandbox-control/test/workspace-follows.test.ts diff --git a/cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql b/cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql new file mode 100644 index 00000000000..21cb02d977f --- /dev/null +++ b/cloud/apps/sandbox-control/migrations/0055_workspace_follows.sql @@ -0,0 +1,12 @@ +-- PARITY-FOLLOW: a member follows a teammate's workspace to keep it in their sidebar's Following +-- section; everyone who can see the workspace sees its followers. One row per member per +-- workspace. Rows go with the workspace (destroy) and with the member (removal); a follower who can +-- no longer see the workspace (it turned private) is left out of every read. +CREATE TABLE IF NOT EXISTS workspace_follows ( + sandbox_id TEXT NOT NULL, + user_id TEXT NOT NULL, + account_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (sandbox_id, user_id) +); +CREATE INDEX IF NOT EXISTS workspace_follows_member ON workspace_follows (account_id, user_id); diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 683e4b4128e..4aea44ac252 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -59,6 +59,7 @@ import { provisionWorkspaceToken } from './api/settings' import { docsPage, openApiDocument } from './api/openapi' import { handleDeviceSessionsRoute } from './device-sessions' import { removeMember } from './member-removal' +import { setFollow } from './workspace-follows' import { createRoutinesApi } from './routines/api' import { handleRoutineHook, isRoutineHookPath } from './routines/hooks' import { tickRoutines } from './routines/runs' @@ -208,6 +209,7 @@ import { WORKSPACE_ERROR_STATUS, WorkspaceError, canOpen, + canSee, isOrgAdmin, listWorkspaces, patchWorkspace, @@ -2114,7 +2116,7 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, throw error } } - const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) + const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|follow|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname) if (!match) { return fail('not_found', 404) } @@ -2143,6 +2145,13 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps, await recordMemberSend(db, row.id, caller.userId, now) return json({ ok: true }) } + if (route === 'PUT follow' || route === 'DELETE follow') { + // Following needs seeing it; an admin addressing a private row for management can't follow it. + if (!canSee(caller, row)) { + throw new WorkspaceError('not_found') + } + return json(await setFollow(db, caller, row, route === 'PUT follow', now)) + } if (route === 'POST presence') { const body = PresenceSchema.safeParse(await readJson(request)) if (!body.success) { diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 2365a4cf5a8..39cf00f7d81 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -61,6 +61,7 @@ import { recordSessionEnd } from './session-cpu' import { flushUsage, queueUsage } from './usage' import { SANDBOX_VCPUS } from './machine-size' import { isRegionalFailure } from './regions' +import { forgetWorkspaceFollows } from './workspace-follows' export const LEASE_MS = 30 * 60_000 /** @@ -1130,6 +1131,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom await markSnapshotsDeleted(deps.db, row.id, deps.now()) // Archive metadata (repo state, file tree) goes with the workspace. await deps.db.prepare('DELETE FROM sandbox_archives WHERE sandbox_id = ?').bind(row.id).run() + // Nobody follows a workspace that is gone (PARITY-FOLLOW). + await forgetWorkspaceFollows(deps.db, row.id) // So does its sealed read snapshot. await deleteReadSnapshot(deps.db, row.id) // And its per-workspace agent Source overrides. diff --git a/cloud/apps/sandbox-control/src/member-removal.ts b/cloud/apps/sandbox-control/src/member-removal.ts index d53d3d580bc..86c1d72fe0b 100644 --- a/cloud/apps/sandbox-control/src/member-removal.ts +++ b/cloud/apps/sandbox-control/src/member-removal.ts @@ -9,6 +9,7 @@ import { memberChangeTime, recordMemberChange } from './member-changes' import { revokeMemberReaderKeys } from './read-snapshots' import { disableMemberRoutines } from './routines/runs' import { forgetMemberPokes } from './team-presence' +import { forgetMemberFollows } from './workspace-follows' export type MemberRemoval = { keysRevoked: number @@ -61,6 +62,8 @@ export async function removeMember( const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now) // Their Pokes opt-in goes (it doubles as proof of membership for receiving one). await forgetMemberPokes(life.db, accountId, userId, now) + // They no longer follow anything here, and stop showing as anyone's follower. + await forgetMemberFollows(life.db, accountId, userId) const grants = await revokeGrantsForMember(life, accountId, userId) // Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running. const routines = await disableMemberRoutines({ life }, accountId, userId) diff --git a/cloud/apps/sandbox-control/src/workspace-follows.ts b/cloud/apps/sandbox-control/src/workspace-follows.ts new file mode 100644 index 00000000000..77c494d0716 --- /dev/null +++ b/cloud/apps/sandbox-control/src/workspace-follows.ts @@ -0,0 +1,80 @@ +// PARITY-FOLLOW: persistent Follow on a team workspace (Conductor's Following section and +// follower avatars). +// PUT /v1/team/workspaces/:id/follow -> {following: true, followers} +// DELETE /v1/team/workspaces/:id/follow -> {following: false, followers} +// Anyone who can see a workspace may follow it, and sees who else follows it (team workspaces are +// visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old +// follow of a workspace that turned private is never shown and never counts. Archived workspaces +// may still be followed: they stay browsable. +import type { SandboxCaller } from './auth' +import type { SandboxRow } from './store' + +/** Followers of each workspace, oldest follow first. */ +export async function followersFor(db: D1Database, ids: readonly string[]): Promise> { + const out = new Map() + if (ids.length === 0) { + return out + } + const { results } = await db + .prepare( + `SELECT sandbox_id, user_id FROM workspace_follows WHERE sandbox_id IN (${ids.map(() => '?').join(', ')}) + ORDER BY created_at ASC, user_id ASC` + ) + .bind(...ids) + .all<{ sandbox_id: string; user_id: string }>() + for (const row of results) { + const list = out.get(row.sandbox_id) ?? [] + list.push(row.user_id) + out.set(row.sandbox_id, list) + } + return out +} + +/** + * The followers a caller may be shown for a row: none unless the caller can see it (`seen`); for a + * private row, only its owner (the only member who can see it). + */ +export function visibleFollowers( + row: Pick, + seen: boolean, + followers: readonly string[] +): string[] { + if (!seen) { + return [] + } + return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) +} + +/** The caller must be able to see the row (the route checks canSee first). */ +export async function setFollow( + db: D1Database, + caller: SandboxCaller, + row: SandboxRow, + follow: boolean, + now: number +): Promise<{ following: boolean; followers: string[] }> { + if (follow) { + await db + .prepare( + `INSERT INTO workspace_follows (sandbox_id, user_id, account_id, created_at) VALUES (?, ?, ?, ?) + ON CONFLICT (sandbox_id, user_id) DO NOTHING` + ) + .bind(row.id, caller.userId, row.account_id, now) + .run() + } else { + await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ? AND user_id = ?').bind(row.id, caller.userId).run() + } + const followers = visibleFollowers(row, true, (await followersFor(db, [row.id])).get(row.id) ?? []) + return { following: followers.includes(caller.userId), followers } +} + +/** The workspace is gone: nobody follows it any more. */ +export async function forgetWorkspaceFollows(db: D1Database, sandboxId: string): Promise { + await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ?').bind(sandboxId).run() +} + +/** The member left the account: their follows go, and they stop showing as a follower. */ +export async function forgetMemberFollows(db: D1Database, accountId: string, userId: string): Promise { + const result = await db.prepare('DELETE FROM workspace_follows WHERE account_id = ? AND user_id = ?').bind(accountId, userId).run() + return result.meta.changes +} diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 28664ab1184..20d67a837b7 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -4,6 +4,7 @@ // GET /v1/team/workspaces/:id // PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?} // POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?} +// PUT|DELETE /v1/team/workspaces/:id/follow (workspace-follows.ts) // GET /v1/team/links/resolve?w=&c= or ?org=&n=&c= // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a @@ -15,6 +16,7 @@ import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './st import { memberNamesFor } from './member-names' import { recordTokenSpend } from './member-usage' import { readSnapshotTimes } from './read-snapshots' +import { followersFor, visibleFollowers } from './workspace-follows' import { sandboxView } from './wire' import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs' import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire' @@ -172,15 +174,17 @@ function repoView(row: SandboxRow) { export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) { const ids = rows.map((r) => r.id) - const [presence, compute, granted, readAt, slug] = await Promise.all([ + const [presence, compute, granted, readAt, slug, follows] = await Promise.all([ presenceFor(db, ids, now), computeMsFor(db, ids), activeGrantUsers(db, ids, caller.userId), readSnapshotTimes(db, ids), - rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null) + rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null), + followersFor(db, ids) ]) + const followersOf = (row: SandboxRow) => visibleFollowers(row, canSee(caller, row), follows.get(row.id) ?? []) const referenced = (row: SandboxRow, live: readonly PresenceRow[]) => - [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter( + [row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id), ...followersOf(row)].filter( (id): id is string => typeof id === 'string' ) const names = await memberNamesFor( @@ -193,6 +197,7 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows // Private rows an admin sees for management show who/what, never live presence. const showPresence = access !== 'none' const live = showPresence ? (presence.get(row.id) ?? []) : [] + const followers = followersOf(row) const memberNames = Object.fromEntries( referenced(row, live).flatMap((id) => (names.has(id) ? [[id, names.get(id)!]] : [])) ) @@ -214,6 +219,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows cost: costView(row, compute.get(row.id) ?? 0, now), access, presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })), + // Who follows it (oldest first), and whether the caller does (PARITY-FOLLOW). + followers, + following: followers.includes(caller.userId), // Display names (token `name` claim) for the ids above; the roster wins where it has one. memberNames, // When its sleeping read-only copy was saved ("As of"); only for those who may read it. diff --git a/cloud/apps/sandbox-control/test/workspace-follows.test.ts b/cloud/apps/sandbox-control/test/workspace-follows.test.ts new file mode 100644 index 00000000000..e075a408a84 --- /dev/null +++ b/cloud/apps/sandbox-control/test/workspace-follows.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest' +import { createHarness } from './harness' + +const AUTH_TOKEN = 'a'.repeat(40) + +async function team() { + const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: AUTH_TOKEN }) + type Who = { sub: string; orgRole: 'owner' | 'admin' | 'member' } + const req = async (who: Who, method: string, path: string, body?: unknown) => + h.call(method, path, { bearer: await h.token(who.sub, 'acme', 'sandbox', { org_role: who.orgRole }), body }) + const alice: Who = { sub: 'alice', orgRole: 'member' } + const bob: Who = { sub: 'bob', orgRole: 'member' } + const carol: Who = { sub: 'carol', orgRole: 'member' } + const olga: Who = { sub: 'olga', orgRole: 'admin' } + const create = async (who: Who, visibility: 'team' | 'private') => { + const made = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${Math.random()}`, machineSize: 'standard', title: 'W' }) + expect(made.status).toBe(200) + const id = made.body.sandbox.id as string + if (visibility === 'team') { + await req(who, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' }) + } + return id + } + const internal = (path: string, body: unknown) => h.call('POST', path, { body, bearer: AUTH_TOKEN }) + return { h, req, alice, bob, carol, olga, create, internal } +} + +describe('workspace follows (PARITY-FOLLOW)', () => { + it('follows and unfollows; everyone who can see it sees followers, oldest first', async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + const bobFollow = await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect(bobFollow.status).toBe(200) + expect(bobFollow.body).toEqual({ following: true, followers: ['bob'] }) + t.h.advance(1_000) + await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`) + // Following twice is a no-op, and keeps Bob first. + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + + const seenByAlice = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace + expect(seenByAlice).toMatchObject({ followers: ['bob', 'carol'], following: false }) + const listed = (await t.req(t.carol, 'GET', '/v1/team/workspaces?scope=team')).body.workspaces + expect(listed.find((w: { id: string }) => w.id === id)).toMatchObject({ followers: ['bob', 'carol'], following: true }) + + const unfollow = await t.req(t.bob, 'DELETE', `/v1/team/workspaces/${id}/follow`) + expect(unfollow.body).toEqual({ following: false, followers: ['carol'] }) + }) + + it("can't follow a private workspace you can't see, and old follows vanish when it turns private", async () => { + const t = await team() + const secret = await t.create(t.alice, 'private') + expect((await t.req(t.bob, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404) + // An admin may address a private row for management, but not follow it. + expect((await t.req(t.olga, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404) + + const shared = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${shared}/follow`) + t.h.advance(1_000) + await t.req(t.alice, 'PUT', `/v1/team/workspaces/${shared}/follow`) + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'private' }) + // The owner still sees their own follow; Bob's is never shown while it is private. + const own = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace + expect(own).toMatchObject({ followers: ['alice'], following: true }) + const adminView = (await t.req(t.olga, 'GET', '/v1/team/workspaces?scope=all')).body.workspaces.find( + (w: { id: string }) => w.id === shared + ) + expect(adminView.followers).toEqual([]) + // Shared again: Bob's follow is back (it was hidden, not lost). + await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'team' }) + expect((await t.req(t.bob, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace).toMatchObject({ + followers: ['bob', 'alice'], + following: true + }) + }) + + it('forgets every follow of a destroyed workspace', async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${id}`)).status).toBe(200) + const left = t.h.raw.prepare('SELECT COUNT(*) AS n FROM workspace_follows WHERE sandbox_id = ?').get(id) as { n: number } + expect(left.n).toBe(0) + }) + + it("forgets a removed member's follows, so they stop showing as a follower", async () => { + const t = await team() + const id = await t.create(t.alice, 'team') + await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`) + await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`) + expect((await t.internal('/v1/internal/org-members/removed', { accountId: 'org:acme', userId: 'bob' })).status).toBe(200) + expect((await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace.followers).toEqual(['carol']) + }) +}) diff --git a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts index 70332cbe133..e90ad1e44b6 100644 --- a/src/shared/cloud-workspaces/cloud-workspaces-wire.ts +++ b/src/shared/cloud-workspaces/cloud-workspaces-wire.ts @@ -62,7 +62,11 @@ export const CloudWorkspaceSchema = z.object({ // Older control planes omit it. fromRoutine: z.boolean().optional().catch(undefined), // The routine that started it, for routine runs (shown as "Routine · "). - routineName: z.string().max(200).nullable().optional().catch(undefined) + routineName: z.string().max(200).nullable().optional().catch(undefined), + // Who follows it (oldest first) and whether the caller does (PARITY-FOLLOW). Older control planes + // omit them. + followers: z.array(Id).max(500).optional().catch(undefined), + following: z.boolean().optional().catch(undefined) }) export type CloudWorkspace = z.infer From 0b47e51cb9ddd7aef946caaad90c5ffd39df8a5c Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:22:04 -0800 Subject: [PATCH 4/4] feat(cloud): SSO-FOLLOWUPS identity-provider-managed members on the Team page; a clear message when single sign-on ends a sign-in (#653) * feat(cloud): SSO-FOLLOWUPS members managed by the identity provider on the Team page; a clear message when single sign-on ends a sign-in * fix(cloud): import the roster type where it is used * feat(cloud): wording for single sign-on and directory sync events in the audit log * fix(cloud): the missing-DNS-record audit line reads as an action (design-squad) --- .../cloud-auth/profile-cloud-auth-status.ts | 3 + .../cloud-auth/profile-cloud-client.ts | 24 ++-- .../profile-cloud-org-delete-service.ts | 5 +- .../profile-cloud-org-members-client.ts | 3 +- .../profile-cloud-reconnect-reason.test.ts | 92 +++++++++++++++ .../profile-cloud-reconnect-reason.ts | 31 +++++ .../profile-cloud-session-refresh.ts | 14 +++ .../src/components/UnexpectedSignoutCard.tsx | 21 ++-- .../billing/team/TeamMemberList.test.tsx | 33 ++++++ .../billing/team/TeamMemberList.tsx | 9 +- .../components/billing/team/TeamPageView.tsx | 8 ++ .../billing/team/team-roster-rows.ts | 5 + .../accounts/orca/OrcaAccountSettingsPane.tsx | 19 ++- .../EnterpriseSettingsView.test.tsx | 43 ++++++- .../enterprise/enterprise-audit-copy.ts | 2 + .../enterprise/enterprise-audit-sso-copy.ts | 109 ++++++++++++++++++ src/renderer/src/i18n/locales/en.json | 34 +++++- src/shared/orca-org-roster.ts | 11 ++ src/shared/orca-profile-reconnect-reason.ts | 6 + src/shared/orca-profiles.ts | 10 +- ...workspace-session-terminal-buffers.test.ts | 4 +- 21 files changed, 449 insertions(+), 37 deletions(-) create mode 100644 src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts create mode 100644 src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts create mode 100644 src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts create mode 100644 src/shared/orca-org-roster.ts create mode 100644 src/shared/orca-profile-reconnect-reason.ts diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts index 1cbbb8e9936..184bc6b9860 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts @@ -2,6 +2,7 @@ import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles' import type { ActiveOrcaProfileState } from '../profile-index-store' import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' import { readCloudSession } from '../cloud-session/profile-cloud-session-owner' +import { getReconnectReason } from '../cloud-session/profile-cloud-reconnect-reason' export function getOrcaProfileAuthStatusFromProfile( active: ActiveOrcaProfileState, @@ -48,12 +49,14 @@ export function getOrcaProfileAuthStatusFromProfile( } } + const reconnectReason = getReconnectReason(active.profile.id) return { activeProfileId: active.profile.id, configured, state: 'reconnect-required', persistence: 'none', cloud, + ...(reconnectReason ? { reconnectReason } : {}), credentialError: session.status === 'decrypt-failed' || session.status === 'unreadable' ? session.error diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts index c6285cd2bdf..984326d5da5 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts @@ -38,7 +38,9 @@ export class OrcaCloudRequestError extends Error { // Preserve the server error discriminator so callers can distinguish business 4xx outcomes. constructor( public readonly statusCode: number, - public readonly errorCode?: string + public readonly errorCode?: string, + /** Auth's finer `reason` beside `error` (a refused refresh: expired, revoked, sso_required…). */ + public readonly reason?: string ) { super(`orca_cloud_request_failed_${statusCode}`) this.name = 'OrcaCloudRequestError' @@ -171,18 +173,23 @@ export function isAmbiguousCloudRequestFailure(error: unknown): boolean { } // Proxies, CDNs and gateways answer with HTML; only the auth server's JSON carries a verdict. -async function readCloudErrorCode(response: Response): Promise { +async function readCloudError(response: Response): Promise<{ error?: string; reason?: string }> { if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) { await cancelUnreadResponseBody(response) - return undefined + return {} } try { const body: unknown = await response.json() - return body && typeof body === 'object' && 'error' in body && typeof body.error === 'string' - ? body.error - : undefined + if (!body || typeof body !== 'object') { + return {} + } + return { + ...('error' in body && typeof body.error === 'string' ? { error: body.error } : {}), + // Additive: older auth deployments send no reason. + ...('reason' in body && typeof body.reason === 'string' ? { reason: body.reason } : {}) + } } catch { - return undefined + return {} } } @@ -199,7 +206,8 @@ async function postJson(url: string, body: unknown, options?: PostJsonOptions signal: AbortSignal.timeout(options?.timeoutMs ?? CLOUD_REQUEST_TIMEOUT_MS) }) if (!response.ok) { - throw new OrcaCloudRequestError(response.status, await readCloudErrorCode(response)) + const failure = await readCloudError(response) + throw new OrcaCloudRequestError(response.status, failure.error, failure.reason) } return (await response.json()) as T } diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts index 0e65797a227..6fbb301760c 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-delete-service.ts @@ -6,7 +6,10 @@ import type { OrcaProfileOrgDeleteResult } from '../../../shared/orca-org-delete' import { ensureActiveOrcaProfile } from '../profile-index-store' -import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from '../cloud-auth/profile-cloud-auth-config' +import { + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from '../cloud-auth/profile-cloud-auth-config' import type { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' import { removeDevOrganization } from '../cloud-auth/profile-cloud-dev-auth' import { runOrgMemberCall } from './profile-cloud-org-members-service' diff --git a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts index 90e14c3e393..19757e02461 100644 --- a/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts @@ -128,7 +128,8 @@ export function normalizeRoster(value: unknown): OrcaOrgMembersRoster { pendingInvites, // Malformed roles must not widen UI permissions; the server still authorizes mutations. viewerRole: normalizeRole(record.viewerRole, 'member'), - canManageMembers: record.canManageMembers === true + canManageMembers: record.canManageMembers === true, + ...(record.directoryManaged === true ? { directoryManaged: true } : {}) } } diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts new file mode 100644 index 00000000000..8aeb7952cac --- /dev/null +++ b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError, refreshOrcaCloudSession } from '../cloud-auth/profile-cloud-client' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import { + getReconnectReason, + reconnectReasonFromRefusal, + rememberReconnectReason +} from './profile-cloud-reconnect-reason' + +const base = 'https://auth.test' +const config: OrcaCloudAuthConfig = { + apiBaseUrl: base, + authorizeEndpoint: `${base}/a`, + sessionEndpoint: `${base}/s`, + refreshEndpoint: `${base}/r`, + capabilitiesEndpoint: `${base}/c`, + profileEndpoint: `${base}/p`, + orgEndpoint: `${base}/o`, + logoutEndpoint: `${base}/l`, + relayTokenEndpoint: `${base}/rt`, + connectorTokenEndpoint: `${base}/ct`, + relayDirectorUrl: base, + clientId: 'orca-desktop', + scope: 'openid' +} +const session: OrcaCloudSession = { + accessToken: 'token', + refreshToken: 'refresh', + expiresAt: 0, + capabilities: { flags: {}, refreshedAt: 0 } +} + +afterEach(() => { + vi.unstubAllGlobals() + rememberReconnectReason('p1', undefined) +}) + +async function refusal(body: unknown): Promise { + vi.stubGlobal( + 'fetch', + vi.fn( + async () => + new Response(JSON.stringify(body), { + status: 401, + headers: { 'content-type': 'application/json' } + }) + ) + ) + return refreshOrcaCloudSession(config, session).catch((error: unknown) => error) +} + +describe('why a sign-in ended', () => { + it('a refused refresh carries auth’s reason beside its error', async () => { + const error = await refusal({ error: 'invalid_refresh_token', reason: 'sso_required' }) + expect(error).toBeInstanceOf(OrcaCloudRequestError) + expect(error).toMatchObject({ + statusCode: 401, + errorCode: 'invalid_refresh_token', + reason: 'sso_required' + }) + }) + + it('an older auth with no reason, or a non-string one, reads as none', async () => { + expect(await refusal({ error: 'invalid_refresh_token' })).toMatchObject({ reason: undefined }) + expect(await refusal({ error: 'invalid_refresh_token', reason: 7 })).toMatchObject({ + reason: undefined + }) + }) + + it('only single sign-on is told apart; every other reason stays the generic sign-in-again', () => { + expect(reconnectReasonFromRefusal('sso_required')).toBe('sso-required') + for (const reason of [ + 'expired', + 'signed_out', + 'revoked', + 'reused', + 'something_new', + undefined + ]) { + expect(reconnectReasonFromRefusal(reason)).toBeUndefined() + } + }) + + it('is remembered per profile and cleared by a refusal without one', () => { + rememberReconnectReason('p1', 'sso-required') + expect(getReconnectReason('p1')).toBe('sso-required') + expect(getReconnectReason('p2')).toBeUndefined() + rememberReconnectReason('p1', undefined) + expect(getReconnectReason('p1')).toBeUndefined() + }) +}) diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts new file mode 100644 index 00000000000..a4e33b068b5 --- /dev/null +++ b/src/main/orca-profiles/cloud-session/profile-cloud-reconnect-reason.ts @@ -0,0 +1,31 @@ +// Why auth ended a profile's sign-in, when it said so in a way worth telling the person apart from +// "your session expired". Today that is one case: their team turned on single sign-on, and the +// sign-in they had predates it (refresh refused with `reason: "sso_required"`). +// +// Kept in memory only: after a restart the generic sign-in-again copy shows, which is still true, +// and the sign-in page offers SSO either way. +import type { OrcaProfileReconnectReason } from '../../../shared/orca-profile-reconnect-reason' + +const reasons = new Map() + +/** Auth's `reason` on a refused refresh, mapped to what the app explains; undefined for the rest. */ +export function reconnectReasonFromRefusal( + reason: string | undefined +): OrcaProfileReconnectReason | undefined { + return reason === 'sso_required' ? 'sso-required' : undefined +} + +export function rememberReconnectReason( + profileId: string, + reason: OrcaProfileReconnectReason | undefined +): void { + if (reason) { + reasons.set(profileId, reason) + } else { + reasons.delete(profileId) + } +} + +export function getReconnectReason(profileId: string): OrcaProfileReconnectReason | undefined { + return reasons.get(profileId) +} diff --git a/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts index f7e33cbb48d..f4dcb66b4ae 100644 --- a/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts @@ -16,6 +16,10 @@ import { wasRefreshTokenAmbiguouslyAttempted } from './profile-cloud-refresh-replay-guard' import { emitOrcaCloudSessionInvalidated } from './profile-cloud-session-invalidation' +import { + reconnectReasonFromRefusal, + rememberReconnectReason +} from './profile-cloud-reconnect-reason' import { commitCloudSessionRotation, readCloudSession, @@ -65,6 +69,14 @@ function isRefreshTokenRejected(error: unknown): boolean { ) } +// Kept before the session is cleared, so the status the renderer re-reads already says why. +function rememberRefusalReason(profileId: string, error: unknown): void { + rememberReconnectReason( + profileId, + reconnectReasonFromRefusal(error instanceof OrcaCloudRequestError ? error.reason : undefined) + ) +} + const inflightCloudSessionRefreshes = new Map>() class StaleCloudSessionMutationError extends Error { @@ -218,6 +230,7 @@ export async function readFreshOrcaCloudSession( } } catch (error) { if (isRefreshTokenRejected(error)) { + rememberRefusalReason(active.profile.id, error) warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session.session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session.session) return { status: 'reconnect-required' } @@ -239,6 +252,7 @@ export async function forceRefreshOrcaCloudSession( } } catch (error) { if (isRefreshTokenRejected(error)) { + rememberRefusalReason(active.profile.id, error) warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session) return { status: 'reconnect-required' } diff --git a/src/renderer/src/components/UnexpectedSignoutCard.tsx b/src/renderer/src/components/UnexpectedSignoutCard.tsx index 86dc10bc0f8..19ffa36ec88 100644 --- a/src/renderer/src/components/UnexpectedSignoutCard.tsx +++ b/src/renderer/src/components/UnexpectedSignoutCard.tsx @@ -175,16 +175,21 @@ export function UnexpectedSignoutCard(): React.JSX.Element | null {

- {email + {authStatus?.reconnectReason === 'sso-required' ? t( - 'auto.components.UnexpectedSignoutCard.7b4d9e1f2a', - 'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.', - { value0: email } + 'auto.components.UnexpectedSignoutCard.ssoRequired', + 'Your team now requires single sign-on. Sign in again and choose Sign in with SSO.' ) - : t( - 'auto.components.UnexpectedSignoutCard.5a1c8d3e6f', - 'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.' - )} + : email + ? t( + 'auto.components.UnexpectedSignoutCard.7b4d9e1f2a', + 'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.', + { value0: email } + ) + : t( + 'auto.components.UnexpectedSignoutCard.5a1c8d3e6f', + 'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.' + )}

diff --git a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx index 849ae209ecc..e290b569be8 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.test.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.test.tsx @@ -154,3 +154,36 @@ it('shows no MFA badge for a member who has not signed in yet', () => { )! expect(pending.textContent).toBe('') }) + +it('a team its identity provider manages: no role or remove controls, and the row says why', () => { + const managed = teamRows({ ...roster, directoryManaged: true }, 'u-neil') + expect(managed.map((row) => [row.key, row.manageable])).toEqual([ + ['member:u-neil', false], + ['member:u-grace', false] + ]) + const { container } = render( + + ) + const grace = container.querySelector('[data-team-row="member:u-grace"]')! + // The role is text, not a select, and names the identity provider as its owner. + expect(grace.querySelector('[role="combobox"]')).toBeNull() + expect(grace.querySelector('[title="Managed by your identity provider"]')?.textContent).toBe( + 'Member' + ) + // Without the flag the owner can still manage the same member. + expect(teamRows(roster, 'u-neil').find((row) => row.key === 'member:u-grace')?.manageable).toBe( + true + ) +}) diff --git a/src/renderer/src/components/billing/team/TeamMemberList.tsx b/src/renderer/src/components/billing/team/TeamMemberList.tsx index c23a07c9b61..099ec1be9d4 100644 --- a/src/renderer/src/components/billing/team/TeamMemberList.tsx +++ b/src/renderer/src/components/billing/team/TeamMemberList.tsx @@ -82,7 +82,14 @@ function RoleControl({ const member = row.member if (!row.manageable) { return ( - + {roleLabel(member.role, t)} ) diff --git a/src/renderer/src/components/billing/team/TeamPageView.tsx b/src/renderer/src/components/billing/team/TeamPageView.tsx index 71edf46cc16..0b4ff7616eb 100644 --- a/src/renderer/src/components/billing/team/TeamPageView.tsx +++ b/src/renderer/src/components/billing/team/TeamPageView.tsx @@ -231,6 +231,14 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element { ) : null} + {roster?.directoryManaged ? ( +

+ {t( + 'auto.components.billing.team.managedByIdpNote', + 'Managed by your identity provider. Add or remove people and change roles there.' + )} +

+ ) : null} {roster ? (

- {accountStatusCopy(authStatus?.state, authStatus?.cloud?.email, t)} + {accountStatusCopy( + authStatus?.state, + authStatus?.cloud?.email, + t, + authStatus?.reconnectReason + )}

{connected ? ( diff --git a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx index dc8eb4fa11a..805f4b6f212 100644 --- a/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx +++ b/src/renderer/src/components/settings/enterprise/EnterpriseSettingsView.test.tsx @@ -77,12 +77,51 @@ describe('audit log', () => { ...FIXTURE_EVENTS[0]!, id: 'aud_new', category: 'security', - action: 'sso.went_live' + action: 'sso.something_new' } const { container } = render( ) - expect(rows(container)).toEqual(['sso.went_live | Security | Grace Hopper | 4 minutes ago']) + expect(rows(container)).toEqual(['sso.something_new | Security | Grace Hopper | 4 minutes ago']) + }) + + it('words every single sign-on and directory sync action auth sends', () => { + // The actions in orca-cloud apps/auth/src/audit/sso-audit.ts. + const actions = [ + 'sso.setup_link_created', + 'sso.configured', + 'sso.went_live', + 'sso.removed', + 'sso.sign_in_refused', + 'sso.sessions_ended', + 'sso.domain_added', + 'sso.domain_verified', + 'sso.domain_removed', + 'sso.domain_record_missing', + 'scim.enabled', + 'scim.disabled', + 'scim.key_created', + 'scim.key_revoked', + 'scim.group_changed', + 'scim.group_membership_changed' + ] + for (const action of actions) { + expect(isKnownAuditAction(action)).toBe(true) + const sentence = auditEventSentence({ ...FIXTURE_EVENTS[0]!, action, target: null }) + expect(sentence).not.toContain('.') + expect(sentence).not.toContain('_') + } + const about = (action: string, label: string): string => + auditEventSentence({ + ...FIXTURE_EVENTS[0]!, + action, + target: { type: 'sso_connection', id: null, label } + }) + expect(about('sso.went_live', 'Okta')).toBe('Turned on single sign-on with Okta') + expect(about('sso.domain_verified', 'acme.com')).toBe('Verified email domain acme.com') + expect(about('sso.domain_record_missing', 'acme.com')).toBe( + 'Found the DNS record for acme.com missing' + ) }) it('pages with Show more, and keeps the list when a page fails', () => { diff --git a/src/renderer/src/components/settings/enterprise/enterprise-audit-copy.ts b/src/renderer/src/components/settings/enterprise/enterprise-audit-copy.ts index cf31667beda..22f49c34c4d 100644 --- a/src/renderer/src/components/settings/enterprise/enterprise-audit-copy.ts +++ b/src/renderer/src/components/settings/enterprise/enterprise-audit-copy.ts @@ -8,6 +8,7 @@ import type { CloudAuditEvent } from '../../../../../shared/cloud-api/cloud-api-types' import { ACCOUNT_AUDIT_ACTIONS, type ActionCopy } from './enterprise-audit-account-copy' +import { SSO_AUDIT_ACTIONS } from './enterprise-audit-sso-copy' export function auditCategoryLabel(category: CloudAuditCategory, t: Translate = translate): string { switch (category) { @@ -212,6 +213,7 @@ const ACTIONS: Record = { t('settings.enterprise.audit.action.secretDeleteNamed', 'Deleted secret {{name}}', { name }) }, ...ACCOUNT_AUDIT_ACTIONS, + ...SSO_AUDIT_ACTIONS, 'routine.create': { plain: (t) => t('settings.enterprise.audit.action.routineCreate', 'Created a routine') }, diff --git a/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts b/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts new file mode 100644 index 00000000000..263321bcd64 --- /dev/null +++ b/src/renderer/src/components/settings/enterprise/enterprise-audit-sso-copy.ts @@ -0,0 +1,109 @@ +// Wording for the single sign-on and directory sync events the auth service sends. `named` takes +// what the event is about: the identity provider's name, or the email domain. +import type { ActionCopy } from './enterprise-audit-account-copy' + +export const SSO_AUDIT_ACTIONS: Record = { + 'sso.setup_link_created': { + plain: (t) => + t('settings.enterprise.audit.action.ssoSetupLink', 'Created a single sign-on setup link') + }, + 'sso.configured': { + plain: (t) => t('settings.enterprise.audit.action.ssoConfigured', 'Set up single sign-on'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoConfiguredNamed', + 'Set up single sign-on with {{name}}', + { + name + } + ) + }, + 'sso.went_live': { + plain: (t) => t('settings.enterprise.audit.action.ssoWentLive', 'Turned on single sign-on'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoWentLiveNamed', + 'Turned on single sign-on with {{name}}', + { name } + ) + }, + 'sso.removed': { + plain: (t) => t('settings.enterprise.audit.action.ssoRemoved', 'Removed single sign-on') + }, + 'sso.sign_in_refused': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoSignInRefused', + 'Tried to sign in without single sign-on' + ) + }, + 'sso.sessions_ended': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoSessionsEnded', + 'Ended sign-ins made before single sign-on was turned on' + ) + }, + 'sso.domain_added': { + plain: (t) => t('settings.enterprise.audit.action.ssoDomainAdded', 'Added an email domain'), + named: (t, name) => + t('settings.enterprise.audit.action.ssoDomainAddedNamed', 'Added email domain {{name}}', { + name + }) + }, + 'sso.domain_verified': { + plain: (t) => + t('settings.enterprise.audit.action.ssoDomainVerified', 'Verified an email domain'), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoDomainVerifiedNamed', + 'Verified email domain {{name}}', + { name } + ) + }, + 'sso.domain_removed': { + plain: (t) => t('settings.enterprise.audit.action.ssoDomainRemoved', 'Removed an email domain'), + named: (t, name) => + t('settings.enterprise.audit.action.ssoDomainRemovedNamed', 'Removed email domain {{name}}', { + name + }) + }, + 'sso.domain_record_missing': { + plain: (t) => + t( + 'settings.enterprise.audit.action.ssoDomainRecordMissing', + 'Found an email domain’s DNS record missing' + ), + named: (t, name) => + t( + 'settings.enterprise.audit.action.ssoDomainRecordMissingNamed', + 'Found the DNS record for {{name}} missing', + { name } + ) + }, + 'scim.enabled': { + plain: (t) => t('settings.enterprise.audit.action.scimEnabled', 'Turned on directory sync') + }, + 'scim.disabled': { + plain: (t) => t('settings.enterprise.audit.action.scimDisabled', 'Turned off directory sync') + }, + 'scim.key_created': { + plain: (t) => + t('settings.enterprise.audit.action.scimKeyCreated', 'Created a directory sync key') + }, + 'scim.key_revoked': { + plain: (t) => + t('settings.enterprise.audit.action.scimKeyRevoked', 'Revoked a directory sync key') + }, + 'scim.group_changed': { + plain: (t) => + t('settings.enterprise.audit.action.scimGroupChanged', 'Changed a directory group') + }, + 'scim.group_membership_changed': { + plain: (t) => + t( + 'settings.enterprise.audit.action.scimGroupMembershipChanged', + 'Changed who is in a directory group' + ) + } +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 974c8862c7b..8ad3809fa9f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1591,7 +1591,29 @@ "cancelScheduledOn": "Plan set to end on {{date}}", "seatsChangedDetail": "Seats changed from {{from}} to {{to}}", "spendCapChanged2": "Changed the monthly spend cap", - "spendCapChangedTo": "Changed the monthly spend cap to {{amount}}" + "spendCapChangedTo": "Changed the monthly spend cap to {{amount}}", + "ssoSetupLink": "Created a single sign-on setup link", + "ssoConfigured": "Set up single sign-on", + "ssoConfiguredNamed": "Set up single sign-on with {{name}}", + "ssoWentLive": "Turned on single sign-on", + "ssoWentLiveNamed": "Turned on single sign-on with {{name}}", + "ssoRemoved": "Removed single sign-on", + "ssoSignInRefused": "Tried to sign in without single sign-on", + "ssoSessionsEnded": "Ended sign-ins made before single sign-on was turned on", + "ssoDomainAdded": "Added an email domain", + "ssoDomainAddedNamed": "Added email domain {{name}}", + "ssoDomainVerified": "Verified an email domain", + "ssoDomainVerifiedNamed": "Verified email domain {{name}}", + "ssoDomainRemoved": "Removed an email domain", + "ssoDomainRemovedNamed": "Removed email domain {{name}}", + "ssoDomainRecordMissing": "Found an email domain’s DNS record missing", + "ssoDomainRecordMissingNamed": "Found the DNS record for {{name}} missing", + "scimEnabled": "Turned on directory sync", + "scimDisabled": "Turned off directory sync", + "scimKeyCreated": "Created a directory sync key", + "scimKeyRevoked": "Revoked a directory sync key", + "scimGroupChanged": "Changed a directory group", + "scimGroupMembershipChanged": "Changed who is in a directory group" }, "interval": { "month": "monthly", @@ -14190,7 +14212,8 @@ "connect": "Connect GitHub", "title": "GitHub", "disconnectError": "Couldn't disconnect GitHub." - } + }, + "ssoRequired": "Your team now requires single sign-on. Sign in again and choose Sign in with SSO." }, "automations": { "showButtonDescription": "Show the Automations shortcut in the sidebar.", @@ -21038,7 +21061,8 @@ "4b7d2e8f1a": "Connect Orca Mobile to this desktop across cellular or any Wi-Fi.", "9a4c6b2d7e": "Skill sharing", "3d8e5f1b9c": "Share skills behind an unlisted link and install them on any machine you use.", - "c5b3e8a17d": "Sign in to Orca" + "c5b3e8a17d": "Sign in to Orca", + "ssoRequired": "Your team now requires single sign-on. Sign in again and choose Sign in with SSO." }, "NativeChatResumeOutcomeRow": { "openChat": "Open chat", @@ -21454,7 +21478,9 @@ "seatRulesShort": "New members above your paid seats are charged now, prorated. Removed seats stay paid until renewal.", "inviteSeatRule": "Each invite uses a seat once accepted.", "enterpriseRowTitle": "Single sign-on, directory sync and the audit log", - "openEnterpriseSettings": "Open Enterprise settings" + "openEnterpriseSettings": "Open Enterprise settings", + "managedByIdp": "Managed by your identity provider", + "managedByIdpNote": "Managed by your identity provider. Add or remove people and change roles there." }, "manageBilling": "Manage billing", "comparePlans": "Compare plans", diff --git a/src/shared/orca-org-roster.ts b/src/shared/orca-org-roster.ts new file mode 100644 index 00000000000..87638c568be --- /dev/null +++ b/src/shared/orca-org-roster.ts @@ -0,0 +1,11 @@ +// A team's roster as auth answers it (GET /v1/desktop/orgs/:orgId/members). +import type { OrcaOrgMember, OrcaOrgPendingInvite, OrcaOrgRole } from './orca-profiles' + +export type OrcaOrgMembersRoster = { + members: OrcaOrgMember[] + pendingInvites: OrcaOrgPendingInvite[] + viewerRole: OrcaOrgRole + canManageMembers: boolean + /** Directory sync is on: the team's identity provider owns membership and roles. */ + directoryManaged?: boolean +} diff --git a/src/shared/orca-profile-reconnect-reason.ts b/src/shared/orca-profile-reconnect-reason.ts new file mode 100644 index 00000000000..f6b4ddc51e0 --- /dev/null +++ b/src/shared/orca-profile-reconnect-reason.ts @@ -0,0 +1,6 @@ +/** + * With auth state `reconnect-required`: why auth ended the sign-in, when it is worth telling the + * person apart from "your session expired". + * `sso-required`: their team turned on single sign-on after they signed in. + */ +export type OrcaProfileReconnectReason = 'sso-required' diff --git a/src/shared/orca-profiles.ts b/src/shared/orca-profiles.ts index 1f8d3daf904..8242230dbc0 100644 --- a/src/shared/orca-profiles.ts +++ b/src/shared/orca-profiles.ts @@ -1,3 +1,5 @@ +import type { OrcaProfileReconnectReason } from './orca-profile-reconnect-reason' +import type { OrcaOrgMembersRoster } from './orca-org-roster' import type { OrcaOrgMemberMfaFields } from './orca-account-mfa' import './constants' import { ORCA_BROWSER_PARTITION } from './browser/browser-session-partition' @@ -56,6 +58,7 @@ export type OrcaProfileAuthStatus = { capabilities?: OrcaCloudCapabilities credentialError?: string setupMessage?: string + reconnectReason?: OrcaProfileReconnectReason } export type OrcaProfileSummary = { @@ -268,12 +271,7 @@ export type OrcaOrgPendingInvite = { createdAt: number } -export type OrcaOrgMembersRoster = { - members: OrcaOrgMember[] - pendingInvites: OrcaOrgPendingInvite[] - viewerRole: OrcaOrgRole - canManageMembers: boolean -} +export type { OrcaOrgMembersRoster } export type OrcaProfileOrgMembersListArgs = { orgId: string diff --git a/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts b/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts index 12cfa49fbd3..24f4ec9df49 100644 --- a/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts +++ b/src/shared/workspace-session/workspace-session-terminal-buffers.test.ts @@ -209,9 +209,7 @@ describe('pruneLocalTerminalScrollbackBuffers', () => { const buffer = result.terminalLayoutsByTabId['remote-tab'].buffersByLeafId?.['pane:1'] ?? '' expect(buffer.length).toBeGreaterThan(0) - expect(getUtf8ByteLength(buffer)).toBeLessThanOrEqual( - TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT - ) + expect(getUtf8ByteLength(buffer)).toBeLessThanOrEqual(TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT) expect(buffer).toHaveLength(TERMINAL_SCROLLBACK_SAVED_PANE_BYTE_LIMIT / 2) })