From 834f8ec55740f03f960a03ad5ccea0752208cde8 Mon Sep 17 00:00:00 2001 From: prem315 Date: Sun, 1 Nov 2026 13:08:09 +0530 Subject: [PATCH] fix(desktop): align conversations with thread RPC models --- apps/desktop/scripts/dev.mjs | 5 +- apps/desktop/scripts/start-electron.mjs | 3 +- apps/web/src/kernel/servers.ts | 4 +- apps/web/src/widgets/session/address.ts | 11 +- apps/web/src/widgets/session/backend.ts | 232 ++++++++++++------ apps/web/src/widgets/session/composer.tsx | 16 +- apps/web/src/widgets/session/index.ts | 4 +- apps/web/src/widgets/session/queue.tsx | 10 +- apps/web/src/widgets/session/schema.ts | 41 ++-- apps/web/src/widgets/session/view.tsx | 36 +-- apps/widget/src/codework.ts | 50 +++- .../test/__artifacts__/desktop.threads.json | 70 ++++++ packages/codework/test/desktop.test.ts | 131 ++++++++++ 13 files changed, 474 insertions(+), 139 deletions(-) create mode 100644 packages/codework/test/__artifacts__/desktop.threads.json create mode 100644 packages/codework/test/desktop.test.ts diff --git a/apps/desktop/scripts/dev.mjs b/apps/desktop/scripts/dev.mjs index 09ef74e5..f5875cb1 100644 --- a/apps/desktop/scripts/dev.mjs +++ b/apps/desktop/scripts/dev.mjs @@ -65,7 +65,10 @@ while (!(await ready())) await sleep(100); let electron; function startElectron() { - electron = run("node", ["scripts/start-electron.mjs"], { + // pnpm inserts a lone `--` before arguments meant for the script. + const extra = process.argv.slice(2); + if (extra[0] === "--") extra.shift(); + electron = run("node", ["scripts/start-electron.mjs", ...extra], { cwd: desktopDir, env: { ...process.env, CODEWORK_WEB_URL: WEB_URL }, }); diff --git a/apps/desktop/scripts/start-electron.mjs b/apps/desktop/scripts/start-electron.mjs index 65928a80..21182c3f 100644 --- a/apps/desktop/scripts/start-electron.mjs +++ b/apps/desktop/scripts/start-electron.mjs @@ -40,7 +40,8 @@ const electronPath = process.platform === "darwin" ? brandedElectron() : electro const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE; -const child = spawn(electronPath, ["."], { +// Extra arguments reach Electron, `--remote-debugging-port=9222` say. +const child = spawn(electronPath, [".", ...process.argv.slice(2)], { stdio: "inherit", cwd: desktopDir, env, diff --git a/apps/web/src/kernel/servers.ts b/apps/web/src/kernel/servers.ts index ada99e74..48be6d91 100644 --- a/apps/web/src/kernel/servers.ts +++ b/apps/web/src/kernel/servers.ts @@ -17,6 +17,8 @@ export interface Problem { /** The default server's problem from its status; undefined while the app can work with it. */ export function problemOf(status: ServerStatus): Problem | undefined { const { cli, server } = status; + // An already running, compatible server is usable even without a local CLI. + if (server._tag === "Running") return undefined; if (cli === null) return { title: "CodeWork Isn't Installed", @@ -43,8 +45,6 @@ export function problemOf(status: ServerStatus): Problem | undefined { title: "Incompatible Server Version", line: `${status.name} runs codework v${server.version}, which this app can't read.`, }; - case "Running": - return undefined; } } diff --git a/apps/web/src/widgets/session/address.ts b/apps/web/src/widgets/session/address.ts index 6e620045..fcbf6e68 100644 --- a/apps/web/src/widgets/session/address.ts +++ b/apps/web/src/widgets/session/address.ts @@ -1,6 +1,13 @@ +import type { ThreadRef } from "./schema"; + const prefix = "codework://session/"; +/** A session's address: its main thread's. Another thread's is `/`. */ export const sessionAddress = (id: string) => `${prefix}${id}`; -export const sessionId = (address: string | undefined) => - address?.startsWith(prefix) ? address.slice(prefix.length) : undefined; +export const threadRef = (address: string | undefined): ThreadRef | undefined => { + if (!address?.startsWith(prefix)) return undefined; + const [sessionId, threadId, ...rest] = address.slice(prefix.length).split("/"); + if (sessionId === undefined || sessionId === "" || threadId === "" || rest.length > 0) return undefined; + return threadId === undefined ? { sessionId } : { sessionId, threadId }; +}; diff --git a/apps/web/src/widgets/session/backend.ts b/apps/web/src/widgets/session/backend.ts index 222bdc14..87038ba0 100644 --- a/apps/web/src/widgets/session/backend.ts +++ b/apps/web/src/widgets/session/backend.ts @@ -25,12 +25,14 @@ import { type Reply, type Snapshot, snapshotKey, + threadKey, topics, + type ThreadRef, type Update, type Window, } from "./schema.ts"; -// A session shows as its main thread until threads get a view of their own. +// Metadata follows the addressed thread; placement and project belong to its session. const toInfo = (info: ThreadInfo): Info => ({ title: info.title ?? UNTITLED, updated: info.updatedAt, @@ -72,18 +74,21 @@ const changes = ( ]; }; +/** Every thread-scoped event names its thread, and the session it belongs to. */ +const OfThread = { sessionId: Schema.String, threadId: Schema.String }; + /** A live text or thinking delta, as `event.subscribe` carries it. */ const Delta = Schema.Struct({ - sessionId: Schema.String, + ...OfThread, messageId: Schema.String, partIndex: Schema.Int, delta: Schema.String, timestamp: Schema.Number, }); const decodeDelta = Schema.decodeUnknownOption(Delta); -const decodeOfSession = Schema.decodeUnknownOption(Schema.Struct({ sessionId: Schema.String })); +const decodeOfThread = Schema.decodeUnknownOption(Schema.Struct(OfThread)); const decodeFailed = Schema.decodeUnknownOption( - Schema.Struct({ sessionId: Schema.String, error: Schema.Struct({ type: Schema.String, message: Schema.String }) }), + Schema.Struct({ ...OfThread, error: Schema.Struct({ type: Schema.String, message: Schema.String }) }), ); /** Appends a delta to the part it belongs to; a part not seen yet starts with it. */ @@ -96,10 +101,19 @@ const fold = (current: Part | undefined, kind: "text" | "thinking", delta: strin ? { ...current, thinking: current.thinking + delta } : { type: "thinking", thinking: delta }; +/** Overlays live text at its original index, preserving tools and other stored parts. */ +const mergeParts = (stored: ReadonlyArray, streamed: ReadonlyMap): Part[] => { + const parts = new Map(stored.map((part, index) => [index, part])); + for (const [index, part] of streamed) parts.set(index, part); + return [...parts.entries()].sort(([a], [b]) => a - b).map(([, part]) => part); +}; + const describe = (error: { readonly _tag: string }) => { switch (error._tag) { case "SessionNotFoundError": return "This session no longer exists."; + case "ThreadNotFoundError": + return "This thread no longer exists."; case "PromptConflictError": return "That message was already sent."; case "Location.DirectoryNotFoundError": @@ -122,10 +136,11 @@ const encodeSnapshot = Schema.encodeEffect(Json.Snapshot); const decodeSnapshot = Schema.decodeUnknownEffect(Json.Snapshot); /** - * Keeps a copy of each followed session in kv and publishes what changes on the session's topic. - * The copy is CodeWork's own conversation (`session.history`), refetched whenever the session's - * durable log moves, so this backend never folds the stored events itself. What CodeWork only says - * live, a reply's text as it streams and whether the agent works, it relays as it happens. + * Keeps a copy of each followed thread in kv and publishes what changes on that thread's topic. + * The copy is that thread's conversation (`thread.history`), refetched whenever its durable log + * moves, so this backend never folds the stored events itself. What CodeWork only says live, a + * reply's text as it streams and whether the agent works, it relays as it happens, for that thread + * alone. A follow that names no thread is the session's main thread. */ export const session = defineBackend({ package: "codework", @@ -136,8 +151,8 @@ export const session = defineBackend({ const scope = yield* Effect.scope; // A snapshot that no longer decodes was stored by an older build: it is seeded again. - const load = (id: string) => - kv.get(snapshotKey(id)).pipe( + const load = (key: string) => + kv.get(snapshotKey(key)).pipe( Effect.flatMap( Option.match({ onNone: () => Effect.succeed(undefined), @@ -154,6 +169,7 @@ export const session = defineBackend({ string, { readonly sessionId: string; + readonly threadId: string; message: HistoryEntry; // Keyed by the part index deltas carry, which can skip parts that stream no text. readonly parts: Map; @@ -161,32 +177,46 @@ export const session = defineBackend({ >(); // Drafts changed since they were last published. const dirty = new Set(); - // Each session's latest snapshot, so a delta can start from the draft CodeWork stored. + // Each followed thread's latest snapshot, by its {@link threadKey}. const latest = new Map(); + // The concrete thread id `thread.info` named for each follow. Live events match this, not the address. + const open = new Map(); + + const keysFor = (event: { readonly sessionId: string; readonly threadId: string }) => + [...open.entries()] + .filter(([, followed]) => followed.sessionId === event.sessionId && followed.threadId === event.threadId) + .map(([key]) => key); + + /** The RPC address: the concrete thread once known, else the request (`threadId` absent is the main thread). */ + const addressed = (ref: ThreadRef) => { + const threadId = ref.threadId ?? open.get(threadKey(ref))?.threadId; + return threadId === undefined ? { sessionId: ref.sessionId } : { sessionId: ref.sessionId, threadId }; + }; /** A draft reads as streamed so far; a reply that has ended stops streaming. */ const withStreamed = (entries: ReadonlyArray) => entries.map((entry) => { const streamed = streaming.get(entry.id); - if (streamed === undefined) return entry; + if (streamed === undefined || streamed.threadId !== entry.threadId) return entry; if (entry.state !== "draft") { streaming.delete(entry.id); dirty.delete(entry.id); return entry; } - streamed.message = { ...entry, parts: streamed.message.parts }; + streamed.message = { ...entry, parts: mergeParts(entry.parts, streamed.parts) }; return streamed.message; }); /** Refetches the conversation, publishes what changed, then stores the snapshot. */ - const refresh = Effect.fn("Session.refresh")(function* (id: string, cursor: number | undefined) { + const refresh = Effect.fn("Session.refresh")(function* (ref: ThreadRef, cursor: number | undefined) { + const key = threadKey(ref); + const target = addressed(ref); // In this order: a prompt promoted between the queue and history reads is then in both, never in neither. - const { info, queue, history } = yield* Effect.all({ - info: codework("thread.info", { sessionId: id }), - queue: codework("thread.queue", { sessionId: id }), - history: codework("thread.history", { sessionId: id }), - }); - const before = yield* load(id); + const info = yield* codework("thread.info", target); + open.set(key, { sessionId: ref.sessionId, threadId: info.id }); + const queue = yield* codework("thread.queue", target); + const history = yield* codework("thread.history", target); + const before = yield* load(key); const next = toInfo(info); const messages = withStreamed(history.entries); // One that is in both has been promoted: the conversation wins. @@ -196,7 +226,7 @@ export const session = defineBackend({ // Published before the snapshot is stored, so a view never holds a snapshot newer than its cursor. for (const update of changes(before, next, messages, queued)) { const payload = yield* encodeUpdate(update).pipe(Effect.orDie); - seq = (yield* bus.publish({ topic: topics.session(id), payload })).seq ?? seq; + seq = (yield* bus.publish({ topic: topics.thread(key), payload })).seq ?? seq; } // A history entry's seq is its place in the durable log, so the newest one is where to resume. const resume = cursor ?? before?.cursor ?? history.entries.at(-1)?.seq; @@ -207,34 +237,42 @@ export const session = defineBackend({ seq, ...(resume === undefined ? {} : { cursor: resume }), }; - yield* kv.set(snapshotKey(id), yield* encodeSnapshot(snapshot).pipe(Effect.orDie)); - latest.set(id, snapshot); + yield* kv.set(snapshotKey(key), yield* encodeSnapshot(snapshot).pipe(Effect.orDie)); + latest.set(key, snapshot); return snapshot; }); - /** Publishes to the session's live subscribers without storing it. */ - const publishLive = (sessionId: string, update: Update) => + /** Publishes to the thread's live subscribers without storing it. */ + const publishLive = (key: string, update: Update) => encodeUpdate(update).pipe( Effect.orDie, - Effect.flatMap((payload) => bus.publish({ topic: topics.session(sessionId), payload, ephemeral: true })), + Effect.flatMap((payload) => bus.publish({ topic: topics.thread(key), payload, ephemeral: true })), Effect.asVoid, ); + const publishEach = (event: { readonly sessionId: string; readonly threadId: string }, update: Update) => + Effect.forEach(keysFor(event), (key) => publishLive(key, update), { discard: true }); + /** Folds what CodeWork only says live: deltas into their drafts, and whether the agent works. */ const observe = (envelope: EventEnvelope): Effect.Effect => { switch (envelope.type) { case "session.llm.text.delta": case "session.llm.thinking.delta": { const delta = Option.getOrUndefined(decodeDelta(envelope.data)); - if (delta === undefined || !following.has(delta.sessionId)) return Effect.void; + const keys = delta === undefined ? [] : keysFor(delta); + if (delta === undefined || keys.length === 0) return Effect.void; return Effect.sync(() => { const streamed = streaming.get(delta.messageId); + // Until the conversation lists the reply, only its parts are kept: it is not published before then. const draft = streamed?.message ?? - latest.get(delta.sessionId)?.messages.find((message) => message.id === delta.messageId) ?? { + keys + .map((key) => latest.get(key)?.messages.find((message) => message.id === delta.messageId)) + .find((message) => message !== undefined) ?? { id: delta.messageId, - seq: latest.get(delta.sessionId)?.cursor ?? 0, - role: "assistant", - state: "draft", + threadId: delta.threadId, + seq: latest.get(keys[0] ?? "")?.cursor ?? 0, + role: "assistant" as const, + state: "draft" as const, createdAt: delta.timestamp, updatedAt: delta.timestamp, parts: [], @@ -242,10 +280,11 @@ export const session = defineBackend({ const kind = envelope.type === "session.llm.text.delta" ? "text" : "thinking"; const parts = streamed?.parts ?? new Map(); parts.set(delta.partIndex, fold(parts.get(delta.partIndex), kind, delta.delta)); - const ordered = [...parts.entries()].sort(([a], [b]) => a - b).map(([, part]) => part); + const ordered = mergeParts(draft.parts, parts); streaming.set(delta.messageId, { sessionId: delta.sessionId, - message: { ...draft, parts: ordered }, + threadId: delta.threadId, + message: { ...draft, threadId: delta.threadId, parts: ordered }, parts, }); dirty.add(delta.messageId); @@ -255,10 +294,10 @@ export const session = defineBackend({ // in the session's log records it: this is the only place the reason shows. case "session.execution.failed": { const failed = Option.getOrUndefined(decodeFailed(envelope.data)); - if (failed === undefined || !following.has(failed.sessionId)) return Effect.void; - return publishLive(failed.sessionId, { _tag: "Running", running: false }).pipe( + if (failed === undefined || keysFor(failed).length === 0) return Effect.void; + return publishEach(failed, { _tag: "Running", running: false }).pipe( Effect.andThen( - publishLive(failed.sessionId, { + publishEach(failed, { _tag: "Failed", kind: failed.error.type, message: failed.error.message, @@ -269,9 +308,9 @@ export const session = defineBackend({ case "session.execution.started": case "session.execution.succeeded": case "session.execution.interrupted": { - const sessionId = Option.getOrUndefined(decodeOfSession(envelope.data))?.sessionId; - if (sessionId === undefined || !following.has(sessionId)) return Effect.void; - return publishLive(sessionId, { + const event = Option.getOrUndefined(decodeOfThread(envelope.data)); + if (event === undefined || keysFor(event).length === 0) return Effect.void; + return publishEach(event, { _tag: "Running", running: envelope.type === "session.execution.started", }); @@ -281,17 +320,31 @@ export const session = defineBackend({ } }; - // Drafts go out at most every 50ms, however fast the deltas arrive. + // Drafts go out at most every 50ms, however fast the deltas arrive. A draft waits until the + // conversation lists it, so a view never has it ahead of the prompt it answers. const flush = Effect.suspend(() => { - const ids = [...dirty]; - dirty.clear(); + const ids = [...dirty].filter((id) => { + const streamed = streaming.get(id); + return ( + streamed !== undefined && + keysFor(streamed).some((key) => latest.get(key)?.messages.some((message) => message.id === id)) + ); + }); return Effect.forEach( ids, (id) => { const streamed = streaming.get(id); - return streamed === undefined - ? Effect.void - : publishLive(streamed.sessionId, { _tag: "Message", message: streamed.message }); + if (streamed === undefined) return Effect.void; + const keys = keysFor(streamed).filter((key) => + latest.get(key)?.messages.some((message) => message.id === id), + ); + const waiting = keysFor(streamed).some( + (key) => !latest.get(key)?.messages.some((message) => message.id === id), + ); + if (!waiting) dirty.delete(id); + return Effect.forEach(keys, (key) => publishLive(key, { _tag: "Message", message: streamed.message }), { + discard: true, + }); }, { discard: true }, ); @@ -299,31 +352,38 @@ export const session = defineBackend({ const following = new Map>(); - /** Seeds, answers `ready`, then refreshes on every move of the session's durable log. */ - const sync = (id: string, ready: Deferred.Deferred) => - Effect.gen(function* () { - const seeded = yield* refresh(id, undefined); + /** Seeds, answers `ready`, then refreshes on every move of this thread's durable log. */ + const sync = (ref: ThreadRef, ready: Deferred.Deferred) => { + const key = threadKey(ref); + const missed = (error: { readonly _tag: string }) => + Deferred.succeed(ready, { _tag: "Failed" as const, message: describe(error) }).pipe( + Effect.andThen(Effect.sync(() => following.delete(key))), + ); + return Effect.gen(function* () { + const seeded = yield* refresh(ref, undefined); + const threadId = open.get(key)?.threadId; yield* Deferred.succeed(ready, { _tag: "Done" }); yield* codework("session.log", { - sessionId: id, + sessionId: ref.sessionId, + ...(threadId === undefined ? {} : { threadId }), follow: true, ...(seeded.cursor === undefined ? {} : { after: seeded.cursor }), }).pipe( Stream.map((item) => ("id" in item ? item.durable?.seq : item.seq)), // A turn commits several events at once; one refetch covers them all. Stream.debounce("50 millis"), - Stream.runForEach((seq) => refresh(id, seq)), + Stream.runForEach((seq) => refresh(ref, seq)), ); }).pipe( - Effect.catchTag("SessionNotFoundError", (error) => - Deferred.succeed(ready, { _tag: "Failed", message: describe(error) }).pipe( - Effect.andThen(Effect.sync(() => following.delete(id))), - ), - ), + Effect.catchTags({ + SessionNotFoundError: missed, + ThreadNotFoundError: missed, + }), // The connection dropped: start over from the stored cursor once it is back. Effect.retry(Schedule.spaced("1 second")), - Effect.repeat({ while: () => following.has(id), schedule: Schedule.spaced("1 second") }), + Effect.repeat({ while: () => following.has(key), schedule: Schedule.spaced("1 second") }), ); + }; // Both loops outlive anything that stops them, a defect included, and say what it was: one that // stopped quietly would freeze every view's live updates while sends still went through. @@ -341,22 +401,29 @@ export const session = defineBackend({ ); /** - * Stops following a session once no view has watched its topic for a while: a view watches + * Stops following a thread once no view has watched its topic for a while: a view watches * from just after it follows until its frame closes, and a closed window stops watching too. * The snapshot stays in kv, so the next follow refreshes it rather than seeding again. */ - const release = (sessionId: string, syncing: Fiber.Fiber) => - bus.watchers(topics.session(sessionId)).pipe( + const release = (key: string, syncing: Fiber.Fiber) => + bus.watchers(topics.thread(key)).pipe( // Long enough to cover a view between its follow and its subscription, or a quick reopen. Stream.debounce("30 seconds"), Stream.filter((count) => count === 0), Stream.runHead, Effect.andThen( Effect.sync(() => { - following.delete(sessionId); - latest.delete(sessionId); + const followed = open.get(key); + following.delete(key); + latest.delete(key); + open.delete(key); + if (followed === undefined) return; + const still = [...open.values()].some( + (item) => item.sessionId === followed.sessionId && item.threadId === followed.threadId, + ); + if (still) return; for (const [id, streamed] of streaming) { - if (streamed.sessionId !== sessionId) continue; + if (streamed.sessionId !== followed.sessionId || streamed.threadId !== followed.threadId) continue; streaming.delete(id); dirty.delete(id); } @@ -365,14 +432,15 @@ export const session = defineBackend({ Effect.andThen(Fiber.interrupt(syncing)), ); - yield* handle(topics.follow, Follow, ({ sessionId }) => + yield* handle(topics.follow, Follow, (ref) => Effect.gen(function* () { - let ready = following.get(sessionId); + const key = threadKey(ref); + let ready = following.get(key); if (ready === undefined) { ready = yield* Deferred.make(); - following.set(sessionId, ready); - const syncing = yield* Effect.forkIn(sync(sessionId, ready), scope); - yield* Effect.forkIn(release(sessionId, syncing), scope); + following.set(key, ready); + const syncing = yield* Effect.forkIn(sync(ref, ready), scope); + yield* Effect.forkIn(release(key, syncing), scope); } return yield* encodeReply(yield* Deferred.await(ready)).pipe(Effect.orDie); }), @@ -382,9 +450,11 @@ export const session = defineBackend({ yield* handle( topics.page, Page, - ({ sessionId, before, limit }) => + (ref) => Effect.gen(function* () { - const snapshot = latest.get(sessionId) ?? (yield* load(sessionId)); + const { before, limit } = ref; + const key = threadKey(ref); + const snapshot = latest.get(key) ?? (yield* load(key)); if (snapshot === undefined) { return yield* encodeWindow({ _tag: "Failed", message: "Follow the session before paging it." }).pipe( Effect.orDie, @@ -411,9 +481,9 @@ export const session = defineBackend({ { ephemeral: true }, ); - const prompt = ({ sessionId, messageId, text, delivery }: Prompt) => + const prompt = ({ messageId, text, delivery, ...ref }: Prompt) => codework("thread.prompt", { - sessionId, + ...addressed(ref), text, id: messageId, ...(delivery === undefined ? {} : { delivery }), @@ -448,10 +518,10 @@ export const session = defineBackend({ ), ); - // The session's own log moves with the change, so the refresh that follows publishes the new info. - yield* handle(topics.configure, Configure, ({ sessionId, model, thinkingLevel }) => + // The thread's log moves with the change, so the refresh that follows publishes the new info. + yield* handle(topics.configure, Configure, ({ model, thinkingLevel, ...ref }) => codework("thread.configure", { - sessionId, + ...addressed(ref), runtime: { ...(model === undefined ? {} : { model }), ...(thinkingLevel === undefined ? {} : { thinkingLevel }), @@ -465,17 +535,17 @@ export const session = defineBackend({ // A cancel that lost to promotion answers `Sent`: the prompt is in the conversation, and the // refresh that follows the log moving shows it there. - yield* handle(topics.cancel, Cancel, ({ sessionId, messageId }) => - codework("thread.cancel", { sessionId, messageId }).pipe( + yield* handle(topics.cancel, Cancel, ({ messageId, ...ref }) => + codework("thread.cancel", { ...addressed(ref), messageId }).pipe( Effect.map(({ cancelled }): Cancelled => (cancelled ? { _tag: "Cancelled" } : { _tag: "Sent" })), Effect.catch((error) => Effect.succeed({ _tag: "Failed", message: describe(error) })), Effect.flatMap((reply) => encodeCancelled(reply).pipe(Effect.orDie)), ), ); - yield* handle(topics.change, Change, ({ sessionId, messageId, delivery, text }) => + yield* handle(topics.change, Change, ({ messageId, delivery, text, ...ref }) => codework("thread.update", { - sessionId, + ...addressed(ref), messageId, ...(delivery === undefined ? {} : { delivery }), ...(text === undefined ? {} : { text }), @@ -488,8 +558,8 @@ export const session = defineBackend({ ), ); - yield* handle(topics.interrupt, Interrupt, ({ sessionId }) => - codework("session.interrupt", { sessionId }).pipe( + yield* handle(topics.interrupt, Interrupt, (ref) => + codework("thread.interrupt", addressed(ref)).pipe( Effect.as({ _tag: "Done" }), Effect.catch((error) => Effect.succeed({ _tag: "Failed", message: describe(error) })), Effect.flatMap((reply) => encodeReply(reply).pipe(Effect.orDie)), diff --git a/apps/web/src/widgets/session/composer.tsx b/apps/web/src/widgets/session/composer.tsx index 88afdd27..5f0d6c03 100644 --- a/apps/web/src/widgets/session/composer.tsx +++ b/apps/web/src/widgets/session/composer.tsx @@ -6,7 +6,7 @@ import { useEffect, useRef, useState } from "react"; import { PromptComposer, ComposerHeader, ComposerSubmit, ComposerButton, type Submit } from "@/components/composer"; import { ModelPicker, type ModelRef, ThinkingPicker } from "@/components/model"; import type { Delivery, ThinkingLevel } from "@codeworksh/widget/codework"; -import { type Info, Json, topics } from "./schema"; +import { type Info, Json, type ThreadRef, topics } from "./schema"; const decodeReply = Schema.decodeUnknownOption(Json.Reply); const encodePrompt = Schema.encodeSync(Json.Prompt); @@ -25,18 +25,18 @@ const unreachable = "The CodeWork server is not reachable."; * an id the view chooses for the user message it becomes; the message itself arrives as an update. * The text stays until the backend accepts it, and the unsent draft survives a remount. * - * The model and reasoning pickers show the session's own choice, which CodeWork keeps with the - * session; a pick shows at once and is sent as a configure request, applying from the next exchange. + * The model and reasoning pickers show the thread's own choice, which CodeWork keeps with the + * thread; a pick shows at once and is sent as a configure request, applying from the next exchange. */ export function SessionComposer({ - sessionId, + thread, instanceId, running, info, onError, restored, }: { - readonly sessionId: string; + readonly thread: ThreadRef; readonly instanceId: string; readonly running: boolean; readonly info: Info; @@ -164,7 +164,7 @@ export function SessionComposer({ const sent = await ask( topics.prompt, encodePrompt({ - sessionId, + ...thread, messageId: crypto.randomUUID(), text: prompt, ...(delivery === undefined ? {} : { delivery }), @@ -176,7 +176,7 @@ export function SessionComposer({ const configure = (change: { model?: ModelRef; thinkingLevel?: ThinkingLevel }) => { setPicked((current) => ({ ...current, ...change })); - void ask(topics.configure, encodeConfigure({ sessionId, ...change })); + void ask(topics.configure, encodeConfigure({ ...thread, ...change })); }; const empty = text.trim() === ""; @@ -230,7 +230,7 @@ export function SessionComposer({ actions={ <> {running && ( - void ask(topics.interrupt, { sessionId })}> + void ask(topics.interrupt, { ...thread })}> )} diff --git a/apps/web/src/widgets/session/index.ts b/apps/web/src/widgets/session/index.ts index 14192762..2d3b643e 100644 --- a/apps/web/src/widgets/session/index.ts +++ b/apps/web/src/widgets/session/index.ts @@ -4,7 +4,7 @@ import { MessageSquare } from "lucide-react"; import { Session } from "./view"; -/** One session's conversation, opened by its `codework://session/` address. */ +/** One thread's conversation: `codework://session/` for a session's main thread, `…//` for another. */ export const session = defineWidget({ kind: "codework:session", title: "Session", @@ -13,7 +13,7 @@ export const session = defineWidget({ minHeight: 200, cardinality: "many", priority: "builtin", - opens: ["codework://session/*"], + opens: ["codework://session/*", "codework://session/*/*"], ownsTab: true, replaceable: true, props: Schema.Struct({}), diff --git a/apps/web/src/widgets/session/queue.tsx b/apps/web/src/widgets/session/queue.tsx index b17d1ea6..5af7be54 100644 --- a/apps/web/src/widgets/session/queue.tsx +++ b/apps/web/src/widgets/session/queue.tsx @@ -4,7 +4,7 @@ import { Option, Schema } from "effect"; import { CornerDownRight, ListEnd, type LucideIcon, Pencil, SendHorizontal, Trash2, Undo2 } from "lucide-react"; import { useRef, useState } from "react"; -import { Json, topics } from "./schema"; +import { Json, type ThreadRef, topics } from "./schema"; const decodeReply = Schema.decodeUnknownOption(Json.Reply); const decodeCancelled = Schema.decodeUnknownOption(Json.Cancelled); @@ -21,13 +21,13 @@ const unreachable = "The CodeWork server is not reachable."; * the queue next updates. */ export function Queue({ - sessionId, + thread, queued, running, onError, onRestore, }: { - readonly sessionId: string; + readonly thread: ThreadRef; readonly queued: readonly QueuedPrompt[]; readonly running: boolean; readonly onError: (message: string | undefined) => void; @@ -70,7 +70,7 @@ export function Queue({ act(prompt.id, async () => { const answer = await bus.request({ topic: topics.change, - payload: { sessionId, messageId: prompt.id, ...patch }, + payload: { ...thread, messageId: prompt.id, ...patch }, }); const reply = decodeReply(answer.payload); if (Option.isSome(reply) && reply.value._tag === "Failed") onError(reply.value.message); @@ -79,7 +79,7 @@ export function Queue({ // Undo restores only what it took back: a prompt the agent already took in stays in the conversation. const cancel = (prompt: QueuedPrompt, restore: boolean) => act(prompt.id, async () => { - const answer = await bus.request({ topic: topics.cancel, payload: { sessionId, messageId: prompt.id } }); + const answer = await bus.request({ topic: topics.cancel, payload: { ...thread, messageId: prompt.id } }); const reply = Option.getOrUndefined(decodeCancelled(answer.payload)); if (reply?._tag === "Failed") onError(reply.message); else if (reply?._tag === "Cancelled" && restore) onRestore(prompt.text); diff --git a/apps/web/src/widgets/session/schema.ts b/apps/web/src/widgets/session/schema.ts index eb242af1..e4241d75 100644 --- a/apps/web/src/widgets/session/schema.ts +++ b/apps/web/src/widgets/session/schema.ts @@ -6,32 +6,43 @@ import { Schema } from "effect"; * halves import this file, so it stays free of React and the DOM. */ +/** A thread of a session: `threadId`, or the session's main thread when absent. */ +export const ThreadRef = Schema.Struct({ sessionId: Schema.String, threadId: Schema.optionalKey(Schema.String) }); +export type ThreadRef = typeof ThreadRef.Type; + +/** + * What names a thread in addresses, topics and kv: its session's id for the main thread, else + * `/`. The main thread is never named by its own id, so it has one key. + */ +export const threadKey = ({ sessionId, threadId }: ThreadRef) => + threadId === undefined ? sessionId : `${sessionId}/${threadId}`; + export const topics = { - /** Requests: start following a session; answered once its snapshot is stored. */ + /** Requests: start following a thread; answered once its snapshot is stored. */ follow: "codework/session.follow", /** Requests: create a session and send its first prompt; answered with its id. */ create: "codework/session.create", prompt: "codework/session.prompt", - /** Requests: choose a session's model or thinking level; they apply from its next turn. */ + /** Requests: choose a thread's model or thinking level; they apply from its next turn. */ configure: "codework/session.configure", interrupt: "codework/session.interrupt", /** Requests: withdraw a queued prompt before the agent takes it in; answered with `Cancelled`. */ cancel: "codework/session.cancel", /** Requests: move a queued prompt to the other lane, or rewrite it, in place. */ change: "codework/session.change", - /** Requests: a window of a followed session's conversation, newest first back from `before`. */ + /** Requests: a window of a followed thread's conversation, newest first back from `before`. */ page: "codework/session.page", - /** Updates to one session's conversation. */ - session: (id: string) => `codework/session/${id}`, + /** Updates to one thread's conversation, by its {@link threadKey}. */ + thread: (key: string) => `codework/session/${key}`, }; -/** The kv key of a session's snapshot. */ -export const snapshotKey = (id: string) => `session/${id}`; +/** The kv key of a thread's snapshot, by its {@link threadKey}. */ +export const snapshotKey = (key: string) => `session/${key}`; -export const Follow = Schema.Struct({ sessionId: Schema.String }); +export const Follow = ThreadRef; export const Prompt = Schema.Struct({ - sessionId: Schema.String, + ...ThreadRef.fields, /** Chosen by the view: the id of the user message this prompt becomes. */ messageId: Schema.String, text: Schema.String, @@ -65,9 +76,9 @@ export const Created = Schema.Union([ ]); export type Created = typeof Created.Type; -export const Interrupt = Schema.Struct({ sessionId: Schema.String }); +export const Interrupt = ThreadRef; -export const Cancel = Schema.Struct({ sessionId: Schema.String, messageId: Schema.String }); +export const Cancel = Schema.Struct({ ...ThreadRef.fields, messageId: Schema.String }); /** The answer to a cancel: withdrawn, already in the conversation, or why neither is known. */ export const Cancelled = Schema.Union([ @@ -79,22 +90,22 @@ export type Cancelled = typeof Cancelled.Type; /** A queued prompt moved to `delivery`, or given new `text`; an absent key is left as it is. */ export const Change = Schema.Struct({ - sessionId: Schema.String, + ...ThreadRef.fields, messageId: Schema.String, delivery: Schema.optionalKey(Delivery), text: Schema.optionalKey(Schema.String), }); -/** A model or thinking level chosen for a session; an absent key is left as it is. */ +/** A model or thinking level chosen for a thread; an absent key is left as it is. */ export const Configure = Schema.Struct({ - sessionId: Schema.String, + ...ThreadRef.fields, model: Schema.optionalKey(Schema.Struct({ provider: Schema.String, id: Schema.String })), thinkingLevel: Schema.optionalKey(ThinkingLevel), }); export type Configure = typeof Configure.Type; export const Page = Schema.Struct({ - sessionId: Schema.String, + ...ThreadRef.fields, /** The oldest message the view holds; omitted asks for the newest messages. */ before: Schema.optionalKey(Schema.String), limit: Schema.Int, diff --git a/apps/web/src/widgets/session/view.tsx b/apps/web/src/widgets/session/view.tsx index a339f2fb..23cfedc0 100644 --- a/apps/web/src/widgets/session/view.tsx +++ b/apps/web/src/widgets/session/view.tsx @@ -8,13 +8,13 @@ import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef, useState import { ComposerNotice, type Notice } from "@/components/banner"; import { Monogram } from "@/components/monogram"; import { useModelsNotice } from "@/components/model"; -import { sessionId } from "./address"; +import { threadRef } from "./address"; import { SessionComposer } from "./composer"; import { Markdown } from "./markdown"; import { Message } from "./message"; import { Queue } from "./queue"; import { useListedSession } from "./projects"; -import { type Info, Json, topics, type Update } from "./schema"; +import { type Info, Json, type ThreadRef, threadKey, topics, type Update } from "./schema"; const decodeReply = Schema.decodeUnknownOption(Json.Reply); const decodeWindow = Schema.decodeUnknownOption(Json.Window); @@ -27,9 +27,9 @@ const PAGE = 60; const contentWidth = "mx-auto w-full max-w-[62rem]"; export function Session({ address, instanceId }: WidgetProps) { - const id = sessionId(address); - if (id === undefined) return

Not a session: {address}

; - return ; + const thread = useMemo(() => threadRef(address), [address]); + if (thread === undefined) return

Not a session: {address}

; + return ; } type State = @@ -106,11 +106,11 @@ const apply = (state: State, update: Update): State => { }; /** - * Asks the session backend to follow the session, loads its newest page, then applies every update + * Asks the session backend to follow the thread, loads its newest page, then applies every update * published after that page. Older pages load on demand. A dropped connection resumes where it * left off. */ -function useConversation(id: string) { +function useConversation(thread: ThreadRef) { const bus = useBus(); const [state, setState] = useState({ status: "loading" }); const paging = useRef(false); @@ -121,13 +121,13 @@ function useConversation(id: string) { ( await bus.request({ topic: topics.page, - payload: { sessionId: id, limit: PAGE, ...(before === undefined ? {} : { before }) }, + payload: { ...thread, limit: PAGE, ...(before === undefined ? {} : { before }) }, }) ).payload, ); return Option.getOrUndefined(reply); }, - [bus, id], + [bus, thread], ); useEffect(() => { @@ -136,10 +136,10 @@ function useConversation(id: string) { if (active) setState({ status: "failed", message }); }; void (async () => { - const reply = decodeReply((await bus.request({ topic: topics.follow, payload: { sessionId: id } })).payload); + const reply = decodeReply((await bus.request({ topic: topics.follow, payload: thread })).payload); if (Option.isSome(reply) && reply.value._tag === "Failed") return fail(reply.value.message); const window = await page(undefined); - if (window === undefined) return fail(`Could not load session ${id}.`); + if (window === undefined) return fail(`Could not load session ${threadKey(thread)}.`); if (window._tag === "Failed") return fail(window.message); const { info, messages, more, queued, seq } = window; if (active) setState({ status: "ready", info, messages, more, queued, after: seq, running: undefined }); @@ -147,10 +147,10 @@ function useConversation(id: string) { return () => { active = false; }; - }, [bus, id, page]); + }, [bus, thread, page]); const after = state.status === "ready" ? state.after : undefined; - useEvents(after === undefined ? undefined : { topics: [topics.session(id)], after }, (item) => { + useEvents(after === undefined ? undefined : { topics: [topics.thread(threadKey(thread))], after }, (item) => { if ("_tag" in item) return; const update = decodeUpdate(item.payload); if (Option.isSome(update)) setState((current) => apply(current, update.value)); @@ -178,11 +178,11 @@ function useConversation(id: string) { return { state, loadOlder }; } -function Conversation({ id, instanceId }: { readonly id: string; readonly instanceId: string }) { +function Conversation({ thread, instanceId }: { readonly thread: ThreadRef; readonly instanceId: string }) { const { setTitle, setIcon, setTab } = useFrame(); - const { state, loadOlder } = useConversation(id); + const { state, loadOlder } = useConversation(thread); // Named from the sessions list at once, so the frame never shows its default title while loading. - const listed = useListedSession(id); + const listed = useListedSession(thread.sessionId); const title = state.status === "ready" ? state.info.title : listed?.title; const project = state.status === "ready" ? state.info.project : listed?.project; const projectId = project?.id; @@ -253,7 +253,7 @@ function Conversation({ id, instanceId }: { readonly id: string; readonly instan {/* Idle too: prompts left waiting by a stop or a failure run with the next message, so they stay in view. */} {state.queued.length > 0 && ( )} + RpcClient.layerProtocolSocket().pipe( + Layer.provide(Socket.layerWebSocket(url)), + Layer.provide(Socket.layerWebSocketConstructorGlobal), + Layer.provide(RpcSerialization.layerNdjson), + ); + +it("desktop keeps fork history, configuration and prompts separate from main", async () => { + const home = mkdtempSync(join(tmpdir(), "codework-desktop-threads-")); + try { + const artifact = await Effect.gen(function* () { + const listener = yield* HttpServer.HttpServer; + if (listener.address._tag === "UnixPathAddress") return yield* Effect.die("Expected TCP listener"); + const url = `ws://127.0.0.1:${listener.address.port}/rpc/v1`; + const rpcContext = yield* Layer.build(Client.layer(url)); + const rpc = yield* Client.make.pipe(Effect.provideContext(rpcContext)); + const mirrorContext = yield* Layer.build(protocol(url)); + const mirror = yield* RpcClient.make(Mirror.Api).pipe(Effect.provideContext(mirrorContext)); + const created = yield* mirror["session.create"]({ directory: home }); + const sessionId = Session.SessionSchema.ID.make(created.session.id); + yield* mirror["thread.prompt"]({ sessionId, text: "Main prompt" }); + yield* rpc["thread.wait"]({ sessionId }); + const history = yield* rpc["thread.history"]({ sessionId }); + const fork = yield* rpc["thread.fork"]({ sessionId, entryId: history.entries.at(-1)!.id }); + const ref = { sessionId, threadId: fork.thread.id }; + const child = yield* Effect.acquireRelease( + Effect.sync(() => + spawn(process.execPath, [fileURLToPath(new URL("../../../apps/server/src/index.ts", import.meta.url))], { + env: { ...process.env, CODEWORK_HOME_DIR: home, CODEWORK_DATABASE: join(home, "app.db") }, + stdio: ["ignore", "pipe", "inherit"], + }), + ), + (child) => + Effect.promise( + () => + new Promise((resolve) => { + if (child.exitCode !== null || child.signalCode !== null) return resolve(); + child.once("exit", () => resolve()); + child.kill("SIGKILL"); + }), + ), + ); + const port = yield* Effect.tryPromise( + () => + new Promise((resolve, reject) => { + child.once("exit", (code) => reject(new Error(`App server exited: ${code}`))); + createInterface({ input: child.stdout! }).on("line", (line) => { + if (line.startsWith('{"type":"ready"')) resolve((JSON.parse(line) as { port: number }).port); + }); + }), + ); + const appContext = yield* Layer.build(protocol(`ws://127.0.0.1:${port}/rpc`)); + const app = yield* RpcClient.make(Desktop.Api).pipe(Effect.provideContext(appContext)); + const ask = (topic: string, payload: Schema.Json) => app["event.request"]({ topic, payload, source: "test" }); + for (const target of [{ sessionId }, ref]) + expect((yield* ask(topics.follow, target)).payload).toEqual({ _tag: "Done" }); + expect((yield* ask(topics.configure, { ...ref, thinkingLevel: "high" })).payload).toEqual({ _tag: "Done" }); + expect((yield* mirror["thread.info"](ref)).thinkingLevel).toBe("high"); + expect((yield* mirror["thread.info"]({ sessionId })).thinkingLevel).toBeUndefined(); + expect((yield* ask(topics.prompt, { ...ref, messageId: "fork-prompt", text: "Fork prompt" })).payload).toEqual( + { _tag: "Done" }, + ); + yield* rpc["thread.wait"](ref); + yield* app["event.subscribe"]({ topics: [topics.thread(threadKey(ref))], after: 0 }).pipe( + Stream.filter( + (item) => + "payload" in item && + Schema.is(Json.Update)(item.payload) && + item.payload._tag === "Message" && + item.payload.message.state === "committed" && + item.payload.message.parts.some((part) => part.type === "text" && part.text === "response 2"), + ), + Stream.runHead, + ); + const page = (target: ThreadRef) => + ask(topics.page, { ...target, limit: 60 }).pipe( + Effect.flatMap((reply) => Schema.decodeUnknownEffect(Json.Window)(reply.payload)), + ); + const main = yield* page({ sessionId }); + const branch = yield* page(ref); + if (main._tag !== "Window" || branch._tag !== "Window") return yield* Effect.die("Missing page"); + expect(main.messages).toHaveLength(2); + expect(branch.messages).toHaveLength(4); + expect(branch.messages.slice(0, 2).every((entry) => entry.threadId === created.id)).toBe(true); + expect(branch.messages.slice(2).every((entry) => entry.threadId === fork.thread.id)).toBe(true); + const missing = yield* ask(topics.follow, { sessionId, threadId: "thr_missing" }); + expect(missing.payload).toEqual({ _tag: "Failed", message: "This thread no longer exists." }); + return { + main: main.messages.map(({ role, state, parts }) => ({ role, state, parts })), + fork: branch.messages.map(({ role, state, parts }) => ({ role, state, parts })), + missing: missing.payload, + }; + }).pipe( + Effect.scoped, + Effect.provide( + Server.layer({ + host: "127.0.0.1", + port: 0, + harness: { home, hostCwd: home, plugins: [], llm: immediateOpen() }, + }), + ), + Effect.timeout("30 seconds"), + Effect.runPromise, + ); + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot( + "./__artifacts__/desktop.threads.json", + ); + } finally { + rmSync(home, { recursive: true, force: true }); + } +}, 40_000);