diff --git a/docs/foundation/LOOP-WALK.md b/docs/foundation/LOOP-WALK.md index 65fe4f4b0..d971f552b 100644 --- a/docs/foundation/LOOP-WALK.md +++ b/docs/foundation/LOOP-WALK.md @@ -119,7 +119,13 @@ reaches its own account's sessions. 3. **Read it.** `POST /api/control/peek-tab` `{tab, channel: "cloud"}` returns `resultUrl` and `openUrl`. `GET ` is `pending`, then `done` with `content` (the session's terminal output so far) or `error`. Ask again for - a newer capture. + a newer capture. For the conversation itself rather than the screen, + `GET /api/control/sessions?project=` returns the session's row + (canonical state, the task, the road to live, `openUrl`) and the last + things said in it (`items`, default 12, at most 40). With no query it + lists the projects' sessions, at most 25 with what needs the person + first, and `total` says how many exist; `?runId=` reads one run. OrangeCat's + signed rail (`POST /api/orangecat/sessions`) answers the same. 4. **Type a key or a command.** `POST /api/control/tab-inject-raw` `{kind: "key", tab, data, channel: "cloud"}`, the bytes the Terminal page sends for a keystroke. diff --git a/scripts/test/agent-session-read.ts b/scripts/test/agent-session-read.ts index 5fdce9cde..84a247b72 100644 --- a/scripts/test/agent-session-read.ts +++ b/scripts/test/agent-session-read.ts @@ -38,6 +38,27 @@ const ask = read("src/app/api/control/peek-tab/route.ts"); assert.match(ask, /resultUrl: `\/api\/control\/peek-tab\/\$\{peekId\}`/); assert.match(ask, /openUrl: sessionOpenUrl\(tab, channel \?\? null\)/); assert.equal(terminalHref("loki", "cloud"), "/terminal?project=loki"); +// The conversation: a token reads its sessions through the same reads as +// OrangeCat's signed rail, and neither route keeps a copy of its own. +const control = read("src/app/api/control/sessions/route.ts"); +assert.match(control, /getApiUserId\(\)/, "sessions and their conversation are read with a token"); +assert.match(control, /readSessions\(userId, \{ \.\.\.query, poll: Boolean\(poll\) \}\)/); +const signed = read("src/app/api/orangecat/sessions/route.ts"); +assert.match(signed, /readSessions\(user\.id, \{ project, runId, items, watch, poll \}\)/); +for (const src of [control, signed]) { + assert.doesNotMatch(src, /lastTranscript|addPeekViewer|loadRunTrack/, "one copy of the reads"); +} +const reads = read("src/lib/session-reads.ts"); +assert.match(reads, /export async function readSessions\(/); +assert.match(reads, /total: rows\.length,/, "a list cut at the cap says how many there were"); +// The conversation read is current, on the session's builder, and shares the +// Terminal's viewer count (so it never ends a person's live view). +assert.match(reads, /projectPreferredChannel\(project\)/, "an unrecorded builder is the project's"); +assert.match(reads, /const command = \{ tab, channel \};/, "peek commands name the builder"); +assert.match(reads, /addPeekViewer\(userId, tab, channel\)/); +assert.match(reads, /removePeekViewer\(userId, tab, channel\)/); +assert.match(reads, /frame\.at >= joinedAt/, "a copy from before the read is not the answer"); + // The live stream is still a browser's: it holds a viewer open on the runner. assert.match(read("src/app/api/control/peek-stream/route.ts"), /getSessionUserId\(\)/); diff --git a/scripts/test/orangecat-sessions.ts b/scripts/test/orangecat-sessions.ts index f880a518c..a84d6716f 100644 --- a/scripts/test/orangecat-sessions.ts +++ b/scripts/test/orangecat-sessions.ts @@ -56,6 +56,35 @@ async function main(): Promise { assert.equal(working.runId, run.id); assert.match(working.statusUrl ?? "", /\/api\/orchestration\/runs\/11111111-/); assert.equal(working.prUrl, run.prUrl); + assert.equal(working.session, "site", "a project's own session is named after it"); + assert.match( + working.openUrl, + /^https:\/\/[^/]+\/terminal\?source=cloud&project=site&run=11111111-/, + "openUrl is the same session, on that run, in Loki's Terminal", + ); + const lane = shapeSessionRow({ + project: "site", + builderPref: "cloud", + presence, + run, + transcriptAt: null, + tab: "site~11111111", + }); + assert.equal(lane.session, "site~11111111", "a parallel lane is named as its own tab"); + assert.match(lane.openUrl, /\/terminal\?source=cloud&project=site~11111111&run=/); + const resolved = shapeSessionRow({ + project: "plain", + builderPref: null, + presence, + run: null, + transcriptAt: null, + channel: "cloud", + }); + assert.match( + resolved.openUrl, + /\/terminal\?source=cloud&project=plain$/, + "the link names the builder the session runs on, not this browser's last choice", + ); console.log(" ✓ a working session: canonical state, one-line task, run and PR"); const local = shapeSessionRow({ @@ -68,6 +97,11 @@ async function main(): Promise { assert.equal(local.online, false, "online means the project's own builder"); assert.equal(local.lastActivityAt, run.lastProgressAt, "no frame: the runner's last progress"); assert.equal(local.prUrl, null, "a non-http URL never crosses"); + assert.match( + local.openUrl, + /\/terminal\?source=machine&tab=site&run=/, + "a local session opens on This computer", + ); console.log(" ✓ online follows the preferred builder; unsafe URL dropped"); const idle = shapeSessionRow({ @@ -81,6 +115,7 @@ async function main(): Promise { assert.equal(idle.label, "Idle"); assert.equal(idle.runId, null); assert.equal(idle.statusUrl, null); + assert.match(idle.openUrl, /\/terminal\?project=quiet$/, "no run: the session itself"); assert.equal(idle.online, true, "no preference: any builder counts"); console.log(" ✓ no run on record is idle"); @@ -195,17 +230,23 @@ async function main(): Promise { // The route watches BEFORE it reads, and waits for a frame newer than its join. const { readFileSync } = await import("node:fs"); - const routeSrc = readFileSync("src/app/api/orangecat/sessions/route.ts", "utf8"); + // The reads live in lib/session-reads.ts, shared with a person's own token. + const routeSrc = readFileSync("src/lib/session-reads.ts", "utf8"); + assert.match( + readFileSync("src/app/api/orangecat/sessions/route.ts", "utf8"), + /readSessions\(user\.id, \{ project, runId, items, watch, poll \}\)/, + ); assert.ok( - routeSrc.indexOf("await watchTab(") < - routeSrc.indexOf("await readTranscript(user.id, tab, channel)"), + routeSrc.indexOf("await watchTab(") > -1 && + routeSrc.indexOf("await watchTab(") < + routeSrc.indexOf("await readTranscript(userId, tab, channel)"), "watch first, then read", ); assert.match(routeSrc, /frame\.at >= joinedAt/, "a snapshot must be newer than the join"); assert.match(routeSrc, /settledFrame\(/, "and whole: every batch of it, not the first"); assert.match( routeSrc, - /rowFor\(user\.id, project, run, presence, !poll\)/, + /rowFor\(userId, project, run, presence, !poll\)/, "a poll never looks at GitHub", ); console.log(" ✓ the route follows before it reads, and never passes an old copy off as live"); diff --git a/src/app/api/control/sessions/route.ts b/src/app/api/control/sessions/route.ts new file mode 100644 index 000000000..841d7d026 --- /dev/null +++ b/src/app/api/control/sessions/route.ts @@ -0,0 +1,69 @@ +/** + * GET /api/control/sessions — a person's agent sessions, read with their own + * browser session or `ck_` token. + * + * The same reads OrangeCat's signed rail answers with (lib/session-reads.ts), + * so an agent that starts Claude Code in a session (tab-inject) can follow it + * the way the person does on Control and Watch: + * + * - no query: the projects' sessions, one row each (canonical state, the + * task in a line, the road to live, `openUrl` into Loki's Terminal), at + * most 25 with what needs the person first; `total` says how many exist. + * - `?runId=`: that one run, with the owner's full track and the agent's + * handoff once it reports; `&items=` adds the end of that run's own + * conversation, `&watch=` (at most 300) holds the session as a + * viewer so the runner keeps streaming it, `&poll=1` never looks at GitHub. + * - `?project=`: that project's row and the last `items` (default 12, at + * most 40) things said in its conversation. + * + * Read only. A plain shell is never a row here: rows are projects and their + * runs, and a shell is neither. + */ +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; +import { getApiUserId } from "@/lib/session"; +import { SESSIONS_MAX_ITEMS } from "@/lib/integrations/orangecat-sessions"; +import { WATCH_MAX_SECONDS } from "@/lib/integrations/orangecat-watch"; +import { readSessions } from "@/lib/session-reads"; + +export const dynamic = "force-dynamic"; + +const Query = z.object({ + project: z.string().trim().min(1).max(120).optional(), + runId: z.string().uuid().optional(), + items: z.coerce.number().int().min(1).max(SESSIONS_MAX_ITEMS).optional(), + /** With runId: hold the run's session as a viewer for this many seconds. */ + watch: z.coerce.number().int().min(1).max(WATCH_MAX_SECONDS).optional(), + /** With runId: a follower's poll, which never looks at GitHub. */ + poll: z.enum(["1", "true"]).optional(), +}); + +export async function GET(req: NextRequest) { + const userId = await getApiUserId(); + if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const params = new URL(req.url).searchParams; + const parsed = Query.safeParse({ + project: params.get("project") ?? undefined, + runId: params.get("runId") ?? undefined, + items: params.get("items") ?? undefined, + watch: params.get("watch") ?? undefined, + poll: params.get("poll") ?? undefined, + }); + if (!parsed.success) { + const issue = parsed.error.issues[0]; + return NextResponse.json( + { error: `${issue?.path.join(".") || "query"}: ${issue?.message ?? "invalid"}` }, + { status: 400 }, + ); + } + + try { + const { poll, ...query } = parsed.data; + const { status, body } = await readSessions(userId, { ...query, poll: Boolean(poll) }); + return NextResponse.json(body, { status, headers: { "Cache-Control": "no-store" } }); + } catch (err) { + console.error("[control/sessions] failed:", (err as Error).message); + return NextResponse.json({ error: "sessions failed" }, { status: 500 }); + } +} diff --git a/src/app/api/orangecat/sessions/route.ts b/src/app/api/orangecat/sessions/route.ts index 3cfaa5985..89d5104e5 100644 --- a/src/app/api/orangecat/sessions/route.ts +++ b/src/app/api/orangecat/sessions/route.ts @@ -7,7 +7,8 @@ * linked to the OrangeCat actor in the body, never as anyone else. * * Three reads on one door: - * - no `project`, no `runId`: every project's session, in one row each. + * - no `project`, no `runId`: the projects' sessions, one row each, at most + * 25 with what needs the person first; `total` says how many exist. * - `runId`: that one run, with the owner's full track (pull request, merge, * deploy, live) and the agent's handoff once it reports. With `items`, * also the last things said in THAT run's own session (a one-off or a @@ -17,48 +18,18 @@ * - `project`: that project's row plus the last `items` things said in its * Claude Code conversation. * - * The conversation is the copy the server keeps for the transcript view - * (lastTranscript in lib/sse-bus). When nobody is viewing the session, a - * read joins as a viewer for a few seconds, exactly as the transcript stream - * does, and waits for the snapshot the runner sends: an older copy alone may - * be missing the latest turns, and is marked `live: false` when it is all - * there is. + * The reads themselves, and how fresh a conversation is, are + * lib/session-reads.ts, shared with the person's own token + * (/api/control/sessions). */ import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { getUserByOrangeCatActorId } from "@/db/queries/users"; -import { getUserProjects, getOrgProjects } from "@/db/queries/user-projects"; -import { - getLatestRunForProjectKey, - getOrchestrationRunById, -} from "@/db/queries/orchestration-runs"; -import { enqueuePeekCommand } from "@/db/queries/pending-commands"; -import { getBuilderPresence } from "@/db/queries/runner-presence"; import { readSignedOrangeCatBody } from "@/lib/integrations/orangecat-webhook"; import { isFreshIssuedAt } from "@/lib/integrations/orangecat-actor-status"; -import { - SESSIONS_DEFAULT_ITEMS, - SESSIONS_MAX_ITEMS, - SESSIONS_MAX_PROJECTS, - orderSessions, - shapeSessionRow, - shapeTranscript, - type SessionRow, - type SessionRowInput, -} from "@/lib/integrations/orangecat-sessions"; -import { WATCH_MAX_SECONDS, watchTab } from "@/lib/integrations/orangecat-watch"; -import type { BuilderChannel } from "@/lib/constants/statuses"; -import { runHandoff } from "@/lib/run-handoff"; -import { askedOf } from "@/lib/multi-dispatch-prompt"; -import { ORCHESTRATION_OUTCOME } from "@/lib/orchestration/contract"; -import { loadRunTrack, type TrackableRun } from "@/lib/run-track-load"; -import { - addPeekViewer, - lastTranscript, - removePeekViewer, - type TranscriptFrame, -} from "@/lib/sse-bus"; -import { mergeVisibleProjects } from "@/lib/visible-projects"; +import { SESSIONS_MAX_ITEMS } from "@/lib/integrations/orangecat-sessions"; +import { WATCH_MAX_SECONDS } from "@/lib/integrations/orangecat-watch"; +import { readSessions } from "@/lib/session-reads"; export const dynamic = "force-dynamic"; @@ -78,147 +49,10 @@ const Body = z.object({ poll: z.boolean().optional(), }); -/** How long a read waits for the runner's first snapshot of a conversation. */ -const SNAPSHOT_WAIT_MS = 6_000; -const SNAPSHOT_POLL_MS = 300; -/** A snapshot's batches arrive back to back; this long without one, it is whole. */ -const SNAPSHOT_SETTLE_MS = 600; - -type Presence = SessionRowInput["presence"]; -type RunRow = TrackableRun & { projectKey: string }; - -/** The builder a run is on, when it is known: a peek is sent to that runner only. */ -function runChannel( - run: { payload?: object | null } | null, - snapChannel: string | null | undefined, -): BuilderChannel | undefined { - const raw = - (run?.payload as { oneOffChannel?: unknown } | null | undefined)?.oneOffChannel ?? snapChannel; - return raw === "cloud" || raw === "local" ? raw : undefined; -} - -async function rowFor( - userId: string, - project: { name: string; builderPref?: string | null }, - run: RunRow | null, - presence: Presence, - ownerView: boolean, -): Promise<{ row: SessionRow; tab: string; channel: BuilderChannel | undefined }> { - const loaded = run ? await loadRunTrack(userId, run, { ownerView }).catch(() => null) : null; - const tab = run?.payload?.sessionTab ?? run?.projectKey ?? project.name; - const pr = loaded?.fix && !loaded.fix.foreignPr ? (loaded.fix.pr?.url ?? null) : null; - const row = shapeSessionRow({ - project: project.name, - builderPref: project.builderPref ?? null, - presence, - run: - run && !loaded - ? runWithoutTrack(run) - : run && loaded - ? { - id: run.id, - state: loaded.canonical.state, - label: loaded.canonical.label, - reason: loaded.canonical.reason, - // What was asked, not the cross-project preamble the agent got. - task: loaded.prompt?.text ? askedOf(loaded.prompt.text) : null, - track: loaded.track.summary, - prUrl: pr, - lastProgressAt: loaded.snap?.lastProgressAt ?? null, - handoff: run.finishedAt ? runHandoff(run.summary) : null, - } - : null, - transcriptAt: lastTranscript(userId, tab)?.at ?? null, - }); - return { row, tab, channel: runChannel(run, loaded?.snap?.builderChannel) }; -} - -/** - * A run whose track could not be loaded still exists and is still open or - * closed: said from the run's own row, never as Idle with no run, which a - * follower would take for settled. - */ -function runWithoutTrack(run: RunRow): NonNullable { - const open = !run.finishedAt; - const failed = - !open && - run.outcome !== ORCHESTRATION_OUTCOME.SUCCESS && - run.outcome !== ORCHESTRATION_OUTCOME.PARTIAL; - return { - id: run.id, - state: open ? "working" : failed ? "failed" : "done", - label: open ? "Working" : failed ? "Failed" : "Done", - reason: open ? null : failed ? "Its details could not be read just now." : null, - task: null, - track: null, - prUrl: null, - lastProgressAt: null, - handoff: open ? null : runHandoff(run.summary), - }; -} - -/** The newest copy once frames have stopped arriving for a moment, or at the deadline. */ -async function settledFrame( - userId: string, - tab: string, - frame: TranscriptFrame, - until: number, -): Promise { - let latest = frame; - while (Date.now() < until) { - await new Promise((r) => setTimeout(r, SNAPSHOT_SETTLE_MS)); - const next = lastTranscript(userId, tab); - if (!next || next.at === latest.at) return latest; - latest = next; - } - return latest; -} - -/** - * The conversation of one session, as fresh as it can be had in a few - * seconds. When someone is already viewing it (a person on Terminal, or a - * bot's watch), the server's copy is live. Otherwise this joins as a viewer, - * which makes the runner send a snapshot, waits for a frame that arrived - * after it joined, and leaves again; if none comes, the older copy is - * returned marked not live, or null when there is none. - */ -async function readTranscript( - userId: string, - tab: string, - channel?: BuilderChannel, -): Promise<{ frame: { at: number; items: TranscriptFrame["items"] }; live: boolean } | null> { - const joinedAt = Date.now(); - const command = { tab, ...(channel ? { channel } : {}) }; - const first = addPeekViewer(userId, tab, channel); - try { - if (!first) { - const cached = lastTranscript(userId, tab); - return cached ? { frame: cached, live: true } : null; - } - await enqueuePeekCommand(userId, "peek_start", command).catch(() => {}); - const until = joinedAt + SNAPSHOT_WAIT_MS; - while (Date.now() < until) { - await new Promise((r) => setTimeout(r, SNAPSHOT_POLL_MS)); - const frame = lastTranscript(userId, tab); - if (frame && frame.at >= joinedAt) { - // The runner posts a snapshot in batches of 100 (transcript-streamer - // MAX_BATCH): wait until no more arrive, or the tail is missing. - return { frame: await settledFrame(userId, tab, frame, until), live: true }; - } - } - const older = lastTranscript(userId, tab); - return older ? { frame: older, live: false } : null; - } finally { - if (removePeekViewer(userId, tab, channel)) { - await enqueuePeekCommand(userId, "peek_stop", command).catch(() => {}); - } - } -} - export async function POST(req: NextRequest) { const dataOrResp = await readSignedOrangeCatBody(req, Body, "sessions not configured"); if (dataOrResp instanceof NextResponse) return dataOrResp; - const { actorId, issuedAt, project: wanted, runId, items, watch, poll } = dataOrResp; + const { actorId, issuedAt, project, runId, items, watch, poll } = dataOrResp; // Signed, but with no nonce: without this a captured request replays forever. if (!isFreshIssuedAt(issuedAt)) { @@ -230,89 +64,8 @@ export async function POST(req: NextRequest) { if (!user) { return NextResponse.json({ ok: true, linked: false, sessions: [] }); } - - const [own, org, presence] = await Promise.all([ - getUserProjects(user.id).catch(() => []), - getOrgProjects(user.id).catch(() => []), - getBuilderPresence(user.id).catch(() => ({ cloud: false, local: false, any: false })), - ]); - const projects = mergeVisibleProjects(own, org); - const generatedAt = new Date().toISOString(); - const builders = { cloud: presence.cloud, local: presence.local }; - - if (runId) { - const run = await getOrchestrationRunById(user.id, runId); - if (!run) { - return NextResponse.json( - { error: "run not found", detail: "No run with that id belongs to this account." }, - { status: 404 }, - ); - } - const project = projects.find( - (p) => p.name.toLowerCase() === run.projectKey.toLowerCase(), - ) ?? { name: run.projectKey }; - const { row, tab, channel } = await rowFor(user.id, project, run, presence, !poll); - // Start (or extend) the watch before reading, so the runner is already - // streaming when the agent writes its answer. - if (watch) await watchTab(user.id, tab, watch, channel); - const read = items ? await readTranscript(user.id, tab, channel) : null; - return NextResponse.json({ - ok: true, - linked: true, - generatedAt, - builders, - sessions: [row], - ...(items - ? { - transcript: read ? shapeTranscript(project.name, read.frame, read.live, items) : null, - } - : {}), - }); - } - - if (wanted) { - const project = projects.find((p) => p.name.toLowerCase() === wanted.toLowerCase()); - if (!project) { - const available = projects.map((p) => p.name).sort((a, b) => a.localeCompare(b)); - return NextResponse.json( - { - error: "project not found", - detail: `No project named "${wanted}". Projects you can read: ${available.join(", ") || "none yet"}.`, - available, - }, - { status: 404 }, - ); - } - const run = await getLatestRunForProjectKey(user.id, project.name); - const { row, tab, channel } = await rowFor(user.id, project, run, presence, true); - const read = await readTranscript(user.id, tab, channel); - return NextResponse.json({ - ok: true, - linked: true, - generatedAt, - builders, - sessions: [row], - transcript: read - ? shapeTranscript(project.name, read.frame, read.live, items ?? SESSIONS_DEFAULT_ITEMS) - : null, - }); - } - - // The list never reaches GitHub or spends the owner's budget: ownerView - // is off, so each row is the run's own facts and its cached ledger. - const rows = await Promise.all( - projects.map(async (project) => { - const latest = await getLatestRunForProjectKey(user.id, project.name).catch(() => null); - return (await rowFor(user.id, project, latest, presence, false)).row; - }), - ); - return NextResponse.json({ - ok: true, - linked: true, - generatedAt, - builders, - sessions: orderSessions(rows).slice(0, SESSIONS_MAX_PROJECTS), - }); + const { status, body } = await readSessions(user.id, { project, runId, items, watch, poll }); + return NextResponse.json(status === 200 ? { ...body, linked: true } : body, { status }); } catch (err) { console.error("[orangecat/sessions] failed:", (err as Error).message); return NextResponse.json({ error: "sessions failed" }, { status: 500 }); diff --git a/src/lib/integrations/orangecat-sessions.ts b/src/lib/integrations/orangecat-sessions.ts index cf4e74796..98b755eb7 100644 --- a/src/lib/integrations/orangecat-sessions.ts +++ b/src/lib/integrations/orangecat-sessions.ts @@ -17,6 +17,7 @@ */ import { APP_URL } from "@/config/brand"; import type { TranscriptItem } from "@/lib/claude-transcript"; +import { sessionOpenUrl } from "@/lib/dispatch-card"; import type { RunHandoff } from "@/lib/run-handoff"; /** Projects listed in one answer; the same ceiling as actor-status. */ @@ -52,6 +53,10 @@ export interface SessionRow { prUrl: string | null; /** Where a person watches this run. */ statusUrl: string | null; + /** The session's name on its builder: the project, or a parallel lane of it. */ + session: string; + /** The same session in Loki's Terminal, on any device the person is signed in on. */ + openUrl: string; /** * What the agent reported when it finished (lib/run-handoff): what it did, * what it checked, what should come next. The answer to a one-off question @@ -78,6 +83,10 @@ export interface SessionRowInput { } | null; /** Epoch ms of the newest cached transcript frame for the session. */ transcriptAt: number | null; + /** The session's tab when it is not the project's own (a parallel lane). */ + tab?: string | null; + /** The builder the session runs on, for its link; else the stored preference. */ + channel?: "cloud" | "local" | null; } const STATES: ReadonlySet = new Set([ @@ -136,6 +145,8 @@ export function shapeSessionRow(input: SessionRowInput): SessionRow { track: run?.track ?? null, prUrl: safeUrl(run?.prUrl), statusUrl: run ? runStatusUrl(run.id) : null, + session: input.tab || input.project, + openUrl: sessionOpenUrl(input.tab || input.project, input.channel ?? builder, run?.id ?? null), handoff: run?.handoff ?? null, }; } diff --git a/src/lib/session-reads.ts b/src/lib/session-reads.ts new file mode 100644 index 000000000..8f4c6c77c --- /dev/null +++ b/src/lib/session-reads.ts @@ -0,0 +1,316 @@ +/** + * One person's agent sessions, read: the list (at most 25 rows, what needs + * the person first, with the `total`), one run, or one project with the last + * things said in its conversation. + * + * Two doors read through here and nothing else: OrangeCat's signed rail + * (/api/orangecat/sessions, as the Loki user linked to an OrangeCat actor) + * and the person's own session or `ck_` token (/api/control/sessions). Both + * answer the same thing, so an agent that steers a session over either one + * reads what the person reads on Control and Watch. + * + * Shaping and the contract are lib/integrations/orangecat-sessions.ts. The + * conversation is the copy the server keeps for the transcript view + * (lastTranscript in lib/sse-bus). When nobody is viewing the session, a + * read joins as a viewer for a few seconds, exactly as the transcript stream + * does, and waits for the snapshot the runner sends: an older copy alone may + * be missing the latest turns, and is marked `live: false` when it is all + * there is. + */ +import { getUserProjects, getOrgProjects } from "@/db/queries/user-projects"; +import { + getLatestRunForProjectKey, + getOrchestrationRunById, +} from "@/db/queries/orchestration-runs"; +import { enqueuePeekCommand } from "@/db/queries/pending-commands"; +import { getBuilderPresence } from "@/db/queries/runner-presence"; +import { + SESSIONS_DEFAULT_ITEMS, + SESSIONS_MAX_PROJECTS, + orderSessions, + shapeSessionRow, + shapeTranscript, + type SessionRow, + type SessionRowInput, +} from "@/lib/integrations/orangecat-sessions"; +import { watchTab } from "@/lib/integrations/orangecat-watch"; +import type { BuilderChannel } from "@/lib/constants/statuses"; +import { projectPreferredChannel } from "@/lib/execution-access"; +import { runHandoff } from "@/lib/run-handoff"; +import { askedOf } from "@/lib/multi-dispatch-prompt"; +import { ORCHESTRATION_OUTCOME } from "@/lib/orchestration/contract"; +import { loadRunTrack, type TrackableRun } from "@/lib/run-track-load"; +import { + addPeekViewer, + lastTranscript, + removePeekViewer, + type TranscriptFrame, +} from "@/lib/sse-bus"; +import { mergeVisibleProjects } from "@/lib/visible-projects"; + +/** How long a read waits for the runner's first snapshot of a conversation. */ +const SNAPSHOT_WAIT_MS = 6_000; +const SNAPSHOT_POLL_MS = 300; +/** A snapshot's batches arrive back to back; this long without one, it is whole. */ +const SNAPSHOT_SETTLE_MS = 600; + +type Presence = SessionRowInput["presence"]; +type RunRow = TrackableRun & { projectKey: string }; +type ProjectRef = { + name: string; + builderPref?: string | null; + dirPath?: string | null; + gitUrl?: string | null; +}; + +export type SessionsQuery = { + /** One project: its row and the end of its conversation. */ + project?: string; + /** One run: its row with the owner's full track. */ + runId?: string; + /** How many conversation items. A project read always includes them. */ + items?: number; + /** With runId: hold the run's session as a viewer for this many seconds. */ + watch?: number; + /** + * With runId: a follower's poll. The run's own facts and its cached ledger + * only, never a look at GitHub: a caller polling every few seconds must not + * spend the owner's GitHub budget (run-track-load's ownerView). + */ + poll?: boolean; +}; + +/** HTTP status and JSON body; each door adds only what is its own. */ +export type SessionsRead = { status: number; body: Record }; + +/** + * The builder a session is on: the one the run recorded, else the one the + * project dispatches to. Always named, so a peek is claimed by that runner + * only and shares the Terminal's viewer count for the session. + */ +function sessionChannel( + run: { payload?: object | null } | null, + snapChannel: string | null | undefined, + project: ProjectRef, +): BuilderChannel { + const raw = + (run?.payload as { oneOffChannel?: unknown } | null | undefined)?.oneOffChannel ?? snapChannel; + return raw === "cloud" || raw === "local" ? raw : projectPreferredChannel(project); +} + +async function rowFor( + userId: string, + project: ProjectRef, + run: RunRow | null, + presence: Presence, + ownerView: boolean, +): Promise<{ row: SessionRow; tab: string; channel: BuilderChannel }> { + const loaded = run ? await loadRunTrack(userId, run, { ownerView }).catch(() => null) : null; + const tab = run?.payload?.sessionTab ?? run?.projectKey ?? project.name; + const channel = sessionChannel(run, loaded?.snap?.builderChannel, project); + const pr = loaded?.fix && !loaded.fix.foreignPr ? (loaded.fix.pr?.url ?? null) : null; + const row = shapeSessionRow({ + project: project.name, + builderPref: project.builderPref ?? null, + presence, + run: + run && !loaded + ? runWithoutTrack(run) + : run && loaded + ? { + id: run.id, + state: loaded.canonical.state, + label: loaded.canonical.label, + reason: loaded.canonical.reason, + // What was asked, not the cross-project preamble the agent got. + task: loaded.prompt?.text ? askedOf(loaded.prompt.text) : null, + track: loaded.track.summary, + prUrl: pr, + lastProgressAt: loaded.snap?.lastProgressAt ?? null, + handoff: run.finishedAt ? runHandoff(run.summary) : null, + } + : null, + transcriptAt: lastTranscript(userId, tab)?.at ?? null, + tab, + channel, + }); + return { row, tab, channel }; +} + +/** + * A run whose track could not be loaded still exists and is still open or + * closed: said from the run's own row, never as Idle with no run, which a + * follower would take for settled. + */ +function runWithoutTrack(run: RunRow): NonNullable { + const open = !run.finishedAt; + const failed = + !open && + run.outcome !== ORCHESTRATION_OUTCOME.SUCCESS && + run.outcome !== ORCHESTRATION_OUTCOME.PARTIAL; + return { + id: run.id, + state: open ? "working" : failed ? "failed" : "done", + label: open ? "Working" : failed ? "Failed" : "Done", + reason: open ? null : failed ? "Its details could not be read just now." : null, + task: null, + track: null, + prUrl: null, + lastProgressAt: null, + handoff: open ? null : runHandoff(run.summary), + }; +} + +/** The newest copy once frames have stopped arriving for a moment, or at the deadline. */ +async function settledFrame( + userId: string, + tab: string, + frame: TranscriptFrame, + until: number, +): Promise { + let latest = frame; + while (Date.now() < until) { + await new Promise((r) => setTimeout(r, SNAPSHOT_SETTLE_MS)); + const next = lastTranscript(userId, tab); + if (!next || next.at === latest.at) return latest; + latest = next; + } + return latest; +} + +/** + * The conversation of one session, as fresh as it can be had in a few + * seconds. When someone is already viewing it (a person on Terminal, or a + * bot's watch), the server's copy is live. Otherwise this joins as a viewer, + * which makes the runner send a snapshot, waits for a frame that arrived + * after it joined, and leaves again; if none comes, the older copy is + * returned marked not live, or null when there is none. + */ +async function readTranscript( + userId: string, + tab: string, + channel: BuilderChannel, +): Promise<{ frame: { at: number; items: TranscriptFrame["items"] }; live: boolean } | null> { + const joinedAt = Date.now(); + const command = { tab, channel }; + const first = addPeekViewer(userId, tab, channel); + try { + if (!first) { + const cached = lastTranscript(userId, tab); + return cached ? { frame: cached, live: true } : null; + } + await enqueuePeekCommand(userId, "peek_start", command).catch(() => {}); + const until = joinedAt + SNAPSHOT_WAIT_MS; + while (Date.now() < until) { + await new Promise((r) => setTimeout(r, SNAPSHOT_POLL_MS)); + const frame = lastTranscript(userId, tab); + if (frame && frame.at >= joinedAt) { + // The runner posts a snapshot in batches of 100 (transcript-streamer + // MAX_BATCH): wait until no more arrive, or the tail is missing. + return { frame: await settledFrame(userId, tab, frame, until), live: true }; + } + } + const older = lastTranscript(userId, tab); + return older ? { frame: older, live: false } : null; + } finally { + if (removePeekViewer(userId, tab, channel)) { + await enqueuePeekCommand(userId, "peek_stop", command).catch(() => {}); + } + } +} + +/** Read one person's sessions, as that person. */ +export async function readSessions(userId: string, query: SessionsQuery): Promise { + const { project: wanted, runId, items, watch, poll } = query; + const [own, org, presence] = await Promise.all([ + getUserProjects(userId).catch(() => []), + getOrgProjects(userId).catch(() => []), + getBuilderPresence(userId).catch(() => ({ cloud: false, local: false, any: false })), + ]); + const projects = mergeVisibleProjects(own, org); + const generatedAt = new Date().toISOString(); + const builders = { cloud: presence.cloud, local: presence.local }; + + if (runId) { + const run = await getOrchestrationRunById(userId, runId); + if (!run) { + return { + status: 404, + body: { error: "run not found", detail: "No run with that id belongs to this account." }, + }; + } + const project: ProjectRef = projects.find( + (p) => p.name.toLowerCase() === run.projectKey.toLowerCase(), + ) ?? { name: run.projectKey }; + const { row, tab, channel } = await rowFor(userId, project, run, presence, !poll); + // Start (or extend) the watch before reading, so the runner is already + // streaming when the agent writes its answer. + if (watch) await watchTab(userId, tab, watch, channel); + const read = items ? await readTranscript(userId, tab, channel) : null; + return { + status: 200, + body: { + ok: true, + generatedAt, + builders, + sessions: [row], + ...(items + ? { + transcript: read ? shapeTranscript(project.name, read.frame, read.live, items) : null, + } + : {}), + }, + }; + } + + if (wanted) { + const project = projects.find((p) => p.name.toLowerCase() === wanted.toLowerCase()); + if (!project) { + const available = projects.map((p) => p.name).sort((a, b) => a.localeCompare(b)); + return { + status: 404, + body: { + error: "project not found", + detail: `No project named "${wanted}". Projects you can read: ${available.join(", ") || "none yet"}.`, + available, + }, + }; + } + const run = await getLatestRunForProjectKey(userId, project.name); + const { row, tab, channel } = await rowFor(userId, project, run, presence, true); + const read = await readTranscript(userId, tab, channel); + return { + status: 200, + body: { + ok: true, + generatedAt, + builders, + sessions: [row], + transcript: read + ? shapeTranscript(project.name, read.frame, read.live, items ?? SESSIONS_DEFAULT_ITEMS) + : null, + }, + }; + } + + // The list never reaches GitHub or spends the owner's budget: ownerView + // is off, so each row is the run's own facts and its cached ledger. + const rows = await Promise.all( + projects.map(async (project) => { + const latest = await getLatestRunForProjectKey(userId, project.name).catch(() => null); + return (await rowFor(userId, project, latest, presence, false)).row; + }), + ); + // At most SESSIONS_MAX_PROJECTS rows, what needs the person first; `total` + // says how many there were, so a cut list is never read as the whole one. + return { + status: 200, + body: { + ok: true, + generatedAt, + builders, + total: rows.length, + sessions: orderSessions(rows).slice(0, SESSIONS_MAX_PROJECTS), + }, + }; +}