An open-source, faster Devin alternative
TypeScript
web: Computer sessions UI on the Computer API v1 (#1058)
opencomputer-app[bot]4129fb169152
diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsindex 2b90e418..4927fc86 100644--- a/cloudflare-workers/api-edge/src/computer_api.test.ts+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -239,6 +239,7 @@ describe("computer API allowlist", () => {["GET", "/computer/sessions/cs_01h/subagents"],["GET", "/computer/sessions/cs_01h/subagents/sa_01h"],["POST", "/computer/sessions/cs_01h/subagents/sa_01h/stop"],+ ["GET", "/computer/capabilities"],["GET", "/computer/secrets"],["GET", "/computer/secrets/API_KEY/events"],["PUT", "/computer/sessions/cs_01h/secrets/API_KEY"],diff --git a/cloudflare-workers/api-edge/src/computer_api.ts b/cloudflare-workers/api-edge/src/computer_api.tsindex 9e36b244..f6a6acb2 100644--- a/cloudflare-workers/api-edge/src/computer_api.ts+++ b/cloudflare-workers/api-edge/src/computer_api.ts@@ -33,6 +33,7 @@ const COMPUTER_API_ROUTES: ReadonlyArray<{pattern: RegExp;}> = [{ methods: new Set(["GET"]), pattern: route("/me") },+ { methods: new Set(["GET"]), pattern: route("/capabilities") },{ methods: new Set(["POST"]), pattern: route("/tickets") },{ methods: new Set(["GET", "POST"]), pattern: route("/sessions") },{ methods: new Set(["GET", "PATCH"]), pattern: route(`/sessions/${SEG}`) },diff --git a/computer/src/runner/api/api.test.ts b/computer/src/runner/api/api.test.tsindex 8d54c2d1..f83e598d 100644--- a/computer/src/runner/api/api.test.ts+++ b/computer/src/runner/api/api.test.ts@@ -77,6 +77,20 @@ describe('SessionApi', () => {for (const e of w.events()) assertEvent(e);});+ it('a message from outside Slack is quoted into the thread under its sender, before the turn; one from Slack is not', async () => {+ const w = await world();+ const posts = () =>+ w.rec.filter((r) => (r as { slack?: string }).slack === 'chat.postMessage').map((r) => (r as { args: { text: string } }).args.text);+ const web = { actor: { ...BOB.actor, via: 'dashboard' as const }, member: 'usr_bob' };+ result(await w.call('turns.send', { input: 'ship it\n<!channel> & go' }, web));+ expect(posts()[0]).toBe('*Bob* from the web:\n> ship it\n> <!channel> & go');+ const at = w.rec.findIndex((r) => (r as { slack?: string }).slack === 'chat.postMessage');+ expect(w.rec.findIndex((r) => (r as { harness?: string }).harness === 'send')).toBeGreaterThan(at);+ await w.t.feed(w.T.first(), w.T.done());+ result(await w.call('turns.send', { input: 'from slack' }, { actor: { ...BOB.actor, via: 'slack' as const }, member: 'usr_bob' }));+ expect(posts().filter((t) => t.includes('from slack'))).toEqual([]);+ });+it('one idempotency key gives one turn', async () => {const w = await world();const ctx = { ...ANN_CTX, idempotencyKey: 'k-1' };@@ -336,6 +350,20 @@ describe('SessionApi', () => {for (const e of w.events()) assertEvent(e);});+ it('the computer naming a session journals the title; a person renaming it marks it renamed', async () => {+ const w = await world();+ expect(w.api.renamed).toBe(false);+ w.api.named('golden', 'Sea poem');+ const named = w.of('session.updated').at(-1)!;+ expect(named.data).toEqual({ changes: { title: { from: 'golden', to: 'Sea poem' } } });+ expect(named.actor).toBeNull();+ result(await w.call('sessions.update', { title: 'Mine' }));+ expect(w.api.renamed).toBe(true);+ // Kept in the session's info, so it outlasts this runner.+ expect(w.t.sess.info.renamed).toBe(true);+ for (const e of w.events()) assertEvent(e);+ });+it('sessions.update speed reaches the harness, the session and the journal; a bad one is refused', async () => {const w = await world();const r = result(await w.call('sessions.update', { speed: 'standard' }));diff --git a/computer/src/runner/api/api.ts b/computer/src/runner/api/api.tsindex 2ae82a89..6aae61ef 100644--- a/computer/src/runner/api/api.ts+++ b/computer/src/runner/api/api.ts@@ -20,8 +20,11 @@// whoever (a Slack `!!`) interrupted it before;// - an API answer to an ask resolves its prompt exactly as a button would// (asks.ts, prompts.ts); a stop of a subagent is the panel's Stop button;-// - Slack sees what it saw before: nothing here posts to it beyond what the-// session's own commands (a model switch) say.+// - Slack sees what it saw before, plus the words: a message into a Slack+// session from anywhere else (the dashboard, the CLI, the API) is posted+// into its thread, quoted under its sender's name, before the session takes+// it, so the thread reads as the whole conversation. Nothing else here posts+// to it beyond what the session's own commands (a model switch) say.import { log } from '../../log.js';import { mintId } from '../../session-ids.js';@@ -64,6 +67,18 @@ const fail = (code: string, message: string, status: number, extra: Record<strin});const actorOf = (a: ApiActor): Actor => ({ ...a, name: a.name ?? a.id });+/** Longest echo of a message into Slack; the rest is cut. */+export const ECHO_MAX = 3_000;+const VIA: Record<string, string> = { dashboard: 'the web', opc: 'the CLI', api: 'the API' };++/** A message from outside Slack as its thread shows it: the sender, where from, and the words quoted (mentions inert). */+export function echoText(text: string, actor: Actor): string {+ const cut = text.length > ECHO_MAX ? `${text.slice(0, ECHO_MAX)}…` : text;+ const safe = cut.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ const quoted = safe.split('\n').map((l) => `> ${l}`).join('\n');+ return `*${actor.name}* from ${VIA[actor.via] ?? actor.via}:\n${quoted}`;+}+export class SessionApi implements Writer {readonly tap: Tap;readonly call: Writer['call'];@@ -104,6 +119,16 @@ export class SessionApi implements Writer {};}+ /** A person set the title over the API (kept in the session's info, across restarts): the computer's naming (work 093) leaves it alone. */+ get renamed(): boolean {+ return !!this.session.info.renamed;+ }++ /** The computer named the session (work 093): the journal says so, and the session list follows. */+ named(from: string, to: string) {+ this.log.append('session.updated', { changes: { title: { from, to } } }, { actor: null });+ }+get sessionId() {return this.log.sessionId;}@@ -168,6 +193,7 @@ export class SessionApi implements Writer {/** A message into the session, as `turns.send` (and a Delivery.api) has it. */async send(text: string, actor: Actor, ifBusy: IfBusy): Promise<CallOutcome> {+ await this.echo(text, actor);if (!this.busy && !this.queue.length) return this.start({ turnId: mintId('tn'), text, actor }, { ifBusy });const cur = this.tap.cur;if (ifBusy === 'interrupt') return this.interruptWith(text, actor);@@ -185,17 +211,27 @@ export class SessionApi implements Writer {}/** A Delivery.api: one the host's writer recorded while no runner ran (`turnId`) starts in that turn, in order; another is a `turns.send`. */- deliver(text: string, d: ApiDelivery): Promise<CallOutcome> {+ async deliver(text: string, d: ApiDelivery): Promise<CallOutcome> {const actor = actorOf(d.actor);if (!d.turnId) {const ctx = { actor: d.actor, member: d.member, idempotencyKey: d.idempotencyKey };return idempotent(this.log, 'turns.send', { sessionId: this.sessionId, input: text, ifBusy: d.ifBusy }, ctx, () => this.send(text, actor, d.ifBusy));}const t = this.log.fold.turn(d.turnId);- if (!this.taken.has(d.turnId) && (!t || t.status === 'queued')) this.queue.push({ turnId: d.turnId, text, actor });+ if (!this.taken.has(d.turnId) && (!t || t.status === 'queued')) {+ this.taken.add(d.turnId);+ await this.echo(text, actor);+ this.queue.push({ turnId: d.turnId, text, actor });+ }this.taken.add(d.turnId);this.idle();- return Promise.resolve(this.sent(d.turnId, 'queued'));+ return this.sent(d.turnId, 'queued');+ }++ /** A message from outside Slack, into a Slack session's thread (never throws: `say` logs Slack's refusals). */+ private async echo(text: string, actor: Actor) {+ if (actor.via === 'slack' || !this.session.thread.slack) return;+ await this.session.thread.say(echoText(text, actor));}private async start(w: Waiting, from: Omit<SentFrom, 'actor' | 'turnId'>): Promise<CallOutcome> {@@ -286,7 +322,7 @@ export class SessionApi implements Writer {if (p.effort !== undefined && p.effort !== s.info.effort) await switchEffort(s, p.effort as EffortLevel);if (p.speed !== undefined && p.speed !== s.info.speed) await switchSpeed(s, p.speed);const changes: Record<string, { from: unknown; to: unknown }> = {};- if (p.title !== undefined && p.title !== s.info.title) (changes.title = { from: s.info.title, to: p.title }), (s.info.title = p.title), s.persist();+ if (p.title !== undefined && p.title !== s.info.title) (changes.title = { from: s.info.title, to: p.title }), (s.info.title = p.title), (s.info.renamed = true), s.persist();const cur = fold.session();if (p.archived !== undefined && p.archived !== cur.archived) changes.archived = { from: cur.archived, to: p.archived };for (const [k, v] of Object.entries(p.metadata ?? {})) if ((cur.metadata[k] ?? null) !== v) changes[`metadata.${k}`] = { from: cur.metadata[k] ?? null, to: v };diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.tsindex 465a04a5..e8ab0442 100644--- a/computer/src/runner/main.ts+++ b/computer/src/runner/main.ts@@ -247,19 +247,23 @@ const hooks: SessionHooks = {turns,};-/** The session's title in Slack after a turn (work 093): one try at a time, none once it is final. */+/** The session's title after a turn (work 093), in Slack and the API: one try at a time, none once it is final. */let titling = false;let titled = false;/** The Codex harness running, for a Codex session. */let codex: Harness | undefined;async function retitle() {const sid = s?.info.sdkSessionId;- if (titling || titled || !sid || !s?.thread.slack) return;+ if (titling || titled || !sid || !s || !(s.thread.slack || api) || api?.api.renamed) return;titling = true;const named = ss?.harness === 'codex' ? codex?.name?.() : nameSession(sid, s.info.cwd);const r = await Promise.resolve(named).finally(() => (titling = false));titled = !!r?.done;- if (r?.title && r.title !== s.info.title) (s.info.title = r.title), await s.thread.rename(r.title);+ if (!r?.title || r.title === s.info.title || api?.api.renamed) return;+ api?.api.named(s.info.title, r.title);+ s.info.title = r.title;+ s.persist();+ if (s.thread.slack) await s.thread.rename(r.title);}/** Codex for a session whose spec names it (work 082), loaded here and only then; undefined is Claude. */diff --git a/computer/src/runner/session.ts b/computer/src/runner/session.tsindex f426d7d4..e46bdf59 100644--- a/computer/src/runner/session.ts+++ b/computer/src/runner/session.ts@@ -62,6 +62,8 @@ export interface SessionInfo {teamId?: string;cwd: string;title: string;+ /** A person set the title (the API's sessions.update): the computer's naming (work 093) leaves it alone. */+ renamed?: boolean;mode: PermissionMode;model?: string;effort?: EffortLevel; // `!effort` (model-switch.ts); DEFAULT_EFFORT withoutdiff --git a/services/managed-agents/scripts/stack.mjs b/services/managed-agents/scripts/stack.mjsindex 087d83e7..220714f1 100644--- a/services/managed-agents/scripts/stack.mjs+++ b/services/managed-agents/scripts/stack.mjs@@ -407,6 +407,8 @@ function writeConfigs(stack, { bootstrap }) {COMPUTER_DEFAULT_DISK_GIB: String(stack.computer?.diskGiB ?? 128),// Warm computers cost like a free organization's each: opt in per stack.COMPUTER_POOL_SIZE: process.env.OC_STACK_COMPUTER_POOL_SIZE || "0",+ // The computer API's rollout gate (api-gate.ts): open, as in production.+ COMPUTER_API_ORGS: "*",SLACK_COMPUTER_SCOPES:"app_mentions:read,assistant:write,channels:history,channels:read,channels:manage,groups:history,groups:read,groups:write,im:history,im:read,im:write,chat:write,files:read,files:write,reactions:write,users:read,users:read.email",...optionalSecrets({@@ -439,6 +441,8 @@ function writeConfigs(stack, { bootstrap }) {{ name: "MEMORY", class_name: "MemoryDurableObject" },{ name: "DATABASES", class_name: "ProjectDatabaseDurableObject" },{ name: "COMPUTERS", class_name: "ComputerDurableObject" },+ // Work 084: one per computer session, the sessions API's copy of its event log.+ { name: "SESSION_LOG", class_name: "SessionLogDurableObject" },],},migrations: [@@ -450,6 +454,7 @@ function writeConfigs(stack, { bootstrap }) {{ tag: "v3", new_sqlite_classes: ["MemoryDurableObject"] },{ tag: "v4", new_sqlite_classes: ["ProjectDatabaseDurableObject"] },{ tag: "v5", new_sqlite_classes: ["ComputerDurableObject"] },+ { tag: "v6", new_sqlite_classes: ["SessionLogDurableObject"] },],observability,});diff --git a/services/managed-agents/src/computer/api-http.ts b/services/managed-agents/src/computer/api-http.tsindex 44a62ec7..1321885b 100644--- a/services/managed-agents/src/computer/api-http.ts+++ b/services/managed-agents/src/computer/api-http.ts@@ -60,6 +60,8 @@ export function matchApiRoute(method: string, suffix: string): Route | null {return { op: method === "PUT" ? "secrets.put" : "secrets.delete", sub: p[2] };}if (p[0] === "me" && p[1] === "secrets" && p.length === 3 && (method === "PUT" || method === "DELETE")) return { op: "secrets" };+ // The same for every session, so the new-session screen can read it before there is one.+ if (is("GET", 1) && p[0] === "capabilities") return { op: "capabilities" };if (p[0] !== "sessions") return null;if (p.length === 1) return method === "GET" ? { op: "list" } : method === "POST" ? { op: "create" } : null;const sessionId = p[1]!;@@ -373,6 +375,7 @@ async function routeApi(return call({ op: "secrets.put", name, body: parsed.value });}if (route.op === "me") return call({ op: "me" });+ if (route.op === "capabilities" && !route.sessionId) return out.send(200, { capabilities: capabilities() });if (route.op === "list") return call({ op: "list", query: [...query.entries()] });const needsBody = request.method === "POST" || request.method === "PATCH";diff --git a/services/managed-agents/src/computer/sessions-api.ts b/services/managed-agents/src/computer/sessions-api.tsindex 3fd004c8..e54bfcd7 100644--- a/services/managed-agents/src/computer/sessions-api.ts+++ b/services/managed-agents/src/computer/sessions-api.ts@@ -380,7 +380,8 @@ export class ComputerSessionsApi {}private actor(caller: ApiCaller): CalvinApiActor {- return { id: caller.member, name: caller.name, via: caller.via, client: caller.client };+ // No profile name (common for email sign-ins): the email reads better than the raw member id.+ return { id: caller.member, name: caller.name || caller.email, via: caller.via, client: caller.client };}// ---------------------------------------------------------------- operationsdiff --git a/services/managed-agents/test/computer-sessions-api.test.ts b/services/managed-agents/test/computer-sessions-api.test.tsindex 123e0bb3..b622a17b 100644--- a/services/managed-agents/test/computer-sessions-api.test.ts+++ b/services/managed-agents/test/computer-sessions-api.test.ts@@ -920,6 +920,7 @@ describe("api-http", () => {expect(matchApiRoute("POST", `/sessions/${SID}/asks/ak_7c1v9b4m8q2x/answer`)).toEqual({ op: "asks.answer", sessionId: SID, sub: "ak_7c1v9b4m8q2x" });expect(matchApiRoute("POST", `/sessions/${SID}/subagents/sa_000000000001/stop`)).toEqual({ op: "subagents.stop", sessionId: SID, sub: "sa_000000000001" });expect(matchApiRoute("GET", "/me")).toEqual({ op: "me" });+ expect(matchApiRoute("GET", "/capabilities")).toEqual({ op: "capabilities" });expect(matchApiRoute("DELETE", `/sessions/${SID}`)).toBeNull();});diff --git a/web/src/App.tsx b/web/src/App.tsxindex 748861a1..a6b220eb 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -1,4 +1,4 @@-import { lazy } from 'react'+import { lazy, Suspense } from 'react'import { Routes, Route, Navigate, useSearchParams } from 'react-router-dom'import { AuthProvider } from './hooks/auth-provider'import ProtectedRoute from './components/ProtectedRoute'@@ -16,6 +16,15 @@ const ManagedComputer = lazy(() => import('./managed-agents/Computer'))const ManagedComputerSecrets = lazy(() => import('./managed-agents/ComputerSecrets'),)+const ComputerSessionsLayout = lazy(+ () => import('./managed-agents/computer-sessions/Layout'),+)+const ComputerSessionsHome = lazy(+ () => import('./managed-agents/computer-sessions/Home'),+)+const ComputerSession = lazy(+ () => import('./managed-agents/computer-sessions/Session'),+)const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))@@ -73,24 +82,8 @@ export default function App() {<Route path="security" element={<ManagedSecurityOnboarding />} /><Route path="getting-started" element={<ManagedAgentsHome />} /><Route path="computer" element={<ManagedComputer />} />- <Route- path="computer/secrets"- element={<ManagedComputerSecrets />}- />- <Route path="automations" element={<ManagedAgentsHome list />} />- <Route- path="model-access/callback"- element={<ModelAccessCallback />}- />- <Route- path="managed-agents/connections"- element={<ManagedAgentConnections />}- />- <Route- path="managed-agents/new"- element={<Navigate to="/new" replace />}- />- <Route path="new" element={<NewProject />} />+ {/* Projects keep the old shell for now: their pages lean on its+ sidebar and environment switcher. */}<Routepath="projects/:projectId"element={<ManagedProjectDetail />}@@ -119,6 +112,41 @@ export default function App() {path="managed-agents/:agentId"element={<ManagedAgentDetail />}/>+ </Route>+ {/* The computer's sessions are their own full-screen view, with+ their own rail and sidebar (work 107); every other page opens in+ the same rail, without the sessions sidebar. */}+ <Route+ element={+ <Suspense fallback={null}>+ <ComputerSessionsLayout />+ </Suspense>+ }+ >+ <Route path="computer/sessions">+ <Route index element={<ComputerSessionsHome />} />+ {/* The same home, for a phone, where the index is the list. */}+ <Route path="new" element={<ComputerSessionsHome />} />+ <Route path=":id" element={<ComputerSession />} />+ </Route>+ <Route+ path="computer/secrets"+ element={<ManagedComputerSecrets />}+ />+ <Route path="automations" element={<ManagedAgentsHome list />} />+ <Route+ path="model-access/callback"+ element={<ModelAccessCallback />}+ />+ <Route+ path="managed-agents/connections"+ element={<ManagedAgentConnections />}+ />+ <Route+ path="managed-agents/new"+ element={<Navigate to="/new" replace />}+ />+ <Route path="new" element={<NewProject />} /><Route path="api-keys" element={<APIKeys />} /><Route path="billing" element={<Billing />} /><Route path="settings" element={<Settings />} />diff --git a/web/src/api/mock-computer-sessions.ts b/web/src/api/mock-computer-sessions.tsnew file mode 100644index 00000000..a18564a5--- /dev/null+++ b/web/src/api/mock-computer-sessions.ts@@ -0,0 +1,550 @@+// Preview data for the Computer API v1 sessions routes (work 107), served by+// mockFetch under VITE_PREVIEW. Times are relative to now so the sidebar reads+// naturally; sending a message plays back a short canned turn.++type Json = Record<string, unknown>++const now = () => Date.now()+const ago = (min: number) => new Date(now() - min * 60_000).toISOString()++let n = 0+const nextId = (prefix: string) =>+ `${prefix}_${(++n).toString(36).padStart(12, '0')}`++const person = { id: 'usr_igor', name: 'Igor', email: '[email protected]' }+const settings = {+ model: 'claude-opus-5-5',+ effort: null,+ mode: 'bypassPermissions',+ speed: null,+}++type MockSession = Json & {+ id: string+ title: string+ status: string+ archived: boolean+ asks: Json[]+ lastText: string | null+ lastSeq: number+ lastActiveAt: string+}+type MockEvent = Json & { seq: number; type: string }++const sessions: MockSession[] = []+const journal = new Map<string, MockEvent[]>()++function session(+ title: string,+ status: string,+ minAgo: number,+ origin: string,+ lastText: string | null,+ extra: Partial<MockSession> = {},+): MockSession {+ const s: MockSession = {+ id: nextId('cs'),+ title,+ status,+ archived: false,+ owner: person,+ origin: {+ type: origin,+ client: null,+ slack:+ origin === 'slack'+ ? {+ teamId: 'T0',+ channelId: 'C0',+ channelName: 'eng',+ threadTs: '1',+ url: 'https://slack.com',+ }+ : null,+ },+ settings,+ metadata: {},+ activeTurnId: null,+ queued: [],+ asks: [],+ subagents: [],+ lastTurn: null,+ lastText,+ context: null,+ lastSeq: 0,+ createdAt: ago(minAgo + 30),+ lastActiveAt: ago(minAgo),+ urls: { dashboard: null },+ ...extra,+ }+ sessions.push(s)+ journal.set(s.id, [])+ return s+}++function emit(s: MockSession, type: string, data: Json, actor?: Json) {+ const events = journal.get(s.id)!+ const seq = events.length + 1+ events.push({+ id: nextId('ev'),+ seq,+ createdAt: new Date().toISOString(),+ sessionId: s.id,+ turnId: s.activeTurnId ?? null,+ actor: actor ?? null,+ type,+ data,+ })+ s.lastSeq = seq+ s.lastActiveAt = new Date().toISOString()+}++// Writes a past conversation with timestamps spread back from `minAgo`.+function history(+ s: MockSession,+ minAgo: number,+ steps: Array<[string, Json, Json?]>,+) {+ const events = journal.get(s.id)!+ steps.forEach(([type, data, actor], i) => {+ events.push({+ id: nextId('ev'),+ seq: events.length + 1,+ createdAt: ago(minAgo + (steps.length - i) * 0.4),+ sessionId: s.id,+ turnId: 'tn_preview',+ actor: actor ?? null,+ type,+ data,+ })+ })+ s.lastSeq = events.length+}++const me = { id: person.id, name: person.name, via: 'dashboard' }+const viaSlack = { id: person.id, name: person.name, via: 'slack' }+const said = (text: string, actor: Json = me): [string, Json, Json] => [+ 'message.received',+ { input: text, delivery: 'started' },+ actor,+]+const tool = (title: string, toolName = 'Bash'): Array<[string, Json]> => {+ const callId = nextId('call')+ return [+ ['tool.started', { toolName, callId, parentCallId: null, title }],+ ['tool.completed', { toolName, callId, parentCallId: null, title }],+ ]+}+const reply = (text: string): [string, Json] => [+ 'message.completed',+ { blockId: nextId('b'), parentCallId: null, text },+]+const done: [string, Json] = [+ 'turn.completed',+ { text: null, durationMs: 1, silent: false },+]++function approvalAsk(s: MockSession, title: string, command: string): Json {+ return {+ id: nextId('ak'),+ sessionId: s.id,+ turnId: 'tn_preview',+ kind: 'approval',+ status: 'open',+ createdAt: ago(3),+ closedAt: null,+ closedBy: null,+ answer: null,+ approval: {+ toolName: 'Bash',+ callId: 'call_x',+ input: { command },+ title,+ alwaysAllows: 'Bash(psql:*)',+ },+ question: null,+ secret: null,+ }+}++function seed() {+ const rotate = session(+ 'Rotate the staging database password',+ 'waiting',+ 3,+ 'dashboard',+ 'Ready to rotate the password and update the secret.',+ )+ const ask = approvalAsk(+ rotate,+ 'Run psql on staging',+ 'psql $STAGING_URL -c "ALTER ROLE app PASSWORD \'…\'"',+ )+ rotate.asks = [ask]+ history(rotate, 3, [+ said('Rotate the staging database password and update the app secret.'),+ ...tool('Read deploy/staging.env', 'Read'),+ ...tool('grep -rn STAGING_DB_PASSWORD .'),+ reply(+ 'The app reads `STAGING_DB_PASSWORD` from the organization secrets. I will set a new password on the `app` role, then update the secret.',+ ),+ ['ask.opened', { ask }],+ ])++ const charts = session(+ 'Pick a chart library for the usage page',+ 'waiting',+ 18,+ 'slack',+ null,+ )+ const question = {+ id: nextId('ak'),+ sessionId: charts.id,+ turnId: 'tn_preview',+ kind: 'question',+ status: 'open',+ createdAt: ago(18),+ closedAt: null,+ closedBy: null,+ answer: null,+ approval: null,+ question: {+ questions: [+ {+ id: 'q1',+ header: 'Library',+ text: 'Which chart library should the usage page use?',+ multiSelect: false,+ options: [+ { label: 'Recharts', description: 'Already in the bundle' },+ { label: 'visx', description: 'Lower level, smaller' },+ { label: 'ECharts', description: 'Heavier, more chart types' },+ ],+ },+ ],+ },+ secret: null,+ }+ charts.asks = [question]+ history(charts, 18, [+ said('Add a daily usage chart to the billing page', viaSlack),+ ...tool('Read web/src/pages/Billing.tsx', 'Read'),+ ['ask.opened', { ask: question }],+ ])++ const flaky = session(+ 'Fix the flaky checkout e2e test',+ 'running',+ 0,+ 'dashboard',+ 'Running the suite 20 times to confirm the fix…',+ { activeTurnId: 'tn_preview' },+ )+ history(flaky, 6, [+ said(+ 'checkout.spec.ts fails about one run in five on CI. Find out why and fix it.',+ ),+ ...tool('Read e2e/checkout.spec.ts', 'Read'),+ ...tool('npx playwright test checkout --repeat-each 10'),+ reply(+ 'It fails when the cart badge renders before the price API answers: the test clicks **Checkout** while the button is still disabled. I will wait for the price instead of the badge.',+ ),+ ...tool('Edit e2e/checkout.spec.ts', 'Edit'),+ [+ 'tool.started',+ {+ toolName: 'Bash',+ callId: 'call_live',+ parentCallId: null,+ title: 'npx playwright test checkout --repeat-each 20',+ },+ ],+ ])++ const churn = session(+ 'Weekly churn report',+ 'idle',+ 52,+ 'slack',+ 'Posted the report: churn is 2.1%, down from 2.6% last week.',+ )+ history(churn, 52, [+ said('Run the weekly churn report and post it in #metrics', viaSlack),+ ...tool('Query PostHog: active orgs by week', 'mcp__posthog__query'),+ ...tool('Render churn chart', 'Bash'),+ reply(+ 'Posted the report in #metrics.\n\n| Week | Churn |\n| --- | --- |\n| Nov 3 | 2.6% |\n| Nov 10 | 2.1% |\n\nThe drop comes from fewer cancellations on the Pro plan.',+ ),+ done,+ ])++ const more: Array<[string, string, number, string, string]> = [+ [+ 'Upgrade React Router to v7',+ 'idle',+ 180,+ 'opc',+ 'Opened #4182: all routes load and tests pass.',+ ],+ [+ 'Investigate 502s on api-edge',+ 'suspended',+ 60 * 20,+ 'slack',+ 'The 502s came from a cold Durable Object; fixed in #4170.',+ ],+ [+ 'Draft the launch post for Sessions',+ 'suspended',+ 60 * 26,+ 'dashboard',+ 'Draft is in docs/launch/sessions.md.',+ ],+ [+ 'Why did the November invoice double?',+ 'suspended',+ 60 * 50,+ 'slack',+ 'Two subscriptions overlapped for a day; refunded the extra.',+ ],+ [+ 'Add rate limits to the public API',+ 'suspended',+ 60 * 74,+ 'api',+ 'Merged #4101: 600 requests a minute per key.',+ ],+ [+ 'Clean up stale feature flags',+ 'suspended',+ 60 * 98,+ 'dashboard',+ 'Removed 14 flags; 3 still read in production.',+ ],+ ]+ for (const [title, status, min, origin, text] of more) {+ const s = session(title, status, min, origin, text)+ history(s, min, [+ said(title),+ ...tool('Explore the repository', 'Task'),+ reply(text),+ done,+ ])+ }+}+seed()++const capabilities = {+ models: [+ {+ id: 'claude-opus-5-5',+ name: 'Claude Opus 5.5',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ contextWindow: 1_000_000,+ default: true,+ },+ {+ id: 'claude-sonnet-5-5',+ name: 'Claude Sonnet 5.5',+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ contextWindow: 1_000_000,+ default: false,+ },+ {+ id: 'gpt-6.1-sol',+ name: 'GPT-6.1 Sol (Codex)',+ efforts: ['low', 'medium', 'high', 'xhigh'],+ contextWindow: 400_000,+ default: false,+ },+ ],+ modes: ['default', 'acceptEdits', 'plan', 'bypassPermissions'],+ features: {+ steer: true,+ compact: true,+ terminal: true,+ workspace: true,+ reasoning: true,+ subagents: true,+ },+}++// A short canned turn: two tool calls and a reply, then idle.+function playTurn(s: MockSession, input: string) {+ s.status = 'running'+ s.activeTurnId = nextId('tn')+ s.lastText = 'Working…'+ const steps: Array<() => void> = [+ () => emit(s, 'turn.started', { model: s.settings, trigger: 'message' }),+ () => {+ const callId = nextId('call')+ emit(s, 'tool.started', {+ toolName: 'Bash',+ callId,+ parentCallId: null,+ title: 'git log --oneline -5',+ })+ setTimeout(+ () =>+ emit(s, 'tool.completed', {+ toolName: 'Bash',+ callId,+ parentCallId: null,+ title: 'git log --oneline -5',+ }),+ 700,+ )+ },+ () => {+ const text = `Done. This is preview data, so nothing ran; in production Computer would now work on: “${input.slice(0, 120)}”.`+ emit(s, 'message.completed', {+ blockId: nextId('b'),+ parentCallId: null,+ text,+ })+ s.lastText = text+ },+ () => {+ emit(s, 'turn.completed', { text: null, durationMs: 4000, silent: false })+ s.status = 'idle'+ s.activeTurnId = null+ },+ ]+ steps.forEach((step, i) => setTimeout(step, 600 + i * 1300))+}++const wait = <T>(ms: number, value: () => T) =>+ new Promise<T>((resolve) => setTimeout(() => resolve(value()), ms))++const PREFIX = '/managed-agents/computer'++// Returns undefined for paths it does not serve.+export function computerSessionsMock(+ path: string,+ method: string,+ body: unknown,+): unknown {+ const [pathname, search = ''] = path.split('?')+ const query = new URLSearchParams(search)+ if (!pathname.startsWith(PREFIX)) return undefined+ const rest = pathname.slice(PREFIX.length)+ const input = (+ typeof body === 'string' ? JSON.parse(body || '{}') : {}+ ) as Json++ if (rest === '/capabilities') return { capabilities }++ // The old dashboard list shares the path without a query; leave it alone.+ if (rest === '/sessions' && method === 'GET' && search) {+ const statuses = query.get('status')?.split(',')+ const q = query.get('q')?.toLowerCase()+ const archived = query.get('archived') ?? 'false'+ const rows = sessions+ .filter((s) => !statuses || statuses.includes(s.status))+ .filter((s) => !q || s.title.toLowerCase().includes(q))+ .filter((s) => archived === 'all' || s.archived === (archived === 'true'))+ .sort((a, b) => b.lastActiveAt.localeCompare(a.lastActiveAt))+ return { sessions: rows, nextCursor: null }+ }+ if (rest === '/sessions' && method === 'POST') {+ const text = typeof input.input === 'string' ? input.input : ''+ const s = session(+ text.split('\n')[0].slice(0, 60) || 'New session',+ 'starting',+ 0,+ 'dashboard',+ null,+ )+ s.settings = { ...settings, ...pick(input, ['model', 'effort', 'mode']) }+ emit(s, 'message.received', { input: text, delivery: 'started' }, me)+ playTurn(s, text)+ return { session: s }+ }++ const m = rest.match(/^\/sessions\/([^/]+)(\/.*)?$/)+ if (!m) return undefined+ const s = sessions.find((x) => x.id === m[1])+ if (!s) return undefined+ const sub = m[2] ?? ''++ if (sub === '' && method === 'GET') return { session: s }+ if (sub === '' && method === 'PATCH') {+ Object.assign(s, pick(input, ['title', 'archived']))+ s.settings = {+ ...(s.settings as Json),+ ...pick(input, ['model', 'effort', 'mode']),+ }+ return { session: s, seq: s.lastSeq }+ }+ if (sub === '/events') {+ const events = journal.get(s.id)!+ const after = query.get('after')+ const page = () => {+ const from = after === null ? 0 : Number(after)+ return {+ events: events.filter((e) => e.seq > from),+ earlierTurns: null,+ lastSeq: s.lastSeq,+ hasMore: false,+ }+ }+ const waitMs = Number(query.get('waitMs') ?? 0)+ if (after !== null && Number(after) >= s.lastSeq && waitMs) {+ // Hold like the server does, but wake early when something arrives.+ return new Promise((resolve) => {+ const started = now()+ const tick = setInterval(() => {+ if (s.lastSeq > Number(after) || now() - started > waitMs) {+ clearInterval(tick)+ resolve(page())+ }+ }, 250)+ })+ }+ return page()+ }+ if (sub === '/turns' && method === 'POST') {+ const text = typeof input.input === 'string' ? input.input : ''+ emit(+ s,+ 'message.received',+ { input: text, ifBusy: input.ifBusy, delivery: 'started' },+ me,+ )+ playTurn(s, text)+ return wait(300, () => ({+ turn: { id: s.activeTurnId, status: 'running' },+ delivery: 'started',+ duplicate: false,+ seq: s.lastSeq,+ }))+ }+ if (sub === '/interrupt' && method === 'POST') {+ emit(s, 'turn.cancelled', {})+ s.status = 'idle'+ s.activeTurnId = null+ return { session: s }+ }+ const askMatch = sub.match(/^\/asks\/([^/]+)\/(answer|dismiss)$/)+ if (askMatch && method === 'POST') {+ const ask = s.asks.find((a) => a.id === askMatch[1])+ if (!ask) return undefined+ Object.assign(ask, {+ status: askMatch[2] === 'answer' ? 'answered' : 'dismissed',+ closedAt: new Date().toISOString(),+ answer: input,+ })+ s.asks = []+ emit(s, 'ask.closed', { ask })+ playTurn(s, 'continue after your answer')+ return { ask, seq: s.lastSeq }+ }+ return undefined+}++function pick(o: Json, keys: string[]): Json {+ return Object.fromEntries(+ keys.filter((k) => o[k] !== undefined).map((k) => [k, o[k]]),+ )+}diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 1fb17f3c..d4448dab 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -11,6 +11,7 @@// screen actually reads, not the full interface.import { ApiError } from './errors'+import { computerSessionsMock } from './mock-computer-sessions'// Fixed clock so screenshots are deterministic.const BASE = new Date('2026-06-26T17:00:00Z').getTime()@@ -824,7 +825,10 @@ const ROUTES: Array<[RegExp, Handler]> = [// Mutations the preview needs to echo something parseable (e.g. the Slack// wizard's POST …/slack/manifest → manifest+steps). Everything else 204-ish.const POST_ROUTES: [RegExp, () => unknown][] = [- [/^\/github-star\/start$/, () => (githubStar = { ...githubStar, started: true })],+ [+ /^\/github-star\/start$/,+ () => (githubStar = { ...githubStar, started: true }),+ ],[/^\/github-star\/claim$/,() => (githubStar = { ...githubStar, eligible: false, claimed: true }),@@ -881,6 +885,8 @@ const POST_ROUTES: [RegExp, () => unknown][] = [export function mockFetch<T>(path: string, options: RequestInit = {}): T {const method = (options.method ?? 'GET').toUpperCase()+ const computerSessions = computerSessionsMock(path, method, options.body)+ if (computerSessions !== undefined) return computerSessions as Tif (/^\/managed-agents\/projects\/[^/]+\/service-connections$/.test(path) &&(method === 'POST' || method === 'DELETE')diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex a9da00ad..a53f0019 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -131,6 +131,12 @@ export function managedAgentsNav(options: {...(options.computerEnabled? [{ to: '/computer', label: 'Computer', icon: Computer, end: true },+ {+ to: '/computer/sessions',+ label: 'Sessions',+ icon: MessagesSquare,+ preview: true,+ },{ to: '/computer/secrets', label: 'Secrets', icon: KeyRound },]: []),diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 3c86db83..48955ef3 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -3,8 +3,7 @@ import { BrainCircuit, Database, KeySquare, Plug } from 'lucide-react'import { managedAgentsNav } from './app-shell-nav'describe('managed agents navigation', () => {- const defaults = {- }+ const defaults = {}it('links Automations to its own page', () => {const nav = managedAgentsNav({@@ -12,15 +11,16 @@ describe('managed agents navigation', () => {computerEnabled: true,})expect(nav.map((group) => group.items.map((item) => item.label))).toEqual([- ['Computer', 'Secrets', 'Automations'],+ ['Computer', 'Sessions', 'Secrets', 'Automations'],['Connections'],])expect(nav[0]?.items[0]).toMatchObject({to: '/computer',label: 'Computer',})- expect(nav[0]?.items[1]).toMatchObject({ to: '/computer/secrets' })- expect(nav[0]?.items[2]).toMatchObject({ to: '/automations' })+ expect(nav[0]?.items[1]).toMatchObject({ to: '/computer/sessions' })+ expect(nav[0]?.items[2]).toMatchObject({ to: '/computer/secrets' })+ expect(nav[0]?.items[3]).toMatchObject({ to: '/automations' })expect(nav[1]?.items[0]).toMatchObject({to: '/managed-agents/connections',label: 'Connections',@@ -33,7 +33,10 @@ describe('managed agents navigation', () => {managedAgentsNav({ ...defaults, computerEnabled: true }).map((group) =>group.items.map((item) => item.label),),- ).toEqual([['Computer', 'Secrets', 'Automations'], ['Connections']])+ ).toEqual([+ ['Computer', 'Sessions', 'Secrets', 'Automations'],+ ['Connections'],+ ])})it('hides the computer from organizations without it (rollout flag)', () => {diff --git a/web/src/managed-agents/computer-sessions-api.ts b/web/src/managed-agents/computer-sessions-api.tsnew file mode 100644index 00000000..67ef3692--- /dev/null+++ b/web/src/managed-agents/computer-sessions-api.ts@@ -0,0 +1,274 @@+import { z } from 'zod'+import { apiFetch } from '@/api/client'++// The Computer API v1 (computer/schema/computer-api.v1.json), called with the+// dashboard's session cookie on the public `/api` base: the api-edge accepts a+// cookie on these routes and the backend records the caller `via: dashboard`.+// Live updates long-poll `GET /events?waitMs`, since tickets for the WebSocket+// still require an API key (work 107).++const PREFIX = '/managed-agents/computer'++// Objects are loose: the schema says every object may gain fields.+const PersonSchema = z.looseObject({+ id: z.string(),+ name: z.string().nullable(),+ email: z.string().nullable().optional(),+})++const QuestionSchema = z.looseObject({+ id: z.string(),+ header: z.string(),+ text: z.string(),+ multiSelect: z.boolean(),+ options: z.array(+ z.looseObject({ label: z.string(), description: z.string().nullable() }),+ ),+})++export const AskSchema = z.looseObject({+ id: z.string(),+ sessionId: z.string(),+ turnId: z.string().nullable(),+ kind: z.string(),+ status: z.string(),+ createdAt: z.string(),+ approval: z+ .looseObject({+ toolName: z.string(),+ title: z.string().nullable().optional(),+ input: z.unknown().optional(),+ alwaysAllows: z.string().nullable().optional(),+ })+ .nullable()+ .optional(),+ question: z+ .looseObject({ questions: z.array(QuestionSchema) })+ .nullable()+ .optional(),+ secret: z.unknown().optional(),+})+export type Ask = z.infer<typeof AskSchema>++export const SessionSchema = z.looseObject({+ id: z.string(),+ title: z.string().nullable(),+ status: z.string(),+ archived: z.boolean(),+ owner: PersonSchema.nullable(),+ origin: z.looseObject({+ type: z.string(),+ client: z.string().nullable().optional(),+ slack: z+ .looseObject({ url: z.string().nullable().optional() })+ .nullable()+ .optional(),+ }),+ settings: z.looseObject({+ model: z.string().nullable(),+ effort: z.string().nullable(),+ mode: z.string().nullable(),+ speed: z.string().nullable().optional(),+ }),+ activeTurnId: z.string().nullable(),+ asks: z.array(AskSchema),+ lastText: z.string().nullable(),+ lastSeq: z.number(),+ createdAt: z.string(),+ lastActiveAt: z.string().nullable(),+})+export type Session = z.infer<typeof SessionSchema>++const SessionPageSchema = z.looseObject({+ sessions: z.array(SessionSchema),+ nextCursor: z.string().nullable(),+})+export type SessionPage = z.infer<typeof SessionPageSchema>++const ActorSchema = z.looseObject({+ id: z.string().nullable().optional(),+ name: z.string().nullable().optional(),+ via: z.string().nullable().optional(),+})++export const EventSchema = z.looseObject({+ id: z.string(),+ seq: z.number(),+ createdAt: z.string(),+ turnId: z.string().nullable(),+ actor: ActorSchema.nullable(),+ type: z.string(),+ data: z.record(z.string(), z.unknown()),+})+export type SessionEvent = z.infer<typeof EventSchema>++const EventPageSchema = z.looseObject({+ events: z.array(EventSchema),+ lastSeq: z.number(),+ hasMore: z.boolean(),+})+export type EventPage = z.infer<typeof EventPageSchema>++const CapabilitiesSchema = z.looseObject({+ models: z.array(+ z.looseObject({+ id: z.string(),+ name: z.string(),+ efforts: z.array(z.string()),+ default: z.boolean(),+ }),+ ),+ modes: z.array(z.string()),+ features: z.looseObject({ steer: z.boolean() }),+})+export type Capabilities = z.infer<typeof CapabilitiesSchema>++const SessionResultSchema = z.looseObject({ session: SessionSchema })+const SendResultSchema = z.looseObject({+ turn: z.looseObject({ id: z.string(), status: z.string() }),+ delivery: z.string(),+})+const AskResultSchema = z.looseObject({ ask: AskSchema })++export type ListSessionsQuery = {+ status?: string+ q?: string+ archived?: 'false' | 'true' | 'all'+ limit?: number+ cursor?: string+}++export function listSessions(query: ListSessionsQuery) {+ const params = new URLSearchParams({ owner: 'anyone', order: 'active' })+ for (const [k, v] of Object.entries(query)) {+ if (v !== undefined && v !== '') params.set(k, String(v))+ }+ return apiFetch(+ `${PREFIX}/sessions?${params}`,+ undefined,+ SessionPageSchema,+ '/api',+ )+}++export type SessionSettings = {+ model?: string+ effort?: string+ mode?: string+}++export function createSession(input: string, settings: SessionSettings = {}) {+ return apiFetch(+ `${PREFIX}/sessions`,+ { method: 'POST', body: JSON.stringify({ input, ...settings }) },+ SessionResultSchema,+ '/api',+ ).then((r) => r.session)+}++export function getSession(id: string) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}`,+ undefined,+ SessionResultSchema,+ '/api',+ ).then((r) => r.session)+}++export function updateSession(+ id: string,+ patch: SessionSettings & { title?: string; archived?: boolean },+) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}`,+ { method: 'PATCH', body: JSON.stringify(patch) },+ SessionResultSchema,+ '/api',+ ).then((r) => r.session)+}++export type IfBusy = 'queue' | 'steer' | 'interrupt'++export function sendTurn(id: string, input: string, ifBusy: IfBusy) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}/turns`,+ { method: 'POST', body: JSON.stringify({ input, ifBusy }) },+ SendResultSchema,+ '/api',+ )+}++export function interruptSession(id: string) {+ return apiFetch<unknown>(+ `${PREFIX}/sessions/${encodeURIComponent(id)}/interrupt`,+ { method: 'POST', body: '{}' },+ undefined,+ '/api',+ )+}++export type AskAnswer =+ | { decision: 'allow' | 'deny' | 'always'; message?: string }+ | {+ answers: Array<{+ questionId: string+ choices: string[]+ text: string | null+ }>+ }++export function answerAsk(sessionId: string, askId: string, answer: AskAnswer) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(sessionId)}/asks/${encodeURIComponent(askId)}/answer`,+ { method: 'POST', body: JSON.stringify(answer) },+ AskResultSchema,+ '/api',+ )+}++export function dismissAsk(sessionId: string, askId: string) {+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(sessionId)}/asks/${encodeURIComponent(askId)}/dismiss`,+ { method: 'POST', body: '{}' },+ AskResultSchema,+ '/api',+ )+}++// One page of events: the last `tailTurns` turns, or those after `after`; with+// `waitMs` the server holds the request until something new arrives+// (long-poll).+export function getEvents(+ id: string,+ opts: { after?: number; tailTurns?: number; limit?: number; waitMs?: number },+ signal?: AbortSignal,+) {+ const params = new URLSearchParams()+ if (opts.after !== undefined) params.set('after', String(opts.after))+ if (opts.tailTurns !== undefined)+ params.set('tailTurns', String(opts.tailTurns))+ if (opts.limit !== undefined) params.set('limit', String(opts.limit))+ if (opts.waitMs !== undefined) params.set('waitMs', String(opts.waitMs))+ return apiFetch(+ `${PREFIX}/sessions/${encodeURIComponent(id)}/events?${params}`,+ { signal },+ EventPageSchema,+ '/api',+ )+}++export function getCapabilities() {+ return apiFetch(+ `${PREFIX}/capabilities`,+ undefined,+ z.looseObject({ capabilities: CapabilitiesSchema }),+ '/api',+ ).then((r) => r.capabilities)+}++export const sessionKeys = {+ all: ['computer-sessions'] as const,+ list: (q: ListSessionsQuery) => ['computer-sessions', 'list', q] as const,+ one: (id: string) => ['computer-sessions', 'one', id] as const,+ capabilities: ['computer-sessions', 'capabilities'] as const,+}diff --git a/web/src/managed-agents/computer-sessions/Home.tsx b/web/src/managed-agents/computer-sessions/Home.tsxnew file mode 100644index 00000000..ccf53aa8--- /dev/null+++ b/web/src/managed-agents/computer-sessions/Home.tsx@@ -0,0 +1,102 @@+import { useState } from 'react'+import { useNavigate } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { ArrowUp, Loader2 } from 'lucide-react'+import { ChatTextarea } from '@/components/chat-textarea'+import { Button } from '@/components/ui/button'+import { notifyError } from '@/lib/errors'+import {+ createSession,+ listSessions,+ sessionKeys,+ type SessionSettings,+} from '../computer-sessions-api'+import { AskCard, SettingsPickers } from './parts'+import { NEEDS_YOU, WORKING } from './state'++// No session open: start one, and answer what is waiting on you.+export default function ComputerSessionsHome() {+ const navigate = useNavigate()+ const qc = useQueryClient()+ const [input, setInput] = useState('')+ const [settings, setSettings] = useState<SessionSettings>({})+ const needs = useQuery({+ queryKey: sessionKeys.list(NEEDS_YOU),+ queryFn: () => listSessions(NEEDS_YOU),+ refetchInterval: 5_000,+ })+ const working = useQuery({+ queryKey: sessionKeys.list(WORKING),+ queryFn: () => listSessions(WORKING),+ refetchInterval: 5_000,+ })+ const start = useMutation({+ mutationFn: () => createSession(input.trim(), settings),+ onSuccess: (session) => {+ setInput('')+ void qc.invalidateQueries({ queryKey: sessionKeys.all })+ void navigate(`/computer/sessions/${session.id}`)+ },+ onError: (e) => notifyError('Could not start the session', e),+ })+ const send = () => {+ if (input.trim() && !start.isPending) start.mutate()+ }++ const waiting = (needs.data?.sessions ?? []).flatMap((s) =>+ s.asks.filter((a) => a.status === 'open').map((ask) => ({ s, ask })),+ )+ const busy = working.data?.sessions.length ?? 0++ return (+ <div className="flex h-full flex-col overflow-y-auto">+ <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col px-6 pt-[18vh] pb-10">+ <h1 className="mb-6 text-center text-2xl font-semibold tracking-tight">+ What should Computer work on?+ </h1>+ <div className="bg-card focus-within:border-ring/60 rounded-xl border shadow-sm transition-colors">+ <ChatTextarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onSend={send}+ placeholder="Describe a task, ask a question, or paste a link"+ className="min-h-20 resize-none border-0 bg-transparent px-4 pt-3.5 text-[15px] shadow-none focus-visible:ring-0 dark:bg-transparent"+ />+ <div className="flex items-center justify-between gap-2 px-2 pb-2">+ <SettingsPickers value={settings} onChange={setSettings} />+ <Button+ size="icon"+ className="rounded-full"+ aria-label="Start session"+ disabled={!input.trim() || start.isPending}+ onClick={send}+ >+ {start.isPending ? (+ <Loader2 className="animate-spin" aria-hidden />+ ) : (+ <ArrowUp aria-hidden />+ )}+ </Button>+ </div>+ </div>++ {waiting.length ? (+ <section className="mt-10 space-y-2">+ <h2 className="text-muted-foreground text-xs font-medium tracking-wide uppercase">+ Needs you+ </h2>+ {waiting.map(({ s, ask }) => (+ <AskCard key={ask.id} ask={ask} session={s} showSession />+ ))}+ </section>+ ) : null}+ <div className="flex-1" />+ {busy ? (+ <p className="text-muted-foreground mt-10 text-center text-xs">+ {busy} {busy === 1 ? 'session is' : 'sessions are'} working+ </p>+ ) : null}+ </div>+ </div>+ )+}diff --git a/web/src/managed-agents/computer-sessions/Layout.tsx b/web/src/managed-agents/computer-sessions/Layout.tsxnew file mode 100644index 00000000..98a94f99--- /dev/null+++ b/web/src/managed-agents/computer-sessions/Layout.tsx@@ -0,0 +1,542 @@+import { Suspense, useEffect, useRef, useState, type ReactNode } from 'react'+import {+ Link,+ NavLink,+ Outlet,+ useLocation,+ useMatch,+ useNavigate,+ useParams,+} from 'react-router-dom'+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'+import {+ Archive,+ CalendarClock,+ Check,+ ChevronsUpDown,+ CreditCard,+ KeyRound,+ Loader2,+ LogOut,+ MessagesSquare,+ Moon,+ Plus,+ Search,+ Settings,+ Sun,+ Plug,+} from 'lucide-react'+import { useAuth } from '@/hooks/useAuth'+import { useTheme } from '@/hooks/useTheme'+import { logout } from '@/api/client'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import { Button } from '@/components/ui/button'+import { ErrorBoundary } from '@/components/error-boundary'+import { BillingWarningBanner, HaltModal } from '@/components/billing-surfaces'+import { cn } from '@/lib/utils'+import {+ listSessions,+ sessionKeys,+ type ListSessionsQuery,+ type Session,+} from '../computer-sessions-api'+import { OpenComputerMark, OriginMark, StatusDot } from './parts'+import {+ isUnread,+ NEEDS_YOU,+ sessionLine,+ sessionTitle,+ useSeen,+ WORKING,+} from './state'+import { timeAgo } from './transcript'++// The computer's own full-screen view (work 107): a flat icon rail, the+// sessions sidebar, and the open session or the new-session home.++// Every other page (automations, secrets, settings, projects…) opens here too,+// in the rail but without the sessions sidebar, so nothing leads back to the+// old shell; only /computer, the onboarding, keeps it.+export default function ComputerSessionsLayout() {+ const searchRef = useRef<HTMLInputElement>(null)+ const { user } = useAuth()+ const { pathname } = useLocation()+ const sessions = !!useMatch('/computer/sessions/*')+ // On a phone the list and a session take turns: the list at+ // /computer/sessions, the session (or the new-session home) on its own.+ const listing = !!useMatch({ path: '/computer/sessions', end: true })+ return (+ <div className="bg-background text-foreground flex h-dvh overflow-hidden">+ <Rail />+ {sessions ? (+ <SessionsSidebar searchRef={searchRef} listing={listing} />+ ) : null}+ <main+ className={cn(+ 'min-w-0 flex-1',+ listing && 'hidden md:block',+ !sessions && 'flex flex-col overflow-y-auto',+ )}+ >+ {sessions ? null : (+ <div className="sticky top-0 z-20">+ <BillingWarningBanner />+ </div>+ )}+ <HaltModal />+ <ErrorBoundary key={`${user?.orgId ?? ''}:${pathname}`}>+ <Suspense+ fallback={+ <div className="flex h-full items-center justify-center">+ <Loader2 className="text-muted-foreground size-5 animate-spin" />+ </div>+ }+ >+ {sessions ? (+ <Outlet />+ ) : (+ <div+ className={cn(+ 'mx-auto flex w-full flex-1 flex-col px-8 py-8 lg:px-12',+ pathname.startsWith('/projects/') ||+ pathname.startsWith('/managed-agents/')+ ? 'max-w-[1600px]'+ : 'max-w-7xl',+ )}+ >+ <Outlet />+ </div>+ )}+ </Suspense>+ </ErrorBoundary>+ </main>+ </div>+ )+}++function RailLink({+ to,+ label,+ end,+ children,+}: {+ to: string+ label: string+ end?: boolean+ children: ReactNode+}) {+ return (+ <NavLink+ to={to}+ end={end}+ title={label}+ aria-label={label}+ className={({ isActive }) =>+ cn(+ 'text-muted-foreground hover:bg-sidebar-accent hover:text-foreground flex size-9 items-center justify-center rounded-md transition-colors',+ isActive && 'bg-sidebar-accent text-foreground',+ )+ }+ >+ {children}+ </NavLink>+ )+}++function Rail() {+ const { user } = useAuth()+ const { dark, setDark } = useTheme()+ const navigate = useNavigate()+ const orgs = user?.orgs ?? []+ const activeOrg = orgs.find((o) => o.isActive)+ return (+ <nav className="bg-sidebar border-sidebar-border flex w-14 shrink-0 flex-col items-center gap-1 border-r py-3">+ <Link+ to={user?.computerEnabled ? '/computer/sessions' : '/automations'}+ title="Computer"+ className="mb-3 flex size-8 items-center justify-center"+ >+ <OpenComputerMark className="size-8" />+ </Link>+ {user?.computerEnabled ? (+ <RailLink to="/computer/sessions" label="Sessions">+ <MessagesSquare className="size-4" aria-hidden />+ </RailLink>+ ) : null}+ <RailLink to="/automations" label="Automations">+ <CalendarClock className="size-4" aria-hidden />+ </RailLink>+ <RailLink to="/computer/secrets" label="Secrets">+ <KeyRound className="size-4" aria-hidden />+ </RailLink>+ <div className="flex-1" />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label="Open account menu"+ title={activeOrg?.name ?? user?.email}+ className="bg-secondary text-muted-foreground hover:text-foreground flex size-8 items-center justify-center rounded-full text-xs font-medium"+ >+ {(activeOrg?.name ?? user?.email ?? '?').charAt(0).toUpperCase()}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="right" align="end" className="min-w-52">+ <DropdownMenuLabel className="truncate">+ {activeOrg?.name ?? 'Account'}+ <span className="text-muted-foreground block truncate text-xs font-normal">+ {user?.email}+ </span>+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ {orgs.length > 1 ? (+ <>+ <DropdownMenuLabel className="text-muted-foreground text-xs font-normal">+ Organizations+ </DropdownMenuLabel>+ <OrgItems />+ <DropdownMenuSeparator />+ </>+ ) : null}+ <DropdownMenuItem+ onClick={() => void navigate('/managed-agents/connections')}+ >+ <Plug className="size-4 opacity-60" aria-hidden />+ Connections+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void navigate('/settings')}>+ <Settings className="size-4 opacity-60" aria-hidden />+ Settings & members+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void navigate('/api-keys')}>+ <KeyRound className="size-4 opacity-60" aria-hidden />+ API keys+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void navigate('/billing')}>+ <CreditCard className="size-4 opacity-60" aria-hidden />+ Billing+ </DropdownMenuItem>+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault()+ setDark(!dark)+ }}+ >+ {dark ? (+ <Sun className="size-4 opacity-60" aria-hidden />+ ) : (+ <Moon className="size-4 opacity-60" aria-hidden />+ )}+ {dark ? 'Light theme' : 'Dark theme'}+ </DropdownMenuItem>+ {user?.capabilities?.signOut !== false ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => void logout()}>+ <LogOut className="size-4 opacity-60" aria-hidden />+ Sign out+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ </nav>+ )+}++/** The organizations to switch between, the active one checked (the old shell's OrgSwitcher). */+function OrgItems() {+ const { user, switchOrg } = useAuth()+ const navigate = useNavigate()+ const [switching, setSwitching] = useState(false)+ const openSession = useMatch('/computer/sessions/:id')+ return (user?.orgs ?? []).map((org) => (+ <DropdownMenuItem+ key={org.id}+ disabled={switching}+ onClick={() => {+ if (org.isActive || switching) return+ setSwitching(true)+ // An open session belongs to the old organization.+ void switchOrg(org.id)+ .then(() => {+ if (openSession) void navigate('/computer/sessions')+ })+ .finally(() => setSwitching(false))+ }}+ >+ <Check+ className={cn(+ 'size-4 shrink-0',+ org.isActive ? 'opacity-100' : 'opacity-0',+ )}+ aria-hidden+ />+ <span className="truncate">{org.name}</span>+ {org.isPersonal ? (+ <span className="text-muted-foreground ml-auto text-xs">personal</span>+ ) : null}+ </DropdownMenuItem>+ ))+}++/** The sessions sidebar's header: the organization, and switching it. */+function OrgSwitcher() {+ const { user } = useAuth()+ const orgs = user?.orgs ?? []+ const active = orgs.find((o) => o.isActive)+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label="Switch organization"+ className="hover:bg-sidebar-accent flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm font-medium transition-colors"+ >+ <span className="bg-secondary text-muted-foreground flex size-6 shrink-0 items-center justify-center rounded text-xs">+ {(active?.name ?? '?').charAt(0).toUpperCase()}+ </span>+ <span className="min-w-0 flex-1 truncate">+ {active?.name ?? 'Organization'}+ </span>+ <ChevronsUpDown+ className="text-muted-foreground size-3.5 shrink-0"+ aria-hidden+ />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="w-(--radix-dropdown-menu-trigger-width) min-w-56"+ >+ <DropdownMenuLabel className="text-muted-foreground text-xs font-normal">+ Organizations+ </DropdownMenuLabel>+ <OrgItems />+ </DropdownMenuContent>+ </DropdownMenu>+ )+}++function useDebounced<T>(value: T, ms: number) {+ const [v, setV] = useState(value)+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms)+ return () => clearTimeout(t)+ }, [value, ms])+ return v+}++function SessionsSidebar({+ searchRef,+ listing,+}: {+ searchRef: React.RefObject<HTMLInputElement | null>+ listing: boolean+}) {+ const [query, setQuery] = useState('')+ const [archived, setArchived] = useState(false)+ const q = useDebounced(query.trim(), 250)++ const needs = useQuery({+ queryKey: sessionKeys.list(NEEDS_YOU),+ queryFn: () => listSessions(NEEDS_YOU),+ refetchInterval: 5_000,+ enabled: !q && !archived,+ })+ const working = useQuery({+ queryKey: sessionKeys.list(WORKING),+ queryFn: () => listSessions(WORKING),+ refetchInterval: 5_000,+ enabled: !q && !archived,+ })+ // Recent is everything not waiting or working; searching or the archive+ // shows one flat list instead.+ const recentQuery: ListSessionsQuery = q+ ? { q, archived: archived ? 'true' : 'false', limit: 30 }+ : archived+ ? { archived: 'true', limit: 30 }+ : { status: 'idle,suspended', limit: 30 }+ const recent = useInfiniteQuery({+ queryKey: sessionKeys.list(recentQuery),+ queryFn: ({ pageParam }) =>+ listSessions({ ...recentQuery, cursor: pageParam }),+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (last) => last.nextCursor ?? undefined,+ refetchInterval: 15_000,+ })+ const recentRows = recent.data?.pages.flatMap((p) => p.sessions) ?? []++ // Infinite scroll: load the next page when the list's end comes into view.+ const endRef = useRef<HTMLDivElement>(null)+ const { hasNextPage, isFetchingNextPage, fetchNextPage } = recent+ useEffect(() => {+ const el = endRef.current+ if (!el || !hasNextPage) return+ const io = new IntersectionObserver((entries) => {+ if (entries[0]?.isIntersecting && !isFetchingNextPage)+ void fetchNextPage()+ })+ io.observe(el)+ return () => io.disconnect()+ }, [hasNextPage, isFetchingNextPage, fetchNextPage])++ const flat = !!q || archived+ return (+ <aside+ className={cn(+ 'bg-sidebar border-sidebar-border min-w-0 flex-1 flex-col border-r md:flex md:w-72 md:flex-none',+ listing ? 'flex' : 'hidden',+ )}+ >+ <div className="space-y-2 p-3">+ <OrgSwitcher />+ <Button asChild variant="outline" className="w-full justify-start">+ <Link to="/computer/sessions/new">+ <Plus aria-hidden />+ New session+ </Link>+ </Button>+ <div className="relative">+ <Search+ className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2"+ aria-hidden+ />+ <input+ ref={searchRef}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={(e) => e.key === 'Escape' && setQuery('')}+ placeholder="Search sessions"+ className="border-input placeholder:text-muted-foreground focus-visible:border-ring/60 h-8 w-full rounded-md border bg-transparent pr-2 pl-8 text-sm outline-none"+ />+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">+ {!flat ? (+ <>+ <Group label="Needs you" rows={needs.data?.sessions} />+ <Group label="Working" rows={working.data?.sessions} />+ </>+ ) : null}+ <Group+ label={q ? 'Results' : archived ? 'Archived' : 'Recent'}+ rows={recentRows}+ loading={recent.isPending}+ empty={+ q+ ? 'No sessions match.'+ : archived+ ? 'Nothing archived.'+ : 'No sessions yet.'+ }+ />+ <div ref={endRef} />+ {isFetchingNextPage ? (+ <Loader2 className="text-muted-foreground mx-auto my-2 size-4 animate-spin" />+ ) : null}+ </div>+ <div className="border-sidebar-border border-t p-2">+ <button+ type="button"+ onClick={() => setArchived((a) => !a)}+ className={cn(+ 'text-muted-foreground hover:text-foreground flex items-center gap-2 rounded-md px-2 py-1 text-xs',+ archived && 'text-foreground',+ )}+ >+ <Archive className="size-3.5" aria-hidden />+ {archived ? 'Back to sessions' : 'Archived'}+ </button>+ </div>+ </aside>+ )+}++function Group({+ label,+ rows,+ loading,+ empty,+}: {+ label: string+ rows: Session[] | undefined+ loading?: boolean+ empty?: string+}) {+ if (!rows?.length && !empty) return null+ return (+ <section className="mb-3">+ <h3 className="text-muted-foreground px-2 pt-1 pb-1 text-[11px] font-medium tracking-wide uppercase">+ {label}+ {rows?.length && !empty ? (+ <span className="ml-1.5 tabular-nums">{rows.length}</span>+ ) : null}+ </h3>+ {rows?.length ? (+ rows.map((s) => <SessionRow key={s.id} session={s} />)+ ) : loading ? null : (+ <p className="text-muted-foreground px-2 py-1 text-xs">{empty}</p>+ )}+ </section>+ )+}++function SessionRow({ session: s }: { session: Session }) {+ const { id: openId } = useParams()+ const seen = useSeen()+ const open = openId === s.id+ const unread = !open && isUnread(s, seen)+ const line = sessionLine(s)+ return (+ <Link+ to={`/computer/sessions/${s.id}`}+ className={cn(+ 'hover:bg-sidebar-accent block rounded-md px-2 py-1.5 transition-colors',+ open && 'bg-sidebar-accent',+ )}+ >+ <div className="flex items-center gap-1.5">+ <StatusDot status={s.status} />+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-sm',+ unread && 'font-semibold',+ )}+ >+ {sessionTitle(s)}+ </span>+ <OriginMark+ origin={s.origin}+ className="text-muted-foreground/70 shrink-0"+ />+ <span className="text-muted-foreground shrink-0 text-[11px] tabular-nums">+ {timeAgo(s.lastActiveAt ?? s.createdAt)}+ </span>+ {unread ? (+ <span+ className="bg-primary size-1.5 shrink-0 rounded-full"+ aria-label="Unread"+ />+ ) : null}+ </div>+ {line ? (+ <p+ className={cn(+ 'text-muted-foreground mt-0.5 truncate pl-3 text-xs',+ s.status === 'waiting' && 'text-amber-600 dark:text-amber-400',+ )}+ >+ {line}+ </p>+ ) : null}+ </Link>+ )+}diff --git a/web/src/managed-agents/computer-sessions/Session.tsx b/web/src/managed-agents/computer-sessions/Session.tsxnew file mode 100644index 00000000..d9628f06--- /dev/null+++ b/web/src/managed-agents/computer-sessions/Session.tsx@@ -0,0 +1,581 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'+import { Link, useParams } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ Archive,+ ArchiveRestore,+ ArrowUp,+ Check,+ ChevronRight,+ CircleAlert,+ Loader2,+ Square,+ X,+ User,+} from 'lucide-react'+import { ApiError, getOrgMembers } from '@/api/client'+import type { OrgMember } from '@/api/schemas'+import { ChatTextarea } from '@/components/chat-textarea'+import { SlackMark } from '@/components/slack-mark'+import { Button } from '@/components/ui/button'+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { notifyError } from '@/lib/errors'+import { cn } from '@/lib/utils'+import { AgentMarkdown } from '../AgentMarkdown'+import {+ getEvents,+ getSession,+ interruptSession,+ sendTurn,+ sessionKeys,+ updateSession,+ type IfBusy,+ type SessionEvent,+ type SessionSettings,+} from '../computer-sessions-api'+import { AskCard, OpenComputerMark, SettingsPickers, StatusDot } from './parts'+import {+ askTitle,+ isBusy,+ markSeen,+ sessionTitle,+ statusLabel,+ useCapabilities,+} from './state'+import {+ buildTranscript,+ formatDuration,+ mergeEvents,+ type TranscriptItem,+} from './transcript'++// Events that change what the session row says (status, asks, title).+const SESSION_EVENTS = /^(session\.|turn\.|ask\.|runtime\.)/++// Loads the last turns, then follows the journal by long-polling+// `GET /events?after&waitMs`. Cookie logins cannot mint a WebSocket ticket yet.+function useSessionEvents(id: string, onSessionEvent: () => void) {+ const [events, setEvents] = useState<SessionEvent[]>([])+ const [loaded, setLoaded] = useState(false)+ const notify = useRef(onSessionEvent)+ useEffect(() => {+ notify.current = onSessionEvent+ })++ // The page is keyed by session, so this runs once per session.+ useEffect(() => {+ const ctl = new AbortController()+ let cursor: number | undefined+ const run = async () => {+ while (!ctl.signal.aborted) {+ try {+ const page =+ cursor === undefined+ ? await getEvents(id, { tailTurns: 20 }, ctl.signal)+ : await getEvents(+ id,+ { after: cursor, limit: 500, waitMs: 25_000 },+ ctl.signal,+ )+ if (ctl.signal.aborted) return+ cursor =+ page.hasMore && page.events.length+ ? page.events[page.events.length - 1].seq+ : page.lastSeq+ if (page.events.length) {+ setEvents((have) => mergeEvents(have, page.events))+ if (page.events.some((e) => SESSION_EVENTS.test(e.type)))+ notify.current()+ }+ setLoaded(true)+ } catch (e) {+ if (ctl.signal.aborted) return+ // The journal moved to a new epoch: start over from its tail.+ if (e instanceof ApiError && e.status === 409) {+ cursor = undefined+ setEvents([])+ continue+ }+ if (e instanceof ApiError && e.status === 404) {+ setLoaded(true)+ return+ }+ await new Promise((r) => setTimeout(r, 3_000))+ }+ }+ }+ void run()+ return () => ctl.abort()+ }, [id])++ return { events, loaded }+}++export default function ComputerSession() {+ const { id = '' } = useParams()+ return <SessionPage key={id} id={id} />+}++function SessionPage({ id }: { id: string }) {+ const qc = useQueryClient()+ const session = useQuery({+ queryKey: sessionKeys.one(id),+ queryFn: () => getSession(id),+ refetchInterval: 15_000,+ })+ const { events, loaded } = useSessionEvents(id, () => {+ void qc.invalidateQueries({ queryKey: sessionKeys.all })+ })+ const items = useMemo(() => buildTranscript(events), [events])+ const s = session.data+ const emails = useMemberEmails()++ // Reading the session marks it read up to what was shown.+ const lastSeq = events[events.length - 1]?.seq+ useEffect(() => {+ if (lastSeq !== undefined) markSeen(id, lastSeq)+ else if (s) markSeen(id, s.lastSeq)+ }, [id, lastSeq, s])++ // Stick to the bottom while the reader is there.+ const scroller = useRef<HTMLDivElement>(null)+ const pinned = useRef(true)+ useLayoutEffect(() => {+ const el = scroller.current+ if (el && pinned.current) el.scrollTop = el.scrollHeight+ }, [items.length, events.length, s?.asks.length])++ if (session.error instanceof ApiError && session.error.status === 404) {+ return (+ <div className="text-muted-foreground flex h-full flex-col items-center justify-center gap-2 text-sm">+ <p>This session does not exist or is not shared with you.</p>+ <Link to="/computer/sessions" className="text-primary hover:underline">+ Start a new session+ </Link>+ </div>+ )+ }++ const openAsks = s?.asks.filter((a) => a.status === 'open') ?? []+ return (+ <div className="flex h-full flex-col">+ <Header id={id} />+ <div+ ref={scroller}+ onScroll={(e) => {+ const el = e.currentTarget+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80+ }}+ className="min-h-0 flex-1 overflow-y-auto"+ >+ <div className="mx-auto max-w-3xl space-y-5 px-6 py-6">+ {!loaded ? (+ <Loader2 className="text-muted-foreground mx-auto size-5 animate-spin" />+ ) : items.length === 0 ? (+ <p className="text-muted-foreground text-center text-sm">+ Nothing here yet.+ </p>+ ) : (+ items.map((item, i) => (+ <Item+ key={item.key}+ item={item}+ emails={emails}+ // A reply opens with who is speaking: the first agent item after a person's message.+ leads={i === 0 || items[i - 1].kind === 'user'}+ />+ ))+ )}+ {s && isBusy(s.status) && !openAsks.length ? (+ <p className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-3.5 animate-spin" aria-hidden />+ {s.status === 'starting' ? 'Starting the computer…' : 'Working…'}+ </p>+ ) : null}+ {s+ ? openAsks.map((ask) => (+ <AskCard key={ask.id} ask={ask} session={s} />+ ))+ : null}+ </div>+ </div>+ <Composer id={id} />+ </div>+ )+}++function Header({ id }: { id: string }) {+ const qc = useQueryClient()+ const { data: s } = useQuery({+ queryKey: sessionKeys.one(id),+ queryFn: () => getSession(id),+ })+ const archive = useMutation({+ mutationFn: (archived: boolean) => updateSession(id, { archived }),+ onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onError: (e) => notifyError('Could not update the session', e),+ })+ const slackUrl = s?.origin.slack?.url+ return (+ <header className="border-border flex h-12 shrink-0 items-center gap-3 border-b px-4">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <h1 className="truncate text-sm font-medium">+ {s ? sessionTitle(s) : ''}+ </h1>+ {s ? (+ <span className="text-muted-foreground flex shrink-0 items-center gap-1.5 text-xs">+ <StatusDot status={s.status} />+ {statusLabel(s.status)}+ </span>+ ) : null}+ {s?.owner?.name ? (+ <span className="text-muted-foreground hidden truncate text-xs md:inline">+ · {s.owner.name}+ </span>+ ) : null}+ </div>+ {slackUrl ? (+ <Button asChild size="sm" variant="ghost">+ <a href={slackUrl} target="_blank" rel="noreferrer">+ <SlackMark className="size-3.5" />+ Open in Slack+ </a>+ </Button>+ ) : null}+ {s ? (+ <Button+ size="icon-sm"+ variant="ghost"+ title={s.archived ? 'Unarchive' : 'Archive'}+ aria-label={s.archived ? 'Unarchive' : 'Archive'}+ disabled={archive.isPending}+ onClick={() => archive.mutate(!s.archived)}+ >+ {s.archived ? <ArchiveRestore /> : <Archive />}+ </Button>+ ) : null}+ </header>+ )+}++// Members' emails by member id (`usr_…`). The computer derives that id from the+// user id: the WorkOS id when there is one, else a hash (`memberId` in managed-agents).+async function memberEmails(+ members: OrgMember[],+): Promise<Map<string, string>> {+ const emails = new Map<string, string>()+ for (const m of members) {+ const workos = /^user_(\w+)$/.exec(m.workosUserId ?? '')+ if (workos) emails.set(`usr_${workos[1].toLowerCase()}`, m.email)+ if (!m.id) continue+ const digest = new Uint8Array(+ await crypto.subtle.digest('SHA-256', new TextEncoder().encode(m.id)),+ )+ const hex = [...digest.slice(0, 13)]+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('')+ emails.set(`usr_x${hex}`, m.email)+ }+ return emails+}++function useMemberEmails(): Map<string, string> | undefined {+ const { data: members } = useQuery({+ queryKey: ['org-members'],+ queryFn: getOrgMembers,+ staleTime: 5 * 60_000,+ })+ const { data } = useQuery({+ queryKey: ['org-members', 'emails', members],+ queryFn: () => memberEmails(members ?? []),+ enabled: !!members,+ staleTime: Infinity,+ })+ return data+}++// A person's avatar: initials of their name, or the first letter of their email.+function initials(author: string): string {+ if (author.includes('@')) return author[0].toUpperCase()+ const words = author.trim().split(/\s+/)+ return words+ .slice(0, 2)+ .map((w) => w[0].toUpperCase())+ .join('')+}++function Item({+ item,+ leads,+ emails,+}: {+ item: TranscriptItem+ leads: boolean+ emails: Map<string, string> | undefined+}) {+ switch (item.kind) {+ case 'user': {+ const email = item.authorId ? emails?.get(item.authorId) : undefined+ return (+ <div className="flex items-end justify-end gap-2">+ <div className="flex max-w-[85%] flex-col items-end gap-1">+ {item.author || email ? (+ <span className="text-muted-foreground text-xs">+ {item.author ?? email}+ {item.via && item.via !== 'dashboard' ? ` via ${item.via}` : ''}+ </span>+ ) : null}+ <div className="bg-secondary rounded-2xl rounded-br-md px-3.5 py-2 text-sm whitespace-pre-wrap">+ {item.text}+ </div>+ </div>+ <TooltipProvider delayDuration={200}>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="bg-secondary text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-full text-[11px] font-medium">+ {item.author || email ? (+ initials(item.author ?? email ?? '')+ ) : (+ <User className="size-3.5" />+ )}+ </span>+ </TooltipTrigger>+ <TooltipContent side="left">+ {item.author ?? email ?? 'Someone'}+ {email && item.author && email !== item.author ? (+ <span className="block opacity-70">{email}</span>+ ) : null}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ )+ }+ case 'agent':+ return (+ <div className="space-y-2">+ {leads ? <AgentByline /> : null}+ <AgentMarkdown>{item.text}</AgentMarkdown>+ </div>+ )+ case 'work':+ return (+ <div className="space-y-2">+ {leads ? <AgentByline /> : null}+ <WorkStep item={item} />+ </div>+ )+ case 'ask':+ // Open asks are answered at the end of the transcript.+ if (item.ask.status === 'open') return null+ return (+ <p className="text-muted-foreground flex items-center gap-1.5 text-xs">+ {item.ask.status === 'answered' ? (+ <Check className="size-3.5" aria-hidden />+ ) : (+ <X className="size-3.5" aria-hidden />+ )}+ {askTitle(item.ask)} · {item.ask.status}+ </p>+ )+ case 'note':+ return (+ <p+ className={cn(+ 'flex items-center gap-1.5 text-xs',+ item.tone === 'error'+ ? 'text-destructive'+ : 'text-muted-foreground',+ )}+ >+ {item.tone === 'error' ? (+ <CircleAlert className="size-3.5" aria-hidden />+ ) : null}+ {item.text}+ </p>+ )+ }+}++function WorkStep({+ item,+}: {+ item: Extract<TranscriptItem, { kind: 'work' }>+}) {+ const [open, setOpen] = useState(false)+ const ms =+ new Date(item.endedAt).getTime() - new Date(item.startedAt).getTime()+ const failed = item.tools.filter((t) => t.status === 'failed').length+ const label = item.open+ ? `Working · ${item.tools.length} ${item.tools.length === 1 ? 'step' : 'steps'}`+ : `Worked for ${formatDuration(ms)}`+ return (+ <div>+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-xs"+ >+ <ChevronRight+ className={cn('size-3.5 transition-transform', open && 'rotate-90')}+ aria-hidden+ />+ {label}+ {failed ? (+ <span className="text-destructive">· {failed} failed</span>+ ) : null}+ </button>+ {open && item.tools.length ? (+ <ul className="border-border mt-1.5 ml-1.5 space-y-0.5 border-l pl-3">+ {item.tools.map((t) => (+ <li+ key={t.callId}+ className="text-muted-foreground flex items-center gap-1.5 font-mono text-xs"+ >+ {t.status === 'running' ? (+ <Loader2 className="size-3 shrink-0 animate-spin" aria-hidden />+ ) : t.status === 'failed' ? (+ <X className="text-destructive size-3 shrink-0" aria-hidden />+ ) : (+ <Check className="size-3 shrink-0 opacity-60" aria-hidden />+ )}+ <span className="truncate">{t.title}</span>+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ )+}++function Composer({ id }: { id: string }) {+ const qc = useQueryClient()+ const { data: s } = useQuery({+ queryKey: sessionKeys.one(id),+ queryFn: () => getSession(id),+ })+ const { data: caps } = useCapabilities()+ const [input, setInput] = useState('')+ const [ifBusy, setIfBusy] = useState<IfBusy>('steer')+ const busy = !!s && isBusy(s.status)+ const canSteer = caps?.features.steer !== false+ const send = useMutation({+ mutationFn: () =>+ sendTurn(id, input.trim(), busy && canSteer ? ifBusy : 'queue'),+ onSuccess: () => {+ setInput('')+ void qc.invalidateQueries({ queryKey: sessionKeys.all })+ },+ onError: (e) => notifyError('Could not send', e),+ })+ const stop = useMutation({+ mutationFn: () => interruptSession(id),+ onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onError: (e) => notifyError('Could not stop', e),+ })+ const settings = useMutation({+ mutationFn: (next: SessionSettings) => updateSession(id, next),+ onSuccess: (session) => qc.setQueryData(sessionKeys.one(id), session),+ onError: (e) => notifyError('Could not change the settings', e),+ })+ const submit = () => {+ if (input.trim() && !send.isPending) send.mutate()+ }+ const slack = s?.origin.type === 'slack'++ return (+ <div className="shrink-0 px-6 pb-5">+ <div className="bg-card focus-within:border-ring/60 mx-auto max-w-3xl rounded-xl border shadow-sm transition-colors">+ <ChatTextarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onSend={submit}+ placeholder={+ busy+ ? ifBusy === 'steer'+ ? 'Steer: tell Computer what to change now'+ : 'Queue a message for when this turn ends'+ : 'Reply to Computer'+ }+ className="min-h-11 resize-none border-0 bg-transparent px-4 pt-3 shadow-none focus-visible:ring-0 dark:bg-transparent"+ />+ <div className="flex items-center justify-between gap-2 px-2 pb-2">+ {s && !slack ? (+ <SettingsPickers+ value={{+ model: s.settings.model ?? undefined,+ effort: s.settings.effort ?? undefined,+ mode: s.settings.mode ?? undefined,+ }}+ onChange={(next) => settings.mutate(next)}+ disabled={settings.isPending}+ />+ ) : (+ <span />+ )}+ <div className="flex items-center gap-1.5">+ {busy && canSteer ? (+ <div className="bg-muted flex rounded-md p-0.5 text-xs">+ {(['steer', 'queue'] as const).map((m) => (+ <button+ key={m}+ type="button"+ onClick={() => setIfBusy(m)}+ className={cn(+ 'rounded px-2 py-0.5 capitalize',+ ifBusy === m+ ? 'bg-background text-foreground shadow-xs'+ : 'text-muted-foreground',+ )}+ >+ {m}+ </button>+ ))}+ </div>+ ) : null}+ {busy ? (+ <Button+ size="icon"+ variant="outline"+ className="rounded-full"+ aria-label="Stop"+ title="Stop"+ disabled={stop.isPending}+ onClick={() => stop.mutate()}+ >+ <Square className="size-3 fill-current" aria-hidden />+ </Button>+ ) : null}+ <Button+ size="icon"+ className="rounded-full"+ aria-label="Send"+ disabled={!input.trim() || send.isPending}+ onClick={submit}+ >+ {send.isPending ? (+ <Loader2 className="animate-spin" aria-hidden />+ ) : (+ <ArrowUp aria-hidden />+ )}+ </Button>+ </div>+ </div>+ </div>+ </div>+ )+}++function AgentByline() {+ return (+ <div className="flex items-center gap-2 text-xs font-medium">+ <OpenComputerMark className="size-6" />+ Computer+ </div>+ )+}diff --git a/web/src/managed-agents/computer-sessions/parts.tsx b/web/src/managed-agents/computer-sessions/parts.tsxnew file mode 100644index 00000000..c859f507--- /dev/null+++ b/web/src/managed-agents/computer-sessions/parts.tsx@@ -0,0 +1,369 @@+import { useState } from 'react'+import { Link } from 'react-router-dom'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { Check, KeyRound, Terminal, X } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { Select } from '@/components/form'+import { SlackMark } from '@/components/slack-mark'+import { notifyError } from '@/lib/errors'+import { cn } from '@/lib/utils'+import {+ answerAsk,+ dismissAsk,+ sessionKeys,+ type Ask,+ type AskAnswer,+ type Session,+ type SessionSettings,+} from '../computer-sessions-api'+import { askTitle, isBusy, sessionTitle, useCapabilities } from './state'++export function StatusDot({+ status,+ className,+}: {+ status: string+ className?: string+}) {+ return (+ <span+ aria-hidden+ className={cn(+ 'inline-block size-1.5 shrink-0 rounded-full',+ status === 'waiting' && 'bg-amber-500',+ isBusy(status) && 'bg-status-running animate-pulse',+ status === 'idle' && 'bg-muted-foreground/40',+ status === 'suspended' && 'bg-muted-foreground/20',+ className,+ )}+ />+ )+}++// The landing page's mark (opencomputer.dev favicon): a stressed serif O on+// a paper tile, redrawn as vectors so it stays sharp at any size.+export function OpenComputerMark({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 32 32"+ className={className}+ role="img"+ aria-label="OpenComputer"+ >+ <rect+ x="0.75"+ y="0.75"+ width="30.5"+ height="30.5"+ rx="7"+ fill="#FAF8F5"+ stroke="#161513"+ strokeOpacity="0.12"+ strokeWidth="1.5"+ />+ <path+ fillRule="evenodd"+ fill="#161513"+ d="M16 5.7c-5.3 0-9.4 4.6-9.4 10.3S10.7 26.3 16 26.3s9.4-4.6 9.4-10.3S21.3 5.7 16 5.7Zm0 1c-2.6 0-4.2 4.1-4.2 9.3s1.6 9.3 4.2 9.3 4.2-4.1 4.2-9.3S18.6 6.7 16 6.7Z"+ />+ </svg>+ )+}++export function OriginMark({+ origin,+ className,+}: {+ origin: Session['origin']+ className?: string+}) {+ if (origin.type === 'slack')+ return <SlackMark className={cn('size-3', className)} />+ if (origin.type === 'opc' || origin.type === 'api')+ return <Terminal className={cn('size-3', className)} aria-hidden />+ return null+}++// Model and permission mode, from the computer's capabilities.+export function SettingsPickers({+ value,+ onChange,+ disabled,+}: {+ value: SessionSettings+ onChange: (next: SessionSettings) => void+ disabled?: boolean+}) {+ const { data: caps } = useCapabilities()+ if (!caps) return null+ const model =+ caps.models.find((m) => m.id === value.model) ??+ caps.models.find((m) => m.default) ??+ caps.models[0]+ return (+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ {caps.models.length > 1 ? (+ <Select+ value={model?.id ?? ''}+ onValueChange={(m) => onChange({ ...value, model: m })}+ options={caps.models.map((m) => ({ value: m.id, label: m.name }))}+ disabled={disabled}+ className="text-muted-foreground hover:border-border h-7 w-auto border-transparent px-2 text-xs whitespace-nowrap"+ />+ ) : null}+ {model && model.efforts.length > 1 ? (+ <Select+ // Unset runs at the computer's default (DEFAULT_EFFORT in computer/src/tiers.ts).+ value={+ value.effort ??+ (model.efforts.includes('medium') ? 'medium' : model.efforts[0])+ }+ onValueChange={(e) => onChange({ ...value, effort: e })}+ options={model.efforts.map((e) => ({ value: e, label: e }))}+ disabled={disabled}+ className="text-muted-foreground hover:border-border h-7 w-auto border-transparent px-2 text-xs whitespace-nowrap capitalize"+ />+ ) : null}+ {caps.modes.length > 1 ? (+ <Select+ // A session asked for no mode runs with full access, as from Slack.+ value={value.mode ?? 'bypassPermissions'}+ onValueChange={(m) => onChange({ ...value, mode: m })}+ options={caps.modes.map((m) => ({ value: m, label: modeLabel(m) }))}+ disabled={disabled}+ className="text-muted-foreground hover:border-border h-7 w-auto border-transparent px-2 text-xs whitespace-nowrap"+ />+ ) : null}+ </div>+ )+}++function modeLabel(mode: string) {+ switch (mode) {+ case 'default':+ return 'Ask before edits'+ case 'acceptEdits':+ return 'Accept edits'+ case 'plan':+ return 'Plan'+ case 'bypassPermissions':+ return 'Full access'+ default:+ return mode+ }+}++function preview(input: unknown): string | null {+ if (input === undefined || input === null) return null+ if (typeof input === 'object') {+ const o = input as Record<string, unknown>+ for (const k of ['command', 'file_path', 'path', 'url', 'query']) {+ if (typeof o[k] === 'string') return o[k]+ }+ }+ const s = typeof input === 'string' ? input : JSON.stringify(input, null, 2)+ return s.length > 600 ? `${s.slice(0, 600)}…` : s+}++// An open ask, answerable here: approve or deny a tool call, or answer the+// agent's questions. A secret is set privately, so it points to Secrets.+export function AskCard({+ ask,+ session,+ showSession,+}: {+ ask: Ask+ session?: Session+ showSession?: boolean+}) {+ const qc = useQueryClient()+ const answer = useMutation({+ mutationFn: (a: AskAnswer) => answerAsk(ask.sessionId, ask.id, a),+ onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onError: (e) => notifyError('Could not answer', e),+ })+ const dismiss = useMutation({+ mutationFn: () => dismissAsk(ask.sessionId, ask.id),+ onSuccess: () => void qc.invalidateQueries({ queryKey: sessionKeys.all }),+ onError: (e) => notifyError('Could not dismiss', e),+ })+ const busy = answer.isPending || dismiss.isPending++ return (+ <div className="bg-card rounded-lg border border-amber-500/40 p-3 shadow-xs">+ {showSession && session ? (+ <Link+ to={`/computer/sessions/${session.id}`}+ className="text-muted-foreground hover:text-foreground mb-1.5 flex items-center gap-1.5 text-xs"+ >+ <StatusDot status="waiting" />+ <span className="truncate">{sessionTitle(session)}</span>+ </Link>+ ) : null}+ {ask.kind === 'approval' ? (+ <ApprovalBody+ ask={ask}+ busy={busy}+ onAnswer={(a) => answer.mutate(a)}+ />+ ) : ask.kind === 'question' ? (+ <QuestionBody+ ask={ask}+ busy={busy}+ onAnswer={(a) => answer.mutate(a)}+ onDismiss={() => dismiss.mutate()}+ />+ ) : (+ <div className="flex items-center justify-between gap-3">+ <p className="flex items-center gap-2 text-sm">+ <KeyRound className="size-4 opacity-60" aria-hidden />+ {askTitle(ask)}+ </p>+ <Button asChild size="sm" variant="outline">+ <Link to="/computer/secrets">Open Secrets</Link>+ </Button>+ </div>+ )}+ </div>+ )+}++function ApprovalBody({+ ask,+ busy,+ onAnswer,+}: {+ ask: Ask+ busy: boolean+ onAnswer: (a: AskAnswer) => void+}) {+ const detail = preview(ask.approval?.input)+ return (+ <div className="space-y-2">+ <p className="text-sm font-medium">{askTitle(ask)}</p>+ {detail ? (+ <pre className="bg-muted text-muted-foreground max-h-40 overflow-auto rounded-md px-2.5 py-1.5 font-mono text-xs whitespace-pre-wrap">+ {detail}+ </pre>+ ) : null}+ <div className="flex flex-wrap gap-1.5">+ <Button+ size="sm"+ disabled={busy}+ onClick={() => onAnswer({ decision: 'allow' })}+ >+ <Check aria-hidden />+ Allow+ </Button>+ {ask.approval?.alwaysAllows ? (+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ title={ask.approval.alwaysAllows}+ onClick={() => onAnswer({ decision: 'always' })}+ >+ Always allow+ </Button>+ ) : null}+ <Button+ size="sm"+ variant="ghost"+ disabled={busy}+ onClick={() => onAnswer({ decision: 'deny' })}+ >+ <X aria-hidden />+ Deny+ </Button>+ </div>+ </div>+ )+}++function QuestionBody({+ ask,+ busy,+ onAnswer,+ onDismiss,+}: {+ ask: Ask+ busy: boolean+ onAnswer: (a: AskAnswer) => void+ onDismiss: () => void+}) {+ const questions = ask.question?.questions ?? []+ const [choices, setChoices] = useState<Record<string, string[]>>({})+ const [texts, setTexts] = useState<Record<string, string>>({})+ const toggle = (qid: string, label: string, multi: boolean) =>+ setChoices((c) => {+ const have = c[qid] ?? []+ const next = have.includes(label)+ ? have.filter((l) => l !== label)+ : multi+ ? [...have, label]+ : [label]+ return { ...c, [qid]: next }+ })+ const complete = questions.every(+ (q) => (choices[q.id]?.length ?? 0) > 0 || (texts[q.id] ?? '').trim(),+ )++ return (+ <div className="space-y-3">+ {questions.map((q) => (+ <div key={q.id} className="space-y-1.5">+ <p className="text-sm font-medium">{q.text || q.header}</p>+ <div className="flex flex-wrap gap-1.5">+ {q.options.map((o) => {+ const on = choices[q.id]?.includes(o.label)+ return (+ <button+ key={o.label}+ type="button"+ title={o.description ?? undefined}+ onClick={() => toggle(q.id, o.label, q.multiSelect)}+ className={cn(+ 'rounded-md border px-2.5 py-1 text-xs transition-colors',+ on+ ? 'border-primary bg-primary text-primary-foreground'+ : 'hover:bg-muted',+ )}+ >+ {o.label}+ </button>+ )+ })}+ </div>+ <input+ value={texts[q.id] ?? ''}+ onChange={(e) =>+ setTexts((t) => ({ ...t, [q.id]: e.target.value }))+ }+ placeholder="Or type an answer"+ className="border-input w-full rounded-md border bg-transparent px-2.5 py-1 text-xs outline-none"+ />+ </div>+ ))}+ <div className="flex gap-1.5">+ <Button+ size="sm"+ disabled={busy || !complete}+ onClick={() =>+ onAnswer({+ answers: questions.map((q) => ({+ questionId: q.id,+ choices: choices[q.id] ?? [],+ text: (texts[q.id] ?? '').trim() || null,+ })),+ })+ }+ >+ Answer+ </Button>+ <Button size="sm" variant="ghost" disabled={busy} onClick={onDismiss}>+ Skip+ </Button>+ </div>+ </div>+ )+}diff --git a/web/src/managed-agents/computer-sessions/state.ts b/web/src/managed-agents/computer-sessions/state.tsnew file mode 100644index 00000000..8c6da0d0--- /dev/null+++ b/web/src/managed-agents/computer-sessions/state.ts@@ -0,0 +1,111 @@+import { useSyncExternalStore } from 'react'+import { useQuery } from '@tanstack/react-query'+import {+ getCapabilities,+ sessionKeys,+ type Ask,+ type ListSessionsQuery,+ type Session,+} from '../computer-sessions-api'++export const NEEDS_YOU: ListSessionsQuery = { status: 'waiting', limit: 50 }+export const WORKING: ListSessionsQuery = {+ status: 'starting,running',+ limit: 50,+}++export const isBusy = (status: string) =>+ status === 'running' || status === 'starting'++export function statusLabel(status: string) {+ switch (status) {+ case 'waiting':+ return 'Needs you'+ case 'running':+ return 'Working'+ case 'starting':+ return 'Starting'+ case 'suspended':+ return 'Asleep'+ default:+ return 'Idle'+ }+}++export function askTitle(ask: Ask): string {+ if (ask.kind === 'approval')+ return `Approve ${ask.approval?.title || ask.approval?.toolName || 'a tool call'}`+ if (ask.kind === 'question') {+ const q = ask.question?.questions[0]+ return q?.text || q?.header || 'Has a question'+ }+ if (ask.kind === 'secret') {+ const name = (ask.secret as { name?: string } | null)?.name+ return name ? `Needs the secret ${name}` : 'Needs a secret'+ }+ return 'Needs you'+}++// The one line under a session's title: what it is waiting on, else the last+// thing it said.+export function sessionLine(s: Session): string {+ const ask = s.asks.find((a) => a.status === 'open') ?? s.asks[0]+ if (s.status === 'waiting' && ask) return askTitle(ask)+ return (s.lastText ?? '').replace(/\s+/g, ' ').trim()+}++export function sessionTitle(s: Session) {+ return s.title?.trim() || 'Untitled session'+}++// Last seq read per session, kept in this browser. A session is unread when it+// moved past what was read, or when it moved since this browser first looked+// and was never opened here.+const SEEN_KEY = 'computer-sessions-seen'+type Seen = { since: string; seq: Record<string, number> }+const listeners = new Set<() => void>()+let seenCache: Seen | null = null++function readSeen(): Seen {+ if (seenCache) return seenCache+ try {+ const raw = localStorage.getItem(SEEN_KEY)+ if (raw) seenCache = JSON.parse(raw) as Seen+ } catch {+ // ignore: a broken entry starts over+ }+ if (!seenCache?.seq) {+ seenCache = { since: new Date().toISOString(), seq: {} }+ localStorage.setItem(SEEN_KEY, JSON.stringify(seenCache))+ }+ return seenCache+}++export function markSeen(id: string, seq: number) {+ const seen = readSeen()+ if ((seen.seq[id] ?? -1) >= seq) return+ seenCache = { ...seen, seq: { ...seen.seq, [id]: seq } }+ localStorage.setItem(SEEN_KEY, JSON.stringify(seenCache))+ listeners.forEach((l) => l())+}++export function useSeen(): Seen {+ return useSyncExternalStore((l) => {+ listeners.add(l)+ return () => listeners.delete(l)+ }, readSeen)+}++export function isUnread(s: Session, seen: Seen) {+ const read = seen.seq[s.id]+ if (read !== undefined) return s.lastSeq > read+ return !!s.lastActiveAt && s.lastActiveAt > seen.since+}++export function useCapabilities() {+ return useQuery({+ queryKey: sessionKeys.capabilities,+ queryFn: getCapabilities,+ staleTime: 5 * 60_000,+ })+}diff --git a/web/src/managed-agents/computer-sessions/transcript.test.ts b/web/src/managed-agents/computer-sessions/transcript.test.tsnew file mode 100644index 00000000..7e77220a--- /dev/null+++ b/web/src/managed-agents/computer-sessions/transcript.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest'+import type { SessionEvent } from '../computer-sessions-api'+import { buildTranscript, formatDuration, mergeEvents } from './transcript'++let seq = 0+const ev = (+ type: string,+ data: Record<string, unknown> = {},+): SessionEvent => ({+ id: `ev_${++seq}`,+ seq,+ createdAt: new Date(Date.UTC(2026, 10, 17, 12, 0, seq)).toISOString(),+ turnId: 'tn_1',+ actor:+ type === 'message.received' ? { name: 'Igor', via: 'dashboard' } : null,+ type,+ data,+})++describe('buildTranscript', () => {+ it('folds tool calls between messages into one work step', () => {+ const items = buildTranscript([+ ev('message.received', { input: 'Fix the test' }),+ ev('tool.started', { callId: 'a', title: 'Read x', toolName: 'Read' }),+ ev('tool.completed', { callId: 'a', title: 'Read x', toolName: 'Read' }),+ ev('tool.started', { callId: 'b', title: 'npm test', toolName: 'Bash' }),+ ev('tool.failed', { callId: 'b', title: 'npm test', toolName: 'Bash' }),+ ev('message.completed', { parentCallId: null, text: 'Fixed.' }),+ ev('turn.completed', {}),+ ev('usage.recorded', {}),+ ])+ expect(items.map((i) => i.kind)).toEqual(['user', 'work', 'agent'])+ const work = items[1]+ expect(work.kind === 'work' && work.tools.map((t) => t.status)).toEqual([+ 'done',+ 'failed',+ ])+ expect(work.kind === 'work' && work.open).toBe(false)+ })++ it('keeps a subagent message inside the work and updates a closed ask', () => {+ const ask = { id: 'ak_1', status: 'open' }+ const items = buildTranscript([+ ev('message.completed', { parentCallId: 'call_1', text: 'sub' }),+ ev('ask.opened', { ask }),+ ev('ask.closed', { ask: { ...ask, status: 'answered' } }),+ ])+ expect(items.map((i) => i.kind)).toEqual(['work', 'ask'])+ expect(items[1].kind === 'ask' && items[1].ask.status).toBe('answered')+ })+})++describe('mergeEvents', () => {+ it('appends in order and drops repeats', () => {+ const a = [ev('other'), ev('other')]+ const b = ev('other')+ expect(mergeEvents(a, [a[1], b]).map((e) => e.seq)).toEqual([+ a[0].seq,+ a[1].seq,+ b.seq,+ ])+ })+})++describe('formatDuration', () => {+ it('reads like a person would say it', () => {+ expect(formatDuration(400)).toBe('1s')+ expect(formatDuration(72_000)).toBe('1m 12s')+ expect(formatDuration(3_600_000)).toBe('1h')+ })+})diff --git a/web/src/managed-agents/computer-sessions/transcript.ts b/web/src/managed-agents/computer-sessions/transcript.tsnew file mode 100644index 00000000..b3dc0e07--- /dev/null+++ b/web/src/managed-agents/computer-sessions/transcript.ts@@ -0,0 +1,213 @@+import type { Ask, SessionEvent } from '../computer-sessions-api'++// Folds a session's events into what the transcript shows: people's messages,+// the agent's replies, and the tool calls between them collapsed into one+// "Worked for …" step (work 107). Types it does not know are skipped, as the+// API asks of every client.++export type ToolStep = {+ callId: string+ title: string+ toolName: string+ status: 'running' | 'done' | 'failed'+}++export type TranscriptItem =+ | {+ kind: 'user'+ key: string+ text: string+ author: string | null+ // The member id (`usr_…`) of whoever sent it.+ authorId: string | null+ via: string | null+ at: string+ }+ | { kind: 'agent'; key: string; text: string; at: string }+ | {+ kind: 'work'+ key: string+ tools: ToolStep[]+ startedAt: string+ endedAt: string+ open: boolean+ }+ | { kind: 'ask'; key: string; ask: Ask }+ | { kind: 'note'; key: string; text: string; tone: 'muted' | 'error' }++const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)++export function buildTranscript(events: SessionEvent[]): TranscriptItem[] {+ const items: TranscriptItem[] = []+ let work: Extract<TranscriptItem, { kind: 'work' }> | null = null+ const asks = new Map<string, Extract<TranscriptItem, { kind: 'ask' }>>()++ const closeWork = () => {+ if (work) work.open = false+ work = null+ }+ const workAt = (e: SessionEvent) => {+ if (!work) {+ work = {+ kind: 'work',+ key: `work-${e.seq}`,+ tools: [],+ startedAt: e.createdAt,+ endedAt: e.createdAt,+ open: true,+ }+ items.push(work)+ }+ work.endedAt = e.createdAt+ return work+ }++ for (const e of events) {+ const d = e.data+ switch (e.type) {+ case 'message.received': {+ closeWork()+ const text = str(d.input)+ if (text)+ items.push({+ kind: 'user',+ key: e.id,+ text,+ // The computer falls back to the member id (`usr_…`) when there is no name: not worth showing.+ author:+ e.actor?.name && e.actor.name !== e.actor.id+ ? e.actor.name+ : null,+ authorId: e.actor?.id ?? null,+ via: e.actor?.via ?? null,+ at: e.createdAt,+ })+ break+ }+ case 'message.completed': {+ const text = str(d.text)+ // A subagent's messages belong to its work, not the conversation.+ if (d.parentCallId) {+ workAt(e)+ break+ }+ closeWork()+ if (text)+ items.push({ kind: 'agent', key: e.id, text, at: e.createdAt })+ break+ }+ case 'reasoning.completed':+ workAt(e)+ break+ case 'tool.started': {+ const w = workAt(e)+ const callId = str(d.callId) ?? e.id+ if (!w.tools.some((t) => t.callId === callId))+ w.tools.push({+ callId,+ title: str(d.title) ?? str(d.toolName) ?? 'Tool',+ toolName: str(d.toolName) ?? '',+ status: 'running',+ })+ break+ }+ case 'tool.completed':+ case 'tool.failed': {+ const w = workAt(e)+ const callId = str(d.callId) ?? e.id+ const status = e.type === 'tool.completed' ? 'done' : 'failed'+ const tool = w.tools.find((t) => t.callId === callId)+ if (tool) tool.status = status+ else+ w.tools.push({+ callId,+ title: str(d.title) ?? str(d.toolName) ?? 'Tool',+ toolName: str(d.toolName) ?? '',+ status,+ })+ break+ }+ case 'ask.opened':+ case 'ask.closed': {+ const ask = d.ask as Ask | undefined+ if (!ask) break+ const seen = asks.get(ask.id)+ if (seen) {+ seen.ask = ask+ break+ }+ closeWork()+ const item = { kind: 'ask' as const, key: `ask-${ask.id}`, ask }+ asks.set(ask.id, item)+ items.push(item)+ break+ }+ case 'turn.failed': {+ closeWork()+ const err = d.error as { message?: unknown } | undefined+ items.push({+ kind: 'note',+ key: e.id,+ text: str(err?.message) ?? 'The turn failed.',+ tone: 'error',+ })+ break+ }+ case 'turn.cancelled':+ closeWork()+ items.push({ kind: 'note', key: e.id, text: 'Stopped', tone: 'muted' })+ break+ case 'session.compacted':+ closeWork()+ items.push({+ kind: 'note',+ key: e.id,+ text: 'Context compacted',+ tone: 'muted',+ })+ break+ case 'turn.completed':+ closeWork()+ break+ }+ }+ return items+}++// Merges a page into what is already loaded, in seq order, once each.+export function mergeEvents(+ have: SessionEvent[],+ page: SessionEvent[],+): SessionEvent[] {+ if (!page.length) return have+ const last = have.length ? have[have.length - 1].seq : -1+ if (page[0].seq > last) return [...have, ...page]+ const bySeq = new Map(have.map((e) => [e.seq, e]))+ for (const e of page) bySeq.set(e.seq, e)+ return [...bySeq.values()].sort((a, b) => a.seq - b.seq)+}++export function formatDuration(ms: number): string {+ const s = Math.max(1, Math.round(ms / 1000))+ if (s < 60) return `${s}s`+ const m = Math.floor(s / 60)+ if (m < 60) return s % 60 ? `${m}m ${s % 60}s` : `${m}m`+ const h = Math.floor(m / 60)+ return m % 60 ? `${h}h ${m % 60}m` : `${h}h`+}++export function timeAgo(iso: string | null | undefined, now = Date.now()) {+ if (!iso) return ''+ const s = Math.max(0, Math.round((now - new Date(iso).getTime()) / 1000))+ if (s < 60) return 'now'+ const m = Math.floor(s / 60)+ if (m < 60) return `${m}m`+ const h = Math.floor(m / 60)+ if (h < 24) return `${h}h`+ const d = Math.floor(h / 24)+ if (d < 7) return `${d}d`+ return new Date(iso).toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ })+}