From 3518013b18cae88605adf0a682e913cbece96bea Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:12:09 -0600 Subject: [PATCH 01/43] feat(ai): add the xAI video entrypoint and keep video provider options (#63707) --- packages/ai/package.json | 1 + packages/ai/src/providers/google.ts | 8 +++++-- packages/ai/src/providers/xai.ts | 7 +++++- packages/ai/src/providers/xai/videos.ts | 2 ++ .../test/provider/media-entrypoints.test.ts | 24 +++++++++++++++++++ packages/core/src/provider.ts | 1 + 6 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 packages/ai/src/providers/xai/videos.ts diff --git a/packages/ai/package.json b/packages/ai/package.json index a7cc15c710c6..4225e67ebdc2 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -136,6 +136,7 @@ "./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts", "./providers/xai": "./src/providers/xai.ts", "./providers/xai/images": "./src/providers/xai/images.ts", + "./providers/xai/videos": "./src/providers/xai/videos.ts", "./providers/zai": "./src/providers/zai.ts", "./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts", "./providers/zai-coding-plan/chat": "./src/providers/zai-coding-plan/chat.ts", diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts index 902eab299b22..a1143b5ebb03 100644 --- a/packages/ai/src/providers/google.ts +++ b/packages/ai/src/providers/google.ts @@ -74,7 +74,8 @@ export const configure = (input: Config = {}) => { interactionsRoute(input).model({ id: modelID }), image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => GoogleImages.model({ ...media, id: modelID, providerOptions }), - video: (modelID: string | ModelID) => GoogleInteractionsVideo.model({ ...media, id: modelID }), + video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + GoogleInteractionsVideo.model({ ...media, id: modelID, providerOptions }), speech: (modelID: string | ModelID) => GoogleSpeech.model({ ...media, id: modelID }), transcription: (modelID: string | ModelID) => GoogleTranscription.model({ ...media, id: modelID }), embedding: (modelID: string | ModelID, providerOptions?: ProviderOptions) => @@ -94,7 +95,10 @@ export const imageModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).image(modelID, input.providerOptions) } -export const videoModel = (modelID: string, settings?: Settings) => configure(toConfig(settings)).video(modelID) +export const videoModel = (modelID: string, settings?: Settings) => { + const input = toConfig(settings) + return configure(input).video(modelID, input.providerOptions) +} export const embeddingModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).embedding(modelID, input.providerOptions) diff --git a/packages/ai/src/providers/xai.ts b/packages/ai/src/providers/xai.ts index ef2ce340b960..6b659a2c7c0d 100644 --- a/packages/ai/src/providers/xai.ts +++ b/packages/ai/src/providers/xai.ts @@ -100,7 +100,8 @@ export const configure = (input: Config = {}) => { chat, image: (modelID: string | ModelID, providerOptions?: ProviderOptions) => XAIImages.model({ ...media, id: modelID, providerOptions }), - video: (modelID: string | ModelID) => XAIVideo.model({ ...media, id: modelID }), + video: (modelID: string | ModelID, providerOptions?: ProviderOptions) => + XAIVideo.model({ ...media, id: modelID, providerOptions }), configure, } } @@ -114,6 +115,10 @@ export const imageModel = (modelID: string, settings?: Settings) => { const input = toConfig(settings) return configure(input).image(modelID, input.providerOptions) } +export const videoModel = (modelID: string, settings?: Settings) => { + const input = toConfig(settings) + return configure(input).video(modelID, input.providerOptions) +} export const responses = provider.responses export const chat = provider.chat export const image = provider.image diff --git a/packages/ai/src/providers/xai/videos.ts b/packages/ai/src/providers/xai/videos.ts new file mode 100644 index 000000000000..96689564e07d --- /dev/null +++ b/packages/ai/src/providers/xai/videos.ts @@ -0,0 +1,2 @@ +export { videoModel as model } from "../xai.js" +export type { Settings } from "../xai.js" diff --git a/packages/ai/test/provider/media-entrypoints.test.ts b/packages/ai/test/provider/media-entrypoints.test.ts index fd46116cd378..4d795ec83a0b 100644 --- a/packages/ai/test/provider/media-entrypoints.test.ts +++ b/packages/ai/test/provider/media-entrypoints.test.ts @@ -561,6 +561,15 @@ const videos: ReadonlyArray> = [ auth: ["x-goog-api-key", "google-key"], provider: "google", }, + { + name: "xai", + load: async () => { + const { model } = await import("@opencode/ai/providers/xai/videos") + return model("grok-imagine-video-1.5", { ...shared, apiKey: "xai-key" }) + }, + url: "https://api.x.ai/v1/videos/generations", + auth: ["authorization", "Bearer xai-key"], + }, ] describe("video entrypoints", () => { @@ -573,6 +582,21 @@ describe("video entrypoints", () => { ) }) +describe("video entrypoint model options", () => { + // Model-level options from settings (as models.dev or config set them) become defaults on every request. + for (const entry of [ + { name: "xai", modelID: "grok-imagine-video-1.5", load: () => import("@opencode/ai/providers/xai/videos") }, + { name: "google", modelID: "gemini-omni-1.2-flash", load: () => import("@opencode/ai/providers/google/videos") }, + ]) + it.effect(`providers/${entry.name}/videos keeps provider options from settings`, () => + Effect.gen(function* () { + const { model } = yield* Effect.promise(entry.load) + const calls = yield* sentVideo(model(entry.modelID, { apiKey: "key", future_option: true })) + expect(JSON.parse(calls[0].body).future_option).toBe(true) + }), + ) +}) + describe("decision entrypoints", () => { for (const entry of decisions) it.effect(`providers/${entry.name}/decisions sends a configured request`, () => diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index fec21c9c463f..a5a757648c42 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -180,6 +180,7 @@ const builtins = new Map Promise>([ ], ["@opencode/ai/providers/xai", () => import("@opencode/ai/providers/xai")], ["@opencode/ai/providers/xai/images", () => import("@opencode/ai/providers/xai/images")], + ["@opencode/ai/providers/xai/videos", () => import("@opencode/ai/providers/xai/videos")], ["@opencode/ai/providers/zai", () => import("@opencode/ai/providers/zai")], ["@opencode/ai/providers/zai/chat", () => import("@opencode/ai/providers/zai/chat")], ["@opencode/ai/providers/zai/images", () => import("@opencode/ai/providers/zai/images")], From b80a3891a471f3e67ed35b4530a0a0ca1cadf194 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:21:33 -0600 Subject: [PATCH 02/43] feat(core): move timed-out shell commands to the background by default (#63699) --- .../client/src/promise/generated/types.ts | 1 - packages/core/src/tool/plugin/shell.ts | 58 ++- packages/core/test/tool-shell.test.ts | 351 +++++++----------- packages/protocol/openapi.json | 3 - packages/schema/src/config/flag.ts | 1 - 5 files changed, 158 insertions(+), 256 deletions(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 591a8731ebc2..fc8133fb489c 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2593,7 +2593,6 @@ export type ConfigEntry = media_blob?: boolean schedules?: boolean artifacts?: boolean - shell_timeout_background?: boolean console_watches?: boolean mcp_events?: boolean part_rows?: boolean diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 12b434fc9573..9357b09e8a71 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -10,7 +10,6 @@ import { Clock, Deferred, Effect, Fiber, Option, Schema, Struct } from "effect" import { Environment } from "../../environment/index.js" import { Job } from "../../job.js" import { FileAccess } from "../../file-access.js" -import { Flag } from "../../flag.js" import { Permission } from "../../permission.js" import { NonNegativeInt } from "../../schema.js" import { Session } from "../../session.js" @@ -37,7 +36,7 @@ const OS = : process.platform === "linux" ? "Linux" : process.platform -const description = (shell?: string, autoBackground = false) => +const description = (shell?: string) => [ "Execute a shell command and return its output.", ...(shell ? [`Commands run on ${OS} using ${shell}.`] : []), @@ -45,31 +44,24 @@ const description = (shell?: string, autoBackground = false) => "Prefer dedicated tools over shell commands when possible.", "When output is large, the full result is saved to a file and a truncated preview is returned.", "Rely on automatic truncation unless filtering the output is more useful.", - autoBackground - ? "Commands still running after their timeout move to the background." - : "Commands accept an optional timeout, background commands have no timeout by default.", + "Commands still running after their timeout move to the background.", "Background commands return immediately, and you will be notified when they complete.", ].join(" ") -const input = (autoBackground: boolean) => - Schema.Struct({ - command: Schema.String.annotate({ description: "Shell command string to execute" }), - workdir: Schema.optionalKey(Schema.String).annotate({ - description: - "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.", - }), - timeout: Schema.optionalKey(NonNegativeInt).annotate({ - description: autoBackground - ? `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}). When it expires, a foreground command moves to the background and a background command is stopped.` - : `Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to ${DEFAULT_TIMEOUT_MS} for foreground commands. Background commands have no timeout by default.`, - }), - background: Schema.optionalKey(Schema.Boolean).annotate({ - description: - "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", - }), - }) - -export const Input = input(false) +export const Input = Schema.Struct({ + command: Schema.String.annotate({ description: "Shell command string to execute" }), + workdir: Schema.optionalKey(Schema.String).annotate({ + description: + "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.", + }), + timeout: Schema.optionalKey(NonNegativeInt).annotate({ + description: `Optional timeout in milliseconds (default ${DEFAULT_TIMEOUT_MS}). When it expires, a foreground command moves to the background and a background command is stopped.`, + }), + background: Schema.optionalKey(Schema.Boolean).annotate({ + description: + "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", + }), +}) const StructuredOutput = Schema.Struct({ output: Schema.String, @@ -287,7 +279,6 @@ export const Plugin = { const shellSelect = yield* ShellSelect.Service const compatibleShell = shellSelect.resolve({ priority: "compat" }) const permission = yield* Permission.Service - const autoBackground = yield* Flag.enabled("shell_timeout_background") const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) { const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" }) @@ -355,15 +346,12 @@ export const Plugin = { editor.add({ name, options: { codemode: false }, - description: description(undefined, autoBackground), - input: input(autoBackground), + description: description(), + input: Input, output: StructuredOutput, execute: (input, context) => { - // With timeout backgrounding, a foreground timeout of 0 falls back to the default so a call can't block - // until the command exits. - const foreground = autoBackground - ? input.timeout || DEFAULT_TIMEOUT_MS - : (input.timeout ?? DEFAULT_TIMEOUT_MS) + // A foreground timeout of 0 falls back to the default, so a call can't block until the command exits. + const foreground = input.timeout || DEFAULT_TIMEOUT_MS const timeout = input.background === true ? (input.timeout ?? 0) : foreground let finalTimeout = timeout // Uninterruptible from spawning to blocking, so an interrupt cannot orphan a started command. @@ -414,7 +402,7 @@ export const Plugin = { ), ) // A foreground timeout moves the command to the background instead of stopping it. - if (autoBackground && input.background !== true) invocation.timeout = 0 + if (input.background !== true) invocation.timeout = 0 }), ) yield* context.progress({ shellID: info.id }) @@ -435,7 +423,7 @@ export const Plugin = { const waiting = jobs.block({ id: job.id, sessionID: context.sessionID }) const blocked = - autoBackground && finalTimeout > 0 + finalTimeout > 0 ? waiting.pipe( Effect.timeoutOption(finalTimeout), Effect.flatMap((result) => @@ -498,7 +486,7 @@ export const Plugin = { Effect.gen(function* () { const tool = event.tools[name] if (!tool) return - tool.description = description(ShellSelect.name(yield* compatibleShell), autoBackground) + tool.description = description(ShellSelect.name(yield* compatibleShell)) }) yield* ctx.session.hook("context", hook) yield* ctx.session.hook("compaction", hook) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index efeadb183dea..881dc514e002 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -278,19 +278,8 @@ const progressOverflowCommand = (bytes: number, release: string) => ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }` : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done` -const withSession = ( - directory: string, - body: (registry: Tool.Interface) => Effect.Effect, - autoBackground?: boolean, -) => +const withSession = (directory: string, body: (registry: Tool.Interface) => Effect.Effect) => Effect.gen(function* () { - if (autoBackground !== undefined) - yield* Effect.promise(() => - Bun.write( - path.join(directory, "opencode.json"), - JSON.stringify({ experimental: { shell_timeout_background: autoBackground } }), - ), - ) const sessions = yield* Session.Service const location = Location.Ref.make({ directory: AbsolutePath.make(directory) }) yield* sessions.create({ @@ -1390,125 +1379,84 @@ describe("ShellTool", () => { { timeout: 15_000 }, ) - it.live( - "reports partial output, the timeout and the exit code when a foreground command times out", - () => - withTempDir((tmp) => { - reset() - // Long enough for the command to print before it is killed. - const timeout = isWindows ? 5_000 : 500 - return withSession(tmp.path, (registry) => - executeTool(registry, call({ command: startingCommand, timeout }, "call-foreground-timeout")), - ).pipe( - Effect.andThen((settled) => - Effect.sync(() => { - expect(settled.metadata).toMatchObject({ timeout: true }) - expect(settled.output).not.toHaveProperty("timeout") - expect(settled.output).toMatchObject({ - exitCode: settled.metadata?.exit ?? null, - }) - if (!isWindows) expect(settled.output.signal).toBe("SIGTERM") - expect(settled.content).toEqual([ - { type: "text", text: "server starting" }, - Expected.text( - expect.stringMatching( - new RegExp( - `^Command timed out after ${timeout / 1_000} seconds\\. If it needs longer and isn't waiting for input, rerun with a larger timeout\\.\\nExit code: ${timedOutExit}$`, - ), - ), - ), - ]) - }), - ), - ) - }), - { timeout: 15_000 }, - ) - it.live("moves a foreground timeout to the background and delivers its original process result once", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const bus = yield* Bus.Service - const notices = yield* Queue.unbounded() - yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( - Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), - Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), - Effect.forkScoped({ startImmediately: true }), - ) - const result = yield* executeTool( - registry, - call({ command: progressOverflowCommand(6, "release"), timeout: 10 }, "call-auto-background"), - ) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - const info = yield* shell.get(id) - expect(result.status).toBe("completed") - expect(info.pid).toBeGreaterThan(0) - expect(result.metadata).toMatchObject({ - status: "running", - shellID: id, - pid: info.pid, - truncated: false, - }) - expect(result.output).toEqual({ + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const bus = yield* Bus.Service + const notices = yield* Queue.unbounded() + yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( + Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), + Stream.runForEach((event) => Queue.offer(notices, event.data.item.payload)), + Effect.forkScoped({ startImmediately: true }), + ) + const result = yield* executeTool( + registry, + call({ command: progressOverflowCommand(6, "release"), timeout: 10 }, "call-auto-background"), + ) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + const info = yield* shell.get(id) + expect(result.status).toBe("completed") + expect(info.pid).toBeGreaterThan(0) + expect(result.metadata).toMatchObject({ + status: "running", + shellID: id, + pid: info.pid, + truncated: false, + }) + expect(result.output).toEqual({ + shellID: id, + pid: info.pid, + outputPath: info.file, + exitCode: null, + output: expect.any(String), + wallTimeSeconds: expect.any(Number), + }) + expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01) + expect(result.metadata).not.toHaveProperty("timeout") + expect(result.content?.[0]).toEqual({ + type: "text", + text: `Command moved to the background (shell ID: ${id}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}\n\nThe command did not finish within its timeout of 0.01 seconds and was moved to the background. Do not start another copy while it is running.`, + }) + expect(info.status).toBe("running") + expect((yield* shell.list()).map((item) => item.id)).toEqual([id]) + + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + const finished = yield* shell.wait(id) + expect(finished).toMatchObject({ + status: "exited", + exit: 0, + pid: info.pid, + }) + expect(yield* Queue.take(notices)).toMatchObject({ + text: expect.stringContaining("xxxxxx"), + metadata: { + source: "shell", shellID: id, - pid: info.pid, - outputPath: info.file, - exitCode: null, - output: expect.any(String), - wallTimeSeconds: expect.any(Number), - }) - expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01) - expect(result.metadata).not.toHaveProperty("timeout") - expect(result.content?.[0]).toEqual({ - type: "text", - text: `Command moved to the background (shell ID: ${id}).\nPID: ${info.pid}\nOutput is streaming to: ${info.file}\n\nThe command did not finish within its timeout of 0.01 seconds and was moved to the background. Do not start another copy while it is running.`, - }) - expect(info.status).toBe("running") - expect((yield* shell.list()).map((item) => item.id)).toEqual([id]) - - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - const finished = yield* shell.wait(id) - expect(finished).toMatchObject({ - status: "exited", + state: "completed", exit: 0, - pid: info.pid, - }) - expect(yield* Queue.take(notices)).toMatchObject({ - text: expect.stringContaining("xxxxxx"), - metadata: { - source: "shell", - shellID: id, - state: "completed", - exit: 0, - }, - }) - expect(yield* Queue.size(notices)).toBe(0) - expect(yield* shell.list()).toEqual([]) - }), - true, + }, + }) + expect(yield* Queue.size(notices)).toBe(0) + expect(yield* shell.list()).toEqual([]) + }), ) }), ) - it.live("returns a fast foreground result directly with timeout backgrounding enabled", () => + it.live("returns a fast foreground result directly", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: helloCommand, timeout: 10_000 })) - expect(result.metadata).toMatchObject({ status: "completed", exit: 0 }) - expect(result.content).toEqual([{ type: "text", text: "hello" }]) - const jobs = yield* Job.Service - expect(yield* jobs.runningBackground).toEqual([]) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool(registry, call({ command: helloCommand, timeout: 10_000 })) + expect(result.metadata).toMatchObject({ status: "completed", exit: 0 }) + expect(result.content).toEqual([{ type: "text", text: "hello" }]) + const jobs = yield* Job.Service + expect(yield* jobs.runningBackground).toEqual([]) + }), ) }), ) @@ -1516,62 +1464,56 @@ describe("ShellTool", () => { it.live("preserves a timeout-promoted command's eventual failure", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const bus = yield* Bus.Service - const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( - Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), - Stream.runHead, - Effect.forkScoped({ startImmediately: true }), - ) - const result = yield* executeTool( - registry, - call({ command: `${progressOverflowCommand(0, "release")}; exit 7`, timeout: 10 }), - ) - const id = ID.make(String(result.metadata?.shellID)) - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - const shell = yield* Shell.Service - expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 7 }) - expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ - text: expect.stringContaining("Exit code: 7"), - metadata: { source: "shell", shellID: id, state: "completed", exit: 7 }, - }) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const bus = yield* Bus.Service + const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( + Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ) + const result = yield* executeTool( + registry, + call({ command: `${progressOverflowCommand(0, "release")}; exit 7`, timeout: 10 }), + ) + const id = ID.make(String(result.metadata?.shellID)) + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + const shell = yield* Shell.Service + expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 7 }) + expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.item.payload).toMatchObject({ + text: expect.stringContaining("Exit code: 7"), + metadata: { source: "shell", shellID: id, state: "completed", exit: 7 }, + }) + }), ) }), ) - it.effect("treats a foreground timeout of zero as the default timeout with timeout backgrounding enabled", () => + it.effect("treats a foreground timeout of zero as the default timeout", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const running = yield* executeTool( - registry, - call({ command: progressOverflowCommand(0, "release"), timeout: 0 }, "call-zero-timeout"), - ).pipe(Effect.forkScoped({ startImmediately: true })) - // The wait starts only after the command spawns, so keep advancing the clock until the call returns. - const result = yield* Fiber.join(running).pipe( - Effect.raceFirst( - Effect.forever(Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("2 minutes")))), - ), - ) - expect(result.content?.[0]).toMatchObject({ - type: "text", - text: expect.stringContaining("did not finish within its timeout of 120 seconds"), - }) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.get(id)).status).toBe("running") - yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) - expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const running = yield* executeTool( + registry, + call({ command: progressOverflowCommand(0, "release"), timeout: 0 }, "call-zero-timeout"), + ).pipe(Effect.forkScoped({ startImmediately: true })) + // The wait starts only after the command spawns, so keep advancing the clock until the call returns. + const result = yield* Fiber.join(running).pipe( + Effect.raceFirst( + Effect.forever(Effect.promise(() => Bun.sleep(20)).pipe(Effect.andThen(TestClock.adjust("2 minutes")))), + ), + ) + expect(result.content?.[0]).toMatchObject({ + type: "text", + text: expect.stringContaining("did not finish within its timeout of 120 seconds"), + }) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.get(id)).status).toBe("running") + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), "")) + expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0 }) + }), ) }), ) @@ -1579,58 +1521,35 @@ describe("ShellTool", () => { it.live("still cancels a timeout-promoted shell through its existing job handle", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool( - registry, - call({ command: progressOverflowCommand(0, "release"), timeout: 10 }), - ) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.get(id)).status).toBe("running") - const jobs = yield* Job.Service - expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) - // Cancelling stops the command and keeps it, output file included. - expect((yield* shell.wait(id)).status).toBe("killed") - expect(yield* shell.list()).toEqual([]) - }), - true, - ) - }), - ) - - it.live("preserves explicit background timeout limits with timeout backgrounding disabled", () => - withTempDir((tmp) => { - reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 10 })) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.wait(id)).status).toBe("timeout") - }), - false, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool( + registry, + call({ command: progressOverflowCommand(0, "release"), timeout: 10 }), + ) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.get(id)).status).toBe("running") + const jobs = yield* Job.Service + expect(yield* jobs.cancel(id)).toMatchObject({ id, status: "cancelled" }) + // Cancelling stops the command and keeps it, output file included. + expect((yield* shell.wait(id)).status).toBe("killed") + expect(yield* shell.list()).toEqual([]) + }), ) }), ) - it.live("stops a background command when its explicit timeout expires with timeout backgrounding enabled", () => + it.live("stops a background command when its explicit timeout expires", () => withTempDir((tmp) => { reset() - return withSession( - tmp.path, - (registry) => - Effect.gen(function* () { - const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 50 })) - const id = ID.make(String(result.metadata?.shellID)) - const shell = yield* Shell.Service - expect((yield* shell.wait(id)).status).toBe("timeout") - }), - true, + return withSession(tmp.path, (registry) => + Effect.gen(function* () { + const result = yield* executeTool(registry, call({ command: idleCommand, background: true, timeout: 50 })) + const id = ID.make(String(result.metadata?.shellID)) + const shell = yield* Shell.Service + expect((yield* shell.wait(id)).status).toBe("timeout") + }), ) }), ) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 61d2670118de..8a95ff085ceb 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -16671,9 +16671,6 @@ "artifacts": { "type": "boolean" }, - "shell_timeout_background": { - "type": "boolean" - }, "console_watches": { "type": "boolean" }, diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index f82cb806850c..3111d6f06bfd 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -15,7 +15,6 @@ export const registry = { media_blob: "Store new session media once in a deduplicated blob table instead of inline in every message row.", schedules: "Enable experimental scheduled tasks that wake a session with a prompt.", artifacts: "Enable experimental artifacts backed by pluggable providers.", - shell_timeout_background: "Move foreground shell commands to the background when their timeout expires.", console_watches: "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console, and wake sessions when they change.", mcp_events: From 0a90308df4d6a3c35b9714aa98ce4a4be9e0c6f0 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:37:12 -0600 Subject: [PATCH 03/43] refactor(ai): address video jobs by the provider's job ID (#63714) --- packages/ai/README.md | 16 +++--- packages/ai/src/index.ts | 10 ++-- .../protocols/google-interactions-video.ts | 15 +++--- packages/ai/src/protocols/minimax-video.ts | 33 +++++++------ packages/ai/src/protocols/openrouter-video.ts | 17 ++++--- packages/ai/src/protocols/seedance-video.ts | 20 ++++---- packages/ai/src/protocols/xai-video.ts | 18 +++---- packages/ai/src/video-client.ts | 37 ++++++++------ packages/ai/src/video.ts | 25 +++++----- .../ai/test/google-interactions-video.test.ts | 26 ++++------ packages/ai/test/minimax-video.test.ts | 26 +++++----- packages/ai/test/openrouter-video.test.ts | 22 ++++----- packages/ai/test/promise.test.ts | 13 ++--- ...google-interactions-video.recorded.test.ts | 4 +- .../provider/minimax-video.recorded.test.ts | 12 ++--- .../openrouter-video.recorded.test.ts | 4 +- .../provider/seedance-video.recorded.test.ts | 4 +- .../test/provider/xai-video.recorded.test.ts | 4 +- packages/ai/test/seedance-video.test.ts | 28 ++++------- packages/ai/test/video.test.ts | 49 +++++++++---------- 20 files changed, 188 insertions(+), 195 deletions(-) diff --git a/packages/ai/README.md b/packages/ai/README.md index 37dcaf837a57..87cdfefd9133 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1035,8 +1035,8 @@ The hosted result is represented as a provider-executed tool call and a tool res Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`, fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's -`token`, plain JSON you can store and read back from another process, so recovering after a restart is the same call -as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`, +`id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart +is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`, `BytePlus`, `MiniMax` and `Google` facades. ```ts @@ -1057,13 +1057,13 @@ const program = Effect.gen(function* () { resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value sound: false, }) - job.token // `{ requestID }` for xAI: store it with the provider and model ID + job.id // the provider's job ID: store it with the provider and model ID - const status = yield* ai.video.status(model, job.token) + const status = yield* ai.video.status(model, job.id) status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired" status.progress // 0..1, only when the provider reports it - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk }) ``` @@ -1132,8 +1132,8 @@ The promise client has the same calls, each accepting `{ signal }`: import { ai } from "@opencode/ai" const job = await ai.video.start({ model, prompt }) -const status = await ai.video.status(model, job.token) -if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4") +const status = await ai.video.status(model, job.id) +if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4") ``` ## Public API @@ -1149,7 +1149,7 @@ Everything below is exported from `@opencode/ai/effect` unless noted. - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams. - **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`. -- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by a stored token; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer. +- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer. - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests. - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes. - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer. diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index e8475955ed7f..e0ddc97baf3f 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -260,14 +260,14 @@ export const make = (options: Options = {}) => { }, video: { request: Video.request, - /** Submit a generation and return its `{ id, token }` at once; nothing polls. */ + /** Submit a generation and return its `{ id }` at once; nothing polls. */ start: (input: VideoRequestInput | VideoRequest, options?: RunOptions) => run(Video.start(input), options), - /** One status read for a stored token. */ - status: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.status(model, token), options), + /** One status read for a job ID. */ + status: (model: VideoModel, id: string, options?: RunOptions) => run(Video.status(model, id), options), /** The finished videos; fails while the job is still running. */ - result: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.result(model, token), options), - cancel: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.cancel(model, token), options), + result: (model: VideoModel, id: string, options?: RunOptions) => run(Video.result(model, id), options), + cancel: (model: VideoModel, id: string, options?: RunOptions) => run(Video.cancel(model, id), options), }, /** Experimental: may change without compatibility guarantees. */ experimental: { diff --git a/packages/ai/src/protocols/google-interactions-video.ts b/packages/ai/src/protocols/google-interactions-video.ts index 93d15a9d7940..79c81433c5e2 100644 --- a/packages/ai/src/protocols/google-interactions-video.ts +++ b/packages/ai/src/protocols/google-interactions-video.ts @@ -49,7 +49,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ interactionID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const Content = Schema.Struct({ @@ -168,7 +169,7 @@ const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* ( // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(Interaction, (value) => ({ - token: { interactionID: value.id }, + token: value.id, snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status) }, })) @@ -179,7 +180,7 @@ const decodeStatus = Effect.fn("GoogleInteractionsVideo.decodeStatus")(function* context: MediaProtocol.PollContext, ) { const output = yield* decodeInteraction(response) - return { id: context.token.interactionID, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* ( @@ -189,7 +190,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* const output = yield* decodeInteraction(response) const decoded = output.value const status = MediaProtocol.status(STATUS, decoded.status) - if (status === "running") return yield* output.pending(context.token.interactionID) + if (status === "running") return yield* output.pending(context.token) const errors = decoded.errors ?? [] const codes = errors.flatMap((error) => { const code = errorCode(error.code) @@ -197,7 +198,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* }) const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : [])) if (status === "cancelled") - return yield* output.ended("cancelled", `${route.name} interaction ${context.token.interactionID} was cancelled`) + return yield* output.ended("cancelled", `${route.name} interaction ${context.token} was cancelled`) if (status === "failed") { const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}` if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code))) @@ -250,7 +251,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* // 7. Protocol and route // --------------------------------------------------------------------------- -const interactionPath = (token: Token) => `${PATH}/${token.interactionID}` +const interactionPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` export const protocol = MediaProtocol.queued(route, { token: Token, @@ -261,7 +262,7 @@ export const protocol = MediaProtocol.queued(rout }) export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) export const GoogleInteractionsVideo = { protocol, diff --git a/packages/ai/src/protocols/minimax-video.ts b/packages/ai/src/protocols/minimax-video.ts index a5ff152e3d1e..fe45f999608d 100644 --- a/packages/ai/src/protocols/minimax-video.ts +++ b/packages/ai/src/protocols/minimax-video.ts @@ -47,7 +47,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ taskID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const BaseResp = optionalNull( @@ -241,7 +242,7 @@ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function* // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { taskID: value.task_id }, + token: value.task_id, snapshot: { id: value.task_id, status: "queued" }, })) @@ -253,7 +254,7 @@ const decodeStatus = Effect.fn("MiniMaxVideo.decodeStatus")(function* ( ) { const output = yield* decodeTask(response) const task = output.value.task ?? output.value - return { id: context.token.taskID, status: MediaProtocol.status(STATUS, task.status ?? "") } + return { id: context.token, status: MediaProtocol.status(STATUS, task.status ?? "") } }) const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( @@ -263,11 +264,11 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( const output = yield* decodeTask(response) const task = output.value.task ?? output.value const status = MediaProtocol.status(STATUS, task.status ?? "") - if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") return yield* failed(output, route.name, task.error?.code ?? undefined, task.error?.message ?? undefined) if (status !== "completed") - return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`) + return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`) const url = task.content?.url ?? undefined if (url === undefined) return yield* output.invalid(`${route.name} completed without a video URL`) const duration = task.duration ?? undefined @@ -283,7 +284,7 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* ( usage: typeof total === "number" ? { type: "seconds", seconds: total } : undefined, providerMetadata: { minimax: { - taskId: context.token.taskID, + taskId: context.token, model: task.model ?? undefined, resolution: task.resolution ?? undefined, ratio: task.ratio ?? undefined, @@ -301,7 +302,7 @@ const decodeHailuoStart = Effect.fn("MiniMaxHailuoVideo.decodeStart")(function* if (error) return yield* error const taskID = output.value.task_id ?? "" if (taskID === "") return yield* output.invalid(`${hailuoRoute.name} returned no task_id`) - return { token: { taskID }, snapshot: { id: taskID, status: "queued" as const } } + return { token: taskID, snapshot: { id: taskID, status: "queued" as const } } }) const decodeHailuoTask = hailuoRoute.decodeJson(HailuoTask) @@ -315,7 +316,7 @@ const decodeHailuoStatus = Effect.fn("MiniMaxHailuoVideo.decodeStatus")(function // A failed task also carries its reason in `base_resp`; any other non-zero code is a failed read. const error = status === "failed" ? undefined : baseError(output, output.value.base_resp) if (error) return yield* error - return { id: context.token.taskID, status } + return { id: context.token, status } }) const decodeHailuoFile = hailuoRoute.decodeJson(HailuoFile) @@ -330,7 +331,7 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function const error = baseError(output, task.base_resp) if (status === "failed") return yield* error ?? failed(output, hailuoRoute.name, undefined, undefined) if (error) return yield* error - if (status !== "completed") return yield* output.pending(context.token.taskID) + if (status !== "completed") return yield* output.pending(context.token) const fileID = task.file_id ?? "" if (fileID === "") return yield* output.invalid(`${hailuoRoute.name} completed without a file_id`) // The task names a file; its download URL takes a second lookup and is valid for one hour. @@ -349,7 +350,7 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function }), ], providerMetadata: { - minimax: { taskId: context.token.taskID, fileId: fileID }, + minimax: { taskId: context.token, fileId: fileID }, }, }) }) @@ -361,13 +362,13 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function export const protocol = MediaProtocol.queued(route, { token: Token, start: { body: { from: fromRequest }, decode: decodeStart }, - status: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeStatus }, - result: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeResult }, + status: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeStatus }, + result: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeResult }, // Cancels a queued task; MiniMax rejects it once the task is running. - cancel: { method: "DELETE", path: (token) => `${PATH}/${token.taskID}` }, + cancel: { method: "DELETE", path: (token) => `${PATH}/${encodeURIComponent(token)}` }, }) -const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token.taskID)}` +const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token)}` export const hailuoProtocol = MediaProtocol.queued(hailuoRoute, { token: Token, @@ -378,11 +379,11 @@ export const hailuoProtocol = MediaProtocol.queued - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) /** Hailuo and the `*-01` models on the v1 API. */ export const hailuoModel = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol: hailuoProtocol, baseURL: DEFAULT_BASE_URL, path: HAILUO_PATH }, input, ) diff --git a/packages/ai/src/protocols/openrouter-video.ts b/packages/ai/src/protocols/openrouter-video.ts index 3ea10d3dc711..6df2a92364d2 100644 --- a/packages/ai/src/protocols/openrouter-video.ts +++ b/packages/ai/src/protocols/openrouter-video.ts @@ -43,7 +43,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ id: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ id: Schema.String, status: optionalNull(Schema.String) }) @@ -133,7 +134,7 @@ const resolution = (value: string) => (/^\dk$/.test(value) ? value.toUpperCase() // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { id: value.id }, + token: value.id, snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status ?? "pending") }, })) @@ -144,7 +145,7 @@ const decodeStatus = Effect.fn("OpenRouterVideo.decodeStatus")(function* ( context: MediaProtocol.PollContext, ) { const output = yield* decodeJob(response) - return { id: context.token.id, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( @@ -154,7 +155,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( const output = yield* decodeJob(response) const job = output.value const status = MediaProtocol.status(STATUS, job.status) - if (status === "queued" || status === "running") return yield* output.pending(context.token.id) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") { const message = `${route.name} generation failed${job.error ? `: ${job.error}` : ""}` if (job.error && /content policy|moderat/i.test(job.error)) return yield* output.contentPolicy(message) @@ -163,7 +164,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( if (status !== "completed") return yield* output.ended( status, - `${route.name} job ${context.token.id} ${status}${job.error ? `: ${job.error}` : ""}`, + `${route.name} job ${context.token} ${status}${job.error ? `: ${job.error}` : ""}`, ) const urls = job.unsigned_urls ?? [] if (urls.length === 0) return yield* output.invalid(`${route.name} completed without a video URL`) @@ -183,7 +184,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( videos, providerMetadata: { openrouter: { - id: context.token.id, + id: context.token, generationId: job.generation_id ?? undefined, cost: job.usage?.cost ?? undefined, isByok: job.usage?.is_byok ?? undefined, @@ -196,7 +197,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* ( // 6. Protocol and route // --------------------------------------------------------------------------- -const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token.id)}` +const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` // OpenRouter has no cancel endpoint; `cancelled` only appears when it stops a job itself. export const protocol = MediaProtocol.queued(route, { @@ -207,7 +208,7 @@ export const protocol = MediaProtocol.queued(rout }) export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) + VideoModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input) export const OpenRouterVideo = { protocol, diff --git a/packages/ai/src/protocols/seedance-video.ts b/packages/ai/src/protocols/seedance-video.ts index beafc561aba3..08563535ea01 100644 --- a/packages/ai/src/protocols/seedance-video.ts +++ b/packages/ai/src/protocols/seedance-video.ts @@ -47,7 +47,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ taskID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ id: Schema.String }) @@ -194,7 +195,7 @@ const make = (provider: Provider) => { }) const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { taskID: value.id }, + token: value.id, snapshot: { id: value.id, status: "queued" }, })) @@ -205,7 +206,7 @@ const make = (provider: Provider) => { context: MediaProtocol.PollContext, ) { const output = yield* decodeTask(response) - return { id: context.token.taskID, status: MediaProtocol.status(STATUS, output.value.status) } + return { id: context.token, status: MediaProtocol.status(STATUS, output.value.status) } }) const decodeResult = Effect.fn("SeedanceVideo.decodeResult")(function* ( @@ -215,7 +216,7 @@ const make = (provider: Provider) => { const output = yield* decodeTask(response) const task = output.value const status = MediaProtocol.status(STATUS, task.status) - if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID) + if (status === "queued" || status === "running") return yield* output.pending(context.token) if (status === "failed") { const code = task.error?.code ?? undefined const detail = task.error?.message ?? undefined @@ -224,9 +225,8 @@ const make = (provider: Provider) => { return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, code?.split(".")[0])) } if (status === "cancelled") - return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`) - if (status === "expired") - return yield* output.ended("expired", `${route.name} task ${context.token.taskID} expired`) + return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`) + if (status === "expired") return yield* output.ended("expired", `${route.name} task ${context.token} expired`) const videoURL = task.content?.video_url ?? undefined if (videoURL === undefined) return yield* output.invalid(`${route.name} completed without a video URL`) const duration = durationSeconds(task) @@ -254,7 +254,7 @@ const make = (provider: Provider) => { }, providerMetadata: { [provider]: { - taskId: context.token.taskID, + taskId: context.token, model: task.model ?? undefined, seed: task.seed ?? undefined, ratio: task.ratio ?? undefined, @@ -272,7 +272,7 @@ const make = (provider: Provider) => { }) }) - const taskPath = (token: Token) => `${PATH}/${token.taskID}` + const taskPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}` // DELETE cancels a queued task. Ark refuses it for a running task, and deletes the record of a finished one. const protocol = MediaProtocol.queued(route, { @@ -284,7 +284,7 @@ const make = (provider: Provider) => { }) const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol, baseURL: provider === "volcengine" ? VOLCENGINE_BASE_URL : BYTEPLUS_BASE_URL, diff --git a/packages/ai/src/protocols/xai-video.ts b/packages/ai/src/protocols/xai-video.ts index 8a804543ffd0..49bb43496a1c 100644 --- a/packages/ai/src/protocols/xai-video.ts +++ b/packages/ai/src/protocols/xai-video.ts @@ -36,7 +36,8 @@ export type Request = VideoRequest> // 2. Token and response schemas // --------------------------------------------------------------------------- -export const Token = Schema.Struct({ requestID: Schema.String }) +/** The provider's job ID; it is all a later status, result or cancel call needs. */ +export const Token = Schema.String export type Token = Schema.Schema.Type const StartResponse = Schema.Struct({ request_id: Schema.String }) @@ -132,7 +133,7 @@ const fromRequest = Effect.fn("XAIVideo.fromRequest")(function* (request: Reques // --------------------------------------------------------------------------- const decodeStart = route.decodeStarted(StartResponse, (value) => ({ - token: { requestID: value.request_id }, + token: value.request_id, snapshot: { id: value.request_id, status: "running" }, })) @@ -148,7 +149,7 @@ const decodeStatus = Effect.fn("XAIVideo.decodeStatus")(function* ( ) { const output = yield* decodeVideoStatus(response) const status = MediaProtocol.status(STATUS, output.value.status) - return { id: context.token.requestID, status, progress: fraction(output.value.progress) } + return { id: context.token, status, progress: fraction(output.value.progress) } }) const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( @@ -158,7 +159,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( const output = yield* decodeVideoStatus(response) const decoded = output.value const status = MediaProtocol.status(STATUS, decoded.status) - if (status === "running") return yield* output.pending(context.token.requestID) + if (status === "running") return yield* output.pending(context.token) if (status === "failed") { const code = decoded.error?.code ?? undefined const message = decoded.error?.message ?? undefined @@ -168,8 +169,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( MediaProtocol.failure(FAILURE, code), ) } - if (status !== "completed") - return yield* output.ended("expired", `${route.name} request ${context.token.requestID} expired`) + if (status !== "completed") return yield* output.ended("expired", `${route.name} request ${context.token} expired`) // `respect_moderation: false` marks a filtered result; a URL may still be present, so only a missing one fails. const moderated = decoded.video?.respect_moderation === false const url = decoded.video?.url ?? undefined @@ -186,7 +186,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( ], providerMetadata: { xai: { - requestId: context.token.requestID, + requestId: context.token, model: decoded.model ?? undefined, respectModeration: decoded.video?.respect_moderation ?? undefined, }, @@ -198,7 +198,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( // 7. Protocol and route // --------------------------------------------------------------------------- -const statusPath = (token: Token) => `${STATUS_PATH}/${token.requestID}` +const statusPath = (token: Token) => `${STATUS_PATH}/${encodeURIComponent(token)}` export const protocol = MediaProtocol.queued(route, { token: Token, @@ -215,7 +215,7 @@ const startPath = (request: Request) => { } export const model = (input: MediaRoute.ModelInput) => - VideoModel.fromRoute( + VideoModel.fromRoute( { protocol, baseURL: DEFAULT_BASE_URL, diff --git a/packages/ai/src/video-client.ts b/packages/ai/src/video-client.ts index 960677c86f96..9f7f6c250a6a 100644 --- a/packages/ai/src/video-client.ts +++ b/packages/ai/src/video-client.ts @@ -1,37 +1,42 @@ -import { Context, Effect, Layer } from "effect" +import { Context, Effect, Layer, Schema } from "effect" import { RequestExecutor } from "./route/executor.js" import { AIError, UnsupportedOperationError } from "./schema/index.js" import type { VideoJob, VideoModel, VideoRequest, VideoResponse, VideoStatus } from "./video.js" export interface Interface { readonly start: (request: VideoRequest) => Effect.Effect - readonly status: (model: VideoModel, token: unknown) => Effect.Effect - readonly result: (model: VideoModel, token: unknown) => Effect.Effect - readonly cancel: (model: VideoModel, token: unknown) => Effect.Effect + readonly status: (model: VideoModel, id: string) => Effect.Effect + readonly result: (model: VideoModel, id: string) => Effect.Effect + readonly cancel: (model: VideoModel, id: string) => Effect.Effect } export class VideoClientService extends Context.Service()("@opencode/VideoClient") {} export const Service = VideoClientService export type Service = VideoClientService +// A video route whose token isn't a string is a programmer defect, not a provider error. +const decodeID = (token: unknown) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie) + export const layer = Layer.effect( Service, Effect.gen(function* () { const executor = yield* RequestExecutor.Service - const attach = (model: VideoModel, token: unknown) => model.route.attach(model, token, executor.execute) + const attach = (model: VideoModel, id: string) => model.route.attach(model, id, executor.execute) return Service.of({ start: (request) => - request.model.route - .start(request, executor.execute) - .pipe(Effect.map((generation) => ({ id: generation.id, token: generation.token }))), - status: (model, token) => - attach(model, token).pipe( + request.model.route.start(request, executor.execute).pipe( + // The token, not the snapshot id, is what `status` and `result` decode; `VideoModel.fromRoute` makes it a string. + Effect.flatMap((generation) => decodeID(generation.token)), + Effect.map((id) => ({ id })), + ), + status: (model, id) => + attach(model, id).pipe( Effect.flatMap((route) => route.status), Effect.map((snapshot) => ({ status: snapshot.status, progress: snapshot.progress })), ), - result: (model, token) => attach(model, token).pipe(Effect.flatMap((route) => route.result)), - cancel: (model, token) => - attach(model, token).pipe( + result: (model, id) => attach(model, id).pipe(Effect.flatMap((route) => route.result)), + cancel: (model, id) => + attach(model, id).pipe( Effect.flatMap( (route) => route.cancel ?? @@ -55,7 +60,7 @@ export const VideoClient = { Service, layer, start: (request: VideoRequest) => Service.use((client) => client.start(request)), - status: (model: VideoModel, token: unknown) => Service.use((client) => client.status(model, token)), - result: (model: VideoModel, token: unknown) => Service.use((client) => client.result(model, token)), - cancel: (model: VideoModel, token: unknown) => Service.use((client) => client.cancel(model, token)), + status: (model: VideoModel, id: string) => Service.use((client) => client.status(model, id)), + result: (model: VideoModel, id: string) => Service.use((client) => client.result(model, id)), + cancel: (model: VideoModel, id: string) => Service.use((client) => client.cancel(model, id)), } as const diff --git a/packages/ai/src/video.ts b/packages/ai/src/video.ts index d97f4fae2d8f..976619d2e621 100644 --- a/packages/ai/src/video.ts +++ b/packages/ai/src/video.ts @@ -19,14 +19,15 @@ import { VideoClient, Service } from "./video-client.js" export type VideoOptions = MediaModel.Options -/** Video generation is always a queued job: submit, then read its status and result by token. */ +/** Video generation is always a queued job: submit, then read its status and result by the provider's job ID. */ export type VideoRoute = MediaRoute.QueuedRoute export class VideoModel extends MediaModel { declare protected readonly _VideoModel: void - static fromRoute( - route: MediaModel.QueuedRouteInput>, VideoResponse, Token>, + /** A video route's token is the provider's job ID, so `VideoJob.id` is exactly what `status` and `result` take. */ + static fromRoute( + route: MediaModel.QueuedRouteInput>, VideoResponse, string>, input: MediaRoute.ModelInput, ) { return new VideoModel({ @@ -105,10 +106,10 @@ export const seconds = (duration: VideoDuration) => Duration.toSeconds(Duration. // Job, status and response // --------------------------------------------------------------------------- -/** A submitted generation. Store `token` (plain JSON) with the model to read the job later, from any process. */ +/** A submitted generation. Store `id` with the model to read the job later, from any process. */ export interface VideoJob { + /** The provider's job ID. */ readonly id: string - readonly token: unknown } export interface VideoStatus { @@ -156,17 +157,17 @@ export function start(input: VideoRequestInput) { return requestEffect(input).pipe(Effect.flatMap((request) => VideoClient.start(request))) } -/** One status read for a stored token. */ -export const status = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.status(model, token) +/** One status read for a job ID. */ +export const status = (model: VideoModel, id: string): Effect.Effect => + VideoClient.status(model, id) /** The finished videos; fails while the job is still running, or with the provider's reason when it failed. */ -export const result = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.result(model, token) +export const result = (model: VideoModel, id: string): Effect.Effect => + VideoClient.result(model, id) /** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */ -export const cancel = (model: VideoModel, token: unknown): Effect.Effect => - VideoClient.cancel(model, token) +export const cancel = (model: VideoModel, id: string): Effect.Effect => + VideoClient.cancel(model, id) export const Video = { request, diff --git a/packages/ai/test/google-interactions-video.test.ts b/packages/ai/test/google-interactions-video.test.ts index 8bbad982ffec..850f0a911eed 100644 --- a/packages/ai/test/google-interactions-video.test.ts +++ b/packages/ai/test/google-interactions-video.test.ts @@ -9,7 +9,7 @@ const layer = (handler: Parameters[0]) => VideoClient.layer.pipe(Layer.provideMerge(dynamicResponse(handler))) const model = Google.configure({ apiKey: "test", baseURL: "https://google.test/v1beta" }).video("gemini-omni-1.2-flash") -const token = { interactionID: "v1_abc" } +const id = "v1_abc" const started = { id: "v1_abc", status: "in_progress", object: "interaction", model: "gemini-omni-1.2-flash" } // "AAAAIGZ0eXBpc29t" is the base64 of an MP4 `ftyp` box header. const completed = { @@ -65,7 +65,7 @@ describe("ai.video.start / Google Interactions", () => { ), ), ) - expect(job).toEqual({ id: "v1_abc", token }) + expect(job).toEqual({ id: "v1_abc" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://google.test/v1beta/interactions?trace=1", ]) @@ -170,7 +170,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const decoded: unknown = JSON.parse(JSON.stringify(job.token)) + const decoded: unknown = job.id return [yield* ai.video.status(model, decoded), yield* ai.video.status(model, decoded)] }).pipe( Effect.provide( @@ -198,7 +198,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { ["in_progress", "completed", "incomplete", "failed", "cancelled", "requires_action", "constructor"], (status) => ai.video - .status(model, token) + .status(model, id) .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: "v1_abc", status }))))), ) expect(statuses.map((value) => value.status)).toEqual([ @@ -213,17 +213,9 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { }), ) - it.effect("rejects a token from another provider", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { requestID: "req_1" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) - it.effect("decodes the inline video with token usage and interaction metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("bytes") expect(response.video.mediaType).toBe("video/mp4") @@ -237,7 +229,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { it.effect("keeps a Files API video URI as a Google reference", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.video.source).toEqual({ type: "ref", provider: "google", @@ -272,7 +264,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { it.effect("fails a result read before the interaction finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toBe( "Google Interactions Video generation v1_abc has not finished; await it before reading the result", @@ -323,7 +315,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { ]) it.effect(`fails the result of a ${terminal.body.status} interaction as ${terminal.tag}`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -334,7 +326,7 @@ describe("ai.video.status / result / cancel / Google Interactions", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe( Effect.provide( layer((input) => diff --git a/packages/ai/test/minimax-video.test.ts b/packages/ai/test/minimax-video.test.ts index 85ea449d0663..c6261892dc80 100644 --- a/packages/ai/test/minimax-video.test.ts +++ b/packages/ai/test/minimax-video.test.ts @@ -11,7 +11,7 @@ const layer = (handler: Parameters[0]) => const minimax = MiniMax.configure({ apiKey: "test", baseURL: "https://minimax.test" }) const h3 = minimax.video("MiniMax-H3-Lite") const hailuo = minimax.video("MiniMax-Hailuo-02") -const token = { taskID: "task_1" } +const id = "task_1" const task = (fields: Record) => ({ task: { id: "task_1", model: "MiniMax-H3-Lite", ...fields } }) const succeeded = task({ @@ -83,7 +83,7 @@ describe("MiniMax Video / H3 start", () => { ), ), ) - expect(job).toEqual({ id: "task_1", token }) + expect(job).toEqual({ id: "task_1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://minimax.test/v2/video_generation?trace=1", ]) @@ -280,7 +280,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("reads statuses from a JSON round-tripped token and keeps unknown ones running", () => Effect.gen(function* () { const calls: Array = [] - const raw: unknown = JSON.parse(JSON.stringify(token)) + const raw: unknown = id const statuses = yield* Effect.forEach( ["queued", "running", "succeeded", "failed", "cancelled", "warming_up", "constructor"], (status) => @@ -307,7 +307,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("returns the finished video with duration, usage and metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(h3, token) + const response = yield* ai.video.result(h3, id) expect(response.video.source).toEqual({ type: "url", url: "https://cdn.minimax.test/out.mp4", @@ -329,14 +329,14 @@ describe("MiniMax Video / H3 status, result and cancel", () => { it.effect("reads the flat response format too", () => Effect.gen(function* () { - const response = yield* ai.video.result(h3, token) + const response = yield* ai.video.result(h3, id) expect(response.video.source).toMatchObject({ url: "https://cdn.minimax.test/out.mp4" }) }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, succeeded.task))))), ) it.effect("fails a result read before the task finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(h3, token).pipe(Effect.flip) + const error = yield* ai.video.result(h3, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("has not finished") }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, task({ status: "running" })))))), @@ -384,7 +384,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { ]) { it.effect(`fails the result of ${terminal.message} with the provider body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(h3, token).pipe(Effect.flip) + const error = yield* ai.video.result(h3, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -396,7 +396,7 @@ describe("MiniMax Video / H3 status, result and cancel", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(h3, token) + .cancel(h3, id) .pipe( Effect.provide( layer((input) => @@ -423,7 +423,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { ["Preparing", "Queueing", "Processing", "Success", "Fail", "Warming"], (status) => ai.video - .status(hailuo, token) + .status(hailuo, id) .pipe( Effect.provide( layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, hailuoTask({ status }))))), @@ -444,7 +444,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("fails a status read that v1 answers with a non-zero base_resp", () => Effect.gen(function* () { - const error = yield* ai.video.status(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.status(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("This task_id does not exist") }).pipe( @@ -468,7 +468,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("looks up the file's download URL, which expires after one hour", () => Effect.gen(function* () { const calls: Array = [] - const response = yield* ai.video.result(hailuo, token).pipe( + const response = yield* ai.video.result(hailuo, id).pipe( Effect.provide( layer((input) => Effect.gen(function* () { @@ -526,7 +526,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { ]) { it.effect(`fails the result with "${terminal.message}"`, () => Effect.gen(function* () { - const error = yield* ai.video.result(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.result(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -536,7 +536,7 @@ describe("MiniMax Video / Hailuo status, result and cancel", () => { it.effect("fails cancel as unsupported without sending a request, since v1 has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(hailuo, token).pipe(Effect.flip) + const error = yield* ai.video.cancel(hailuo, id).pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") expect(error.message).toContain("cancel") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), diff --git a/packages/ai/test/openrouter-video.test.ts b/packages/ai/test/openrouter-video.test.ts index ebaa13aaf889..8f3761bc5a21 100644 --- a/packages/ai/test/openrouter-video.test.ts +++ b/packages/ai/test/openrouter-video.test.ts @@ -10,7 +10,7 @@ const layer = (handler: Parameters[0]) => const openrouter = OpenRouter.configure({ apiKey: "test", baseURL: "https://openrouter.test/api/v1" }) const model = openrouter.video("x-ai/grok-imagine-video-1.5-lite") -const token = { id: "gen-vid-1-abc" } +const id = "gen-vid-1-abc" const started = (input: HandlerInput) => json(input, { id: "gen-vid-1-abc", @@ -48,7 +48,7 @@ describe("ai.video.start / OpenRouter", () => { }, }) .pipe(Effect.provide(record(calls))) - expect(job).toEqual({ id: "gen-vid-1-abc", token }) + expect(job).toEqual({ id: "gen-vid-1-abc" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["POST https://openrouter.test/api/v1/videos"]) expect(calls[0].headers.get("authorization")).toBe("Bearer test") expect(JSON.parse(calls[0].body)).toEqual({ @@ -151,8 +151,8 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { ["pending", "in_progress", "completed", "failed", "cancelled", "expired", "warming_up"], (status) => ai.video - .status(model, JSON.parse(JSON.stringify(token))) - .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, status }))))), + .status(model, id) + .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, status }))))), ) expect(statuses.map((value) => value.status)).toEqual([ "queued", @@ -170,7 +170,7 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { Effect.gen(function* () { const calls: Array = [] const response = yield* Effect.gen(function* () { - const result = yield* ai.video.result(model, token) + const result = yield* ai.video.result(model, id) expect(yield* result.video.bytes()).toEqual(Uint8Array.from([1, 2, 3])) return result }).pipe( @@ -204,7 +204,7 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { it.effect("attaches no credentials to a result URL on another host", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token) + const response = yield* ai.video.result(model, id) expect(response.video.headers).toEqual({}) }).pipe( Effect.provide( @@ -217,10 +217,10 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { it.effect("fails a result read before the job finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toContain("has not finished") - }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, status: "in_progress" }))))), + }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, status: "in_progress" }))))), ) for (const terminal of [ @@ -247,16 +247,16 @@ describe("ai.video.status / result / cancel / OpenRouter", () => { ]) { it.effect(`fails the result of a job that ${terminal.body.status} with "${terminal.body.error}"`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip) + const error = yield* ai.video.result(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) - }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id: token.id, ...terminal.body }))))), + }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { id, ...terminal.body }))))), ) } it.effect("fails cancel as unsupported without a request, since OpenRouter has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(model, token).pipe(Effect.flip) + const error = yield* ai.video.cancel(model, id).pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), ) diff --git a/packages/ai/test/promise.test.ts b/packages/ai/test/promise.test.ts index da8af3e306d6..98a5ba8ebe2e 100644 --- a/packages/ai/test/promise.test.ts +++ b/packages/ai/test/promise.test.ts @@ -188,15 +188,16 @@ describe("AI promise client", () => { const model = xai.video("grok-imagine-video-1.5") const job = await ai.video.start({ model, prompt: "A kite" }) - expect(job).toEqual({ id: "req_1", token: { requestID: "req_1" } }) + expect(job).toEqual({ id: "req_1" }) - const token: unknown = JSON.parse(JSON.stringify(job.token)) - expect(await ai.video.status(model, token)).toEqual({ status: "running", progress: 0.5 }) - expect(await ai.video.status(model, token)).toEqual({ status: "completed" }) - const response = await ai.video.result(model, token) + // The ID is plain text: store it and read the job back from any process. + const id = job.id + expect(await ai.video.status(model, id)).toEqual({ status: "running", progress: 0.5 }) + expect(await ai.video.status(model, id)).toEqual({ status: "completed" }) + const response = await ai.video.result(model, id) expect(response.video).toBeInstanceOf(Media.Asset) expect(response.video.source).toMatchObject({ type: "url", url: "https://vidgen.x.ai/out.mp4" }) - expect(await ai.video.cancel(model, token).catch((error: unknown) => error)).toMatchObject({ + expect(await ai.video.cancel(model, id).catch((error: unknown) => error)).toMatchObject({ reason: { _tag: "UnsupportedOperation" }, }) diff --git a/packages/ai/test/provider/google-interactions-video.recorded.test.ts b/packages/ai/test/provider/google-interactions-video.recorded.test.ts index 8706f5e3366a..a0d662bc7543 100644 --- a/packages/ai/test/provider/google-interactions-video.recorded.test.ts +++ b/packages/ai/test/provider/google-interactions-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("Google Interactions Video recorded", () => { duration: "3 seconds", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -38,7 +38,7 @@ describe("Google Interactions Video recorded", () => { ) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.mediaType).toBe("video/mp4") expect((yield* response.video.bytes()).length).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/minimax-video.recorded.test.ts b/packages/ai/test/provider/minimax-video.recorded.test.ts index c8bf453a3224..a24090bee68f 100644 --- a/packages/ai/test/provider/minimax-video.recorded.test.ts +++ b/packages/ai/test/provider/minimax-video.recorded.test.ts @@ -14,10 +14,10 @@ const recorded = recordedTests({ requires: ["MINIMAX_API_KEY"], }) -const settle = (model: VideoModel, token: unknown) => +const settle = (model: VideoModel, id: string) => Effect.gen(function* () { const observed: Array = [] - yield* ai.video.status(model, token).pipe( + yield* ai.video.status(model, id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -41,10 +41,10 @@ describe("MiniMax Video recorded", () => { resolution: "480p", duration: "4 seconds", }) - const observed = yield* settle(model, job.token) + const observed = yield* settle(model, job.id) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.info?.durationSeconds).toBe(4) @@ -68,11 +68,11 @@ describe("MiniMax Video recorded", () => { resolution: "512p", duration: "6 seconds", }) - const observed = yield* settle(model, job.token) + const observed = yield* settle(model, job.id) expect(observed.at(-1)?.status).toBe("completed") // The task names a file; the result looks up its one-hour download URL. - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/openrouter-video.recorded.test.ts b/packages/ai/test/provider/openrouter-video.recorded.test.ts index 0f5205c2e579..85ac20ad03fe 100644 --- a/packages/ai/test/provider/openrouter-video.recorded.test.ts +++ b/packages/ai/test/provider/openrouter-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("OpenRouter Video recorded", () => { duration: "1 second", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -40,7 +40,7 @@ describe("OpenRouter Video recorded", () => { expect(observed.every((status) => status.progress === undefined)).toBe(true) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(Date.parse("2026-01-01")) diff --git a/packages/ai/test/provider/seedance-video.recorded.test.ts b/packages/ai/test/provider/seedance-video.recorded.test.ts index 669abe150513..d979cfe59bc1 100644 --- a/packages/ai/test/provider/seedance-video.recorded.test.ts +++ b/packages/ai/test/provider/seedance-video.recorded.test.ts @@ -31,7 +31,7 @@ describe("Seedance Video recorded", () => { sound: false, }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -40,7 +40,7 @@ describe("Seedance Video recorded", () => { ) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.expiresAt).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/xai-video.recorded.test.ts b/packages/ai/test/provider/xai-video.recorded.test.ts index 8b6fe07e1f09..2aefc6c9e157 100644 --- a/packages/ai/test/provider/xai-video.recorded.test.ts +++ b/packages/ai/test/provider/xai-video.recorded.test.ts @@ -29,7 +29,7 @@ describe("xAI Video recorded", () => { duration: "2 seconds", }) const observed: Array = [] - yield* ai.video.status(model, job.token).pipe( + yield* ai.video.status(model, job.id).pipe( Effect.tap((status) => Effect.sync(() => observed.push(status))), Effect.repeat({ schedule: Schedule.spaced(queuedPoll.interval ?? "10 millis"), @@ -43,7 +43,7 @@ describe("xAI Video recorded", () => { expect(progress).toEqual([...progress].sort((a, b) => a - b)) expect(observed.at(-1)?.status).toBe("completed") - const response = yield* ai.video.result(model, job.token) + const response = yield* ai.video.result(model, job.id) expect(response.videos).toHaveLength(1) expect(response.video.source.type).toBe("url") expect(response.video.info?.durationSeconds).toBe(2) diff --git a/packages/ai/test/seedance-video.test.ts b/packages/ai/test/seedance-video.test.ts index aa677c8739ed..c13e709459ea 100644 --- a/packages/ai/test/seedance-video.test.ts +++ b/packages/ai/test/seedance-video.test.ts @@ -11,7 +11,7 @@ const layer = (handler: Parameters[0]) => const model = Volcengine.configure({ apiKey: "test", baseURL: "https://ark.test/api/v3" }).video( "doubao-seedance-2-0-260128", ) -const token = { taskID: "cgt-1" } +const id = "cgt-1" const succeeded = { id: "cgt-1", model: "doubao-seedance-2-0-260128", @@ -66,7 +66,7 @@ describe("ai.video.start / Seedance", () => { ), ), ) - expect(job).toEqual({ id: "cgt-1", token: { taskID: "cgt-1" } }) + expect(job).toEqual({ id: "cgt-1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://ark.test/api/v3/contents/generations/tasks?trace=1", ]) @@ -213,7 +213,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const restored: unknown = JSON.parse(JSON.stringify(job.token)) + const restored: unknown = job.id return yield* Effect.forEach([1, 2, 3], () => ai.video.status(model, restored)) }).pipe( Effect.provide( @@ -242,7 +242,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { Effect.gen(function* () { const raw = ["queued", "running", "succeeded", "failed", "cancelled", "expired", "paused", "constructor"] const statuses = yield* Effect.forEach(raw, (status) => - ai.video.status(model, token).pipe(Effect.provide(reply({ id: "cgt-1", status }))), + ai.video.status(model, id).pipe(Effect.provide(reply({ id: "cgt-1", status }))), ) expect(statuses.map((value) => value.status)).toEqual([ "queued", @@ -259,7 +259,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("returns the video as a URL that expires 24 hours after the task finished, with usage and metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token).pipe(Effect.provide(reply(succeeded))) + const response = yield* ai.video.result(model, id).pipe(Effect.provide(reply(succeeded))) expect(response.video.source).toEqual({ type: "url", url: "https://ark-content.test/out.mp4", @@ -287,7 +287,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("derives duration from frames, types mov output and keeps the last frame URL", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, token).pipe( + const response = yield* ai.video.result(model, id).pipe( Effect.provide( reply({ status: "succeeded", @@ -315,7 +315,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { it.effect("fails a result read before the task finishes", () => Effect.gen(function* () { const errors = yield* Effect.forEach(["queued", "running"], (status) => - ai.video.result(model, token).pipe(Effect.flip, Effect.provide(reply({ id: "cgt-1", status }))), + ai.video.result(model, id).pipe(Effect.flip, Effect.provide(reply({ id: "cgt-1", status }))), ) expect(errors.map((error) => error.reason._tag)).toEqual(["InvalidRequest", "InvalidRequest"]) expect(errors[0].message).toBe( @@ -380,7 +380,7 @@ describe("ai.video.status / result / cancel / Seedance", () => { ]) { it.effect(`fails the result of ${terminal.body.error?.code ?? terminal.body.status} tasks with the body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, token).pipe(Effect.flip, Effect.provide(reply(terminal.body))) + const error = yield* ai.video.result(model, id).pipe(Effect.flip, Effect.provide(reply(terminal.body))) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toContain(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -392,10 +392,10 @@ describe("ai.video.status / result / cancel / Seedance", () => { Effect.gen(function* () { const calls: Array = [] yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, {})))))) const refused = yield* ai.video - .cancel(model, token) + .cancel(model, id) .pipe( Effect.flip, Effect.provide( @@ -415,12 +415,4 @@ describe("ai.video.status / result / cancel / Seedance", () => { ]) }), ) - - it.effect("rejects a token from another provider without a request", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { requestID: "req_1" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) }) diff --git a/packages/ai/test/video.test.ts b/packages/ai/test/video.test.ts index 8e78d2e8e03d..529dedb66f40 100644 --- a/packages/ai/test/video.test.ts +++ b/packages/ai/test/video.test.ts @@ -51,7 +51,7 @@ describe("ai.video.start / xAI", () => { ), ), ) - expect(job).toEqual({ id: "req_1", token: { requestID: "req_1" } }) + expect(job).toEqual({ id: "req_1" }) expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ "POST https://xai.test/v1/videos/generations?trace=1", ]) @@ -151,13 +151,12 @@ describe("ai.video.start / xAI", () => { // --------------------------------------------------------------------------- describe("ai.video.status / result / cancel", () => { - it.effect("reads one status per call from a JSON round-tripped token", () => + it.effect("reads one status per call by job ID", () => Effect.gen(function* () { const calls: Array = [] const statuses = yield* Effect.gen(function* () { const job = yield* ai.video.start({ model, prompt: "x" }) - const token: unknown = JSON.parse(JSON.stringify(job.token)) - return [yield* ai.video.status(model, token), yield* ai.video.status(model, token)] + return [yield* ai.video.status(model, job.id), yield* ai.video.status(model, job.id)] }).pipe( Effect.provide( layer((input) => @@ -178,28 +177,28 @@ describe("ai.video.status / result / cancel", () => { }), ) + it.effect("encodes the job ID into the request path", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.video + .status(model, "../files?x=1") + .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, done)))))) + expect(calls.map((call) => call.url)).toEqual(["https://xai.test/v1/videos/..%2Ffiles%3Fx%3D1"]) + }), + ) + it.effect("keeps unknown statuses running, including inherited property names", () => Effect.gen(function* () { const statuses = yield* Effect.forEach(["warming_up", "constructor"], (status) => - ai.video - .status(model, { requestID: "req_1" }) - .pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { status }))))), + ai.video.status(model, "req_1").pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { status }))))), ) expect(statuses.map((value) => value.status)).toEqual(["running", "running"]) }), ) - it.effect("rejects a token from another provider", () => - Effect.gen(function* () { - const error = yield* ai.video.status(model, { operation: "models/x/operations/y" }).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidRequest") - expect(error.message).toContain("cannot resume") - }).pipe(Effect.provide(layer(() => Effect.die("a foreign token reached the network")))), - ) - it.effect("returns the finished video as an expiring URL with xAI metadata", () => Effect.gen(function* () { - const response = yield* ai.video.result(model, { requestID: "req_1" }) + const response = yield* ai.video.result(model, "req_1") expect(response.video.source).toEqual({ type: "url", url: "https://vidgen.x.ai/out.mp4", mediaType: "video/mp4" }) expect(response.video.info).toEqual({ durationSeconds: 10 }) expect(response.providerMetadata).toEqual({ @@ -222,7 +221,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("fails a result read before the job finishes", () => Effect.gen(function* () { - const error = yield* ai.video.result(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.result(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") expect(error.message).toBe("xAI Video generation req_1 has not finished; await it before reading the result") expect(error.reason.body).toBe(JSON.stringify({ status: "pending", progress: 40 })) @@ -261,7 +260,7 @@ describe("ai.video.status / result / cancel", () => { `fails the result of ${terminal.body.error?.code ?? terminal.body.status} jobs with the provider body`, () => Effect.gen(function* () { - const error = yield* ai.video.result(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.result(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe(terminal.tag) expect(error.message).toBe(terminal.message) expect(error.reason.body).toBe(JSON.stringify(terminal.body)) @@ -272,7 +271,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("returns moderated results and fails withheld videos as a content policy failure", () => Effect.gen(function* () { const flagged = yield* ai.video - .result(model, { requestID: "req_1" }) + .result(model, "req_1") .pipe( Effect.provide( layer((input) => @@ -284,7 +283,7 @@ describe("ai.video.status / result / cancel", () => { ) expect(flagged.providerMetadata).toEqual({ xai: { requestId: "req_1", respectModeration: false } }) const withheld = yield* ai.video - .result(model, { requestID: "req_1" }) + .result(model, "req_1") .pipe( Effect.flip, Effect.provide( @@ -297,7 +296,7 @@ describe("ai.video.status / result / cancel", () => { it.effect("fails cancel as unsupported without sending a request, since xAI has no cancel endpoint", () => Effect.gen(function* () { - const error = yield* ai.video.cancel(model, { requestID: "req_1" }).pipe(Effect.flip) + const error = yield* ai.video.cancel(model, "req_1").pipe(Effect.flip) expect(error.reason._tag).toBe("UnsupportedOperation") expect(error.message).toContain("cancel") }).pipe(Effect.provide(layer(() => Effect.die("cancel reached the network")))), @@ -317,8 +316,8 @@ describe("ai.video / transient read failures", () => { const calls: Array = [] const response = yield* settle( Effect.gen(function* () { - expect(yield* ai.video.status(model, { requestID: "req_1" })).toEqual({ status: "completed" }) - return yield* ai.video.result(model, { requestID: "req_1" }) + expect(yield* ai.video.status(model, "req_1")).toEqual({ status: "completed" }) + return yield* ai.video.result(model, "req_1") }), 5, ).pipe( @@ -341,7 +340,7 @@ describe("ai.video / transient read failures", () => { Effect.gen(function* () { const calls: Array = [] const fiber = yield* Effect.forkChild( - ai.video.status(model, { requestID: "req_1" }).pipe( + ai.video.status(model, "req_1").pipe( Effect.provide( layer((input) => Effect.gen(function* () { @@ -364,7 +363,7 @@ describe("ai.video / transient read failures", () => { Effect.gen(function* () { const calls: Array = [] const error = yield* ai.video - .status(model, { requestID: "req_1" }) + .status(model, "req_1") .pipe( Effect.flip, Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => failure(input, 400))))), From de63679df018d91e7bfd81d443971bcabd36372a Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:38:21 -0600 Subject: [PATCH 04/43] docs(core): Console watch tool says CI wakes on a failure and once when all checks finish (#63656) --- packages/core/src/plugin/provider/opencode-watches.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/plugin/provider/opencode-watches.ts b/packages/core/src/plugin/provider/opencode-watches.ts index b0a6b6ac83c4..e951b4758311 100644 --- a/packages/core/src/plugin/provider/opencode-watches.ts +++ b/packages/core/src/plugin/provider/opencode-watches.ts @@ -253,7 +253,7 @@ export const make = Effect.fnUntraced(function* (ctx: Context, http: HttpClient. editor.namespace({ name: namespace, description: - "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console. The session wakes on its own when they change. A pull request it opened wakes it as each check finishes, so don't wait on CI with `gh pr checks --watch`, `gh run watch` or `sleep`.", + "Watch Slack threads, GitHub pull requests, issues, commits and Actions runs, and the workspace's MCP servers' events through OpenCode Console. The session wakes on its own when they change. A pull request it opened wakes it when a check fails and once when all have finished, so don't wait on CI with `gh pr checks --watch`, `gh run watch` or `sleep`.", }) editor.add({ name: "watch", From f2687cc30aca4db94482794b4e37c6ef2229b51c Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:56:05 -0600 Subject: [PATCH 05/43] fix(core): import legacy auth.json only into the user's database file (#63716) --- packages/core/src/database/database.ts | 13 ++++++++----- packages/core/src/database/migration.ts | 4 ++-- packages/core/test/database-migration.test.ts | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/packages/core/src/database/database.ts b/packages/core/src/database/database.ts index b18521b30841..5cf243fd028a 100644 --- a/packages/core/src/database/database.ts +++ b/packages/core/src/database/database.ts @@ -30,7 +30,9 @@ export class Service extends Context.Service()("@opencode/st // releasing a shared semaphore resumes the waiting object's fiber inside the // releasing object's I/O context, where its first storage call is rejected as // cross-object I/O. -const databaseLayer = (lock: Effect.Effect) => +// Only a database file the user opens imports their legacy auth.json; in-memory and injected databases belong to +// embedders and tests, which must not pick up the user's credentials. +const databaseLayer = (lock: Effect.Effect, legacyCredentials = false) => Layer.effect( Service, Effect.gen(function* () { @@ -48,7 +50,7 @@ const databaseLayer = (lock: Effect.Effect) => // Durable Object SQLite always enforces foreign keys and rejects the pragma. if (supportsForeignKeyToggle && !durableObject) yield* db.run("PRAGMA foreign_keys = ON") const semaphore = yield* lock - yield* semaphore.withPermit(DatabaseMigration.apply(db)) + yield* semaphore.withPermit(DatabaseMigration.apply(db, { legacyCredentials })) return { db } }).pipe(Effect.orDie), @@ -70,9 +72,10 @@ export function layer(options: Options = { path: ":memory:" }) { return Layer.unwrap( Effect.gen(function* () { const provide = (filename: string) => - databaseLayer(filename === ":memory:" ? Semaphore.make(1) : Effect.succeed(lockFor(filename))).pipe( - Layer.provide(sqliteLayer({ filename })), - ) + (filename === ":memory:" + ? databaseLayer(Semaphore.make(1)) + : databaseLayer(Effect.succeed(lockFor(filename)), true) + ).pipe(Layer.provide(sqliteLayer({ filename }))) const filename = options.path ?? ":memory:" if (filename === ":memory:") return provide(filename) const file = isAbsolute(filename) ? filename : join((yield* Global.Service).data, filename) diff --git a/packages/core/src/database/migration.ts b/packages/core/src/database/migration.ts index 9f006d1eb561..5d3512820b1a 100644 --- a/packages/core/src/database/migration.ts +++ b/packages/core/src/database/migration.ts @@ -21,7 +21,7 @@ export type Migration = { // Not serialized here: the Database layer holds a lock scoped to the database // it is bootstrapping, since two instances over one file must not race. -export function apply(db: Database) { +export function apply(db: Database, options = { legacyCredentials: true }) { return Effect.gen(function* () { // OpenCode owns the unprefixed table namespace. Embedders sharing this // database may own underscore-prefixed tables, which bootstrap ignores. @@ -36,7 +36,7 @@ export function apply(db: Database) { yield* db.transaction((tx) => Effect.gen(function* () { yield* schema.up(tx) - yield* legacyCredentials.up(tx) + if (options.legacyCredentials) yield* legacyCredentials.up(tx) yield* tx.run( sql`CREATE TABLE ${sql.identifier("migration")} (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`, ) diff --git a/packages/core/test/database-migration.test.ts b/packages/core/test/database-migration.test.ts index bfdfd4adbfd1..fd3bc387e270 100644 --- a/packages/core/test/database-migration.test.ts +++ b/packages/core/test/database-migration.test.ts @@ -553,6 +553,22 @@ describe("DatabaseMigration", () => { ) }) + test("leaves legacy credentials out of in-memory databases", async () => { + await using tmp = await tmpdir() + await Bun.write( + path.join(tmp.path, "auth.json"), + JSON.stringify({ openai: { type: "oauth", refresh: "refresh", access: "access", expires: 123 } }), + ) + + const rows = await Effect.runPromise( + Database.Service.use((database) => database.db.all(sql`SELECT id FROM credential`)).pipe( + Effect.provide(Database.layer({ path: ":memory:" })), + Effect.provideService(Global.Service, Global.make({ data: tmp.path })), + ), + ) + expect(rows).toEqual([]) + }) + test("bootstraps a fresh database when the legacy credential file is malformed", async () => { await using tmp = await tmpdir() await Bun.write(path.join(tmp.path, "auth.json"), "not json") From a554d70499d306242e8fe659aafc82ec431f2483 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:04:03 +0000 Subject: [PATCH 06/43] release: v2.3.0 (#63719) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- CHANGELOG.md | 111 ++++++++++++++++++++++++++ bun.lock | 62 +++++++------- package.json | 2 +- packages/ai/package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 2 +- packages/client/package.json | 2 +- packages/codemode/package.json | 2 +- packages/core/package.json | 2 +- packages/data/app/package.json | 2 +- packages/data/core/package.json | 2 +- packages/data/server/package.json | 2 +- packages/desktop/package.json | 2 +- packages/gui-plugins/package.json | 2 +- packages/http-recorder/package.json | 2 +- packages/httpapi-codegen/package.json | 2 +- packages/latex/package.json | 2 +- packages/merman/package.json | 2 +- packages/nav-menus/package.json | 2 +- packages/patchmark/package.json | 2 +- packages/plugin-browser/package.json | 2 +- packages/plugin/package.json | 2 +- packages/plugins/figma/package.json | 2 +- packages/protocol/package.json | 2 +- packages/schema/package.json | 2 +- packages/sdk/package.json | 2 +- packages/server/package.json | 2 +- packages/session-ui/package.json | 2 +- packages/simulation/package.json | 2 +- packages/theme/package.json | 2 +- packages/tui/package.json | 2 +- packages/ui/package.json | 2 +- packages/util/package.json | 2 +- sdks/vscode/package.json | 2 +- services/update/package.json | 2 +- 35 files changed, 175 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4130730c722..315980ddfe6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,117 @@ Release notes for OpenCode V2, newest first. +## v2.3.0 — 2026-11-13 + +### Highlights + +- **Background Subagents by Default**: Subagents now return immediately, continue in the background, and report back whenever they become idle. You can keep working in the parent session while multiple subagents run concurrently. ([#63382](https://github.com/anomalyco/opencode/pull/63382)) +- **Quieter Transcripts by Default**: The TUI now summarizes each run of tool calls and thoughts into one collapsible activity row, so the answer is easier to follow. To see every step again, set **Verbosity** to `medium` or `high` in settings, or set `session.verbosity` in your TUI config; an existing setting is kept. ([#63207](https://github.com/anomalyco/opencode/pull/63207)) +- **Jump to an Earlier Prompt**: In the desktop app, open **Jump to message** from the command palette or press `Cmd+Alt+G` (`Ctrl+Alt+G` on Windows and Linux) to search prompts across the current session and jump directly to one. ([#63585](https://github.com/anomalyco/opencode/pull/63585)) + +### Core + +#### Improvements + +- Subagents now always run in the background, return their session ID immediately, and report results to their parent whenever they become idle. ([#63382](https://github.com/anomalyco/opencode/pull/63382)) +- Added experimental support for MCP events, behind the `mcp_events` flag. ([#63254](https://github.com/anomalyco/opencode/pull/63254), [#63261](https://github.com/anomalyco/opencode/pull/63261), [#63269](https://github.com/anomalyco/opencode/pull/63269)) +- Shell commands now survive server handoffs and keep their output when interrupted. +- Added experimental support for moving a shell command to the background when its timeout expires, behind the `shell_timeout_background` flag. With the flag on, an explicit timeout on a background command stops it. ([#63024](https://github.com/anomalyco/opencode/pull/63024), [#63703](https://github.com/anomalyco/opencode/pull/63703)) +- Local Windows shell commands now run through the process daemon. +- Added support for freeform tool input on compatible models. +- Added LM Studio decision-model support. +- Agents are now told when their session is a fork. Thanks @hasta84. ([#63235](https://github.com/anomalyco/opencode/pull/63235)) +- Tool output truncation now keeps the beginning of the output and preserves a usable preview if the full output cannot be saved. +- Tail reads no longer load the entire file into memory. +- Providers can present a client certificate for gateways that require mutual TLS. Set `settings.tls` with `cert`, `key` and an optional `passphrase` on the provider; values accept `{file:}` and `{env:}` like `apiKey`. ([#61832](https://github.com/anomalyco/opencode/pull/61832)) +- When a subagent goes idle while its own background work is still running, its report to the parent now says it is still running, so the parent waits for the final report instead of treating the partial answer as done. ([#63675](https://github.com/anomalyco/opencode/pull/63675)) +- Code Mode gets simpler structured results from file and skill tools: `write` and `edit` return their confirmation as a string, `patch` returns an empty result, and `skill` returns the skill's directory and content. ([#63616](https://github.com/anomalyco/opencode/pull/63616), [#63635](https://github.com/anomalyco/opencode/pull/63635), [#63618](https://github.com/anomalyco/opencode/pull/63618), [#63623](https://github.com/anomalyco/opencode/pull/63623)) + +#### Bug fixes + +- Fixed case-only file renames in patches on case-insensitive filesystems. +- Fixed stale thinking being retained after Claude Agent prompts or tools change. +- Fixed directly driven child sessions not resuming after a restart. +- Fixed plugin replacement stopping when cleanup of an earlier plugin fails. +- Fixed MCP OAuth refreshes and localhost redirects when a server rewrites `127.0.0.1`. +- Fixed saved API keys being omitted from local-model discovery. +- Local model discovery (Ollama, LM Studio, vLLM) waits up to 15 seconds per request instead of 1, so remote or tunnelled endpoints list their models, and a slow endpoint no longer delays other endpoints or config reloads. ([#63700](https://github.com/anomalyco/opencode/pull/63700)) +- In Code Mode, calling a namespace as if it were a tool now suggests up to three real tools under it. ([#63697](https://github.com/anomalyco/opencode/pull/63697)) +- Fixed retryable provider streams losing completed work when interrupted. +- Fixed GitHub Copilot requests using the wrong endpoint before models finish loading. +- Fixed exhausted request rate limits being treated as terminal. Thanks @Kyle-j-bush. ([#59816](https://github.com/anomalyco/opencode/pull/59816)) +- Fixed LM Studio models with a null context length and accepted decision-type models. Thanks @tomzhu1024. ([#56214](https://github.com/anomalyco/opencode/pull/56214)) + +### TUI + +#### Improvements + +- Transcript verbosity now defaults to `low`, which summarizes each run of tools and thoughts into one activity row. A `session.verbosity` you already set is kept. ([#63207](https://github.com/anomalyco/opencode/pull/63207)) +- Session IDs found in messages can now be opened directly. +- Activity tabs are clickable and open the correct view. +- Shell mode has its own prompt color under the new designs. + +#### Bug fixes + +- Restored pasted text when undo brings back its placeholder. +- Restored the live draft after browsing prompt history. +- Fixed copying a paste from within the prompt selection. +- Preserved the Mini composer caret when closing the command palette. +- Prevented image bytes from being retained in transcript storage when image previews are disabled. +- Fixed paste-chip contrast across light and dark themes. +- Fixed plugin-provided themes updating live. +- Session lists now open at the top rather than at the current session. +- Mini scrollback now shows the subagent card instead of obsolete launch instructions. + +### Desktop + +#### Improvements + +- Added **Jump to message** to the command palette with `Cmd+Alt+G` / `Ctrl+Alt+G`, including prompts not yet loaded in the timeline. Thanks @usrnk1. ([#63585](https://github.com/anomalyco/opencode/pull/63585)) +- Added the experimental **Recent** sessions sidebar, with cross-server recency, local pins, reordering, and standard session-row actions. +- Recent sessions are limited to the last seven days and 30 rows, and can be hidden or muted. +- Added an experimental customizable sessions sidebar. +- Mermaid diagrams can now be maximized for zooming and panning. ([#59250](https://github.com/anomalyco/opencode/pull/59250)) +- Added `Alt+Enter` to place a follow-up first in the queue and `Mod+Enter` to steer the next queued prompt. +- Holding the modifier key now shows tab shortcut numbers. +- Each server’s terminal shell can be selected from its menu. +- Added a free-limit panel in place of the composer when applicable. +- Session IDs are easier to find and copy. + +#### Bug fixes + +- Recent sessions now keep stable recency ordering through list reloads, renames, and completed runs. +- Fixed browser panes not retrying after server plugins finish loading. +- Fixed mention suggestions being recreated while typing. +- Fixed SSH prompts failing to advance or close after connection. +- Fixed pasted provider-auth redirect URLs being rejected. +- Restored message footers in the New timeline. +- Fixed links whose labels contain inline code. +- Fixed the desktop main process freezing while probing the login-shell environment. +- Fixed the drag region after changing layout direction. +- Fixed vertical-tab previews snapping to the wrong tab. +- Fixed the file-tree sidebar opening animation. +- Fixed pairing QR-code contrast in light themes. Thanks @ssskay. ([#63220](https://github.com/anomalyco/opencode/pull/63220)) +- Fixed activity-tab navigation and click handling. Thanks @OpeOginni. ([#60168](https://github.com/anomalyco/opencode/pull/60168)) + +### SDK + +#### Improvements + +- Event subscriptions can now receive `experimental.mcp.event` events from MCP event subscriptions. +- Model capability schemas now advertise supported freeform tool-input formats. +- Session throughput is now measured from the first streamed token. +- Session creation documentation now clarifies the `parentID` field. + +### Extensions + +#### Improvements + +- Promise-based tools can cooperatively stop through `ToolContext.signal`. +- Added the experimental `session.fork` hook. +- Promise plugin cleanup failures no longer prevent subsequent plugin replacements. +- `@opencode/plugin/effect` now exports `Tool`, so an `execute.before` hook can reject a call with `Tool.Error` without importing `@opencode/schema/tool`. ([#63698](https://github.com/anomalyco/opencode/pull/63698)) + ## v2.2.7 — 2026-11-10 ### Highlights diff --git a/bun.lock b/bun.lock index b4572e69a872..f454e5bb0c34 100644 --- a/bun.lock +++ b/bun.lock @@ -29,7 +29,7 @@ }, "packages/ai": { "name": "@opencode/ai", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@aws-sdk/credential-providers": "3.1057.0", "@opencode/schema": "workspace:*", @@ -51,7 +51,7 @@ }, "packages/app": { "name": "@opencode/app", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@corvu/drawer": "catalog:", "@dnd-kit/abstract": "0.5.0", @@ -106,7 +106,7 @@ }, "packages/cli": { "name": "@opencode/cli", - "version": "2.2.7", + "version": "2.3.0", "bin": { "opencode": "./bin/opencode.cjs", "opencode2": "./bin/opencode2.cjs", @@ -171,7 +171,7 @@ }, "packages/client": { "name": "@opencode/client", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/protocol": "workspace:*", "@opencode/schema": "workspace:*", @@ -197,7 +197,7 @@ }, "packages/codemode": { "name": "@opencode/codemode", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "acorn": "8.15.0", "effect": "catalog:", @@ -210,7 +210,7 @@ }, "packages/core": { "name": "@opencode/core", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@ai-sdk/provider": "3.0.19", "@effect/platform-node": "catalog:", @@ -280,7 +280,7 @@ }, "packages/data/app": { "name": "@opencode/data-app", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@kobalte/core": "catalog:", "@opencode/data-core": "workspace:*", @@ -308,7 +308,7 @@ }, "packages/data/core": { "name": "@opencode/data-core", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@planetscale/database": "1.19.0", "drizzle-orm": "catalog:", @@ -325,7 +325,7 @@ }, "packages/data/server": { "name": "@opencode/data-server", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/data-core": "workspace:*", "effect": "catalog:", @@ -341,7 +341,7 @@ }, "packages/desktop": { "name": "@opencode/desktop", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@zip.js/zip.js": "2.7.62", "electron-context-menu": "5.0.0", @@ -388,7 +388,7 @@ }, "packages/gui-plugins": { "name": "@opencode/gui-plugins", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@betteroffice/docx": "0.4.3", "@betteroffice/fonts": "0.4.0", @@ -433,7 +433,7 @@ }, "packages/http-recorder": { "name": "@opencode/http-recorder", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@effect/platform-node-shared": "catalog:", }, @@ -452,7 +452,7 @@ }, "packages/httpapi-codegen": { "name": "@opencode/httpapi-codegen", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "effect": "catalog:", "prettier": "3.6.2", @@ -465,7 +465,7 @@ }, "packages/latex": { "name": "@opencode/latex", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/plugin": "workspace:*", "@opentui/core": "catalog:", @@ -479,7 +479,7 @@ }, "packages/merman": { "name": "@opencode/merman", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/plugin": "workspace:*", "@opentui/core": "catalog:", @@ -494,7 +494,7 @@ }, "packages/nav-menus": { "name": "@opencode/nav-menus", - "version": "2.2.7", + "version": "2.3.0", "devDependencies": { "@happy-dom/global-registrator": "20.0.11", "@types/bun": "catalog:", @@ -505,7 +505,7 @@ }, "packages/patchmark": { "name": "@opencode/patchmark", - "version": "2.2.7", + "version": "2.3.0", "devDependencies": { "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", @@ -518,7 +518,7 @@ }, "packages/plugin": { "name": "@opencode/plugin", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode/ai": "workspace:*", @@ -563,7 +563,7 @@ }, "packages/plugin-browser": { "name": "@opencode/plugin-browser", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/plugin": "workspace:*", "@opencode/schema": "workspace:*", @@ -578,7 +578,7 @@ }, "packages/plugins/figma": { "name": "@opencode/plugin-figma", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "gray-matter": "4.0.3", }, @@ -593,7 +593,7 @@ }, "packages/protocol": { "name": "@opencode/protocol", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/schema": "workspace:*", "effect": "catalog:", @@ -608,7 +608,7 @@ }, "packages/schema": { "name": "@opencode/schema", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@standard-schema/spec": "catalog:", "effect": "catalog:", @@ -632,7 +632,7 @@ }, "packages/sdk": { "name": "@opencode/sdk", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/client": "workspace:*", "@opencode/core": "workspace:*", @@ -653,7 +653,7 @@ }, "packages/server": { "name": "@opencode/server", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", @@ -676,7 +676,7 @@ }, "packages/session-ui": { "name": "@opencode/session-ui", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@kitlangton/solid-motion": "0.2.2", "@kobalte/core": "catalog:", @@ -708,7 +708,7 @@ }, "packages/simulation": { "name": "@opencode/simulation", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/ai": "workspace:*", "@opencode/core": "workspace:*", @@ -746,7 +746,7 @@ }, "packages/theme": { "name": "@opencode/theme", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opentui/core": "catalog:", "effect": "catalog:", @@ -760,7 +760,7 @@ }, "packages/tui": { "name": "@opencode/tui", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@opencode/client": "workspace:*", "@opencode/core": "workspace:*", @@ -792,7 +792,7 @@ }, "packages/ui": { "name": "@opencode/ui", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@kitlangton/solid-motion": "0.2.2", "@kobalte/core": "catalog:", @@ -828,7 +828,7 @@ }, "packages/util": { "name": "@opencode/util", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "@effect/opentelemetry": "catalog:", "@effect/platform-node": "catalog:", @@ -967,7 +967,7 @@ }, "services/update": { "name": "@opencode/update", - "version": "2.2.7", + "version": "2.3.0", "dependencies": { "jose": "6.0.11", "semver": "catalog:", diff --git a/package.json b/package.json index 2a6bb3fd6fd5..be068aa103ad 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "$schema": "https://json.schemastore.org/package.json", "name": "opencode", "description": "AI-powered development tool", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "packageManager": "bun@1.4.4", diff --git a/packages/ai/package.json b/packages/ai/package.json index 4225e67ebdc2..776cc31ec4b8 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "2.2.7", + "version": "2.3.0", "name": "@opencode/ai", "type": "module", "license": "MIT", diff --git a/packages/app/package.json b/packages/app/package.json index 43d1204cbf69..6b76d843204f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/app", - "version": "2.2.7", + "version": "2.3.0", "description": "", "type": "module", "exports": { diff --git a/packages/cli/package.json b/packages/cli/package.json index c4ab68a394d2..232259ba3265 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/cli", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "bin": { diff --git a/packages/client/package.json b/packages/client/package.json index a9341a6342f0..d2236f03a8d1 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/client", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/codemode/package.json b/packages/codemode/package.json index 16650e2574e3..7f256b2a3aeb 100644 --- a/packages/codemode/package.json +++ b/packages/codemode/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/codemode", - "version": "2.2.7", + "version": "2.3.0", "description": "Effect-native confined code execution over schema-described tools", "type": "module", "license": "MIT", diff --git a/packages/core/package.json b/packages/core/package.json index 17d3523e170d..d036299f6879 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "2.2.7", + "version": "2.3.0", "name": "@opencode/core", "type": "module", "license": "MIT", diff --git a/packages/data/app/package.json b/packages/data/app/package.json index 4f820ecc9538..6df85f0cbc71 100644 --- a/packages/data/app/package.json +++ b/packages/data/app/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/data-app", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/data/core/package.json b/packages/data/core/package.json index fa82a434c8c6..0661bbfd8e70 100644 --- a/packages/data/core/package.json +++ b/packages/data/core/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/data-core", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/data/server/package.json b/packages/data/server/package.json index 68b25c7e7606..ee94bda8e0c2 100644 --- a/packages/data/server/package.json +++ b/packages/data/server/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/data-server", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 080ff96607b0..57c342590155 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@opencode/desktop", "private": true, - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "homepage": "https://opencode.ai", diff --git a/packages/gui-plugins/package.json b/packages/gui-plugins/package.json index 165d02635d8f..ec7002e7b8f5 100644 --- a/packages/gui-plugins/package.json +++ b/packages/gui-plugins/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/gui-plugins", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/http-recorder/package.json b/packages/http-recorder/package.json index ca1bf59b168e..c1b693600b00 100644 --- a/packages/http-recorder/package.json +++ b/packages/http-recorder/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "2.2.7", + "version": "2.3.0", "name": "@opencode/http-recorder", "description": "Record and replay Effect HTTP and WebSocket traffic with deterministic cassettes", "type": "module", diff --git a/packages/httpapi-codegen/package.json b/packages/httpapi-codegen/package.json index c7c5d539e329..d6a23118aabd 100644 --- a/packages/httpapi-codegen/package.json +++ b/packages/httpapi-codegen/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/httpapi-codegen", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "exports": { diff --git a/packages/latex/package.json b/packages/latex/package.json index 3d9dc127f835..01e1a07b36e6 100644 --- a/packages/latex/package.json +++ b/packages/latex/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/latex", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "exports": { diff --git a/packages/merman/package.json b/packages/merman/package.json index d88c09fc2e30..9e7e091c02aa 100644 --- a/packages/merman/package.json +++ b/packages/merman/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/merman", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "exports": { diff --git a/packages/nav-menus/package.json b/packages/nav-menus/package.json index b8f1b51f017f..347aa76137e6 100644 --- a/packages/nav-menus/package.json +++ b/packages/nav-menus/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/nav-menus", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/patchmark/package.json b/packages/patchmark/package.json index 365586be562d..ae47158a4f05 100644 --- a/packages/patchmark/package.json +++ b/packages/patchmark/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/patchmark", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/plugin-browser/package.json b/packages/plugin-browser/package.json index 9797aeb6d929..f62071eb9e0b 100644 --- a/packages/plugin-browser/package.json +++ b/packages/plugin-browser/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/plugin-browser", - "version": "2.2.7", + "version": "2.3.0", "description": "OpenCode's desktop browser plugin", "type": "module", "license": "MIT", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 75a385a94fdd..3a2b9f1070bb 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/plugin", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "scripts": { diff --git a/packages/plugins/figma/package.json b/packages/plugins/figma/package.json index e6a823358fbe..fa4124fe976a 100644 --- a/packages/plugins/figma/package.json +++ b/packages/plugins/figma/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/plugin-figma", - "version": "2.2.7", + "version": "2.3.0", "description": "Figma MCP integration and official Figma skills for OpenCode", "type": "module", "license": "MIT", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 95322f82ecc1..ab46122371be 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/protocol", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/schema/package.json b/packages/schema/package.json index d56448daf16f..902caec18c34 100644 --- a/packages/schema/package.json +++ b/packages/schema/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/schema", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 060dae2bb390..7d90452f20f0 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "2.2.7", + "version": "2.3.0", "name": "@opencode/sdk", "type": "module", "license": "MIT", diff --git a/packages/server/package.json b/packages/server/package.json index b6b2b0e02e13..a598638a2aae 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/server", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/session-ui/package.json b/packages/session-ui/package.json index 104aa4898bc9..2363de96914b 100644 --- a/packages/session-ui/package.json +++ b/packages/session-ui/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/session-ui", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/simulation/package.json b/packages/simulation/package.json index 14d5ea9dea25..43d88a6dcbe9 100644 --- a/packages/simulation/package.json +++ b/packages/simulation/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/simulation", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/theme/package.json b/packages/theme/package.json index 85a3baa81c55..b8b90d54b49c 100644 --- a/packages/theme/package.json +++ b/packages/theme/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/theme", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/tui/package.json b/packages/tui/package.json index b75c0ea71564..7bbccc0273fd 100644 --- a/packages/tui/package.json +++ b/packages/tui/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/tui", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "license": "MIT", diff --git a/packages/ui/package.json b/packages/ui/package.json index 18fddd26c790..c9ef71caa4b6 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@opencode/ui", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/packages/util/package.json b/packages/util/package.json index 7c5fdf03559a..eacd6dff07a0 100644 --- a/packages/util/package.json +++ b/packages/util/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/util", - "version": "2.2.7", + "version": "2.3.0", "type": "module", "license": "MIT", "repository": { diff --git a/sdks/vscode/package.json b/sdks/vscode/package.json index 6ab9e3402696..9205385b1e4d 100644 --- a/sdks/vscode/package.json +++ b/sdks/vscode/package.json @@ -2,7 +2,7 @@ "name": "opencode", "displayName": "opencode", "description": "opencode for VS Code", - "version": "2.2.7", + "version": "2.3.0", "publisher": "sst-dev", "repository": { "type": "git", diff --git a/services/update/package.json b/services/update/package.json index 7d9c7a9e63f5..2560a3a2c1e5 100644 --- a/services/update/package.json +++ b/services/update/package.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/package.json", "name": "@opencode/update", - "version": "2.2.7", + "version": "2.3.0", "private": true, "type": "module", "scripts": { From 688b60c078b07afd2c0b614f543732488caee939 Mon Sep 17 00:00:00 2001 From: Aarav Sareen <96787824+arvsrn@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:34:10 +0530 Subject: [PATCH 07/43] fix(app): keep new timeline status below reports and shorten file lists (#63686) --- .../src/session/timeline/message-timeline.tsx | 5 +- .../src/timeline-next/projection.test.ts | 62 +++++++++++++++++ .../src/timeline-next/projection.ts | 18 ++--- packages/session-ui/src/timeline-next/row.tsx | 1 + .../src/timeline-next/status-line.tsx | 3 + .../src/timeline-next/timeline-next.css | 10 +++ .../src/timeline-next/tools/context-group.tsx | 3 +- .../session-ui/src/tools/tool-renderer.tsx | 67 +++++++++++++------ 8 files changed, 138 insertions(+), 31 deletions(-) diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index 8f498fe8ea6a..591a7b843b3f 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -513,7 +513,7 @@ function MessageTimelineView( // The lane keeps its height while empty, so Working and the hint come and go without moving the rows around it. // The bottom lane also keeps its height while live status moves into the Activity row, so the tail the activity pill // floats in never closes and a pinned timeline does not shift when input waits. - const activity = (live: () => boolean) => ( + const activity = (live: () => boolean, inRow = false) => (
@@ -567,7 +568,7 @@ function MessageTimelineView( // row: Working hides and returns several times in one step, and each change would move that input 36px. const shown = createMemo((was) => was || working() || backgroundHintPresence.present(), false) - return {activity(() => true)} + return {activity(() => true, true)} }} )} diff --git a/packages/session-ui/src/timeline-next/projection.test.ts b/packages/session-ui/src/timeline-next/projection.test.ts index 0aa1b5280854..71431a34a698 100644 --- a/packages/session-ui/src/timeline-next/projection.test.ts +++ b/packages/session-ui/src/timeline-next/projection.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test" import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise" import { Predicate } from "effect" import { createRoot } from "solid-js" +import { subagentReport } from "../storybook/current-session-fixtures" import { timelinePresets } from "../timeline/detail" import { createNextTimelineProjection, workedDuration } from "./projection" import { replayScript, scenarios } from "./stories/session-replay" @@ -87,6 +88,67 @@ describe("New timeline projection", () => { expect(groups).toEqual(["first", "notice", "second"]) }) + + test("a subagent's report shows above the status line before the agent takes it, and the user's input below", () => { + const steer = { id: "steer", type: "user", text: "Also check the tests", time: { created: 2 } } as const + + const messages: SessionMessageInfo[] = [ + { id: "user", type: "user", text: "Go", time: { created: 0 } }, + step("working", 1, { + content: [ + { + id: "shell", + type: "tool", + name: "shell", + state: { status: "running", input: { command: "sleep 60" }, metadata: {} }, + time: { created: 1 }, + }, + ], + }), + steer, + subagentReport("report", 3, { + childID: "child", + agent: "explore", + state: "completed", + description: "Trace the bug", + body: "Found it.", + }), + ] + + const rows = (messages: SessionMessageInfo[], pending: ReadonlySet) => + createRoot((dispose) => { + const projection = createNextTimelineProjection({ + sessionMessages: () => messages, + status: () => ({ type: "busy" }), + timelineDetail: () => detailed, + pendingInputIDs: () => pending, + }) + + const result = projection.rows().map((row) => { + if (!Predicate.isTagged(row, "AssistantPart")) return row._tag + + return row.group.type === "part" + ? row.group.ref.messageID + : row.group.refs.map((ref) => ref.messageID).join("+") + }) + + dispose() + + return result + }) + + const alone = messages.filter((message) => message !== steer) + + expect(rows(alone, new Set(["report"]))).toEqual(["UserMessage", "working", "report"]) + expect(rows(messages, new Set(["steer", "report"]))).toEqual([ + "UserMessage", + "working", + "report", + "Activity", + "TurnGap", + "UserMessage", + ]) + }) }) describe("workedDuration", () => { diff --git a/packages/session-ui/src/timeline-next/projection.ts b/packages/session-ui/src/timeline-next/projection.ts index ff2c382cf9f0..c7a5d4c34b2b 100644 --- a/packages/session-ui/src/timeline-next/projection.ts +++ b/packages/session-ui/src/timeline-next/projection.ts @@ -314,18 +314,14 @@ function constructRows(input: Input) { }), ] - // Like the TUI, a queued compaction waits after the active turn and ahead of every undelivered input: - // steers, which own turns, and synthetic notices, which ride at the end of the active one. - const pendingAt = rows.findIndex( - (row) => - input.pendingInputIDs?.has(row.userMessageID) || - (Predicate.isTagged(row, "Notice") && input.pendingInputIDs?.has(row.messageID)), - ) + // Like the TUI, a queued compaction waits after the active turn and ahead of every steer still waiting for delivery. + // Notices waiting for delivery are already in the active turn, since they report what happened. + const pendingAt = rows.findIndex((row) => input.pendingInputIDs?.has(row.userMessageID)) rows.splice( pendingAt < 0 ? rows.length : pendingAt, 0, - // Live status ends the work the model has seen, so it stays above everything still waiting for delivery. + // Live status ends the turn, so it stays above the input the user steered in, which waits for the agent to reply. ...(input.status.type !== "idle" && activeMessageID && (pendingAt >= 0 || input.queuedCompactionIDs.length > 0) ? [new TimelineRow.Activity({ userMessageID: activeMessageID })] : []), @@ -380,7 +376,11 @@ function constructTurns(input: Input) { if (echoesUserShell(message, userShellIDs)) return if (isNotice(message)) { - if (current) current.entries.push({ type: "notice", message }) + // A notice still waiting for delivery, such as a subagent reporting back, already happened, so it joins the + // working turn above the status line, even when input the user steered in meanwhile waits below it. + const turn = input.pendingInputIDs?.has(message.id) ? (execution?.turn ?? current) : current + + if (turn) turn.entries.push({ type: "notice", message }) else leading.push(message) return diff --git a/packages/session-ui/src/timeline-next/row.tsx b/packages/session-ui/src/timeline-next/row.tsx index 4ffa71fcc230..b2b83513b99a 100644 --- a/packages/session-ui/src/timeline-next/row.tsx +++ b/packages/session-ui/src/timeline-next/row.tsx @@ -460,6 +460,7 @@ export function createNextTimelineRowRenderer(input: { return ( input.disclosure.set(row().group.key, open)} onSizeChange={onSizeChange} diff --git a/packages/session-ui/src/timeline-next/status-line.tsx b/packages/session-ui/src/timeline-next/status-line.tsx index b7ee04e680f2..88d34a12c114 100644 --- a/packages/session-ui/src/timeline-next/status-line.tsx +++ b/packages/session-ui/src/timeline-next/status-line.tsx @@ -12,6 +12,8 @@ export function StatusLane(props: { collapsed?: boolean /** The space above the next row of the turn, so the line sits where that row will. */ spacing?: TimelineGap + /** The lane sits in a row of the timeline, which clips what reaches past it, rather than in its open tail. */ + inRow?: boolean class?: string children?: JSX.Element }) { @@ -21,6 +23,7 @@ export function StatusLane(props: { data-component="timeline-status-lane" data-collapsed={props.collapsed ? "" : undefined} data-spacing={props.spacing} + data-in-row={props.inRow ? "" : undefined} class={props.class} > diff --git a/packages/session-ui/src/timeline-next/timeline-next.css b/packages/session-ui/src/timeline-next/timeline-next.css index 83dba6cc5847..d4a7ac385321 100644 --- a/packages/session-ui/src/timeline-next/timeline-next.css +++ b/packages/session-ui/src/timeline-next/timeline-next.css @@ -581,9 +581,19 @@ --timeline-status-space: var(--timeline-gap-l); } + /* The background hint's 24px button is centred on the 16px line and reaches 4px past it. A row clips at its own + height, so in a row the lane keeps that room below the line, whether or not the hint shows, so the input waiting + below does not move when it comes and goes. */ + &[data-in-row] { + --timeline-status-hint-overflow: calc((24px - var(--line-height-compact)) / 2); + height: calc(var(--line-height-compact) + var(--timeline-status-space) + var(--timeline-status-hint-overflow)); + padding-bottom: var(--timeline-status-hint-overflow); + } + &[data-collapsed] { height: 0; padding-top: 0; + padding-bottom: 0; overflow: hidden; } diff --git a/packages/session-ui/src/timeline-next/tools/context-group.tsx b/packages/session-ui/src/timeline-next/tools/context-group.tsx index 15e761e4576a..a0532fa76af5 100644 --- a/packages/session-ui/src/timeline-next/tools/context-group.tsx +++ b/packages/session-ui/src/timeline-next/tools/context-group.tsx @@ -285,6 +285,7 @@ function GroupItem(props: { props.onToolOpenChange?.(tool().id, open)} onSizeChange={props.onSizeChange} @@ -542,7 +543,7 @@ function activityLabel(group: SessionMessageAssistantTool[], i18n: UiI18n) { const main = { // A few files read better by name; past that, the count says more than a list that truncates. edit: - files.length <= 3 + files.length <= 2 ? files.map((path) => getFilename(path)).join(", ") : i18n.plural("ui.timeline.activity.files", files.length), run: commands[0]!, diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 66d56646609f..1e8fe7d6cf9c 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -865,26 +865,48 @@ export function CurrentReadToolGroup(props: { open?: boolean onOpenChange?: (open: boolean) => void onSizeChange?: () => void + /** Names each file once, and up to this many while closed; past that the closed row says how many files. */ + names?: number }) { const i18n = useI18n() const [state, setState] = createStore({ truncated: false }) const disclosure = createDisclosure({ open: () => props.open, onOpenChange: (open) => props.onOpenChange?.(open) }) const open = disclosure.open - const expandable = () => open() || state.truncated const pending = createMemo(() => props.tools.some((tool) => tool.state.status === "streaming" || tool.state.status === "running"), ) - const files = createMemo(() => - props.tools.flatMap((tool) => { + const files = createMemo(() => { + const reads = props.tools.flatMap((tool) => { const input = toolInput(currentToolInput(tool)) const name = getFilename(input.path ?? "") - return name ? [{ id: tool.id, name, args: readArgs(input) }] : [] - }), + return name ? [{ id: tool.id, path: input.path ?? "", name, args: readArgs(input) }] : [] + }) + + if (props.names === undefined) return reads + + // A file read in several ranges is named once, without one range standing for the rest. + return [ + ...reads + .reduce((unique, file) => { + const seen = unique.get(file.path) + + return unique.set(file.path, seen ? { ...seen, args: [] } : file) + }, new Map()) + .values(), + ] + }) + + const summary = createMemo(() => + props.names !== undefined && !open() && files().length > props.names + ? i18n.plural("ui.timeline.activity.files", files().length) + : undefined, ) + const expandable = () => open() || state.truncated || !!summary() + let list: HTMLSpanElement | undefined const measure = () => { @@ -925,20 +947,27 @@ export function CurrentReadToolGroup(props: { - - {(file, index) => ( - <> - 0}> - - {file().name} - - {(arg) => {` ${arg}`}} - - , - - - )} - + + {(file, index) => ( + <> + 0}> + + {file().name} + + {(arg) => {` ${arg}`}} + + , + + + )} + + } + > + {(text) => text()} +
From f2156d79c9b3c313f999246562ecfba1513880bf Mon Sep 17 00:00:00 2001 From: Aarav Sareen <96787824+arvsrn@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:42:03 +0530 Subject: [PATCH 08/43] fix(app): show subagents in grouped activity as events in the New timeline (#63685) --- .../src/timeline-next/event-row.tsx | 3 +- .../session-ui/src/timeline-next/events.ts | 11 +- .../src/timeline-next/projection.test.ts | 67 +++- .../src/timeline-next/projection.ts | 41 +- packages/session-ui/src/timeline-next/row.tsx | 10 +- .../session-ui/src/timeline-next/rules.ts | 2 +- .../src/timeline-next/timeline-next.css | 7 +- .../src/timeline-next/tools/context-group.tsx | 373 ++++++++++++------ packages/ui/src/i18n/en.ts | 8 + 9 files changed, 385 insertions(+), 137 deletions(-) diff --git a/packages/session-ui/src/timeline-next/event-row.tsx b/packages/session-ui/src/timeline-next/event-row.tsx index b612d7a39be1..b00622c01665 100644 --- a/packages/session-ui/src/timeline-next/event-row.tsx +++ b/packages/session-ui/src/timeline-next/event-row.tsx @@ -70,7 +70,8 @@ export function TimelineEventRow(props: { ) } -function TimelineEventItem(props: { event: TimelineEvent; onRevealShell?: (shellID: string) => void }) { +/** One subagent or shell an events row or an opened activity group lists: who did it and what it was. */ +export function TimelineEventItem(props: { event: TimelineEvent; onRevealShell?: (shellID: string) => void }) { const i18n = useI18n() const data = useData() diff --git a/packages/session-ui/src/timeline-next/events.ts b/packages/session-ui/src/timeline-next/events.ts index d4d159f23bbe..fbc3cf699c29 100644 --- a/packages/session-ui/src/timeline-next/events.ts +++ b/packages/session-ui/src/timeline-next/events.ts @@ -35,10 +35,12 @@ export const kindKeys = { shell: "ui.timeline.event.shells", } as const -/** How a group's label counts work it started, beside its other calls: "1 command, started 1 shell". */ +/** How a group's label counts work that runs on, beside its other calls: "1 command, started 1 shell". */ export const launchKeys = { started: { shell: "ui.timeline.activity.startedShells", subagent: "ui.timeline.activity.startedSubagents" }, ran: { shell: "ui.timeline.activity.commands", subagent: "ui.timeline.activity.subagents" }, + finished: { shell: "ui.timeline.activity.finishedShells", subagent: "ui.timeline.activity.finishedSubagents" }, + stopped: { shell: "ui.timeline.activity.stoppedShells", subagent: "ui.timeline.activity.stoppedSubagents" }, } as const // Text a call or notice carries, where it is not empty. @@ -99,6 +101,13 @@ export function noticeEvent(message: SessionMessageInfo): TimelineEvent | undefi return { ...item, verb: "finished", failed: state === "error" } } +/** Which subagent or shell an event is about, where it says. */ +export function workKey(event: TimelineEvent) { + const id = event.kind === "shell" ? event.shellID : event.sessionID + + return id ? `${event.kind}:${id}` : undefined +} + /** * A run of events as one label: each verb once, in the order it first happened, with how many of each kind, and how * many failed overall. Two finishes in a row read "Finished 2 subagents". diff --git a/packages/session-ui/src/timeline-next/projection.test.ts b/packages/session-ui/src/timeline-next/projection.test.ts index 71431a34a698..549e2513abb6 100644 --- a/packages/session-ui/src/timeline-next/projection.test.ts +++ b/packages/session-ui/src/timeline-next/projection.test.ts @@ -3,7 +3,7 @@ import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } import { Predicate } from "effect" import { createRoot } from "solid-js" import { subagentReport } from "../storybook/current-session-fixtures" -import { timelinePresets } from "../timeline/detail" +import { timelinePresets, type TimelineDetail } from "../timeline/detail" import { createNextTimelineProjection, workedDuration } from "./projection" import { replayScript, scenarios } from "./stories/session-replay" @@ -149,6 +149,71 @@ describe("New timeline projection", () => { "UserMessage", ]) }) + + test("a subagent finishes in the group that started it only when nothing comes between; otherwise it reports in its own row", () => { + const launched: SessionMessageInfo[] = [ + { id: "user", type: "user", text: "Go", time: { created: 0 } }, + step("launch", 1, { + finish: "tool-calls", + content: [ + { + id: "call", + type: "tool", + name: "subagent", + state: { + status: "completed", + input: { description: "Review the diff", agent: "review" }, + content: [{ type: "text", text: "" }], + metadata: { sessionID: "child", status: "running" }, + }, + time: { created: 1, completed: 2 }, + }, + ], + time: { created: 1, completed: 2 }, + }), + ] + + const report = subagentReport("report", 4, { + childID: "child", + agent: "review", + state: "completed", + description: "Review the diff", + body: "Looks good.", + }) + + const said = step("said", 3, { + finish: "stop", + content: [{ type: "text", text: "Started a review." }], + time: { created: 3, completed: 3 }, + }) + + const groups = (messages: SessionMessageInfo[], detail: TimelineDetail) => + createRoot((dispose) => { + const projection = createNextTimelineProjection({ + sessionMessages: () => messages, + status: () => ({ type: "idle" }), + timelineDetail: () => detail, + }) + + const result = projection + .rows() + .flatMap((row) => + Predicate.isTagged(row, "AssistantPart") && row.group.type !== "part" + ? [`${row.group.type}:${row.group.refs.map((ref) => ref.messageID).join("+")}`] + : [], + ) + + dispose() + + return result + }) + + const grouped = { ...detailed, subagents: { placement: "grouped" as const } } + + expect(groups([...launched, report], grouped)).toEqual(["context:launch+report"]) + expect(groups([...launched, said, report], grouped)).toEqual(["context:launch", "events:report"]) + expect(groups([...launched, report], detailed)).toEqual(["events:launch", "events:report"]) + }) }) describe("workedDuration", () => { diff --git a/packages/session-ui/src/timeline-next/projection.ts b/packages/session-ui/src/timeline-next/projection.ts index c7a5d4c34b2b..5edf5cea944b 100644 --- a/packages/session-ui/src/timeline-next/projection.ts +++ b/packages/session-ui/src/timeline-next/projection.ts @@ -22,7 +22,7 @@ import { type TurnThinkingPlacement, } from "../timeline/turn-phase-machine" import { errorInfo } from "./errors" -import { noticeEvent } from "./events" +import { noticeEvent, toolEvent, workKey, type TimelineEvent } from "./events" import { contentGroup, contentShows, @@ -31,6 +31,7 @@ import { liveThinkingShows, noticePlacement, textShows, + toolRule, } from "./rules" type Notice = Exclude @@ -651,6 +652,25 @@ function groupNotices( // Live status renders nothing while other feedback shows, so a group below it spaces from the content above it. const above = Predicate.isTagged(previous, "Activity") ? result.at(-2) : previous const message = Predicate.isTagged(row, "Notice") ? messageByID.get(row.messageID) : undefined + const event = message && noticeEvent(message) + + // Work that reports back right after the activity group that started it, with nothing between, finishes there. + if ( + event && + !event.failed && + Predicate.isTagged(previous, "AssistantPart") && + previous.group.type === "context" && + previous.userMessageID === row.userMessageID && + launches(previous.group, event, messageByID) + ) { + result[result.length - 1] = new TimelineRow.AssistantPart({ + ...previous, + group: { ...previous.group, refs: [...previous.group.refs, { messageID: message.id, partID: message.id }] }, + }) + + return result + } + const type = message ? noticeGroup(detail, message) : undefined const current = @@ -710,6 +730,25 @@ function joins( return previous.type === "events" && current.type === "events" && notices(previous) && notices(current) } +// Whether an activity group started the work an event is about. +function launches( + group: Exclude, + event: TimelineEvent, + messageByID: ReadonlyMap, +) { + const key = workKey(event) + + return ( + key !== undefined && + group.refs.some((ref) => { + const content = resolveContent(messageByID.get(ref.messageID), ref.partID) + const launch = content?.type === "tool" && toolRule(content).layout === "event" ? toolEvent(content) : undefined + + return launch !== undefined && workKey(launch) === key + }) + ) +} + function noticeGroup(detail: TimelineDetail, message: SessionMessageInfo) { if (noticeEvent(message)) return "events" as const diff --git a/packages/session-ui/src/timeline-next/row.tsx b/packages/session-ui/src/timeline-next/row.tsx index b2b83513b99a..5b0b04ecddfd 100644 --- a/packages/session-ui/src/timeline-next/row.tsx +++ b/packages/session-ui/src/timeline-next/row.tsx @@ -32,7 +32,7 @@ import { useSources } from "../context/sources" import { turnSources } from "../sources/sources" import { SessionReadToolGroup, SessionUserMessage } from "../message/current-message" import { SessionCompactionMessage, SessionCompactionQueued } from "../message/message-content" -import { taskAgentName, type ContextGroupPart } from "../tools/tool-renderer" +import { taskAgentName } from "../tools/tool-renderer" import { SessionRetry } from "../components/session-retry" import { SessionError } from "../components/session-error" import type { TimelineDetail } from "../timeline/detail" @@ -57,7 +57,7 @@ import { contentOpens, diffOpens, goal as goalMessage, thoughtOpens, toolRule, u import { Separator } from "./separator" import { timelineGaps } from "./spacing" import { AssistantContent } from "./tools/assistant-content" -import { ContextGroup } from "./tools/context-group" +import { ContextGroup, type ActivityGroupPart } from "./tools/context-group" import { FileGroup } from "./tools/file-group" import { PatchTool } from "./tools/patch" import { ShellMessage } from "./tools/shell" @@ -335,7 +335,7 @@ export function createNextTimelineRowRenderer(input: { const contents = indexGroupContents(group.refs) const streaming = phase(row().userMessageID).streamingReasoningRef - return group.refs.flatMap((ref) => { + return group.refs.flatMap((ref) => { const content = contents.get(ref.messageID)?.get(ref.partID) if (content?.type === "tool") { @@ -364,6 +364,9 @@ export function createNextTimelineRowRenderer(input: { ] if (ref.messageID !== ref.partID || !message) return [] + const event = noticeEvent(message) + + if (event) return [{ type: "event", id: ref.partID, event }] if (message.type !== "assistant" && message.type !== "user") return [{ type: "notice", id: ref.partID, render: () => }] @@ -402,6 +405,7 @@ export function createNextTimelineRowRenderer(input: { open={input.disclosure.value(key()) === true} onOpenChange={(open) => input.disclosure.set(key(), open)} onSizeChange={onSizeChange} + onRevealShell={input.revealPart} /> ) diff --git a/packages/session-ui/src/timeline-next/rules.ts b/packages/session-ui/src/timeline-next/rules.ts index 506668b30b06..6b55eb4a4932 100644 --- a/packages/session-ui/src/timeline-next/rules.ts +++ b/packages/session-ui/src/timeline-next/rules.ts @@ -208,7 +208,7 @@ export function echoesUserShell(message: SessionMessageInfo, userShellIDs: Reado /** * Where a notice shows. What the user did and what changed the session always stands on its own. Background work - * reports its outcome as its own row, following the setting its launch follows: a subagent's the subagent setting, a + * reports its outcome as an event, following the setting its launch follows: a subagent's the subagent setting, a * shell's the shell setting. */ export function noticePlacement(detail: TimelineDetail, message: SessionMessageInfo): TimelinePlacement { diff --git a/packages/session-ui/src/timeline-next/timeline-next.css b/packages/session-ui/src/timeline-next/timeline-next.css index d4a7ac385321..326ace238aa9 100644 --- a/packages/session-ui/src/timeline-next/timeline-next.css +++ b/packages/session-ui/src/timeline-next/timeline-next.css @@ -323,13 +323,15 @@ } /* An event row opens to the subagents and shells it counts, each read like a nested row and leading to its session or - to the call that ran it. */ + to the call that ran it. An opened activity group lists the ones it started or heard back from the same way. */ [data-timeline="next"] [data-component="timeline-event-list"] { display: flex; flex-direction: column; gap: 8px; padding-top: 4px; +} +[data-timeline="next"] :is([data-component="timeline-event-list"], [data-slot="context-tool-group-item"]) { [data-slot="timeline-event-item"] { display: flex; align-items: center; @@ -376,7 +378,7 @@ color: var(--v2-text-text-base); } - [data-component="tag"] { + [data-slot="timeline-event-item"] [data-component="tag"] { flex-shrink: 0; } } @@ -517,6 +519,7 @@ } [data-component="context-tool-group-list"] [data-slot="context-tool-group-item"], + [data-component="context-tool-group-list"] [data-slot="timeline-event-item"], [data-component="timeline-event-list"] [data-slot="timeline-event-item"] { min-height: var(--line-height-compact); } diff --git a/packages/session-ui/src/timeline-next/tools/context-group.tsx b/packages/session-ui/src/timeline-next/tools/context-group.tsx index a0532fa76af5..24fcc42ba700 100644 --- a/packages/session-ui/src/timeline-next/tools/context-group.tsx +++ b/packages/session-ui/src/timeline-next/tools/context-group.tsx @@ -24,19 +24,26 @@ import { toolMetadata, type ContextGroupPart, } from "../../tools/tool-renderer" -import { kindKeys, launchKeys, summarizeEvents, toolEvent, verbKeys } from "../events" +import { TimelineEventRow } from "../event-row" +import { kindKeys, launchKeys, summarizeEvents, toolEvent, verbKeys, workKey, type TimelineEvent } from "../events" import { toolRule, toolStopped, type ToolMode } from "../rules" import { FileGroup } from "./file-group" import { ThoughtRow } from "./thought" import { ToolDisplay } from "./tool-display" +/** A part of an activity group: a call, a thought, a notice, or background work reporting back. */ +export type ActivityGroupPart = ContextGroupPart | { type: "event"; id: string; event: TimelineEvent } + +// Subagents and background work listed one after another in an opened group, as one nested events row. +type WorkRun = { type: "work"; id: string; events: TimelineEvent[] } + /** * A stretch of the agent's work folded into one row, named by what it did: "Explored 3 files · 2 commands". It only * records what happened; the status line below the turn says what is live. A stretch of thoughts alone is those * thoughts, without a group around them. */ export function ContextGroup(props: { - parts: ContextGroupPart[] + parts: ActivityGroupPart[] open: boolean onOpenChange: (open: boolean) => void onSizeChange?: () => void @@ -49,12 +56,24 @@ export function ContextGroup(props: { fileOpen?: (path: string) => boolean | undefined onFileOpenChange?: (path: string, open: boolean) => void patchGroupKey?: (tools: SessionMessageAssistantTool[]) => string + onRevealShell?: (shellID: string) => void }) { const i18n = useI18n() const tools = createMemo(() => props.parts.filter((part) => part.type === "tool")) const reasoning = createMemo(() => props.parts.flatMap((part) => (part.type === "reasoning" ? [part] : []))) const thoughtsOnly = createMemo(() => reasoning().length > 0 && reasoning().length === props.parts.length) - const activity = createMemo(() => activityLabel(tools(), i18n)) + const partEvents = createMemo(() => workEvents(props.parts)) + const events = createMemo(() => [...partEvents().values()]) + + // A group of only subagents and work reporting back reads as the events row it is, not a group around one. Until a + // call has anything to count, it stays a group, so the row never renders empty. + const workOnly = createMemo( + () => + events().length > 0 && + props.parts.every((part) => part.type === "event" || (part.type === "tool" && toolRule(part).name === "subagent")), + ) + + const activity = createMemo(() => activityLabel(tools(), events(), i18n)) const label = createMemo(() => { const value = activity() @@ -69,16 +88,40 @@ export function ContextGroup(props: { const items = createMemo(() => (props.open ? props.parts : []).reduce< - (SessionMessageAssistantTool[] | Exclude)[] + ( + | SessionMessageAssistantTool[] + | Exclude + | WorkRun + )[] >((groups, tool) => { + const previous = groups.at(-1) + + // Subagents started one after another, and work reporting back, read as one events row nested in the group: + // "Started 3 subagents". + if (tool.type === "event" || (tool.type === "tool" && toolRule(tool).name === "subagent")) { + // A subagent still being asked for has nothing to list yet, and a report its launch already says is not + // listed twice. + const event = partEvents().get(tool) + + if (!event) return groups + + if (previous && !Array.isArray(previous) && previous.type === "work") { + previous.events.push(event) + + return groups + } + + groups.push({ type: "work", id: tool.id, events: [event] }) + + return groups + } + if (tool.type !== "tool") { groups.push(tool) return groups } - const previous = groups.at(-1) - if (Array.isArray(previous) && previous[0] && joins(previous[0], tool)) { previous.push(tool) @@ -136,113 +179,152 @@ export function ContextGroup(props: { } > -
part.id).join(",")} + part.id).join(",")}> + +
+ } > - - }> - {(value) => ( - - {value().verb} - - {value().main} - - 0}> - - {value().others.join(", ")} - - - )} - - - } +
part.id).join(",")} > -
- - {(item) => { - const group = createMemo(() => { - const value = item() - - return Array.isArray(value) ? value : undefined - }) - - const reasoning = createMemo(() => { - const value = item() - - return !Array.isArray(value) && value.type === "reasoning" ? value : undefined - }) - - const callback = createMemo(() => { - const value = item() - - return !Array.isArray(value) && - (value.type === "notice" || value.type === "shell" || value.type === "text") - ? value - : undefined - }) - - return ( - - {(part) =>
{part().render()}
} -
- } - > - {(part) => ( -
- props.onReasoningOpenChange?.(part().id, open)} - onContentRendered={props.onSizeChange} - /> -
- )} + + }> + {(value) => ( + + {value().verb} + + {value().main} - } - > - {(group) => ( -
- -
- )} -
- ) - }} -
-
- -
+ 0}> + + {value().others.join(", ")} + + + )} + + + } + > +
+ + {(item) => { + const group = createMemo(() => { + const value = item() + + return Array.isArray(value) ? value : undefined + }) + + const reasoning = createMemo(() => { + const value = item() + + return !Array.isArray(value) && value.type === "reasoning" ? value : undefined + }) + + const callback = createMemo(() => { + const value = item() + + return !Array.isArray(value) && + (value.type === "notice" || value.type === "shell" || value.type === "text") + ? value + : undefined + }) + + const work = createMemo(() => { + const value = item() + + return !Array.isArray(value) && value.type === "work" ? value : undefined + }) + + return ( + + {(part) =>
{part().render()}
} +
+ } + > + {(work) => ( +
+ { + props.onToolOpenChange?.(`events:${work().id}`, open) + props.onSizeChange?.() + }} + onRevealShell={props.onRevealShell} + /> +
+ )} + + } + > + {(part) => ( +
+ props.onReasoningOpenChange?.(part().id, open)} + onContentRendered={props.onSizeChange} + /> +
+ )} + + } + > + {(group) => ( +
+ +
+ )} + + ) + }} +
+
+
+ + ) } @@ -422,7 +504,7 @@ function UsedTitle(props: { label: ReturnType }) { ) } -function usedLabel(parts: ContextGroupPart[], i18n: UiI18n) { +function usedLabel(parts: ActivityGroupPart[], i18n: UiI18n) { const count = parts.filter((part) => part.type === "reasoning").length if (!count) { @@ -451,6 +533,52 @@ function usedLabel(parts: ContextGroupPart[], i18n: UiI18n) { } } +/** + * What each subagent or background shell in a group did, in order. Work that reports back in the group that started + * it reads once, as how it ended: the launch says "Finished" and the report is not counted again. + */ +function workEvents(parts: ActivityGroupPart[]) { + const launch = (part: ActivityGroupPart) => + part.type === "tool" && toolRule(part).layout === "event" ? toolEvent(part) : undefined + + const launched = new Set( + parts.flatMap((part) => { + const event = launch(part) + const key = event && workKey(event) + + return key ? [key] : [] + }), + ) + + const reports = new Map( + parts.flatMap((part) => { + const key = part.type === "event" ? workKey(part.event) : undefined + + return key && part.type === "event" ? [[key, part.event] as const] : [] + }), + ) + + return new Map( + parts.flatMap((part): [ActivityGroupPart, TimelineEvent][] => { + if (part.type === "event") { + const key = workKey(part.event) + + return key && launched.has(key) ? [] : [[part, part.event]] + } + + const event = launch(part) + + if (!event) return [] + const key = workKey(event) + const outcome = key ? reports.get(key) : undefined + + return [ + [part, outcome && event.verb === "started" ? { ...event, verb: outcome.verb, failed: outcome.failed } : event], + ] + }), + ) +} + // The most consequential work names a group: changing files over running commands, and both over reading. const modePriority: ToolMode[] = ["edit", "run", "tool", "explore"] @@ -465,25 +593,16 @@ const decodeChangedPath = Schema.decodeUnknownOption(Schema.Struct({ file: Schem /** * Names a stretch of the agent's work by its main mode, then what its other calls did: "Edited 4 files · 2 commands, - * started 1 shell". Work that runs on is counted by what was started, not among the calls that started it; a stretch of - * only that reads like an events row: "Started 2 subagents". + * started 1 shell". Work that runs on is counted by what happened to it, not among the calls that started it; a + * stretch of only that reads like an events row: "Started 2 subagents · finished 2 subagents". */ -function activityLabel(group: SessionMessageAssistantTool[], i18n: UiI18n) { +function activityLabel(group: SessionMessageAssistantTool[], events: TimelineEvent[], i18n: UiI18n) { const tools = group.filter((tool) => toolRule(tool).layout !== "event") + const launches = summarizeEvents(events).verbs - const launches = summarizeEvents( - group.flatMap((tool) => { - const event = toolRule(tool).layout === "event" ? toolEvent(tool) : undefined - - return event ? [event] : [] - }), - ).verbs - - const launched = launches.flatMap((bucket) => { - const keys = bucket.verb === "started" || bucket.verb === "ran" ? launchKeys[bucket.verb] : undefined - - return keys ? bucket.kinds.map((item) => i18n.plural(keys[item.kind], item.count)) : [] - }) + const launched = launches.flatMap((bucket) => + bucket.kinds.map((item) => i18n.plural(launchKeys[bucket.verb][item.kind], item.count)), + ) const modes = new Set(tools.map((tool) => toolRule(tool).mode)) const mode = modePriority.find((item) => modes.has(item)) diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index 18e84db8ab6a..ab7904a432dd 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -180,6 +180,14 @@ const source = { "ui.timeline.activity.startedShells.other": "started {{count}} shells", "ui.timeline.activity.startedSubagents.one": "started {{count}} subagent", "ui.timeline.activity.startedSubagents.other": "started {{count}} subagents", + "ui.timeline.activity.finishedShells.one": "finished {{count}} shell", + "ui.timeline.activity.finishedShells.other": "finished {{count}} shells", + "ui.timeline.activity.finishedSubagents.one": "finished {{count}} subagent", + "ui.timeline.activity.finishedSubagents.other": "finished {{count}} subagents", + "ui.timeline.activity.stoppedShells.one": "stopped {{count}} shell", + "ui.timeline.activity.stoppedShells.other": "stopped {{count}} shells", + "ui.timeline.activity.stoppedSubagents.one": "stopped {{count}} subagent", + "ui.timeline.activity.stoppedSubagents.other": "stopped {{count}} subagents", "ui.timeline.event.started": "Started", "ui.timeline.event.finished": "Finished", "ui.timeline.event.stopped": "Stopped", From 9dab916b16e07879160a389d82d9ceb1c75b4403 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:23:14 -0600 Subject: [PATCH 09/43] refactor(ai): address async image jobs by ID like video (#63720) --- packages/ai/README.md | 19 ++- packages/ai/src/image-client.ts | 89 +++++++++++-- packages/ai/src/image.ts | 50 +++++-- packages/ai/src/index.ts | 10 +- packages/ai/src/media-client.ts | 100 ++++++++------ packages/ai/src/public.ts | 2 + packages/ai/test/image-job.test.ts | 207 +++++++++++++++++++++++++++++ packages/ai/test/image.test.ts | 2 - packages/ai/test/image.types.ts | 13 ++ packages/ai/test/promise.test.ts | 23 ++++ 10 files changed, 445 insertions(+), 70 deletions(-) create mode 100644 packages/ai/test/image-job.test.ts diff --git a/packages/ai/README.md b/packages/ai/README.md index 87cdfefd9133..0f1cfd51da6e 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1031,6 +1031,23 @@ const program = Effect.gen(function* () { The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes. +### Image jobs + +`ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same +calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and +read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read; +`result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an +`UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on +every image model today all four fail with an `UnsupportedOperation` reason before sending anything. + +```ts +const program = Effect.gen(function* () { + const job = yield* ai.image.start({ model, prompt: "A lighthouse" }) + const status = yield* ai.image.status(model, job.id) // { status, progress? } + if (status.status === "completed") return yield* ai.image.result(model, job.id) +}) +``` + ## Video generation Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`, @@ -1147,7 +1164,7 @@ Everything below is exported from `@opencode/ai/effect` unless noted. - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model. - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model. - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams. -- **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. +- **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs). - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`. - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer. - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests. diff --git a/packages/ai/src/image-client.ts b/packages/ai/src/image-client.ts index 44e819e389fc..63bddd00841b 100644 --- a/packages/ai/src/image-client.ts +++ b/packages/ai/src/image-client.ts @@ -1,20 +1,89 @@ -import { Context } from "effect" +import { Context, Effect, Layer, Schema, Stream } from "effect" +import type { AwaitOptions } from "./generation.js" import { MediaClient } from "./media-client.js" -import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js" +import { RequestExecutor } from "./route/executor.js" +import { AIError, UnsupportedOperationError } from "./schema/index.js" +import type { ImageEvent, ImageJob, ImageModel, ImageRequest, ImageResponse, ImageStatus } from "./image.js" -export type Interface = MediaClient.Interface +/** `start`, `status`, `result` and `cancel` fail with `UnsupportedOperation` on inline and stream routes. */ +export interface Interface + extends Pick, "generate" | "stream"> { + readonly start: (request: ImageRequest) => Effect.Effect + readonly status: (model: ImageModel, id: string) => Effect.Effect + readonly result: (model: ImageModel, id: string) => Effect.Effect + readonly cancel: (model: ImageModel, id: string) => Effect.Effect +} export class ImageClientService extends Context.Service()("@opencode/ImageClient") {} export const Service = ImageClientService export type Service = ImageClientService -export const ImageClient = { +const responseEvents = (response: ImageResponse) => [ + ...response.images.map((image, index) => ({ type: "image" as const, index, image })), + { type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata }, +] + +// A queued image route whose token isn't a string is a programmer defect, not a provider error. +const decodeID = (token: unknown) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie) + +export const layer = Layer.effect( Service, - ...MediaClient.make(Service, { - modality: "image", - responseEvents: (response: ImageResponse) => [ - ...response.images.map((image, index) => ({ type: "image" as const, index, image })), - { type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata }, - ], + Effect.gen(function* () { + const executor = yield* RequestExecutor.Service + const media = MediaClient.operations(executor.execute, { + modality: "image", + responseEvents, + }) + const attach = (model: ImageModel, id: string, operation: string) => { + if (model.route.kind !== "queued") return Effect.fail(MediaClient.notQueued("image", model.route, operation)) + return model.route.attach(model, id, executor.execute) + } + return Service.of({ + generate: media.generate, + stream: media.stream, + start: (request) => + media.start(request).pipe( + // The token, not the snapshot id, is what `status` and `result` decode; `ImageModel.fromRoute` makes it a string. + Effect.flatMap((generation) => decodeID(generation.token)), + Effect.map((id) => ({ id })), + ), + status: (model, id) => + attach(model, id, "status").pipe( + Effect.flatMap((route) => route.status), + Effect.map((snapshot) => ({ status: snapshot.status, progress: snapshot.progress })), + ), + result: (model, id) => attach(model, id, "result").pipe(Effect.flatMap((route) => route.result)), + cancel: (model, id) => + attach(model, id, "cancel").pipe( + Effect.flatMap( + (route) => + route.cancel ?? + Effect.fail( + new AIError({ + reason: new UnsupportedOperationError({ + operation: "image.cancel", + provider: model.provider, + route: model.route.id, + message: `${model.provider}/${model.route.id} has no way to cancel an image generation`, + }), + }), + ), + ), + ), + }) }), +) + +export const ImageClient = { + Service, + layer, + responseEvents, + generate: (request: ImageRequest, options?: AwaitOptions) => + Service.use((client) => client.generate(request, options)), + stream: (request: ImageRequest, options?: AwaitOptions) => + Stream.unwrap(Service.useSync((client) => client.stream(request, options))), + start: (request: ImageRequest) => Service.use((client) => client.start(request)), + status: (model: ImageModel, id: string) => Service.use((client) => client.status(model, id)), + result: (model: ImageModel, id: string) => Service.use((client) => client.result(model, id)), + cancel: (model: ImageModel, id: string) => Service.use((client) => client.cancel(model, id)), } as const diff --git a/packages/ai/src/image.ts b/packages/ai/src/image.ts index fb242669ddae..dd1799d920e6 100644 --- a/packages/ai/src/image.ts +++ b/packages/ai/src/image.ts @@ -1,5 +1,5 @@ import { Effect, Schema, Stream } from "effect" -import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js" +import { ProgressEvent, QueuedEvent, type AwaitOptions, type Status } from "./generation.js" import { Media } from "./media.js" import { MediaModel, composeRoute, tryRequest } from "./media-model.js" import { MediaRoute } from "./route/media.js" @@ -24,7 +24,10 @@ export type ImageRoute = MediaRoute.AnyRoute extends MediaModel { declare protected readonly _ImageModel: void - /** The number of type arguments selects the kind: ``, ``, or ``. */ + /** + * The number of type arguments selects the kind: `` for inline or queued, `` for + * stream. A queued route's token is the provider's job ID, so `ImageJob.id` is exactly what `status` and `result` take. + */ static fromRoute( route: MediaModel.InlineRouteInput>, ImageResponse>, input: MediaRoute.ModelInput, @@ -33,12 +36,12 @@ export class ImageModel extends Med route: MediaModel.StreamRouteInput>, ImageEvent, Frame, State>, input: MediaRoute.ModelInput, ): ImageModel - static fromRoute( - route: MediaModel.QueuedRouteInput>, ImageResponse, Token>, + static fromRoute( + route: MediaModel.QueuedRouteInput>, ImageResponse, string>, input: MediaRoute.ModelInput, ): ImageModel - static fromRoute( - route: MediaModel.AnyRouteInput>, ImageEvent, ImageResponse, Frame, State, Token>, + static fromRoute( + route: MediaModel.AnyRouteInput>, ImageEvent, ImageResponse, Frame, State, string>, input: MediaRoute.ModelInput, ) { return new ImageModel({ @@ -99,9 +102,21 @@ export type ImageRequestInput = Omit< } // --------------------------------------------------------------------------- -// Response and events +// Job, status, response and events // --------------------------------------------------------------------------- +/** A submitted generation on a queued route. Store `id` with the model to read the job later, from any process. */ +export interface ImageJob { + /** The provider's job ID. */ + readonly id: string +} + +export interface ImageStatus { + readonly status: Status + /** 0..1, only when the provider reports progress. */ + readonly progress?: number +} + export class ImageResponse extends Schema.Class("Image.Response")({ images: Schema.Array(Media.AssetSchema), usage: Schema.optional(MediaUsage), @@ -193,21 +208,32 @@ export function stream(input: ImageRequestInput, options?: AwaitOptions) { return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => ImageClient.stream(request, options)))) } -/** Inline and streaming routes fail with `UnsupportedOperation`. */ +/** Submit a generation and return at once; nothing polls. Inline and stream routes fail with `UnsupportedOperation`. */ export function start( input: ImageRequestInput, -): Effect.Effect, AIError, Service> +): Effect.Effect export function start(input: ImageRequestInput) { return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request))) } -export const resume = (model: ImageModel, token: unknown): Effect.Effect, AIError, Service> => - ImageClient.resume(model, token) +/** One status read for a job ID. */ +export const status = (model: ImageModel, id: string): Effect.Effect => + ImageClient.status(model, id) + +/** The finished images; fails while the job is still running, or with the provider's reason when it failed. */ +export const result = (model: ImageModel, id: string): Effect.Effect => + ImageClient.result(model, id) + +/** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */ +export const cancel = (model: ImageModel, id: string): Effect.Effect => + ImageClient.cancel(model, id) export const Image = { request, generate, stream, start, - resume, + status, + result, + cancel, } as const diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index e0ddc97baf3f..c85e1cd913b2 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -241,10 +241,14 @@ export const make = (options: Options = {}) => { input: ImageRequestInput | ImageRequest, options?: AwaitOptions & RunOptions, ) => iterate(Image.stream(input, options), options), + /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */ start: (input: ImageRequestInput | ImageRequest, options?: RunOptions) => - run(Image.start(input), options).then(handle), - resume: (model: ImageModel, token: unknown, options?: RunOptions) => - run(Image.resume(model, token), options).then(handle), + run(Image.start(input), options), + /** One status read for a job ID. */ + status: (model: ImageModel, id: string, options?: RunOptions) => run(Image.status(model, id), options), + /** The finished images; fails while the job is still running. */ + result: (model: ImageModel, id: string, options?: RunOptions) => run(Image.result(model, id), options), + cancel: (model: ImageModel, id: string, options?: RunOptions) => run(Image.cancel(model, id), options), }, decision: { request: Decision.request, diff --git a/packages/ai/src/media-client.ts b/packages/ai/src/media-client.ts index 622bfa7fdbad..5de4cbe584e9 100644 --- a/packages/ai/src/media-client.ts +++ b/packages/ai/src/media-client.ts @@ -2,7 +2,7 @@ import { type Context, Effect, Layer, Stream } from "effect" import { resultEvents, type AwaitOptions, type Generation, type Observation } from "./generation.js" import { RequestExecutor } from "./route/executor.js" import type { MediaRoute } from "./route/media.js" -import { AIError, UnsupportedOperationError } from "./schema/index.js" +import { AIError, UnsupportedOperationError, type ProviderID } from "./schema/index.js" /** A media request whose model carries the route that executes it. */ export interface RoutedRequest extends MediaRoute.MediaRequest { @@ -17,55 +17,71 @@ export interface Interface, Even readonly resume: (model: Req["model"], token: unknown) => Effect.Effect, AIError> } -/** One modality's layer and service accessors, dispatching each request on its route's `kind`. */ +export interface Input { + readonly modality: string + /** A completed response expanded into the streaming event shape. */ + readonly responseEvents: (response: Response) => ReadonlyArray +} + +/** `${modality}.${operation}` on a route that is not queued. */ +export const notQueued = ( + modality: string, + route: { readonly provider: ProviderID; readonly id: string }, + operation: string, +) => + new AIError({ + reason: new UnsupportedOperationError({ + operation: `${modality}.${operation}`, + provider: route.provider, + route: route.id, + message: `${route.provider}/${route.id} is not a queued route; use generate or stream`, + }), + }) + +/** One modality's operations over an executor, dispatching each request on its route's `kind`. */ +export const operations = , Event, Response>( + execute: MediaRoute.Execute, + input: Input, +): Interface => { + const start = (request: Req) => { + const route = request.model.route + if (route.kind !== "queued") return Effect.fail(notQueued(input.modality, route, "start")) + return route.start(request, execute) + } + return { + start, + resume: (model, token) => { + if (model.route.kind !== "queued") return Effect.fail(notQueued(input.modality, model.route, "resume")) + return model.route.resume(model, token, execute) + }, + generate: (request, options) => { + const route = request.model.route + if (route.kind !== "queued") return route.generate(request, execute) + return start(request).pipe(Effect.flatMap((generation) => generation.await(options))) + }, + stream: (request, options) => { + const route = request.model.route + if (route.kind === "stream") return route.stream(request, execute) + if (route.kind === "queued") + return Stream.unwrap( + start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))), + ) + return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents)) + }, + } +} + +/** One modality's layer and service accessors over `operations`. */ export const make = , Event, Response>( service: Context.Service>, - input: { - readonly modality: string - /** A completed response expanded into the streaming event shape. */ - readonly responseEvents: (response: Response) => ReadonlyArray - }, + input: Input, ) => ({ responseEvents: input.responseEvents, layer: Layer.effect( service, Effect.gen(function* () { const executor = yield* RequestExecutor.Service - const notQueued = (route: MediaRoute.AnyRoute, operation: string) => - new AIError({ - reason: new UnsupportedOperationError({ - operation: `${input.modality}.${operation}`, - provider: route.provider, - route: route.id, - message: `${route.provider}/${route.id} is not a queued route; use generate or stream`, - }), - }) - const start = (request: Req) => { - const route = request.model.route - if (route.kind !== "queued") return Effect.fail(notQueued(route, "start")) - return route.start(request, executor.execute) - } - return service.of({ - start, - resume: (model, token) => { - if (model.route.kind !== "queued") return Effect.fail(notQueued(model.route, "resume")) - return model.route.resume(model, token, executor.execute) - }, - generate: (request, options) => { - const route = request.model.route - if (route.kind !== "queued") return route.generate(request, executor.execute) - return start(request).pipe(Effect.flatMap((generation) => generation.await(options))) - }, - stream: (request, options) => { - const route = request.model.route - if (route.kind === "stream") return route.stream(request, executor.execute) - if (route.kind === "queued") - return Stream.unwrap( - start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))), - ) - return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents)) - }, - }) + return service.of(operations(executor.execute, input)) }), ), generate: (request: Req, options?: AwaitOptions) => service.use((client) => client.generate(request, options)), diff --git a/packages/ai/src/public.ts b/packages/ai/src/public.ts index d38f6a6046e8..14eb9b4f24b3 100644 --- a/packages/ai/src/public.ts +++ b/packages/ai/src/public.ts @@ -109,12 +109,14 @@ export type { } from "./schema/index.js" export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageResponse } from "./image.js" export type { + ImageJob, ImageModelOptions, ImageOptions, ImageRequest, ImageRequestInput, ImageResolution, ImageRoute, + ImageStatus, } from "./image.js" export { VideoAspectRatio, VideoDuration, VideoModel, VideoModelSchema, VideoResponse } from "./video.js" export type { diff --git a/packages/ai/test/image-job.test.ts b/packages/ai/test/image-job.test.ts new file mode 100644 index 000000000000..cba227bd9e42 --- /dev/null +++ b/packages/ai/test/image-job.test.ts @@ -0,0 +1,207 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer, Schema } from "effect" +import type { HttpClientResponse } from "effect/http" +import { + ai, + ImageClient, + ImageModel, + ImageResponse, + Media, + type GenerationStatus, + type ImageRequest, +} from "../src/effect.js" +import { Google } from "../src/providers.js" +import { Auth, MediaProtocol } from "../src/route.js" +import { it } from "./lib/effect.js" +import { dynamicResponse, json, observe, settle, type Call } from "./lib/http.js" + +const layer = (handler: Parameters[0]) => + ImageClient.layer.pipe(Layer.provideMerge(dynamicResponse(handler))) + +// No shipped image protocol is queued, so this test-only one exercises the job calls over the real route machinery. +const route = MediaProtocol.identity({ id: "test-queued-image", name: "Queued Image", provider: "test" }) + +const STATUS = { pending: "running", done: "completed", failed: "failed" } as const satisfies Record< + string, + GenerationStatus +> + +const decodeJob = route.decodeJson( + Schema.Struct({ + status: Schema.String, + progress: Schema.optional(Schema.Number), + url: Schema.optional(Schema.String), + }), +) + +const decodeStatus = (response: HttpClientResponse.HttpClientResponse, context: MediaProtocol.PollContext) => + decodeJob(response).pipe( + Effect.map((output) => ({ + id: context.token, + status: MediaProtocol.status(STATUS, output.value.status), + progress: output.value.progress, + })), + ) + +const decodeResult = Effect.fn("QueuedImage.decodeResult")(function* ( + response: HttpClientResponse.HttpClientResponse, + context: MediaProtocol.PollContext, +) { + const output = yield* decodeJob(response) + const status = MediaProtocol.status(STATUS, output.value.status) + if (status === "running") return yield* output.pending(context.token) + if (status === "failed") return yield* output.ended("failed", `${route.name} generation failed`) + if (output.value.url === undefined) return yield* output.invalid(`${route.name} completed without an image URL`) + return new ImageResponse({ images: [Media.url(output.value.url, { mediaType: "image/png" })] }) +}) + +const jobPath = (id: string) => `/jobs/${encodeURIComponent(id)}` + +const protocol = (cancel: boolean) => + MediaProtocol.queued(route, { + token: Schema.String, + start: { + body: { from: (request) => Effect.succeed(MediaProtocol.json({ prompt: request.prompt })) }, + decode: route.decodeStarted(Schema.Struct({ id: Schema.String }), (value) => ({ + token: value.id, + snapshot: { id: value.id, status: "queued" }, + })), + }, + status: { path: jobPath, decode: decodeStatus }, + result: { path: jobPath, decode: decodeResult }, + cancel: cancel ? { method: "DELETE", path: jobPath } : undefined, + }) + +const queued = (cancel = true) => + ImageModel.fromRoute( + { protocol: protocol(cancel), baseURL: "https://queued.test", path: "/jobs" }, + { id: "queued-image", auth: Auth.bearer("test") }, + ) + +const model = queued() + +describe("ai.image.start / status / result / cancel", () => { + it.effect("start submits and returns the job ID without polling", () => + Effect.gen(function* () { + const calls: Array = [] + const job = yield* ai.image + .start({ model, prompt: "A lighthouse" }) + .pipe( + Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, { id: "job_1" }))))), + ) + expect(job).toEqual({ id: "job_1" }) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["POST https://queued.test/jobs"]) + expect(JSON.parse(calls[0].body)).toEqual({ prompt: "A lighthouse" }) + }), + ) + + it.effect("status reads one status per call by job ID", () => + Effect.gen(function* () { + const calls: Array = [] + const statuses = yield* Effect.all([ai.image.status(model, "job/1"), ai.image.status(model, "job/1")]).pipe( + Effect.provide( + layer((input) => + observe(calls, input).pipe( + Effect.map(({ nth }) => + json(input, nth === 1 ? { status: "pending", progress: 0.4 } : { status: "done", url: "x" }), + ), + ), + ), + ), + ) + expect(statuses).toEqual([ + { status: "running", progress: 0.4 }, + { status: "completed", progress: undefined }, + ]) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual([ + "GET https://queued.test/jobs/job%2F1", + "GET https://queued.test/jobs/job%2F1", + ]) + }), + ) + + it.effect("result fails while the job is running and returns the images once it completes", () => + Effect.gen(function* () { + const pending = yield* ai.image + .result(model, "job_1") + .pipe(Effect.flip, Effect.provide(layer((input) => Effect.succeed(json(input, { status: "pending" }))))) + expect(pending.reason._tag).toBe("InvalidRequest") + expect(pending.message).toContain("has not finished") + + const response = yield* ai.image + .result(model, "job_1") + .pipe( + Effect.provide( + layer((input) => Effect.succeed(json(input, { status: "done", url: "https://queued.test/out.png" }))), + ), + ) + expect(response.images.map((image) => image.source)).toEqual([ + { type: "url", url: "https://queued.test/out.png", mediaType: "image/png", expiresAt: undefined }, + ]) + }), + ) + + it.effect("cancel calls the provider when it has a cancel call and fails typed when it has none", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.image + .cancel(model, "job_1") + .pipe(Effect.provide(layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, {})))))) + expect(calls.map((call) => `${call.method} ${call.url}`)).toEqual(["DELETE https://queued.test/jobs/job_1"]) + + const error = yield* ai.image + .cancel(queued(false), "job_1") + .pipe(Effect.flip, Effect.provide(layer(() => Effect.die("cancel reached the network")))) + expect(error.reason._tag).toBe("UnsupportedOperation") + expect("operation" in error.reason && error.reason.operation).toBe("image.cancel") + }), + ) + + it.effect("generate still polls a queued route to the result", () => + Effect.gen(function* () { + const calls: Array = [] + const response = yield* settle( + ai.image.generate({ model, prompt: "A lighthouse" }, { poll: { interval: "1 second" } }), + 5, + ).pipe( + Effect.provide( + layer((input) => + observe(calls, input).pipe( + Effect.map(({ call, nth }) => { + if (call.method === "POST") return json(input, { id: "job_1" }) + return json( + input, + nth === 1 ? { status: "pending" } : { status: "done", url: "https://queued.test/a.png" }, + ) + }), + ), + ), + ), + ) + expect(response.images).toHaveLength(1) + expect(calls[0].method).toBe("POST") + }), + ) + + it.effect("every job call fails with UnsupportedOperation on an inline route before sending", () => + Effect.gen(function* () { + const inline = Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image") + const errors = yield* Effect.all( + [ + ai.image.start({ model: inline, prompt: "A lighthouse" }), + ai.image.status(inline, "job_1"), + ai.image.result(inline, "job_1"), + ai.image.cancel(inline, "job_1"), + ].map((effect) => Effect.flip(effect)), + ) + expect(errors.map((error) => [error.reason._tag, "operation" in error.reason && error.reason.operation])).toEqual( + [ + ["UnsupportedOperation", "image.start"], + ["UnsupportedOperation", "image.status"], + ["UnsupportedOperation", "image.result"], + ["UnsupportedOperation", "image.cancel"], + ], + ) + }).pipe(Effect.provide(layer(() => Effect.die("an unsupported job call reached the network")))), + ) +}) diff --git a/packages/ai/test/image.test.ts b/packages/ai/test/image.test.ts index b44949bfdc74..155abfd86945 100644 --- a/packages/ai/test/image.test.ts +++ b/packages/ai/test/image.test.ts @@ -1095,7 +1095,6 @@ describe("Image", () => { const prompt = "A lighthouse" const errors = yield* Effect.all( [ - ai.image.start({ model: Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image"), prompt }), ai.image.generate({ model: Google.configure({ apiKey: "test" }).image("gemini-3.1-flash-image"), prompt, @@ -1106,7 +1105,6 @@ describe("Image", () => { ) expect(errors.map((error) => [error.reason._tag, "operation" in error.reason && error.reason.operation])).toEqual( [ - ["UnsupportedOperation", "image.start"], ["UnsupportedOperation", "media.n"], ["UnsupportedOperation", "media.n"], ], diff --git a/packages/ai/test/image.types.ts b/packages/ai/test/image.types.ts index c3f846de68f6..225292e142db 100644 --- a/packages/ai/test/image.types.ts +++ b/packages/ai/test/image.types.ts @@ -3,15 +3,19 @@ import { ai, ImageClient, ImageModel, + type ImageJob, type ImageModelOptions, type ImageOptions, type ImageRequest, + type ImageResponse, + type ImageStatus, Media, } from "../src/effect.js" import type { Service } from "../src/image-client.js" import { Anthropic, Google, OpenAI, XAI, ZAI } from "../src/providers.js" type Requirements = T extends Effect.Effect ? R : never +type Success = T extends Effect.Effect ? A : never type Equal = [A, B] extends [B, A] ? true : false type Assert = T @@ -178,6 +182,15 @@ const generated = ImageClient.generate(request) type GenerateRequirements = Assert, Service>> void (true satisfies GenerateRequirements) +type StartSuccess = Assert>, ImageJob>> +type StatusSuccess = Assert>, ImageStatus>> +type ResultSuccess = Assert>, ImageResponse>> +type CancelSuccess = Assert>, void>> +void (true satisfies StartSuccess) +void (true satisfies StatusSuccess) +void (true satisfies ResultSuccess) +void (true satisfies CancelSuccess) + // @ts-expect-error Image requests use `n`, not `count`. ai.image.generate({ model: openai, prompt: "A lighthouse", count: 2 }) // @ts-expect-error Exact sizes are provider options, not common fields. diff --git a/packages/ai/test/promise.test.ts b/packages/ai/test/promise.test.ts index 98a5ba8ebe2e..98750b636c82 100644 --- a/packages/ai/test/promise.test.ts +++ b/packages/ai/test/promise.test.ts @@ -210,6 +210,29 @@ describe("AI promise client", () => { await ai.dispose() }) + test("rejects image job calls on an inline route without a request", async () => { + const seen: Array = [] + const ai = AI.make({ layer: executor(seen) }) + const model = openai.image("gpt-image-2") + const reasons = await Promise.all( + [ + ai.image.start({ model, prompt: "A lighthouse" }), + ai.image.status(model, "job_1"), + ai.image.result(model, "job_1"), + ai.image.cancel(model, "job_1"), + ].map((call) => call.then(() => undefined).catch((error: unknown) => error)), + ) + expect(reasons).toEqual( + ["start", "status", "result", "cancel"].map((operation) => + expect.objectContaining({ + reason: expect.objectContaining({ _tag: "UnsupportedOperation", operation: `image.${operation}` }), + }), + ), + ) + expect(seen).toEqual([]) + await ai.dispose() + }) + test("forwards per-call options to generate, stream, and loop, and checks compaction support", async () => { const seen: Array = [] const ai = AI.make({ layer: executor([]) }) From 928bb44255513451c10a8bc2fc7686c2d05ec7d1 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:26:56 -0600 Subject: [PATCH 10/43] feat(ai): accept only images as video start and end frames (#63721) --- packages/ai/README.md | 4 ++ packages/ai/src/media.ts | 21 ++++++++++ packages/ai/src/video.ts | 13 +++--- .../ai/test/google-interactions-video.test.ts | 4 +- packages/ai/test/minimax-video.test.ts | 2 +- packages/ai/test/openrouter-video.test.ts | 2 +- packages/ai/test/seedance-video.test.ts | 2 +- packages/ai/test/video.test.ts | 40 ++++++++++++++++++- packages/ai/test/video.types.ts | 6 ++- 9 files changed, 80 insertions(+), 14 deletions(-) diff --git a/packages/ai/README.md b/packages/ai/README.md index 0f1cfd51da6e..db73e71af7c0 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1090,6 +1090,10 @@ everything else is provider-specific and goes under `providerOptions`, typed fro fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed. +`start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with +`Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references +whose type isn't stated are sent and checked by the provider. `references` take any kind. + `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads diff --git a/packages/ai/src/media.ts b/packages/ai/src/media.ts index b35da7c89cb5..9ac2ca44c291 100644 --- a/packages/ai/src/media.ts +++ b/packages/ai/src/media.ts @@ -239,6 +239,20 @@ export const AssetSchema = AssetEncoded.pipe( }), ) +/** + * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with + * `Media.image`; an asset known to be a video, audio or document is rejected. + */ +export const ImageAssetSchema = AssetInstance.check( + Schema.makeFilter( + (asset) => + asset.kind === "image" || + ((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) || + `expected an image, got ${asset.mediaType}`, + ), +).pipe(Schema.brand("Media.ImageAsset")) +export type ImageAsset = typeof ImageAssetSchema.Type + const download = Effect.fn("Media.download")(function* ( source: Extract, headers: Record | undefined, @@ -330,6 +344,13 @@ export type Data = Uint8Array | ArrayBuffer | URL | string /** What file inputs accept: an `Asset` or plain `Data`. */ export type Input = Asset | Data +/** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */ +export const image = (input: Input, mediaType?: string): ImageAsset => { + const asset = make(input, mediaType) + if (!Schema.is(ImageAssetSchema)(asset)) throw invalid(`expected an image, got ${asset.mediaType}`) + return asset +} + /** * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged. diff --git a/packages/ai/src/video.ts b/packages/ai/src/video.ts index 976619d2e621..a318e07a5b7a 100644 --- a/packages/ai/src/video.ts +++ b/packages/ai/src/video.ts @@ -66,9 +66,9 @@ const VideoRequestSchema = Schema.Struct({ model: VideoModelSchema, prompt: Schema.String, /** Image the video starts on exactly. */ - start: Schema.optional(Media.AssetSchema), + start: Schema.optional(Media.ImageAssetSchema), /** Image the video ends on exactly. */ - end: Schema.optional(Media.AssetSchema), + end: Schema.optional(Media.ImageAssetSchema), /** Images, videos or audio that guide the subject or style without pinning a frame. */ references: Schema.optional(Schema.Array(Media.AssetSchema)), duration: Schema.optional(VideoDuration), @@ -93,8 +93,9 @@ export type VideoRequestInput = Omit< VideoRequest, "start" | "end" | "references" | "providerOptions" > & { - readonly start?: Media.Input - readonly end?: Media.Input + /** An image: `Media.image(...)`, or a URL, data URL, base64 string or bytes, which must not be a known non-image. */ + readonly start?: Media.ImageAsset | Media.Data + readonly end?: Media.ImageAsset | Media.Data readonly references?: ReadonlyArray readonly providerOptions?: NoInfer> } @@ -135,8 +136,8 @@ export class VideoResponse extends Schema.Class("Video.Response") /** Normalize video request input into a plain `VideoRequest`. */ export const request = (input: VideoRequestInput): VideoRequest => ({ ...input, - start: input.start === undefined ? undefined : Media.make(input.start), - end: input.end === undefined ? undefined : Media.make(input.end), + start: input.start === undefined ? undefined : Media.image(input.start), + end: input.end === undefined ? undefined : Media.image(input.end), references: input.references?.map((reference) => Media.make(reference)), }) diff --git a/packages/ai/test/google-interactions-video.test.ts b/packages/ai/test/google-interactions-video.test.ts index 850f0a911eed..4aabcbaf4f0a 100644 --- a/packages/ai/test/google-interactions-video.test.ts +++ b/packages/ai/test/google-interactions-video.test.ts @@ -100,8 +100,8 @@ describe("ai.video.start / Google Interactions", () => { const { body } = yield* sent({ model, prompt: "Morph", - start: Media.fromDataUrl("data:image/png;base64,AQID"), - end: Media.ref("google", "https://generativelanguage.googleapis.com/v1beta/files/last", "image/jpeg"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), + end: Media.image(Media.ref("google", "https://generativelanguage.googleapis.com/v1beta/files/last", "image/jpeg")), }) expect(body.input).toEqual([ { type: "image", data: "AQID", mime_type: "image/png" }, diff --git a/packages/ai/test/minimax-video.test.ts b/packages/ai/test/minimax-video.test.ts index c6261892dc80..7434dcd76481 100644 --- a/packages/ai/test/minimax-video.test.ts +++ b/packages/ai/test/minimax-video.test.ts @@ -207,7 +207,7 @@ describe("MiniMax Video / Hailuo start", () => { const requests = yield* sent([ { model: hailuo, - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", references: ["https://example.test/face.png"], duration: "10 seconds", diff --git a/packages/ai/test/openrouter-video.test.ts b/packages/ai/test/openrouter-video.test.ts index 8f3761bc5a21..8f15b749933c 100644 --- a/packages/ai/test/openrouter-video.test.ts +++ b/packages/ai/test/openrouter-video.test.ts @@ -36,7 +36,7 @@ describe("ai.video.start / OpenRouter", () => { .start({ model, prompt: "A red balloon floats up", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", duration: "6 seconds", aspect: "16:9", diff --git a/packages/ai/test/seedance-video.test.ts b/packages/ai/test/seedance-video.test.ts index c13e709459ea..519c14c2725d 100644 --- a/packages/ai/test/seedance-video.test.ts +++ b/packages/ai/test/seedance-video.test.ts @@ -44,7 +44,7 @@ describe("ai.video.start / Seedance", () => { .start({ model, prompt: "The kitten yawns at the camera", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", duration: "5 seconds", aspect: "16:9", diff --git a/packages/ai/test/video.test.ts b/packages/ai/test/video.test.ts index 529dedb66f40..931a40b0540e 100644 --- a/packages/ai/test/video.test.ts +++ b/packages/ai/test/video.test.ts @@ -1,7 +1,7 @@ import { describe, expect } from "bun:test" import { Effect, Fiber, Layer, Stream } from "effect" import * as TestClock from "effect/testing/TestClock" -import { Media, VideoClient, ai } from "../src/effect.js" +import { AIError, Media, VideoClient, ai } from "../src/effect.js" import { XAI } from "../src/providers.js" import { it } from "./lib/effect.js" import { dynamicResponse, json, observe, settle, type Call, type HandlerInput } from "./lib/http.js" @@ -25,7 +25,7 @@ describe("ai.video.start / xAI", () => { .start({ model, prompt: "Make the water crash down", - start: Media.fromDataUrl("data:image/png;base64,AQID"), + start: Media.image(Media.fromDataUrl("data:image/png;base64,AQID")), end: "https://example.test/last.png", references: [ Media.ref("xai", "file_1"), @@ -123,6 +123,42 @@ describe("ai.video.start / xAI", () => { }).pipe(Effect.provide(layer(() => Effect.die("an unsupported reference reached the network")))), ) + it.effect("rejects start and end frames that are known not to be images before sending", () => + Effect.gen(function* () { + const video = yield* ai.video.start({ model, prompt: "x", start: "data:video/mp4;base64,AAAA" }).pipe(Effect.flip) + expect(video.reason._tag).toBe("InvalidRequest") + expect(video.message).toContain("expected an image, got video/mp4") + const audio = yield* ai.video + .start({ model, prompt: "x", end: Media.url("https://example.test/a.mp3", { mediaType: "audio/mpeg" }) }) + .pipe(Effect.flip) + expect(audio.reason._tag).toBe("InvalidRequest") + }).pipe(Effect.provide(layer(() => Effect.die("a non-image frame reached the network")))), + ) + + it.effect("Media.image throws a typed AIError for a known non-image", () => + Effect.sync(() => { + expect(() => Media.image("data:video/mp4;base64,AAAA")).toThrow(AIError) + expect(() => Media.image("data:video/mp4;base64,AAAA")).toThrow("expected an image, got video/mp4") + }), + ) + + it.effect("sends frames whose type it can't tell, like URLs and provider file references", () => + Effect.gen(function* () { + const calls: Array = [] + yield* ai.video + .start({ model, prompt: "x", start: "https://example.test/frame?id=7", end: Media.ref("xai", "file_1") }) + .pipe( + Effect.provide( + layer((input) => observe(calls, input).pipe(Effect.map(() => json(input, { request_id: "r" })))), + ), + ) + expect(JSON.parse(calls[0].body)).toMatchObject({ + image: { url: "https://example.test/frame?id=7" }, + last_frame: { file_id: "file_1" }, + }) + }), + ) + it.effect("rejects durations that aren't seconds before sending", () => Effect.gen(function* () { // @ts-expect-error Durations are Effect duration strings in seconds. diff --git a/packages/ai/test/video.types.ts b/packages/ai/test/video.types.ts index ad289ae77b7b..8b2962ff45fd 100644 --- a/packages/ai/test/video.types.ts +++ b/packages/ai/test/video.types.ts @@ -31,7 +31,7 @@ void invalidCustomOptions ai.video.start({ model: custom, prompt: "A kitten", - start: Media.bytes(Uint8Array.from([1]), "image/png"), + start: Media.image(Media.bytes(Uint8Array.from([1]), "image/png")), end: "data:image/png;base64,AQID", references: [Media.bytes(Uint8Array.from([1]), "image/png"), "https://example.com/voice.mp3"], duration: "8 seconds", @@ -66,6 +66,10 @@ ai.video.start({ model: Anthropic.configure({ apiKey: "test" }).model("claude-so // @ts-expect-error Image models cannot be used for video requests. ai.video.start({ model: OpenAI.configure({ apiKey: "test" }).image("gpt-image-2"), prompt: "A kitten" }) +// @ts-expect-error Start and end frames are images; a plain asset of any kind needs `Media.image(...)`. +ai.video.start({ model: xai, prompt: "A kitten", start: Media.bytes(Uint8Array.from([1]), "video/mp4") }) +ai.video.start({ model: xai, prompt: "A kitten", start: Media.image("https://example.com/first.png") }) + // @ts-expect-error Aspect ratios are `${w}:${h}` strings or "auto". ai.video.start({ model: xai, prompt: "A kitten", aspect: "wide" }) // @ts-expect-error Durations are Effect duration strings in seconds, not numbers. From 5bf661138b1524fdbfafa82fd8cde1918cf05f73 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:34:24 -0600 Subject: [PATCH 11/43] feat(core): tell the model its session ID is in OPENCODE_SESSION_ID (#63718) --- packages/core/src/tool/plugin/shell.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index 9357b09e8a71..0fa456f60a6c 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -46,6 +46,7 @@ const description = (shell?: string) => "Rely on automatic truncation unless filtering the output is more useful.", "Commands still running after their timeout move to the background.", "Background commands return immediately, and you will be notified when they complete.", + "The current session ID is available in the OPENCODE_SESSION_ID environment variable.", ].join(" ") export const Input = Schema.Struct({ From f413b302fb8c87bcd435795bcb9fbd5d71946e2a Mon Sep 17 00:00:00 2001 From: Aarav Sareen <96787824+arvsrn@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:27:52 +0530 Subject: [PATCH 12/43] fix(app): keep subagent rows in order inside grouped activity in the New timeline (#63725) --- .../src/timeline-next/tools/context-group.tsx | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/packages/session-ui/src/timeline-next/tools/context-group.tsx b/packages/session-ui/src/timeline-next/tools/context-group.tsx index 24fcc42ba700..a220bfdb3147 100644 --- a/packages/session-ui/src/timeline-next/tools/context-group.tsx +++ b/packages/session-ui/src/timeline-next/tools/context-group.tsx @@ -62,8 +62,7 @@ export function ContextGroup(props: { const tools = createMemo(() => props.parts.filter((part) => part.type === "tool")) const reasoning = createMemo(() => props.parts.flatMap((part) => (part.type === "reasoning" ? [part] : []))) const thoughtsOnly = createMemo(() => reasoning().length > 0 && reasoning().length === props.parts.length) - const partEvents = createMemo(() => workEvents(props.parts)) - const events = createMemo(() => [...partEvents().values()]) + const events = createMemo(() => [...workEvents(props.parts).values()]) // A group of only subagents and work reporting back reads as the events row it is, not a group around one. Until a // call has anything to count, it stays a group, so the row never renders empty. @@ -97,16 +96,27 @@ export function ContextGroup(props: { const previous = groups.at(-1) // Subagents started one after another, and work reporting back, read as one events row nested in the group: - // "Started 3 subagents". + // "Started 3 subagents". The rows keep the order things happened in, which the label does not. if (tool.type === "event" || (tool.type === "tool" && toolRule(tool).name === "subagent")) { - // A subagent still being asked for has nothing to list yet, and a report its launch already says is not - // listed twice. - const event = partEvents().get(tool) + // A subagent still being asked for has nothing to list yet. + const event = tool.type === "event" ? tool.event : toolEvent(tool) if (!event) return groups + const run = previous && !Array.isArray(previous) && previous.type === "work" ? previous : undefined + const key = tool.type === "event" ? workKey(event) : undefined - if (previous && !Array.isArray(previous) && previous.type === "work") { - previous.events.push(event) + // Work reporting back right after its launch, with nothing between, finishes the launch's row. With + // anything between, the launch and the report each keep their row. + const launch = key && run ? run.events.findIndex((item) => item.verb === "started" && workKey(item) === key) : -1 + + if (run && launch >= 0) { + run.events[launch] = { ...run.events[launch]!, verb: event.verb, failed: event.failed } + + return groups + } + + if (run) { + run.events.push(event) return groups } @@ -534,8 +544,8 @@ function usedLabel(parts: ActivityGroupPart[], i18n: UiI18n) { } /** - * What each subagent or background shell in a group did, in order. Work that reports back in the group that started - * it reads once, as how it ended: the launch says "Finished" and the report is not counted again. + * What each subagent or background shell in a group did, for its label. Work that reports back anywhere in the group + * that started it is counted once, as how it ended: "Finished", not "Started" and "Finished". */ function workEvents(parts: ActivityGroupPart[]) { const launch = (part: ActivityGroupPart) => From 77b26fdebd1a3c2b38bd15c94e40721284651306 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:18:41 -0600 Subject: [PATCH 13/43] chore(perf): bench with strobe 0.35.0 (#63731) --- bun.lock | 16 ++++++++-------- package.json | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/bun.lock b/bun.lock index f454e5bb0c34..c7b9e34a9411 100644 --- a/bun.lock +++ b/bun.lock @@ -1024,7 +1024,7 @@ "@effect/platform-node-shared": "4.1.0", "@effect/sql-sqlite-bun": "4.1.0", "@effect/sql-sqlite-node": "4.1.0", - "@hona/strobe": "0.34.0", + "@hona/strobe": "0.35.0", "@kobalte/core": "0.13.13", "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", @@ -1566,19 +1566,19 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="], - "@hona/strobe": ["@hona/strobe@0.34.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.34.0", "@hona/strobe-darwin-x64": "0.34.0", "@hona/strobe-linux-arm64": "0.34.0", "@hona/strobe-linux-x64": "0.34.0", "@hona/strobe-win32-arm64": "0.34.0", "@hona/strobe-win32-x64": "0.34.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-3zh8ptLWFd1NP/uMRwLx7WexuoYmlLkQBdkkfMQe7Ntgh+jT2MhwQOiJ5DARL0x9ehEefYlex3VggQv5oV+mUw=="], + "@hona/strobe": ["@hona/strobe@0.35.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.35.0", "@hona/strobe-darwin-x64": "0.35.0", "@hona/strobe-linux-arm64": "0.35.0", "@hona/strobe-linux-x64": "0.35.0", "@hona/strobe-win32-arm64": "0.35.0", "@hona/strobe-win32-x64": "0.35.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-TyK/tmjziBja9SF7h805YXkQSA/5BU6oykGzAW/7q+PVQZblD9lf3+t5wy2uOzJZ4BXzCVULOYw/VCuAhwVbCg=="], - "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.34.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-uk67cN/3OfXsXWsADG8vTZluuxyqTS+/A9o3K72F90nJVR4zKE31rGDfjSjvzItNpITe5wkQPOkXWXwh4bC5sg=="], + "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.35.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-rTlMVvSPCas5mWecvzngZl5VkTrCrl7VB95yNKXLagHMEQLVvXtMMd8RrMrUig0nLAEN2Z7E+BZibWTORH9dXQ=="], - "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.34.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-n0aSQ1/I9RmC5K3n4LxG7AvFa3Jieib6KQApP1Y0s/hj+x13ad4taf3gNf8F2YN7VVW050ASVf2cl8T3YZbYcA=="], + "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.35.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-l6yozlIxwyHBN2K2M/BIjVLG475fGxvGUOPgTAopM/nd/fJs95nyi1NH+wG/EAl5I5OjNvF5uxSFxfP2lyJWSg=="], - "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.34.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-WtqYcbgZyiP1Uk16dPW7lSRaHC87sn+9lgC9wV5ZHKPjQA3o+EZKik+yKNSJF9dRWzMm+brySf78XpMWxGv0jA=="], + "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.35.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-Unu1jpsI4e2vLB/Oki0m31W83MSlapzhkDYnNYJ0SO7knDaHQZsoV4ql6aJTkS3ZUgm33m6LyeDY/0KI+5Rfaw=="], - "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.34.0", "", { "os": "linux", "cpu": "x64" }, "sha512-mHBSonDppJzJ/n80gkyqg4fcNqokQgvH26p3CqLk38r8DFtunzYf0FqwcpXbTmxs1z3JD7ToffNtJPky3jb7xg=="], + "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.35.0", "", { "os": "linux", "cpu": "x64" }, "sha512-AzmgqmNfQaK/qh62nB6A7n2YPKcf9fkIaz3+Lr8KeGAZKTvshAAUXKjkbiySR6ShQ6NT8JXh2825EMUYquVLOg=="], - "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.34.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-XwYdRJFDuj90jDcv2XmBQ8HAyRCoK6ms2RfztT5kuPgGeQdbH2Wi/yNz/e0akHvlg8RigziJ9QYeHdjfzzTgOQ=="], + "@hona/strobe-win32-arm64": ["@hona/strobe-win32-arm64@0.35.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-omC3E1jdbnLXIx4gvXjaZCXb9ikVOeQnRoxapTNIZ+gvrrPKRSyJ4AF4IzG9O59vLqhzpvdsUvFabkgFBpCQNA=="], - "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.34.0", "", { "os": "win32", "cpu": "x64" }, "sha512-moHbYiWex//RLEEhHUaHb4ec9bpmxy4A/YeIfgGccFjgf9VmPmvxNhuccM6gO72KNTcKJsCITqQO9Adr58bCbw=="], + "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.35.0", "", { "os": "win32", "cpu": "x64" }, "sha512-vyL0Qb3EuhGn/BGsOcj101hddvxj65RKiv+2+GS6+hDOODMebESIBGCS0mt1UVfAzGtLNKN+rBzz02Kg9966XQ=="], "@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="], diff --git a/package.json b/package.json index be068aa103ad..c914a3ab5d6f 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "@effect/sql-sqlite-node": "4.1.0", "@npmcli/arborist": "9.4.0", "@types/bun": "1.4.3", - "@hona/strobe": "0.34.0", + "@hona/strobe": "0.35.0", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@opentui/core": "0.8.4", From 377b528b05a51a0cfa51640ef39ad86d71375039 Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:52:16 +0100 Subject: [PATCH 14/43] fix(app): show hover background on subagent breadcrumbs (#63742) --- packages/app/src/session/session-identity-header.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/app/src/session/session-identity-header.tsx b/packages/app/src/session/session-identity-header.tsx index ed7786e2781b..626388c35d7c 100644 --- a/packages/app/src/session/session-identity-header.tsx +++ b/packages/app/src/session/session-identity-header.tsx @@ -435,7 +435,8 @@ export function SessionLocation(props: { - + {/* A child's lineage follows, whose buttons pad 6px; a title pads 4px. */} + ) @@ -499,21 +500,20 @@ export function SessionAncestorTrail(props: { data-slot={ancestor.direct ? "session-title-parent" : "session-title-ancestor"} data-session-id={ancestor.id} title={ancestor.title} - class="max-w-[min(200px,40vw)] shrink-0 truncate text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:text-v2-text-text-muted" - classList={{ "ps-1": index() === 0 }} + class="h-7 max-w-[min(200px,40vw)] shrink-0 truncate rounded-[6px] px-1.5 text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:bg-v2-overlay-simple-overlay-hover hover:text-v2-text-text-muted focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:text-v2-text-text-muted focus-visible:outline-none" onClick={() => open(props.sessionID, ancestor.id)} > {ancestor.title} - + )} - + ) From a5170d6e019341864d948189d1420096005de8e0 Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:53:39 +0100 Subject: [PATCH 15/43] feat(stories): browse app states in the standalone components lab (#63737) --- .../component-tests/components-lab.spec.ts | 24 + packages/app/src/components-lab/browser.tsx | 745 ++++++++++++++++++ packages/app/src/components-lab/catalog.ts | 32 +- .../components-lab/dialog-story-runtime.tsx | 11 +- packages/app/src/components-lab/inspector.css | 28 + packages/app/src/components-lab/lab.tsx | 667 +--------------- .../src/composer/composer-touch.stories.tsx | 18 +- .../app/src/composer/composer.stories.tsx | 214 ++--- .../app/src/home/home.standalone.stories.tsx | 260 ++++++ packages/app/src/home/route.tsx | 34 +- packages/app/src/home/sessions/controller.tsx | 5 +- .../home/sessions/delete-dialog.stories.tsx | 21 +- packages/app/src/home/sessions/search.ts | 7 +- .../new-session/draft.standalone.stories.tsx | 205 +++++ .../location/dialog.standalone.stories.tsx | 26 +- .../app/src/new-session/wordmark.stories.tsx | 87 +- .../connect/dialog.standalone.stories.tsx | 15 +- .../providers/connect/mcp-dialog.stories.tsx | 21 +- .../models/manage.standalone.stories.tsx | 43 +- .../select-dialog.standalone.stories.tsx | 26 +- .../models/unpaid.standalone.stories.tsx | 64 +- .../src/runtime/plugin/dialogs.stories.tsx | 42 +- .../runtime/plugin/titlebar-items.stories.tsx | 107 ++- .../app/src/servers/registry/row.stories.tsx | 26 +- .../session/commands/fork-dialog.stories.tsx | 20 +- .../commands/jump-to-message.stories.tsx | 131 ++- .../src/session/commands/jump-to-message.tsx | 11 +- .../composer/activity-chips.stories.tsx | 37 +- .../composer/composer-docks.stories.tsx | 57 +- .../free-limit-panel.standalone.stories.tsx | 45 ++ .../location-missing.standalone.stories.tsx | 142 ++++ .../session/composer/queue-panel.stories.tsx | 89 ++- .../src/session/composer/recovery-story.tsx | 38 + .../session/composer/todo-pill.stories.tsx | 15 +- .../header/session-header-actions.stories.tsx | 35 +- .../src/session/question-switch.stories.tsx | 25 + ...r-unavailable-panel.standalone.stories.tsx | 88 +++ .../src/session/session-screen.stories.tsx | 23 +- .../timeline/background-work.stories.tsx | 10 +- .../session/timeline/search-bar.stories.tsx | 122 +++ .../src/session/timeline/search-controller.ts | 40 +- .../src/session/timeline/sources.stories.tsx | 31 +- .../src/settings/shell.standalone.stories.tsx | 15 +- .../src/settings/timeline-detail.stories.tsx | 64 +- .../commands/dialog.standalone.stories.tsx | 81 +- .../src/shell/titlebar/inbox-card.stories.tsx | 58 +- .../src/shell/titlebar/inbox-list.stories.tsx | 21 +- .../src/shell/titlebar/navigation-story.tsx | 207 +++++ .../sidebar-customized.standalone.stories.tsx | 16 + .../titlebar/tab-strip.standalone.stories.tsx | 19 + .../src/usage/dialog.standalone.stories.tsx | 22 +- .../selection/dialog.standalone.stories.tsx | 12 +- packages/stories/index.html | 2 +- packages/stories/mocks/app/context/layout.ts | 5 + packages/stories/playwright/README.md | 2 + packages/stories/src/frame.tsx | 87 +- packages/stories/src/index-plugin.ts | 8 + packages/stories/src/lab.tsx | 54 ++ packages/stories/src/main.ts | 6 + packages/stories/src/providers.tsx | 51 ++ packages/stories/vite.config.ts | 3 +- 61 files changed, 3218 insertions(+), 1202 deletions(-) create mode 100644 packages/app/component-tests/components-lab.spec.ts create mode 100644 packages/app/src/components-lab/browser.tsx create mode 100644 packages/app/src/components-lab/inspector.css create mode 100644 packages/app/src/home/home.standalone.stories.tsx create mode 100644 packages/app/src/new-session/draft.standalone.stories.tsx create mode 100644 packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx create mode 100644 packages/app/src/session/composer/location-missing.standalone.stories.tsx create mode 100644 packages/app/src/session/composer/recovery-story.tsx create mode 100644 packages/app/src/session/server-unavailable-panel.standalone.stories.tsx create mode 100644 packages/app/src/session/timeline/search-bar.stories.tsx create mode 100644 packages/app/src/shell/titlebar/navigation-story.tsx create mode 100644 packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx create mode 100644 packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx create mode 100644 packages/stories/src/lab.tsx create mode 100644 packages/stories/src/main.ts create mode 100644 packages/stories/src/providers.tsx diff --git a/packages/app/component-tests/components-lab.spec.ts b/packages/app/component-tests/components-lab.spec.ts new file mode 100644 index 000000000000..d83e4d295fba --- /dev/null +++ b/packages/app/component-tests/components-lab.spec.ts @@ -0,0 +1,24 @@ +import { expect, story } from "../../stories/playwright/story" + +story("opens a component from the standalone catalog and previews its states", async ({ page }) => { + await page.goto("/") + await expect(page.getByRole("tree")).toBeVisible({ timeout: 30_000 }) + await page.getByRole("button", { name: /Search components/ }).click() + + const search = page.getByPlaceholder("Search components") + + await search.fill("Composer docks") + await search.press("Enter") + await page.getByText("Queue Three", { exact: true }).click() + await expect(page.getByText("Rename the Alpha export", { exact: true })).toBeVisible() +}) + +story("edits a story's state argument from the inspector", async ({ page }) => { + await page.goto("/?story=../../app/src/composer/composer-touch.stories.tsx") + await page + .getByRole("region", { name: "components-lab controls" }) + .getByRole("button", { name: "state", exact: true }) + .click() + await page.getByRole("menuitemradio", { name: "shell", exact: true }).click() + await expect(page.getByLabel("Composer state", { exact: true })).toHaveValue("shell") +}) diff --git a/packages/app/src/components-lab/browser.tsx b/packages/app/src/components-lab/browser.tsx new file mode 100644 index 000000000000..cc876cd70fc0 --- /dev/null +++ b/packages/app/src/components-lab/browser.tsx @@ -0,0 +1,745 @@ +import { makeEventListener } from "@solid-primitives/event-listener" +import { + batch, + createEffect, + createMemo, + createResource, + createRoot, + createSignal, + ErrorBoundary, + getOwner, + on, + onCleanup, + onMount, + Show, + untrack, + type JSX, + type ParentComponent, +} from "solid-js" +import { createStore, reconcile } from "solid-js/store" +import { Dynamic, insert } from "solid-js/web" +import { DialogProvider } from "@opencode/ui/context/dialog" +import { useTheme } from "@opencode/ui/theme" +import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning" +import { choice, defineControls, matchesCombo, toolbar, type Field } from "knobs" +import { canvas, commandPalette, restyle, split, toast, type CommandPalette } from "knobs/ui" +import { Tree } from "knobs/ui/solid" +import { useLanguage } from "@/runtime/i18n/language" +import { SessionRouteFrame } from "@/session/session-frame" +import { fileName, knobArgs, labFields, stateArgs, type LabEntry, type StoryArgs } from "./catalog" +import { + createLabStageState, + INITIAL_LAB_BROWSE_STATE, + labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, + transitionLabStage, + type LabBrowseEvent, + type LabStageEffect, + type LabStageEvent, +} from "./machine" +import { applyMotionPatch, motionFields, motionScopes, motionValues, sameMotion, storyMotion } from "./motion" +import "./inspector.css" + +// How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so +// a transition still finishes and Play keeps moving. +const hold = 1600 + +const searchIcon = `` + +const themeIcon = `` + +const gridIcon = `` + +type Row = { id: string; label: string; detail?: string; children?: Row[] } + +type LabParams = { story?: string; view?: string } + +type LabPlugin = ParentComponent<{ file: string }> + +export function LabBrowser(props: { + params: LabParams + setParams: (patch: LabParams) => void + loadCatalog: () => Promise<{ entries: LabEntry[]; failed: number }> + workspace?: ParentComponent + plugin: LabPlugin +}) { + const language = useLanguage() + const theme = useTheme() + const [resource] = createResource(() => props.loadCatalog()) + + const catalog = () => (resource.loading ? undefined : resource.latest) + + const [scheme, setScheme] = createSignal<"dark" | "light">("dark") + let palette: CommandPalette | undefined + let toggle: ((id: string) => void) | undefined + let focusTree: ((id?: string) => void) | undefined + let browse = INITIAL_LAB_BROWSE_STATE + + const dispatchBrowse = (event: LabBrowseEvent) => { + const next = transitionLabBrowse(browse, event) + browse = next.state + next.effects.forEach(() => focusTree?.(props.params.story)) + } + + const entries = () => catalog()?.entries ?? [] + const grid = () => props.params.view === "grid" + const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === props.params.story))) + + const open = (file: string) => { + dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) + props.setParams({ story: file, view: undefined }) + } + + const rows = createMemo(() => folder(entries(), [])) + + const search = () => { + if (palette?.isOpen) return palette.close() + + palette ??= commandPalette({ + hotkey: false, + recents: false, + placeholder: language.t("lab.search"), + look: { theme: scheme() }, + commands: () => + entries().map((entry) => ({ + id: entry.file, + label: entry.title.split("/").join(" / "), + hint: fileName(entry.file), + keywords: entry.states.map((state) => state.name), + run: () => open(entry.file), + })), + }) + palette.open() + } + + // The palette takes its look when it's made. + createEffect( + on( + scheme, + () => { + palette?.dispose() + palette = undefined + }, + { defer: true }, + ), + ) + + // Ahead of the app's own palette, which listens on the document. + makeEventListener( + window, + "keydown", + (event) => { + if (!matchesCombo("Mod+K", event)) return + event.preventDefault() + event.stopImmediatePropagation() + search() + }, + { capture: true }, + ) + + // A story's modal overlay (a menu or dialog open by default) sets `pointer-events: none` on the body, which would + // freeze the lab around it. The lab stays usable while it's open. + const unblock = document.createElement("style") + + unblock.textContent = "body { pointer-events: auto !important; }" + document.head.append(unblock) + + createEffect(() => theme.previewColorScheme(scheme())) + onCleanup(() => { + theme.cancelPreview() + palette?.dispose() + unblock.remove() + }) + + createEffect(() => { + const failed = catalog()?.failed + + if (failed) toast(language.plural("lab.failed", failed)) + }) + + // The story's knobs panel mounts in the inspector pane. + const inspector = pane(() => null) + + const stories = pane(() => ( + + row.detail} + label={language.t("lab.components")} + expanded={rows().map((row) => row.id)} + selection={props.params.story ? [props.params.story] : []} + // Digits pick the story's states. + typeahead={(key) => !/^[0-9]$/.test(key)} + onReady={(tree) => { + // Opens the folders down to the story in the address, and later ones picked from the palette. + createEffect(() => props.params.story && tree.reveal(props.params.story)) + toggle = (id) => tree.expand(id, !tree.isExpanded(id)) + focusTree = (id) => tree.focus(id) + }} + // Moving by keys selects as it goes, so a folder opens and closes only by a click, Enter, Space or ←/→. + onSelect={(_, primary) => { + if (!primary?.startsWith("folder:")) return primary && open(primary) + + if (selectShouldToggleFolder(browse)) toggle?.(primary) + }} + onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} + /> + + )) + + const stage = pane(() => ( + + entry.title.startsWith("UI/") || isDialogEntry(entry))} + scheme={untrack(scheme)} + onOpen={open} + plugin={props.plugin} + /> + + } + > + + {language.t("lab.pick")} + + } + > + {(entry) => ( + + )} + + + )) + + const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) + + makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { + capture: true, + }) + // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. + makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener( + window, + "keydown", + (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), + { capture: true }, + ) + makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) + makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) + makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) + + let element!: HTMLDivElement + + onMount(() => { + const layout = split(element, { + theme: "dark", + storage: null, + panes: [ + { + id: "stories", + size: 260, + min: 200, + max: 420, + collapsible: true, + title: language.t("lab.components"), + element: stories, + actions: [ + { label: language.t("lab.search"), icon: searchIcon, shortcut: "Mod+K", run: search }, + { + label: language.t("lab.grid"), + icon: gridIcon, + run: () => props.setParams({ view: grid() ? undefined : "grid" }), + }, + { + label: language.t("lab.theme"), + icon: themeIcon, + run: () => setScheme(scheme() === "dark" ? "light" : "dark"), + }, + ], + }, + { id: "stage", min: 360, element: stage }, + { id: "inspector", size: 300, min: 260, max: 460, collapsible: true, title: "", element: inspector }, + ], + }) + + createEffect(() => layout.pane("stories").title(language.t("lab.components"), entries().length)) + createEffect(() => layout.pane("inspector").title(selected()?.title.split("/").join(" / ") ?? "")) + createEffect(on(scheme, (next) => restyle(layout.element, { theme: next }), { defer: true })) + onCleanup(() => layout.dispose()) + }) + + return ( + +
+ + ) +} + +/** One story on the app's background, with its args and states as a knobs panel in the inspector. */ +function Stage(props: { + entry: LabEntry + inspector: HTMLElement + scheme: "dark" | "light" + workspace?: ParentComponent + plugin: LabPlugin +}) { + const Workspace: ParentComponent = props.workspace ?? ((props) => props.children) + + const language = useLanguage() + const entry = props.entry + const fields = labFields(entry) + const names = entry.states.map((state) => state.name) + const [args, setArgs] = createStore(stateArgs(entry, 0)) + const [stageState, setStageState] = createSignal(createLabStageState(names)) + const index = createMemo(() => labStageIndex(stageState())) + const [canvas, setCanvas] = createSignal() + const component = entry.component + const fallback = component && ((values: StoryArgs) => ) + // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. + const render = () => entry.states[index()]?.render ?? entry.render ?? fallback + let timer: ReturnType | undefined + + // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. + const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) + + // One batch, so a state with its own render function never renders with the previous state's args. + const dispatch = (event: LabStageEvent) => + batch(() => { + const next = transitionLabStage(untrack(stageState), event) + setStageState(next.state) + next.effects.forEach(perform) + }) + + const perform = (effect: LabStageEffect) => { + if (effect.type === "timer.schedule") { + clearTimeout(timer) + timer = setTimeout( + () => dispatch({ type: "tick", attempt: effect.attempt }), + (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, + ) + + return + } + + if (effect.type === "timer.clear") return clearTimeout(timer) + + if (effect.type === "state.apply") { + setArgs(reconcile(stateArgs(entry, effect.index))) + + if (effect.preset === "now") preset(effect.index) + + // Undo or a reset moved the state: bring the other knobs to the state's args too. + if (effect.preset === "later") + queueMicrotask(() => { + if (untrack(stageState).status !== "disposed") preset(effect.index) + }) + + return + } + + // Coalesced: a story registers its replay buttons one by one. + if (effect.type === "motion.queue") return queueMicrotask(() => dispatch({ type: "motion.flushed" })) + const next = storyMotion(entry.motion) + + if (!sameMotion(next, motion)) return setShown(next) + store.sync(motionValues(motion)) + } + + const [first, ...rest] = names + + const states: { [key: string]: Field } = + first === undefined || rest.length === 0 + ? {} + : { + // Story args can themselves be named `state` (e.g. the touch composer) or `play`. + "lab.preset": choice(first, [first, ...rest], { variants: true }), + "lab.playback": toolbar( + [ + { + id: "previous", + label: language.t("lab.previous"), + icon: "M200 48 80 128l120 80ZM48 48h16v160H48Z", + run: () => dispatch({ type: "step", delta: -1 }), + }, + { id: "play", label: language.t("lab.play"), icon: "play", run: () => dispatch({ type: "play" }) }, + { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => dispatch({ type: "pause" }) }, + { + id: "next", + label: language.t("lab.next"), + icon: "M56 48l120 80-120 80ZM192 48h16v160h-16Z", + run: () => dispatch({ type: "step", delta: 1 }), + }, + ], + { labels: false, label: language.t("lab.play") }, + ), + } + + // The story's Knobs join its args here, so the inspector is the one place for its controls. Registering a knob or a + // replay button (as the story mounts) rebuilds it where it was. + let motion = storyMotion(entry.motion) + const [shown, setShown] = createSignal(motion, { equals: sameMotion }) + + const inspect = () => { + const scopes = motionScopes(motion) + + return defineControls( + "components-lab", + { ...states, ...fields, ...motionFields(motion) }, + { + storage: null, + persist: "none", + // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. + ship: () => import("knobs/panel"), + defaultLabel: { ...(first !== undefined && { "": first }), ...scopes.defaultLabels }, + presets: Object.fromEntries( + entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), + ), + // A state leaves the Knobs where they are: they're the story's tuning, not part of a state. + inPresets: scopes.inPresets, + scopedPresets: scopes.scopedPresets, + onChange: (patch, values, meta) => { + applyMotionPatch(motion, patch) + + if (!("lab.preset" in patch)) { + if (meta.source !== "preset") dispatch({ type: "pause" }) + + return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) + } + + dispatch({ type: "panel.state", name: String(values["lab.preset"]), fromPreset: meta.source === "preset" }) + }, + }, + ) + } + + let store!: ReturnType + + createEffect(() => { + motion = shown() + store = untrack(inspect) + store.sync(motionValues(motion)) + onCleanup( + store.mount(props.inspector, { + theme: props.scheme, + // At some pane widths automatic sizing alternates between chips and a list on every frame. + presetDisplay: "chips", + header: { title: false, buttons: ["undo", "redo", "reset"] }, + variants: false, + session: false, + empty: language.t("lab.noControls"), + hints: { digits: "always" }, + }), + ) + + // A rebuild stays on the state it was showing, and its fresh knobs show that state's args. + if (rest.length > 0) + untrack(() => { + setArgs(reconcile(stateArgs(entry, index()))) + preset(index()) + }) + }) + + onCleanup(motionTuning.subscribe(() => dispatch({ type: "motion.changed" }))) + onCleanup(() => dispatch({ type: "disposed" })) + + if (names.length > 1) { + bindPresetNumbers(props.inspector, names.length, (number) => dispatch({ type: "select", index: number - 1 })) + } + + return ( + // Contained layout makes the canvas hold its stories' dialogs, which the provider below portals into it. + // A press inside the story (its own replay buttons, a dock) stops Play rather than being undone by it. +
dispatch({ type: "pause" })} + > + + + + {(fn) => ( + + { + // A failing state does not stick: the next state or edit tries again. + createEffect(on(() => ({ ...args }), reset, { defer: true })) + + return ( +
+                        {String(error)}
+                      
+ ) + }} + > + {untrack(() => fn(args))} +
+
+ )} +
+
+
+
+ ) +} + +/** The tree under `path`: a folder for each further title segment and a row for each story, by name. */ +function folder(entries: LabEntry[], path: string[]): Row[] { + const depth = path.length + const inside = entries.filter((entry) => path.every((segment, index) => entry.title.split("/")[index] === segment)) + const names = [...new Set(inside.flatMap((entry) => entry.title.split("/").slice(depth, -1).slice(0, 1)))] + + return [ + ...names.map((name) => ({ + id: `folder:${[...path, name].join("/")}`, + label: name, + children: folder(inside, [...path, name]), + })), + ...inside.flatMap((entry) => + entry.title.split("/").length === depth + 1 + ? [ + { + id: entry.file, + label: entry.title.split("/").at(-1) ?? entry.title, + // Files may share a title; the file name tells them apart. + detail: + inside.filter((other) => other.title === entry.title).length > 1 ? fileName(entry.file) : undefined, + }, + ] + : [], + ), + ].toSorted((a, b) => a.label.localeCompare(b.label)) +} + +// knobs' split takes each pane's content as a node; Solid keeps it reactive where it sits. +/** The library's stories on a canvas that pans and zooms, each in its first state; clicking one opens it on its own. */ +function Grid(props: { + entries: LabEntry[] + scheme: "dark" | "light" + onOpen: (file: string) => void + plugin: LabPlugin +}) { + const language = useLanguage() + const owner = getOwner() + let element!: HTMLDivElement + + onMount(() => { + const visibility = new Map void>() + + const observer = new IntersectionObserver( + (entries) => batch(() => entries.forEach((entry) => visibility.get(entry.target)?.(entry.isIntersecting))), + { root: element }, + ) + + const board = canvas(element, { + theme: props.scheme, + label: language.t("lab.grid"), + // Neighbours share the library's folder: actions, forms, overlays, then app dialogs. + items: props.entries + .toSorted((a, b) => folderOf(a).localeCompare(folderOf(b))) + .map((entry) => { + const size = tileSize(entry) + + return { + id: entry.file, + title: entry.title.split("/").at(-1), + w: size.w, + h: size.h, + render: (card: HTMLElement) => + createRoot((dispose) => { + // The shell keeps its size and hit target as previews enter and leave the viewport. + card.dataset.labStory = entry.file + const [visible, setVisible] = createSignal(false) + visibility.set(card, setVisible) + observer.observe(card) + insert(card, () => ( + + + + )) + onCleanup(() => { + observer.unobserve(card) + visibility.delete(card) + }) + + return dispose + }, owner ?? undefined), + } + }), + }) + + // The canvas captures the pointer to pan, so a card never sees its click: a press that ends where it began opens + // the story it began on. + let press: { file: string; x: number; y: number } | undefined + + const down = (event: PointerEvent) => { + const file = event.target instanceof Element ? event.target.closest("[data-lab-story]") : null + + press = file?.dataset.labStory ? { file: file.dataset.labStory, x: event.clientX, y: event.clientY } : undefined + } + + const up = (event: PointerEvent) => { + if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) props.onOpen(press.file) + press = undefined + } + + element.addEventListener("pointerdown", down, true) + window.addEventListener("pointerup", up, true) + onCleanup(() => { + element.removeEventListener("pointerdown", down, true) + window.removeEventListener("pointerup", up, true) + observer.disconnect() + board.dispose() + }) + }) + + return
+} + +// A story's first state at its natural size, holding its own dialogs as the stage does. +function Tile(props: { entry: LabEntry; plugin: LabPlugin }) { + const [canvas, setCanvas] = createSignal() + const component = props.entry.component + const render = props.entry.gridPreview ?? props.entry.states[0]?.render ?? props.entry.render + + return ( +
+ {/* The provider waits for the card, so a story that opens a dialog at once opens it inside. */} + + {(container) => ( +
+ + +
{String(error)}
} + > + {render + ? untrack(() => render(stateArgs(props.entry, 0))) + : component && } +
+
+
+
+ )} +
+
+ ) +} + +function isDialogEntry(entry: LabEntry) { + return entry.title.startsWith("App/Dialogs/") || entry.file.endsWith("/overlays/dialog/dialog.stories.tsx") +} + +function tileSize(entry: LabEntry) { + if (entry.fullscreen) return { w: 1120, h: 720 } + + if (isDialogEntry(entry)) return { w: 720, h: 820 } + + return { w: 320, h: 240 } +} + +function folderOf(entry: LabEntry) { + if (isDialogEntry(entry)) return `1:dialogs:${entry.title}` + + return `0:${entry.file.match(/ui\/src\/([^/]+)\//)?.[1] ?? ""}` +} + +function typing(target: EventTarget | null) { + return target instanceof HTMLElement && (target.isContentEditable || !!target.closest("input, textarea, select")) +} + +function bindPresetNumbers(inspector: HTMLElement, count: number, select: (number: number) => void) { + let pending: { number: number; timer: ReturnType } | undefined + + const clear = () => { + clearTimeout(pending?.timer) + pending = undefined + } + + const keydown = (event: KeyboardEvent) => { + if ( + event.defaultPrevented || + event.isComposing || + event.metaKey || + event.ctrlKey || + event.altKey || + event.shiftKey || + typing(event.target) || + !/^[0-9]$/.test(event.key) + ) + return clear() + + if (!pending && (event.key === "0" || Number(event.key) > count)) return + + event.preventDefault() + event.stopPropagation() + + if (event.repeat) return + + const number = (pending?.number ?? 0) * 10 + Number(event.key) + clear() + + if (number > count) return + + if (number * 10 > count) return select(number) + + // A prefix can be a preset on its own. Wait for the next digit before mounting a story that might take focus. + pending = { + number, + timer: setTimeout(() => { + pending = undefined + select(number) + }, 450), + } + } + + // Knobs handles single digits on a focused preset strip before the event reaches the window. + makeEventListener( + inspector, + "keydown", + (event) => { + if ( + event.target instanceof Element && + event.target.closest(".knobs-presets") && + !event.target.closest(".knobs-card") + ) + keydown(event) + }, + { capture: true }, + ) + makeEventListener(window, "keydown", keydown) + makeEventListener(window, "pointerdown", clear, { capture: true }) + makeEventListener(window, "blur", clear) + onCleanup(clear) +} + +function pane(content: () => JSX.Element) { + const element = document.createElement("div") + + element.className = "size-full" + insert(element, content) + + return element +} diff --git a/packages/app/src/components-lab/catalog.ts b/packages/app/src/components-lab/catalog.ts index 924c06874b9d..8e6510960c53 100644 --- a/packages/app/src/components-lab/catalog.ts +++ b/packages/app/src/components-lab/catalog.ts @@ -24,7 +24,7 @@ type StoryObject = { argTypes?: { [key: string]: ArgType } render?: StoryRender // `motion` names the Knobs (by id, group or card) the story uses, so the inspector shows them beside its args. - parameters?: { layout?: string; motion?: readonly string[] } + parameters?: { layout?: string; motion?: readonly string[]; gridPreview?: () => JSX.Element } } export type StoryModule = { [name: string]: StoryObject | StoryRender | string[] | undefined } @@ -40,10 +40,39 @@ export type LabEntry = { argTypes: { [key: string]: ArgType } render?: StoryRender fullscreen: boolean + gridPreview?: () => JSX.Element motion: readonly string[] states: LabState[] } +/** Loads every story file. A file that fails to import is reported rather than hiding the rest. */ +export async function loadLabCatalog( + modules: Record Promise>, + sources: Record Promise>, +) { + const files = Object.entries(modules) + + const results: PromiseSettledResult[] = [] + + // A few files at a time: hundreds of parallel module requests overflow a dev server reached through a proxy. + for (let index = 0; index < files.length; index += 8) { + const chunk = files.slice(index, index + 8).map(async ([file, load]) => { + const [module, source] = await Promise.all([load(), sources[file]?.() ?? ""]) + + return labEntry(file, module, source) + }) + + results.push(...(await Promise.allSettled(chunk))) + } + + return { + entries: results + .flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])) + .toSorted((a, b) => a.title.localeCompare(b.title)), + failed: results.filter((result) => result.status === "rejected").length, + } +} + // A story file as the lab shows it. A module lists its exports alphabetically, so `source`, the file's text, gives the // order the author wrote the states in. export function labEntry(file: string, module: StoryModule, source: string): LabEntry { @@ -76,6 +105,7 @@ export function labEntry(file: string, module: StoryModule, source: string): Lab }, render: meta.render, fullscreen: meta.parameters?.layout === "fullscreen", + gridPreview: meta.parameters?.gridPreview, motion: meta.parameters?.motion ?? [], states, } diff --git a/packages/app/src/components-lab/dialog-story-runtime.tsx b/packages/app/src/components-lab/dialog-story-runtime.tsx index fb1b596567b1..95f3ef4bd23f 100644 --- a/packages/app/src/components-lab/dialog-story-runtime.tsx +++ b/packages/app/src/components-lab/dialog-story-runtime.tsx @@ -353,9 +353,10 @@ function findMatchingPaths(root: string, query: string, type: string | null) { type DialogStoryRuntimeOptions = { servers?: ServerConnection.Any[] + platform?: Platform } -function createStoryFetch(): typeof fetch { +export function createStoryFetch(): typeof fetch { const encoder = new TextEncoder() const handler = async (input: RequestInfo | URL, init?: RequestInit) => { @@ -541,7 +542,7 @@ function createStoryFetch(): typeof fetch { return Object.assign(handler, { preconnect: globalThis.fetch.preconnect }) } -function createMemoryStorage() { +export function createMemoryStorage() { const namespaces = new Map>() const bucket = (name = "default") => { @@ -574,14 +575,12 @@ function createMemoryStorage() { export function DialogStoryRuntime(props: ParentProps) { const servers = () => props.servers ?? [STORY_SERVER] - const storage = createMemoryStorage() - - const platform: Platform = { + const platform: Platform = props.platform ?? { platform: "web", openExternal() {}, restart: async () => {}, notify: async () => {}, - storage, + storage: createMemoryStorage(), fetch: createStoryFetch(), } diff --git a/packages/app/src/components-lab/inspector.css b/packages/app/src/components-lab/inspector.css new file mode 100644 index 000000000000..3085e0a849a6 --- /dev/null +++ b/packages/app/src/components-lab/inspector.css @@ -0,0 +1,28 @@ +.knobs-panel.knobs-inline[data-controls="components-lab"] { + border-radius: 0; +} + +.knobs-panel[data-controls="components-lab"] .knobs-presets-track { + counter-reset: lab-preset; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-chip { + counter-increment: lab-preset; + padding-inline-start: 30px; + text-align: start; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-key { + display: none; +} + +.knobs-panel[data-controls="components-lab"] .knobs-preset-chip::before { + content: counter(lab-preset); + position: absolute; + inset-inline-start: 6px; + inline-size: 2ch; + text-align: end; + color: var(--_k-fg-3); + font-size: var(--_k-text-meta); + font-variant-numeric: tabular-nums; +} diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index 4e90eb06fbb4..811acb7d9370 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -1,30 +1,5 @@ -import { makeEventListener } from "@solid-primitives/event-listener" import { useSearchParams } from "@solidjs/router" -import { - batch, - createEffect, - createMemo, - createResource, - createRoot, - createSignal, - ErrorBoundary, - getOwner, - on, - onCleanup, - onMount, - Show, - untrack, - type JSX, -} from "solid-js" -import { createStore, reconcile } from "solid-js/store" -import { Dynamic, insert } from "solid-js/web" -import { DialogProvider } from "@opencode/ui/context/dialog" -import { useTheme } from "@opencode/ui/theme" -import { motionGlobals, motionTuning } from "@opencode/ui/motion-tuning" -import { choice, defineControls, matchesCombo, toolbar, type Field } from "knobs" -import { canvas, commandPalette, restyle, split, toast, type CommandPalette } from "knobs/ui" -import { Tree } from "knobs/ui/solid" -import { useLanguage } from "@/runtime/i18n/language" +import { createMemo, Show, type ParentProps } from "solid-js" import { CommentsProvider } from "@/composer/comments" import { ComposerPersistenceProvider } from "@/composer/persistence" import { ModelsProvider } from "@/providers/models/models" @@ -33,42 +8,11 @@ import { ServerProvider, useServer } from "@/runtime/server/current" import { ServerConnection, useServers } from "@/runtime/server/registry" import { isServerHealthy } from "@/runtime/server/health-machine" import { useGlobal } from "@/runtime/server/runtime" -import { SessionRouteFrame } from "@/session/session-frame" import { SessionUIProvider } from "@/shell/routes/session-ui-provider" import { FileProvider } from "@/workspaces/files/model" import { LocationProvider } from "@/workspaces/location" -import { - fileName, - knobArgs, - labEntry, - labFields, - stateArgs, - type LabEntry, - type StoryArgs, - type StoryModule, -} from "./catalog" -import { - createLabStageState, - INITIAL_LAB_BROWSE_STATE, - labStageIndex, - selectShouldToggleFolder, - transitionLabBrowse, - transitionLabStage, - type LabBrowseEvent, - type LabStageEffect, - type LabStageEvent, -} from "./machine" -import { applyMotionPatch, motionFields, motionScopes, motionValues, sameMotion, storyMotion } from "./motion" - -// How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so -// a transition still finishes and Play keeps moving. -const hold = 1600 - -const searchIcon = `` - -const themeIcon = `` - -const gridIcon = `` +import { LabBrowser } from "./browser" +import { loadLabCatalog, type StoryModule } from "./catalog" // Standalone stories mount fixture runtimes that must not access the live app's storage. // Vite needs the patterns as literals in each call. @@ -92,446 +36,17 @@ const sources = import.meta.glob( { query: "?raw", import: "default" }, ) -/** Loads every story file. A file that fails to import is reported rather than hiding the rest. */ -async function loadCatalog() { - const files = Object.entries(modules) - const results: PromiseSettledResult[] = [] - - // A few files at a time: hundreds of parallel module requests overflow a dev server reached through a proxy. - for (let index = 0; index < files.length; index += 8) { - const chunk = files.slice(index, index + 8).map(async ([file, load]) => { - const [module, source] = await Promise.all([load(), sources[file]?.() ?? ""]) - - return labEntry(file, module, source) - }) - - results.push(...(await Promise.allSettled(chunk))) - } - - return { - entries: results - .flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])) - .toSorted((a, b) => a.title.localeCompare(b.title)), - failed: results.filter((result) => result.status === "rejected").length, - } -} - -type Row = { id: string; label: string; detail?: string; children?: Row[] } - -/** The development components lab: every story file in knobs' workspace, rendered with the app's providers and theme. */ export default function ComponentsLab() { - const language = useLanguage() - const theme = useTheme() const [params, setParams] = useSearchParams<{ story?: string; view?: string }>() - const [catalog] = createResource(loadCatalog) - const [scheme, setScheme] = createSignal<"dark" | "light">("dark") - let palette: CommandPalette | undefined - let toggle: ((id: string) => void) | undefined - let focusTree: ((id?: string) => void) | undefined - let browse = INITIAL_LAB_BROWSE_STATE - - const dispatchBrowse = (event: LabBrowseEvent) => { - const next = transitionLabBrowse(browse, event) - browse = next.state - next.effects.forEach(() => focusTree?.(params.story)) - } - - const entries = () => catalog()?.entries ?? [] - const grid = () => params.view === "grid" - const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === params.story))) - - const open = (file: string) => { - dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) - setParams({ story: file, view: undefined }) - } - - const rows = createMemo(() => folder(entries(), [])) - - const search = () => { - if (palette?.isOpen) return palette.close() - - palette ??= commandPalette({ - hotkey: false, - recents: false, - placeholder: language.t("lab.search"), - look: { theme: scheme() }, - commands: () => - entries().map((entry) => ({ - id: entry.file, - label: entry.title.split("/").join(" / "), - hint: fileName(entry.file), - keywords: entry.states.map((state) => state.name), - run: () => open(entry.file), - })), - }) - palette.open() - } - - // The palette takes its look when it's made. - createEffect( - on( - scheme, - () => { - palette?.dispose() - palette = undefined - }, - { defer: true }, - ), - ) - - // Ahead of the app's own palette, which listens on the document. - makeEventListener( - window, - "keydown", - (event) => { - if (!matchesCombo("Mod+K", event)) return - event.preventDefault() - event.stopImmediatePropagation() - search() - }, - { capture: true }, - ) - - // A story's modal overlay (a menu or dialog open by default) sets `pointer-events: none` on the body, which would - // freeze the lab around it. The lab stays usable while it's open. - const unblock = document.createElement("style") - - unblock.textContent = "body { pointer-events: auto !important; }" - document.head.append(unblock) - - createEffect(() => theme.previewColorScheme(scheme())) - onCleanup(() => { - theme.cancelPreview() - palette?.dispose() - unblock.remove() - }) - - createEffect(() => { - const failed = catalog()?.failed - - if (failed) toast(language.plural("lab.failed", failed)) - }) - - // The story's knobs panel mounts in the inspector pane. - const inspector = pane(() => null) - - const stories = pane(() => ( - - row.detail} - label={language.t("lab.components")} - expanded={rows().map((row) => row.id)} - selection={params.story ? [params.story] : []} - // Digits pick the story's states. - typeahead={(key) => !/^[1-9]$/.test(key)} - onReady={(tree) => { - // Opens the folders down to the story in the address, and later ones picked from the palette. - createEffect(() => params.story && tree.reveal(params.story)) - toggle = (id) => tree.expand(id, !tree.isExpanded(id)) - focusTree = (id) => tree.focus(id) - }} - // Moving by keys selects as it goes, so a folder opens and closes only by a click, Enter, Space or ←/→. - onSelect={(_, primary) => { - if (!primary?.startsWith("folder:")) return primary && open(primary) - - if (selectShouldToggleFolder(browse)) toggle?.(primary) - }} - onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} - /> - - )) - - const stage = pane(() => ( - entry.title.startsWith("UI/") || isDialogEntry(entry))} - scheme={untrack(scheme)} - onOpen={open} - /> - } - > - - {language.t("lab.pick")} -
- } - > - {(entry) => } - - - )) - - const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) - - makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { - capture: true, - }) - // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. - makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) - makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) - makeEventListener( - window, - "keydown", - (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), - { capture: true }, - ) - makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) - makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) - makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) - - let element!: HTMLDivElement - - onMount(() => { - const layout = split(element, { - theme: "dark", - storage: null, - panes: [ - { - id: "stories", - size: 260, - min: 200, - max: 420, - collapsible: true, - title: language.t("lab.components"), - element: stories, - actions: [ - { label: language.t("lab.search"), icon: searchIcon, shortcut: "Mod+K", run: search }, - { - label: language.t("lab.grid"), - icon: gridIcon, - run: () => setParams({ view: grid() ? undefined : "grid" }), - }, - { - label: language.t("lab.theme"), - icon: themeIcon, - run: () => setScheme(scheme() === "dark" ? "light" : "dark"), - }, - ], - }, - { id: "stage", min: 360, element: stage }, - { id: "inspector", size: 300, min: 260, max: 460, collapsible: true, title: "", element: inspector }, - ], - }) - - createEffect(() => layout.pane("stories").title(language.t("lab.components"), entries().length)) - createEffect(() => layout.pane("inspector").title(selected()?.title.split("/").join(" / ") ?? "")) - createEffect(on(scheme, (next) => restyle(layout.element, { theme: next }), { defer: true })) - onCleanup(() => layout.dispose()) - }) return ( - -
- - ) -} - -/** One story on the app's background, with its args and states as a knobs panel in the inspector. */ -function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" | "light" }) { - const language = useLanguage() - const entry = props.entry - const fields = labFields(entry) - const names = entry.states.map((state) => state.name) - const [args, setArgs] = createStore(stateArgs(entry, 0)) - const [stageState, setStageState] = createSignal(createLabStageState(names)) - const index = createMemo(() => labStageIndex(stageState())) - const [canvas, setCanvas] = createSignal() - const component = entry.component - const fallback = component && ((values: StoryArgs) => ) - // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. - const render = () => entry.states[index()]?.render ?? entry.render ?? fallback - let timer: ReturnType | undefined - - // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. - const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) - - // One batch, so a state with its own render function never renders with the previous state's args. - const dispatch = (event: LabStageEvent) => - batch(() => { - const next = transitionLabStage(untrack(stageState), event) - setStageState(next.state) - next.effects.forEach(perform) - }) - - const perform = (effect: LabStageEffect) => { - if (effect.type === "timer.schedule") { - clearTimeout(timer) - timer = setTimeout( - () => dispatch({ type: "tick", attempt: effect.attempt }), - (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, - ) - - return - } - - if (effect.type === "timer.clear") return clearTimeout(timer) - - if (effect.type === "state.apply") { - setArgs(reconcile(stateArgs(entry, effect.index))) - - if (effect.preset === "now") preset(effect.index) - - // Undo or a reset moved the state: bring the other knobs to the state's args too. - if (effect.preset === "later") - queueMicrotask(() => { - if (untrack(stageState).status !== "disposed") preset(effect.index) - }) - - return - } - - // Coalesced: a story registers its replay buttons one by one. - if (effect.type === "motion.queue") return queueMicrotask(() => dispatch({ type: "motion.flushed" })) - const next = storyMotion(entry.motion) - - if (!sameMotion(next, motion)) return setShown(next) - store.sync(motionValues(motion)) - } - - const [first, ...rest] = names - - const states: { [key: string]: Field } = - first === undefined || rest.length === 0 - ? {} - : { - state: choice(first, [first, ...rest], { variants: true }), - play: toolbar( - [ - { - id: "previous", - label: language.t("lab.previous"), - icon: "M200 48 80 128l120 80ZM48 48h16v160H48Z", - run: () => dispatch({ type: "step", delta: -1 }), - }, - { id: "play", label: language.t("lab.play"), icon: "play", run: () => dispatch({ type: "play" }) }, - { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => dispatch({ type: "pause" }) }, - { - id: "next", - label: language.t("lab.next"), - icon: "M56 48l120 80-120 80ZM192 48h16v160h-16Z", - run: () => dispatch({ type: "step", delta: 1 }), - }, - ], - { labels: false }, - ), - } - - // The story's Knobs join its args here, so the inspector is the one place for its controls. Registering a knob or a - // replay button (as the story mounts) rebuilds it where it was. - let motion = storyMotion(entry.motion) - const [shown, setShown] = createSignal(motion, { equals: sameMotion }) - - const inspect = () => { - const scopes = motionScopes(motion) - - return defineControls( - "components-lab", - { ...states, ...fields, ...motionFields(motion) }, - { - storage: null, - persist: "none", - // Beta is a production build, where knobs resolves its production entry: the panel mounts only when shipped. - ship: () => import("knobs/panel"), - defaultLabel: { ...(first !== undefined && { "": first }), ...scopes.defaultLabels }, - presets: Object.fromEntries( - entry.states.slice(1).map((state, offset) => [state.name, knobArgs(fields, stateArgs(entry, offset + 1))]), - ), - // A state leaves the Knobs where they are: they're the story's tuning, not part of a state. - inPresets: scopes.inPresets, - scopedPresets: scopes.scopedPresets, - onChange: (patch, values, meta) => { - applyMotionPatch(motion, patch) - - if (!("state" in patch)) { - if (meta.source !== "preset") dispatch({ type: "pause" }) - - return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) - } - - dispatch({ type: "panel.state", name: String(values.state), fromPreset: meta.source === "preset" }) - }, - }, - ) - } - - let store!: ReturnType - - createEffect(() => { - motion = shown() - store = untrack(inspect) - store.sync(motionValues(motion)) - onCleanup( - store.mount(props.inspector, { - theme: props.scheme, - header: { title: false, buttons: ["undo", "redo", "reset"] }, - variants: false, - session: false, - empty: language.t("lab.noControls"), - hints: { digits: "always" }, - }), - ) - - // A rebuild stays on the state it was showing, and its fresh knobs show that state's args. - if (rest.length > 0) - untrack(() => { - setArgs(reconcile(stateArgs(entry, index()))) - preset(index()) - }) - }) - - onCleanup(motionTuning.subscribe(() => dispatch({ type: "motion.changed" }))) - onCleanup(() => dispatch({ type: "disposed" })) - - makeEventListener(window, "keydown", (event) => { - const digit = Number(event.key) - - if (names.length < 2 || !Number.isInteger(digit) || digit < 1 || digit > Math.min(9, names.length)) return - - if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) return - event.preventDefault() - dispatch({ type: "select", index: digit - 1 }) - }) - - return ( - // Contained layout makes the canvas hold its stories' dialogs, which the provider below portals into it. - // A press inside the story (its own replay buttons, a dock) stops Play rather than being undone by it. -
dispatch({ type: "pause" })} - > - - - - {(fn) => ( - - { - // A failing state does not stick: the next state or edit tries again. - createEffect(on(() => ({ ...args }), reset, { defer: true })) - - return ( -
-                        {String(error)}
-                      
- ) - }} - > - {untrack(() => fn(args))} -
-
- )} -
-
-
-
+ loadLabCatalog(modules, sources)} + workspace={Workspace} + plugin={Plugin} + /> ) } @@ -539,7 +54,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" * The provider stack of a draft session in the first project of the first healthy server, so a story that reads the * server, models, location or composer state renders as it does in the app. Without a server, stories render bare. */ -function Workspace(props: { children: JSX.Element }) { +function Workspace(props: ParentProps) { const servers = useServers() const global = useGlobal() @@ -561,7 +76,7 @@ function Workspace(props: { children: JSX.Element }) { ) } -function Project(props: { children: JSX.Element }) { +function Project(props: ParentProps) { const server = useServer() // The list puts the most recently active project first, and on a busy server that changes every few seconds. The @@ -592,164 +107,8 @@ function Project(props: { children: JSX.Element }) { } // A story of a plugin renders as its contributions do: inside that plugin's context from the app's host. -function Plugin(props: { file: string; children: JSX.Element }) { +function Plugin(props: ParentProps<{ file: string }>) { const id = props.file.match(/gui-plugins\/src\/([^/]+)\//)?.[1] return id ? {() => props.children} : props.children } - -/** The tree under `path`: a folder for each further title segment and a row for each story, by name. */ -function folder(entries: LabEntry[], path: string[]): Row[] { - const depth = path.length - const inside = entries.filter((entry) => path.every((segment, index) => entry.title.split("/")[index] === segment)) - const names = [...new Set(inside.flatMap((entry) => entry.title.split("/").slice(depth, -1).slice(0, 1)))] - - return [ - ...names.map((name) => ({ - id: `folder:${[...path, name].join("/")}`, - label: name, - children: folder(inside, [...path, name]), - })), - ...inside.flatMap((entry) => - entry.title.split("/").length === depth + 1 - ? [ - { - id: entry.file, - label: entry.title.split("/").at(-1) ?? entry.title, - // Files may share a title; the file name tells them apart. - detail: - inside.filter((other) => other.title === entry.title).length > 1 ? fileName(entry.file) : undefined, - }, - ] - : [], - ), - ].toSorted((a, b) => a.label.localeCompare(b.label)) -} - -// knobs' split takes each pane's content as a node; Solid keeps it reactive where it sits. -/** The library's stories on a canvas that pans and zooms, each in its first state; clicking one opens it on its own. */ -function Grid(props: { entries: LabEntry[]; scheme: "dark" | "light"; onOpen: (file: string) => void }) { - const language = useLanguage() - const owner = getOwner() - let element!: HTMLDivElement - - onMount(() => { - const board = canvas(element, { - theme: props.scheme, - label: language.t("lab.grid"), - // Neighbours share the library's folder: actions, forms, overlays, then app dialogs. - items: props.entries - .toSorted((a, b) => folderOf(a).localeCompare(folderOf(b))) - .map((entry) => { - const size = tileSize(entry) - - return { - id: entry.file, - title: entry.title.split("/").at(-1), - w: size.w, - h: size.h, - render: (card: HTMLElement) => - createRoot((dispose) => { - insert(card, () => ) - - return dispose - }, owner ?? undefined), - } - }), - }) - - // The canvas captures the pointer to pan, so a card never sees its click: a press that ends where it began opens - // the story it began on. - let press: { file: string; x: number; y: number } | undefined - - const down = (event: PointerEvent) => { - const file = event.target instanceof Element ? event.target.closest("[data-lab-story]") : null - - press = file?.dataset.labStory ? { file: file.dataset.labStory, x: event.clientX, y: event.clientY } : undefined - } - - const up = (event: PointerEvent) => { - if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) props.onOpen(press.file) - press = undefined - } - - element.addEventListener("pointerdown", down, true) - window.addEventListener("pointerup", up, true) - onCleanup(() => { - element.removeEventListener("pointerdown", down, true) - window.removeEventListener("pointerup", up, true) - board.dispose() - }) - }) - - return
-} - -// A story's first state at its natural size, holding its own dialogs as the stage does. -function Tile(props: { entry: LabEntry }) { - const [canvas, setCanvas] = createSignal() - const component = props.entry.component - const render = props.entry.states[0]?.render ?? props.entry.render - - return ( -
- {/* The provider waits for the card, so a story that opens a dialog at once opens it inside. */} - - {(container) => ( -
- - -
{String(error)}
} - > - {render - ? untrack(() => render(stateArgs(props.entry, 0))) - : component && } -
-
-
-
- )} -
-
- ) -} - -function isDialogEntry(entry: LabEntry) { - return entry.title.startsWith("App/Dialogs/") || entry.file.endsWith("/overlays/dialog/dialog.stories.tsx") -} - -function tileSize(entry: LabEntry) { - if (entry.fullscreen) return { w: 1120, h: 720 } - - if (isDialogEntry(entry)) return { w: 720, h: 820 } - - return { w: 320, h: 240 } -} - -function folderOf(entry: LabEntry) { - if (isDialogEntry(entry)) return `1:dialogs:${entry.title}` - - return `0:${entry.file.match(/ui\/src\/([^/]+)\//)?.[1] ?? ""}` -} - -function typing(target: EventTarget | null) { - return target instanceof HTMLElement && (target.isContentEditable || !!target.closest("input, textarea, select")) -} - -function pane(content: () => JSX.Element) { - const element = document.createElement("div") - - element.className = "size-full" - insert(element, content) - - return element -} diff --git a/packages/app/src/composer/composer-touch.stories.tsx b/packages/app/src/composer/composer-touch.stories.tsx index f2491b38cd16..61dad183d34d 100644 --- a/packages/app/src/composer/composer-touch.stories.tsx +++ b/packages/app/src/composer/composer-touch.stories.tsx @@ -1,4 +1,4 @@ -import { For, Show, createMemo, onCleanup, onMount } from "solid-js" +import { For, Show, createEffect, createMemo, on, onCleanup, onMount } from "solid-js" import { createStore } from "solid-js/store" import type { ModelSelection } from "@/providers/models/selection" import { STORY_MODEL } from "@opencode/session-ui/storybook" @@ -22,6 +22,7 @@ const states = [ { id: "shell", name: "Shell command" }, { id: "sending", name: "Sending" }, { id: "suggestions", name: "Slash suggestions open" }, + { id: "context", name: "Context suggestions open" }, ] as const type State = (typeof states)[number]["id"] @@ -37,6 +38,7 @@ const drafts: Record = { shell: "bun test composer", sending: "Ship it", suggestions: "", + context: "", } const selectedModel = { @@ -75,6 +77,7 @@ const context: ComposerSuggestion[] = [ { id: "file:src/composer/editor/editor.tsx", kind: "file", + recent: true, label: "src/composer/editor/editor.tsx", path: "src/composer/editor/editor.tsx", mention: { @@ -191,7 +194,11 @@ function TouchComposer(props: { state: State }) { const model = { ...editor, model: { selection, paid: true, loading: false } } satisfies ComposerModel - onMount(() => props.state === "suggestions" && editor.openCommands()) + onMount(() => { + if (props.state === "suggestions") editor.openCommands() + + if (props.state === "context") editor.openContext() + }) return ( <> @@ -227,6 +234,13 @@ function TouchComposer(props: { state: State }) { function TouchStates(props: { state: State }) { const [view, setView] = createStore({ state: props.state, generation: 0 }) + createEffect( + on( + () => props.state, + (state) => setView("state", state), + { defer: true }, + ), + ) const touch = matchMedia("(hover: none) and (pointer: coarse)") const [device, setDevice] = createStore({ touch: touch.matches }) const sync = () => setDevice("touch", touch.matches) diff --git a/packages/app/src/composer/composer.stories.tsx b/packages/app/src/composer/composer.stories.tsx index 5ebd3ec95951..fc13a2d72c1b 100644 --- a/packages/app/src/composer/composer.stories.tsx +++ b/packages/app/src/composer/composer.stories.tsx @@ -5,7 +5,7 @@ import { STORY_MODEL, emptySessionDocument, pendingAndQueuedDocument } from "@op import { Composer } from "./composer" import type { ComposerModel } from "./model" import { createComposerEditor } from "./editor/interaction" -import type { ComposerPersistedState, ComposerSuggestion } from "./types" +import type { ComposerHistory, ComposerPersistedState, ComposerSuggestion } from "./types" import { buildPromptRequest } from "./request" import { promptLength } from "./prompt-parts" import { SessionPreview } from "@/session/story-model" @@ -52,16 +52,17 @@ function ComposerStory(props: { comments?: ComposerPersistedState["context"]["items"] working?: boolean stopping?: boolean + sending?: boolean suggestions?: "command" | "context" | "none" failure?: boolean label?: string inspectRequest?: boolean continueOnStop?: boolean longLabels?: boolean - alternate?: "queue" | "steer" + alternate?: "none" | "queue" | "steer" manySuggestions?: boolean history?: boolean - manyHistory?: boolean + many?: boolean /** File search waits for the story's "Return files" button, like a slow server. */ fileSearch?: boolean suggestionBoundary?: () => HTMLElement | undefined @@ -163,51 +164,53 @@ function ComposerStory(props: { signal?.addEventListener("abort", () => setFileSearch("pending", undefined), { once: true }) }) }, - history: props.history - ? { - entries: (mode) => - mode === "shell" - ? [{ prompt: text("bun typecheck") }] - : [ - { prompt: text("Explain the latest changes") }, - { - prompt: [ - ...text("Review the composer layout\nKeep keyboard navigation accessible"), - { - type: "path", - id: "history-layout", - filename: "layout.png", - mime: "image/png", - path: "C:/shots/layout.png", - }, - ], - metadata: "review", - }, - { prompt: text("Run the focused tests") }, - ...(props.manyHistory - ? Array.from({ length: 16 }, (_, index) => ({ prompt: text(`Earlier prompt ${index + 1}`) })) - : []), - ], - add() {}, - capture: () => (draft.context.items.some((item) => item.key === "history-comment") ? "review" : undefined), - restore: (metadata) => - setDraft( - "context", - "items", - metadata === "review" - ? [ + get history(): ComposerHistory | undefined { + if (!props.history && !props.many) return undefined + + return { + entries: (mode) => + mode === "shell" + ? [{ prompt: text("bun typecheck") }] + : [ + { prompt: text("Explain the latest changes") }, + { + prompt: [ + ...text("Review the composer layout\nKeep keyboard navigation accessible"), { - type: "file", - key: "history-comment", - path: "src/composer.tsx", - selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, - comment: "Keep the search separate from the draft", + type: "path", + id: "history-layout", + filename: "layout.png", + mime: "image/png", + path: "C:/shots/layout.png", }, - ] - : [], - ), - } - : undefined, + ], + metadata: "review", + }, + { prompt: text("Run the focused tests") }, + ...(props.many + ? Array.from({ length: 16 }, (_, index) => ({ prompt: text(`Earlier prompt ${index + 1}`) })) + : []), + ], + add() {}, + capture: () => (draft.context.items.some((item) => item.key === "history-comment") ? "review" : undefined), + restore: (metadata) => + setDraft( + "context", + "items", + metadata === "review" + ? [ + { + type: "file", + key: "history-comment", + path: "src/composer.tsx", + selection: { startLine: 12, startChar: 0, endLine: 14, endChar: 0 }, + comment: "Keep the search separate from the draft", + }, + ] + : [], + ), + } + }, readImage: async () => pixel, view: { placeholder: () => "Ask anything, / for commands, @ for context...", @@ -231,20 +234,25 @@ function ComposerStory(props: { submit: { stopping: () => !!props.stopping, working: () => !!props.working, - queue: props.alternate - ? { - count: () => 0, - delivery: () => (props.alternate === "queue" ? "steer" : "queue"), - alternate: () => props.alternate, - editing: () => undefined, - confirmEdit() {}, - undoing: () => false, - cancelEdit() {}, - editFirst: () => false, - first() {}, - steerFirst() {}, - } - : undefined, + busy: () => !!props.sending, + get queue() { + const alternate = props.alternate + + if (!alternate || alternate === "none") return undefined + + return { + count: () => 0, + delivery: () => (alternate === "queue" ? "steer" : "queue"), + alternate: () => alternate, + editing: () => undefined, + confirmEdit() {}, + undoing: () => false, + cancelEdit() {}, + editFirst: () => false, + first() {}, + steerFirst() {}, + } + }, onSubmit: () => { const value = draft.prompt.map((part) => ("content" in part ? part.content : `[${part.filename}]`)).join("") @@ -324,7 +332,7 @@ function ComposerStory(props: { return (
{story.activity} @@ -370,8 +378,11 @@ type FlowArgs = { working: boolean stopping: boolean failure: boolean + sending: boolean label: string suggestions: "command" | "context" | "none" + alternate: "none" | "queue" | "steer" + many: boolean } export default { @@ -379,8 +390,20 @@ export default { component: Composer, parameters: { layout: "centered" }, // States that only change the composer's props share this render, so moving between them keeps one composer. - args: { working: false, stopping: false, failure: false, label: "Ready", suggestions: "none" }, - argTypes: { suggestions: { control: "select", options: ["none", "command", "context"] } }, + args: { + working: false, + stopping: false, + failure: false, + sending: false, + label: "Ready", + suggestions: "none", + alternate: "none", + many: false, + }, + argTypes: { + suggestions: { control: "select", options: ["none", "command", "context"] }, + alternate: { control: "select", options: ["none", "queue", "steer"] }, + }, render: (args: FlowArgs) => , } @@ -388,9 +411,9 @@ export const EmptyDraft = {} export const PromptHistory = { args: { many: false }, - render: (args: { many: boolean }) => ( + render: (args: FlowArgs) => (
- +
), } @@ -400,8 +423,9 @@ export const TextDraft = { args: { prompt: text("Explain this change") } } export const MultilineDraft = { args: { prompt: text("Review the implementation\nThen run the focused tests") } } export const MixedAttachments = { - render: () => ( + render: (args: FlowArgs) => ( ( + render: (args: FlowArgs) => ( } +export const SlowFileSearch = { render: (args: FlowArgs) => } -function ConstrainedCommandSuggestionsStory() { +function ConstrainedCommandSuggestionsStory(props: FlowArgs) { let boundary: HTMLDivElement | undefined return (
- boundary} /> + boundary} />
) } -export const ConstrainedCommandSuggestions = { render: () => } +export const ConstrainedCommandSuggestions = { + args: { suggestions: "command" }, + render: (args: FlowArgs) => , +} export const DetachedCommandSuggestionBoundary = { - render: () => { + args: { suggestions: "command" }, + render: (args: FlowArgs) => { const detached = document.createElement("div") - return detached} /> + return detached} /> }, } @@ -507,6 +536,8 @@ export const SteeringFollowUp = { args: { prompt: text("Use this correction at t export const FailedSubmissionRestoration = { args: { prompt: text("Preserve this draft on failure"), failure: true } } +export const Sending = { args: { prompt: text("Run the focused tests"), sending: true } } + export const NewSessionFirstPrompt = { args: { prompt: text("Create the Session and implement the change"), label: "New Session draft" }, } @@ -522,48 +553,45 @@ export const RightToLeft = { export const NarrowLayout = { parameters: { viewport: { defaultViewport: "mobile1" } }, - render: () => ( + args: { prompt: text("Verify the narrow Composer") }, + render: (args: FlowArgs) => (
- +
), } export const ToolbarOverflow = { - args: { alternate: "queue" }, - argTypes: { alternate: { control: "select", options: ["none", "queue", "steer"] } }, - render: (args: { alternate: "none" | "queue" | "steer" }) => ( + args: { alternate: "queue", working: true, prompt: text("Keep all controls reachable when the toolbar overflows") }, + render: (args: FlowArgs) => (
- +
), } export const DemoFirstClassSkillIDs = { name: "Demo: First-class skill IDs", - render: () => ( + args: { suggestions: "context", label: "Select a skill from the context menu" }, + render: (args: FlowArgs) => ( - + ), } export const DemoStructuredCustomCommand = { name: "Demo: Structured custom command", - render: () => ( + render: (args: FlowArgs) => ( , + args: { label: "Composer is ready", prompt: text("Continue with the resolved Session selection") }, + render: (args: FlowArgs) => , } export const DemoContinueOnStop = { name: "Demo: Continue on Stop", - render: () => ( + args: { working: true, stopping: true, label: "Session execution is running" }, + render: (args: FlowArgs) => ( - + ), } @@ -695,7 +725,7 @@ function ServerStatusDemo() { ) } -function SelectionPrecedenceDemo() { +function SelectionPrecedenceDemo(props: FlowArgs) { const [store, setStore] = createStore({ durable: true }) const selection = createMemo(() => @@ -728,7 +758,7 @@ function SelectionPrecedenceDemo() { > {store.durable ? "Remove durable Session state" : "Restore durable Session state"} - +
) diff --git a/packages/app/src/home/home.standalone.stories.tsx b/packages/app/src/home/home.standalone.stories.tsx new file mode 100644 index 000000000000..a39b8ab969dd --- /dev/null +++ b/packages/app/src/home/home.standalone.stories.tsx @@ -0,0 +1,260 @@ +import type { SessionInfo } from "@opencode/client/promise" +import { createEffect, createMemo, on, onCleanup, Show } from "solid-js" +import { createStore } from "solid-js/store" +import { DialogStoryRuntime, STORY_PROJECTS, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { normalizeProjectInfo } from "@/runtime/server/global-sync/utils" +import { useServer } from "@/runtime/server/current" +import { useLanguage } from "@/runtime/i18n/language" +import { SettingsSurfaceProvider } from "@/settings/surface" +import type { HomeController } from "./model" +import { createHomeProjectsController } from "./projects/controller" +import { HomeView } from "./route" +import { groupSessions, type HomeSessionsController } from "./sessions/controller" +import type { HomeSessionsListView } from "./sessions/load-machine" +import { buildHomeSessionRecords, homeSessionLocation } from "./sessions/records" +import { createHomeSessionSearchController } from "./sessions/search" + +const scenarios = ["populated", "loading", "empty", "offline"] as const + +type HomeArgs = { scenario: (typeof scenarios)[number]; project: string; search: string } + +const projects = STORY_PROJECTS.map(normalizeProjectInfo) + +function recentSessions(): SessionInfo[] { + const titles = [ + [0, 0, "Review the session location picker"], + [1, 0, "Document the worktree setup steps"], + [2, 0, "Update the release notes page"], + [0, 1, "Keep search focused when switching projects"], + [1, 1, "Review the provider setup guide"], + [2, 4, "Polish mobile navigation"], + ] as const + + return titles.map(([index, daysAgo, title], i) => { + const project = projects[index] + + const day = new Date() + day.setDate(day.getDate() - daysAgo) + day.setHours(10, 30 - i, 0, 0) + + return { + id: `ses_home_${i}`, + projectID: project.id, + title, + location: { directory: project.worktree }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: +day, updated: +day }, + } + }) +} + +function HomeStory(props: HomeArgs) { + const server = useServer() + + const language = useLanguage() + + const [state, setState] = createStore<{ + directory?: string + scenario: HomeArgs["scenario"] + activity: string + visible: typeof projects + sessions: SessionInfo[] + }>({ + scenario: props.scenario, + activity: "", + visible: projects, + sessions: recentSessions(), + }) + + const visible = () => state.visible + + const directory = () => state.directory + + const setDirectory = (value?: string) => setState("directory", value) + + const setActivity = (value: string) => setState("activity", value) + + const selected = createMemo(() => visible().find((project) => project.worktree === directory())) + + createEffect( + on( + () => props.scenario, + (next) => { + setState({ scenario: next, visible: projects, sessions: recentSessions(), activity: "" }) + }, + ), + ) + createEffect( + on( + () => props.project, + (name) => setDirectory(projects.find((item) => item.name === name)?.worktree), + ), + ) + + const home: HomeController = { + selection: { + value: () => ({ server: server.key, directory: directory() }), + focusServer: () => setDirectory(undefined), + }, + server: { + list: () => [STORY_SERVER], + focused: () => STORY_SERVER, + health: () => (state.scenario === "offline" ? { type: "unreachable" } : { type: "healthy" }), + label: () => "This computer", + context: () => server.ctx, + focusedContext: () => server.ctx, + focusedSync: () => server.ctx.sync, + }, + project: { + list: visible, + forServer: visible, + selected, + newSession: () => selected() ?? visible()[0], + select: (_, next) => setDirectory(directory() === next ? undefined : next), + add: (_, directories) => { + const added = projects.filter((item) => directories.includes(item.worktree)) + setState("visible", (items) => [ + ...items, + ...added.filter((project) => !items.some((item) => item.id === project.id)), + ]) + setDirectory(added[0]?.worktree) + }, + openNewSession: () => setActivity(`New session in ${selected()?.name ?? visible()[0]?.name}`), + openProjectNewSession: (_, path) => setActivity(`New session in ${path}`), + openProjectSession: (_, _path, session) => setActivity(`Opened ${session.title}`), + }, + } + + const navigation = createHomeProjectsController(home) + + const records = createMemo(() => + buildHomeSessionRecords({ + sessions: () => (state.scenario === "populated" ? state.sessions : []), + projectDirectories: () => { + const project = selected() + + return project && [project.worktree, ...project.sandboxes] + }, + projects: visible, + }), + ) + + const listView = (): HomeSessionsListView => { + if (state.scenario === "offline") return { status: "unavailable", reason: "offline" } + + if (state.scenario === "loading") return { status: "loading", skeleton: true } + + return { status: "ready", revealing: false } + } + + const recent: HomeSessionsController = { + copy: { language }, + platform: { desktop: true }, + tab: { isOpen: () => false }, + location: { value: (record) => homeSessionLocation(record.session.location.directory, "main"), sync() {} }, + data: { + listView, + records, + groups: createMemo(() => groupSessions(records(), language)), + searchRecords: records, + loading: () => state.scenario === "loading", + retry: () => setState("scenario", "populated"), + }, + session: { + server: () => server.key, + canCreate: () => visible().length > 0 && state.scenario !== "offline", + showProjectName: () => !selected(), + lookup: async (id) => records().find((record) => record.session.id === id), + create: home.project.openNewSession, + open: (session) => setActivity(`Opened ${session.title}`), + archive: async () => {}, + rename: async (_, session, title) => { + setState("sessions", (item) => item.id === session.id, "title", title) + + return true + }, + export: (_, session) => setActivity(`Export ${session.title}`), + exporting: () => false, + showDelete: async (_, session) => setActivity(`Delete ${session.title}`), + }, + } + + const search = createHomeSessionSearchController(home, recent) + + createEffect( + on( + () => props.search, + (value) => { + search.query.close() + + if (!value || value === "none") return + + // The inspector selects a preset on pointerdown. Let Home finish handling that outside press before opening search. + const frame = requestAnimationFrame(() => { + search.query.input(value) + search.query.focus() + }) + + onCleanup(() => cancelAnimationFrame(frame)) + }, + ), + ) + + return ( +
+ setActivity("Opened settings"), help: () => setActivity("Opened help") }, + project: { + ...navigation.project, + openNewSession: home.project.openProjectNewSession, + edit: (_, project) => setActivity(`Edit ${project.name}`), + hide: (_, project) => { + setState("visible", (items) => items.filter((item) => item.worktree !== project.worktree)) + + if (directory() === project.worktree) setDirectory(undefined) + }, + }, + }} + sessions={recent} + search={search} + /> + + {state.activity} + +
+ ) +} + +export default { + title: "App/Home", + id: "app-home", + parameters: { layout: "fullscreen" }, + args: { scenario: "populated", project: "all", search: "none" }, + argTypes: { + scenario: { control: "select", options: scenarios }, + project: { control: "select", options: ["all", ...projects.map((project) => project.name)] }, + search: { control: "select", options: ["none", "review", "worktree", "billing"] }, + }, + render: (args: HomeArgs) => ( + + + + + + ), +} + +export const Populated = {} + +export const ProjectFilter = { args: { project: "docs" } } + +export const SessionSearch = { args: { search: "review" } } + +export const Loading = { args: { scenario: "loading" } } + +export const Empty = { args: { scenario: "empty" } } + +export const Offline = { args: { scenario: "offline" } } diff --git a/packages/app/src/home/route.tsx b/packages/app/src/home/route.tsx index 6626e90f8f77..de440b56f5e8 100644 --- a/packages/app/src/home/route.tsx +++ b/packages/app/src/home/route.tsx @@ -1,6 +1,7 @@ import { ScrollView } from "@opencode/ui/scroll-view" import { createMediaQuery } from "@solid-primitives/media" -import { Show } from "solid-js" +import { onMount, Show } from "solid-js" +import { useLayout } from "@/shell/state/layout" import { createHomeController } from "./model" import { createHomeProjectsController } from "./projects/controller" import { HomeUtilityNav } from "./projects/view" @@ -11,12 +12,27 @@ import { createHomeSessionsController } from "./sessions/controller" import { HomeSessions } from "./sessions/region" export function Home() { - const mobile = createMediaQuery("(max-width: 767px)") + const layout = useLayout() const home = createHomeController() const projects = createHomeProjectsController(home) const sessions = createHomeSessionsController(home) const search = createHomeSessionSearchController(home, sessions) - const scroll = createHomeScrollController(sessions.data.groups) + + onMount(() => { + if (layout.home.searchFocus.take()) search.query.focus() + }) + + return +} + +export function HomeView(props: { + projects: ReturnType + sessions: ReturnType + search: ReturnType +}) { + const mobile = createMediaQuery("(max-width: 767px)") + + const scroll = createHomeScrollController(props.sessions.data.groups) return (
- +
- + - +
diff --git a/packages/app/src/home/sessions/controller.tsx b/packages/app/src/home/sessions/controller.tsx index fffbb8039416..58dfeb214c53 100644 --- a/packages/app/src/home/sessions/controller.tsx +++ b/packages/app/src/home/sessions/controller.tsx @@ -658,7 +658,10 @@ function localDay(date: Date) { return date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate() } -function groupSessions(records: HomeSessionRecord[], language: ReturnType): HomeSessionGroup[] { +export function groupSessions( + records: HomeSessionRecord[], + language: ReturnType, +): HomeSessionGroup[] { const now = new Date() const today = localDay(now) const yesterday = localDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)) diff --git a/packages/app/src/home/sessions/delete-dialog.stories.tsx b/packages/app/src/home/sessions/delete-dialog.stories.tsx index ae2718e85fb9..fd05ff5f2fd7 100644 --- a/packages/app/src/home/sessions/delete-dialog.stories.tsx +++ b/packages/app/src/home/sessions/delete-dialog.stories.tsx @@ -6,7 +6,9 @@ import { createStore } from "solid-js/store" import { useLanguage } from "@/runtime/i18n/language" import { sessionTitle } from "@/session/title" -function DeleteSessionStory(props: { sessionTitle?: string }) { +type Args = { sessionTitle: string; deleting: boolean } + +function DeleteSessionStory(props: Args) { const dialog = useDialog() const language = useLanguage() @@ -20,16 +22,17 @@ function DeleteSessionStory(props: { sessionTitle?: string }) { -
) @@ -177,3 +177,19 @@ export const Favorites = { ), } + +export const ProviderOnly = { + render: () => ( + + + + ), +} + +export const NoModels = { + render: () => ( + + + + ), +} diff --git a/packages/app/src/providers/models/unpaid.standalone.stories.tsx b/packages/app/src/providers/models/unpaid.standalone.stories.tsx index e37304c26db0..f0d9444739c8 100644 --- a/packages/app/src/providers/models/unpaid.standalone.stories.tsx +++ b/packages/app/src/providers/models/unpaid.standalone.stories.tsx @@ -1,9 +1,10 @@ -// @ts-nocheck import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" -import { createSignal, onMount } from "solid-js" -import { DialogSelectModelUnpaid } from "./unpaid" +import { createMemo, createSignal, onMount } from "solid-js" import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { isFreeModel } from "./models" +import { useLocal, type ModelSelection } from "@/providers/models/selection" +import { DialogSelectModelUnpaid } from "./unpaid" const names = [ "MiMo V2.5 Free", @@ -14,30 +15,38 @@ const names = [ "Big Pickle", ] -function SelectModelWithoutProviders(props) { +function SelectModelWithoutProviders(props: { count: number }) { const dialog = useDialog() - const models = names.map((name, index) => ({ - id: name.toLowerCase().replaceAll(" ", "-"), - name, - provider: { id: "opencode", name: "OpenCode" }, - cost: { input: 0, output: 0 }, - limit: { context: 128_000 }, - capabilities: { - reasoning: index !== 5, - input: { text: true, image: false, audio: false, video: false, pdf: false }, - }, - })) + const local = useLocal() + + const models = createMemo(() => { + const free = local.model.list().find(isFreeModel) + + if (!free) return [] + + return names.slice(0, props.count).map((name, index) => ({ + ...free, + id: name.toLowerCase().replaceAll(" ", "-"), + name, + provider: { ...free.provider, name: "OpenCode" }, + limit: { ...free.limit, context: 128_000 }, + capabilities: { + ...free.capabilities, + reasoning: index !== 5, + input: { text: true, image: false, audio: false, video: false, pdf: false }, + }, + })) + }) - const [current, setCurrent] = createSignal(models[2]) + const [selected, setSelected] = createSignal("deepseek-v4-flash-free") const model = { - list: () => models.slice(0, props.count), - current, - set(value) { - setCurrent(models.find((item) => item.id === value?.modelID)) - }, - } + ...local.model, + list: models, + current: () => models().find((item) => item.id === selected()), + set: (key) => setSelected(key?.modelID), + } satisfies ModelSelection const open = () => dialog.show(() => ) @@ -54,13 +63,14 @@ export default { title: "App/Dialogs/Select Model", id: "app-dialog-select-model", args: { count: names.length }, - argTypes: { count: { control: { type: "range", min: 1, max: names.length, step: 1 } } }, -} - -export const WithoutProviders = { - render: (args) => ( + argTypes: { count: { control: { type: "range", min: 0, max: names.length, step: 1 } } }, + render: (args: { count: number }) => ( ), } + +export const WithoutProviders = {} + +export const NoFreeModels = { args: { count: 0 } } diff --git a/packages/app/src/runtime/plugin/dialogs.stories.tsx b/packages/app/src/runtime/plugin/dialogs.stories.tsx index 0017cdc8751c..2f757a46a69a 100644 --- a/packages/app/src/runtime/plugin/dialogs.stories.tsx +++ b/packages/app/src/runtime/plugin/dialogs.stories.tsx @@ -4,28 +4,33 @@ import { onMount } from "solid-js" import { createStore } from "solid-js/store" import { PluginSelectDialog } from "./dialogs" -function PluginSelectStory() { +type Args = { optionCount: number; grouped: boolean; descriptions: boolean } + +function PluginSelectStory(props: Args) { const dialog = useDialog() + const [store, setStore] = createStore({ selected: "Nothing selected" }) + const destinations = [ + { title: "Design notes", description: "Research and references", group: "Recent", value: "design" }, + { title: "Project roadmap", description: "Upcoming milestones", group: "Recent", value: "roadmap" }, + { title: "Engineering", description: "Implementation and architecture", group: "Teams", value: "engineering" }, + { title: "Product", description: "Planning and feedback", group: "Teams", value: "product" }, + { title: "Support", description: "Customer questions", group: "Teams", value: "support" }, + ] + const open = () => dialog.show(() => ( ({ + ...item, + group: props.grouped ? item.group : undefined, + description: props.descriptions ? item.description : undefined, + })), }} done={(value) => { setStore("selected", value ?? "Selection dismissed") @@ -49,8 +54,13 @@ function PluginSelectStory() { export default { title: "App/Dialogs/Plugin Selection", id: "app-dialog-plugin-selection", + args: { optionCount: 5, grouped: true, descriptions: true } satisfies Args, + argTypes: { optionCount: { control: { type: "range", min: 0, max: 5, step: 1 } } }, + render: (args: Args) => , } -export const Default = { - render: () => , -} +export const Default = {} + +export const TitlesOnly = { args: { grouped: false, descriptions: false } } + +export const NoDestinations = { args: { optionCount: 0 } } diff --git a/packages/app/src/runtime/plugin/titlebar-items.stories.tsx b/packages/app/src/runtime/plugin/titlebar-items.stories.tsx index 83e3400d4bed..90ec690d5949 100644 --- a/packages/app/src/runtime/plugin/titlebar-items.stories.tsx +++ b/packages/app/src/runtime/plugin/titlebar-items.stories.tsx @@ -1,58 +1,97 @@ -import { For } from "solid-js" +import { createEffect, createSignal, For, Show } from "solid-js" import type { TitlebarItem } from "@opencode/plugin/gui" import { TitlebarItems } from "./titlebar-items" -const catalogs = import.meta.glob<{ default: Record }>( - "../../../../gui-plugins/src/updater/i18n/*.ts", - { eager: true }, -) +type Labels = { "status.label": string; "action.installRestart": string; "action.installing": string } + +const catalogs = import.meta.glob<{ default: Labels }>("../../../../gui-plugins/src/updater/i18n/*.ts", { eager: true }) const rtl = new Set(["ar", "dv", "fa", "he", "ur"]) const locales = Object.entries(catalogs) .map(([file, module]) => ({ locale: file.split("/").pop()!.replace(".ts", ""), - label: module.default["status.label"]!, + labels: module.default, })) .sort((a, b) => a.locale.localeCompare(b.locale)) -const items = (label: string) => { - const item: TitlebarItem = { id: "update", label, run: () => {} } +const actions = ["label only", "install", "installing", "toggle off", "toggle on"] as const - return { ids: () => [item.id], item: () => item } -} +type Args = { locale: string; layout: string; action: (typeof actions)[number]; label: string } export default { title: "App/Titlebar/Items", id: "app-titlebar-items", component: TitlebarItems, -} - -/** The update pill in every updater locale; hover or focus a pill to expand its label. */ -export const UpdateLabels = { - render: () => ( + args: { locale: "all", layout: "both", action: "label only", label: "" }, + argTypes: { + locale: { options: ["all", ...locales.map((entry) => entry.locale)] }, + layout: { options: ["both", "horizontal", "vertical"] }, + action: { options: actions }, + }, + render: (args: Args) => (
- - {(entry) => ( -
- {entry.locale} -
-
- -
-
-
- + args.locale === "all" || args.locale === entry.locale)}> + {(entry) => { + const [action, setAction] = createSignal(args.action) + createEffect(() => setAction(args.action)) + + const toggle = () => action() === "toggle on" || action() === "toggle off" + + const item = (): TitlebarItem => ({ + id: "update", + label: args.label || entry.labels["status.label"], + get title() { + if (action() === "installing") return entry.labels["action.installing"] + + if (action() === "install") return entry.labels["action.installRestart"] + }, + busy: action() === "installing", + icon: toggle() ? "terminal" : undefined, + pressed: toggle() ? action() === "toggle on" : undefined, + run: () => { + if (action() === "install") return setAction("installing") + + if (toggle()) setAction(action() === "toggle on" ? "toggle off" : "toggle on") + }, + }) + + const items = { ids: () => ["update"], item } + + return ( +
+ {entry.locale} + +
+
+ +
+
+
+ +
+ +
+
-
- )} + ) + }}
), } + +/** The update pill in every updater locale; hover or focus a pill to expand its label. */ +export const UpdateLabels = {} + +export const ReadyToInstall = { args: { locale: "en", action: "install", layout: "horizontal" } } + +export const Installing = { args: { locale: "en", action: "installing" } } + +export const Pressed = { args: { locale: "en", layout: "vertical", action: "toggle on", label: "Terminal" } } diff --git a/packages/app/src/servers/registry/row.stories.tsx b/packages/app/src/servers/registry/row.stories.tsx index ae5e419ac1df..f69f31c8f855 100644 --- a/packages/app/src/servers/registry/row.stories.tsx +++ b/packages/app/src/servers/registry/row.stories.tsx @@ -15,12 +15,14 @@ const states: { label: string; health?: ServerHealth }[] = [ { label: "Not checked" }, ] -export default { title: "App/Servers/Health indicator", id: "app-server-health" } - -export const States = { - render: () => ( +export default { + title: "App/Servers/Health indicator", + id: "app-server-health", + args: { health: "All" }, + argTypes: { health: { options: ["All", ...states.map((state) => state.label)] } }, + render: (args: { health: string }) => (
- + args.health === "All" || args.health === state.label)}> {(state) => (
@@ -33,3 +35,17 @@ export const States = {
), } + +export const States = {} + +export const Authentication = { args: { health: "Waiting for sign-in" } } + +export const Connecting = { args: { health: "Connecting" } } + +export const Connected = { args: { health: "Connected" } } + +export const Unreachable = { args: { health: "Failed" } } + +export const Incompatible = { args: { health: "Incompatible" } } + +export const Unknown = { args: { health: "Not checked" } } diff --git a/packages/app/src/session/commands/fork-dialog.stories.tsx b/packages/app/src/session/commands/fork-dialog.stories.tsx index ebea73c255d4..ef467f69f91b 100644 --- a/packages/app/src/session/commands/fork-dialog.stories.tsx +++ b/packages/app/src/session/commands/fork-dialog.stories.tsx @@ -4,8 +4,11 @@ import { onMount } from "solid-js" import { createStore } from "solid-js/store" import { ForkDialog } from "./fork-dialog" -function ForkDialogStory() { +type Args = { messageCount: number; forking: boolean } + +function ForkDialogStory(props: Args) { const dialog = useDialog() + const [store, setStore] = createStore({ selected: "No message selected" }) const messages = [ @@ -28,7 +31,9 @@ function ForkDialogStory() { const open = () => dialog.show(() => ( 0} + pendingMessageID={props.forking && props.messageCount > 0 ? messages[0].id : undefined} onSelect={(messageID) => { setStore("selected", messageID) dialog.close() @@ -51,8 +56,13 @@ function ForkDialogStory() { export default { title: "App/Dialogs/Fork Session", id: "app-dialog-fork-session", + args: { messageCount: 8, forking: false } satisfies Args, + argTypes: { messageCount: { control: { type: "range", min: 0, max: 8, step: 1 } } }, + render: (args: Args) => , } -export const Default = { - render: () => , -} +export const Default = {} + +export const NoMessages = { args: { messageCount: 0 } } + +export const Forking = { args: { forking: true } } diff --git a/packages/app/src/session/commands/jump-to-message.stories.tsx b/packages/app/src/session/commands/jump-to-message.stories.tsx index ea0fb8b8fbb9..7dd4c60c1195 100644 --- a/packages/app/src/session/commands/jump-to-message.stories.tsx +++ b/packages/app/src/session/commands/jump-to-message.stories.tsx @@ -1,10 +1,18 @@ import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" import { Keybind } from "@opencode/ui/keybind" -import { For, onMount, Show } from "solid-js" +import { createEffect, createSignal, For, on, onMount, Show } from "solid-js" import { useLanguage } from "@/runtime/i18n/language" import { formatKeybindParts, matchKeybind, parseKeybind } from "@/shell/commands/command" import { JumpToMessage } from "./jump-to-message" +import { + selectJumpHistory, + selectJumpOpening, + selectJumpStatus, + transitionJumpToMessage, + type JumpToMessageEvent, + type JumpToMessageState, +} from "./jump-to-message-machine" const shortcut = "mod+alt+g" @@ -48,12 +56,28 @@ const turns = [ reply, })) -function SessionStory(props: { query?: string; empty?: boolean; failed?: boolean }) { +const scenes = ["browse", "closed", "empty", "loading", "failed", "paged", "opening", "openFailed"] as const + +type Args = { scene: (typeof scenes)[number]; query: string } + +const recent = turns.slice(4) + +const older = turns.slice(0, 4) + +function snapshot(scene: Args["scene"], history: typeof turns): JumpToMessageState { + if (scene === "loading" || scene === "failed") return { status: scene, attempt: 1 } + + if (scene === "opening") return { status: "opening", history, target: older[0]!.id, attempt: 2 } + + return { status: "ready", history, failed: scene === "openFailed", attempt: 1 } +} + +function SessionStory(props: Args) { const language = useLanguage() const dialog = useDialog() - const prompts = () => (props.empty ? [] : turns) + const [prompts, setPrompts] = createSignal(turns) const bubbles = new Map() @@ -61,30 +85,78 @@ function SessionStory(props: { query?: string; empty?: boolean; failed?: boolean let transcript!: HTMLDivElement - const open = (query = "") => - dialog.show(() => ( - dialog.close() : undefined} - onClose={() => dialog.close()} - onJump={(prompt) => { - dialog.close() - const bubble = bubbles.get(prompt.id) - bubble?.focus({ preventScroll: true }) - bubble?.scrollIntoView({ block: "center", inline: "nearest" }) - }} - /> - )) + const open = () => + dialog.show(() => { + const history = prompts() === recent ? older : [] + + const [state, setState] = createSignal(snapshot(props.scene, history)) + + const status = () => { + const note = selectJumpStatus(state()) + + return note && language.t(`dialog.jump.${note}`) + } + + const dispatch = (event: JumpToMessageEvent) => { + const next = transitionJumpToMessage(state(), event) + setState(next.state) + + for (const effect of next.effects) { + if (effect.type === "history.load") dispatch({ type: "history.loaded", attempt: effect.attempt, history }) + + if (effect.type === "open.load") { + setPrompts(turns) + dispatch({ type: "opened", attempt: effect.attempt }) + } + + if (effect.type === "jump") { + dialog.close() + const bubble = bubbles.get(effect.id) + bubble?.focus({ preventScroll: true }) + bubble?.scrollIntoView({ block: "center", inline: "nearest" }) + } + } + } + + const [query, setQuery] = createSignal(props.query) + createEffect(() => setQuery(props.query)) + + return ( + dispatch({ type: "retry" }) : undefined} + onClose={() => dialog.close()} + onJump={(row) => + dispatch({ type: "selected", id: row.id, loaded: prompts().some((turn) => turn.id === row.id) }) + } + /> + ) + }) onMount(() => { transcript.scrollTop = transcript.scrollHeight session.focus({ preventScroll: true }) - - void open(props.query) }) + createEffect( + on([() => props.scene, () => props.query], ([scene], previous) => { + if (previous?.[0] === scene) { + if (!dialog.active && scene !== "closed") void open() + + return + } + + setPrompts(scene === "empty" ? [] : scene === "browse" || scene === "closed" ? turns : recent) + + if (scene === "closed") return dialog.close() + void open() + }), + ) + return (
, + args: { scene: "browse", query: "" }, + argTypes: { scene: { options: scenes } }, parameters: { layout: "fullscreen" }, } -export const Browse = { render: () => } +export const Browse = {} + +export const MultilineMatch = { args: { query: "loading dock" } } -export const MultilineMatch = { render: () => } +export const Empty = { args: { scene: "empty" } } -export const Empty = { render: () => } +export const HistoryFailed = { args: { scene: "failed" } } -export const HistoryFailed = { render: () => } +export const NoMatches = { args: { query: "missing bookmark" } } -export const NoMatches = { render: () => } +export const MixedDirection = { args: { query: "ليلى" } } diff --git a/packages/app/src/session/commands/jump-to-message.tsx b/packages/app/src/session/commands/jump-to-message.tsx index 0eb8ff7d6397..f63a28f4bc7a 100644 --- a/packages/app/src/session/commands/jump-to-message.tsx +++ b/packages/app/src/session/commands/jump-to-message.tsx @@ -16,6 +16,8 @@ export type JumpPrompt = { id: string; text: string; created: number } export function JumpToMessage(props: { prompts: JumpPrompt[] initialQuery?: string + query?: string + onQuery?: (value: string) => void status?: string opening?: boolean onJump: (prompt: JumpPrompt) => void @@ -24,7 +26,14 @@ export function JumpToMessage(props: { }) { const language = useLanguage() - const [query, setQuery] = createSignal(props.initialQuery ?? "") + const [localQuery, setLocalQuery] = createSignal(props.initialQuery ?? "") + + const query = () => props.query ?? localQuery() + + const setQuery = (value: string) => { + if (props.query === undefined) setLocalQuery(value) + props.onQuery?.(value) + } const timestamp = createMemo( () => diff --git a/packages/app/src/session/composer/activity-chips.stories.tsx b/packages/app/src/session/composer/activity-chips.stories.tsx index c65b17ab7dc3..24196d58074a 100644 --- a/packages/app/src/session/composer/activity-chips.stories.tsx +++ b/packages/app/src/session/composer/activity-chips.stories.tsx @@ -9,8 +9,7 @@ import { subagentReport, } from "@opencode/session-ui/storybook" import { timelinePresets } from "@opencode/session-ui/timeline/detail" -import { createEffect, createMemo, on, onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js" import { SessionPreview } from "@/session/story-model" import type { SessionActivityItem } from "./activity-chips" @@ -188,16 +187,26 @@ function liveDocument(stage: Stage): SessionDocument { } // Scripted with `activity-story-stage` events on `document` so a recording can step through the work. -function LiveActivity() { - const [story, setStory] = createStore({ stage: 0 }) - const stage = createMemo(() => stages[story.stage]) - const value = createMemo(() => liveDocument(stage())) +function LiveActivity(props: PreviewArgs) { + const [recorded, setRecorded] = createSignal() + const value = createMemo(() => liveDocument(recorded() ?? stages[props.stage] ?? stages[0])) + + createEffect( + on( + () => [props.stage, props.subagents, props.shells], + () => setRecorded(undefined), + { defer: true }, + ), + ) onMount(() => { const step = (event: Event) => { if (!(event instanceof CustomEvent)) return - setStory("stage", Number(event.detail)) + const stage = stages[Number(event.detail)] + + if (!stage) return + setRecorded(stage) pin("smooth") } @@ -213,12 +222,12 @@ function LiveActivity() { document={value()} timelineDetail={timelineDetail} activity={{ - subagents: subagents - .slice(stage().finished, stage().started) - .map((_, index) => subagentItem(index + stage().finished)), - shells: shells - .slice(stage().finishedShells, stage().shells) - .map((_, index) => shellItem(index + stage().finishedShells)), + subagents: Array.from({ length: recorded()?.started ?? props.subagents }, (_, index) => + subagentItem(index), + ).slice(recorded()?.finished ?? 0), + shells: Array.from({ length: recorded()?.shells ?? props.shells }, (_, index) => shellItem(index)).slice( + recorded()?.finishedShells ?? 0, + ), onOpen: (item) => { // The preview has no child route, so show the launch in its timeline. const part = document.querySelector( @@ -268,4 +277,4 @@ export const SubagentsAndShells = { args: { stage: 4, subagents: 2, shells: 2 } export const ManySubagents = { args: { stage: 4, subagents: 12, shells: 2 } } -export const Live = { render: () => } +export const Live = { render: (args: PreviewArgs) => } diff --git a/packages/app/src/session/composer/composer-docks.stories.tsx b/packages/app/src/session/composer/composer-docks.stories.tsx index 08956b435966..f11579ceb764 100644 --- a/packages/app/src/session/composer/composer-docks.stories.tsx +++ b/packages/app/src/session/composer/composer-docks.stories.tsx @@ -21,7 +21,9 @@ import { SubagentBar } from "./subagent-bar" type DockArgs = { question: boolean permission: boolean + responding: boolean websearch: boolean + providers: "ready" | "loading" | "loadFailed" | "empty" queue: number subagent: boolean } @@ -64,16 +66,25 @@ function ComposerDocksPreview(props: DockArgs) { const dequeue = (id: string) => setState("rows", (rows) => rows.filter((index) => `queued_${index}` !== id)) + // Keep a dismissed request closed when an unrelated inspector field changes. + for (const key of ["question", "permission", "websearch", "subagent"] as const) { + createEffect( + on( + () => props[key], + (value) => setState(key, value), + { defer: true }, + ), + ) + } + createEffect( on( - () => [props.question, props.permission, props.websearch, props.queue, props.subagent] as const, - ([question, permission, websearch, queue, subagent]) => { - setState({ question, permission, websearch, subagent }) - queueTo(queue) - }, + () => props.providers, + (value) => setState("providers", value), { defer: true }, ), ) + createEffect(on(() => props.queue, queueTo, { defer: true })) const replay = (id: string, label: string, run: () => void) => onCleanup(motionTuning.action({ id: `docks.${id}`, label, group: "Composer", subsection: "Docks", run })) @@ -115,25 +126,28 @@ function ComposerDocksPreview(props: DockArgs) { state.question ? { ...activeQuestionRequest, id: `${activeQuestionRequest.id}:${state.revision}` } : undefined, websearch: { request: () => (state.websearch ? websearchRequest : undefined), - options: () => [ - { value: "exa", label: "Exa" }, - { value: "parallel", label: "Parallel" }, - ], + options: () => + state.providers !== "ready" + ? [] + : [ + { value: "exa", label: "Exa" }, + { value: "parallel", label: "Parallel" }, + ], selected: () => state.searchProvider, specific: () => false, - loading: () => false, - loadFailed: () => false, + loading: () => state.providers === "loading", + loadFailed: () => state.providers === "loadFailed", failed: () => false, optionUnavailable: () => false, sending: () => false, connected: () => true, select: (value) => setState("searchProvider", value), - retry() {}, + retry: () => setState("providers", "ready"), submit: async () => void setState("websearch", false), } satisfies WebSearchRequestModel, elicitationRequest: () => undefined, - permissionRequest: () => (state.permission ? activePermissionRequest : undefined), - permissionResponding: () => false, + permissionRequest: () => (state.permission ? activePermissionRequest : undefined), + permissionResponding: () => props.responding, decide: () => { deciding = true setState("permission", false) @@ -217,8 +231,17 @@ export default { }, argTypes: { queue: { control: { type: "range", min: 0, max: 4, step: 1 } }, + providers: { options: ["ready", "loading", "loadFailed", "empty"] }, }, - args: { question: false, permission: false, websearch: false, queue: 0, subagent: false } satisfies DockArgs, + args: { + question: false, + permission: false, + responding: false, + websearch: false, + providers: "ready", + queue: 0, + subagent: false, + } satisfies DockArgs, render: (args: DockArgs) => , } @@ -234,6 +257,10 @@ export const QuestionAndPermission = { args: { question: true, permission: true export const WebSearch = { args: { websearch: true } } +export const WebSearchRetry = { args: { websearch: true, providers: "loadFailed" } } + +export const PermissionResponding = { args: { permission: true, responding: true } } + export const Subagent = { args: { subagent: true } } // Opens a question, then answers it and dismisses the next one: the closes a reviewer should watch. diff --git a/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx b/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx new file mode 100644 index 000000000000..7bb60338e721 --- /dev/null +++ b/packages/app/src/session/composer/free-limit-panel.standalone.stories.tsx @@ -0,0 +1,45 @@ +import { Show } from "solid-js" +import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { SessionFreeLimitPanel } from "./free-limit-panel" +import { RecoverySession, RestoredComposer } from "./recovery-story" + +type Args = { reset: "today" | "tomorrow" | "unknown"; paid: boolean } + +function LimitStory(props: Args) { + const resetAt = () => { + if (props.reset === "unknown") return null + const at = new Date() + + if (props.reset === "tomorrow") at.setDate(at.getDate() + 1) + + return at.setHours(23, 59, 59, 999) + } + + return ( + + undefined} />}> + + + + ) +} + +export default { + title: "OpenCode/Session/Free limit", + id: "session-free-limit", + args: { reset: "today", paid: false } satisfies Args, + argTypes: { reset: { options: ["today", "tomorrow", "unknown"] } }, + render: (args: Args) => ( + + + + ), +} + +export const LimitReached = {} + +export const NextDayReset = { args: { reset: "tomorrow" } } + +export const UnknownReset = { args: { reset: "unknown" } } + +export const PaidProviderConnected = { args: { paid: true } } diff --git a/packages/app/src/session/composer/location-missing.standalone.stories.tsx b/packages/app/src/session/composer/location-missing.standalone.stories.tsx new file mode 100644 index 000000000000..6613c575c361 --- /dev/null +++ b/packages/app/src/session/composer/location-missing.standalone.stories.tsx @@ -0,0 +1,142 @@ +import type { SessionInfo, SessionMoveInput, WorktreeDirectory } from "@opencode/client/promise" +import { Button } from "@opencode/ui/button" +import { createSignal, onMount, Show } from "solid-js" +import { + createMemoryStorage, + createStoryFetch, + DialogStoryRuntime, + STORY_DIRECTORY, + STORY_PROJECTS, +} from "@/components-lab/dialog-story-runtime" +import type { Platform } from "@/runtime/platform/platform" +import { useData } from "@/runtime/server/current" +import { ToastRegion } from "@/shell/notifications/toast" +import { SessionLocationMissing } from "./location-missing" +import { RecoverySession, RestoredComposer } from "./recovery-story" + +const worktrees: WorktreeDirectory[] = ["timeline", "review", "settings"].map((name) => ({ + directory: `${STORY_DIRECTORY}-${name}`, + strategy: "git", +})) + +type Args = { directory: string; git: boolean; worktrees: "available" | "none"; failFirstMove: boolean } + +function RecoveryStory(props: Args) { + const session: SessionInfo = { + id: "ses_missing", + projectID: STORY_PROJECTS[0].id, + location: { directory: props.directory }, + title: "Timeline fixtures", + time: { created: 1, updated: 2 }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } + + const fallback = createStoryFetch() + + let failed = false + + const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + + const path = new URL(request.url).pathname + + if (path === "/api/project") + return Response.json(STORY_PROJECTS.map((p) => ({ ...p, vcs: props.git ? "git" : undefined }))) + + if (path === "/api/worktree" && request.method === "POST") + return Response.json({ directory: `${STORY_DIRECTORY}-new` }) + + if (path === "/api/worktree") return Response.json(props.worktrees === "available" ? worktrees : []) + + if (path === `/api/session/${session.id}/move`) { + if (props.failFirstMove && !failed) { + failed = true + + return new Response("The checkout is busy", { status: 503 }) + } + + const body: Pick = await request.json() + session.location.directory = body.directory + + return new Response(null, { status: 204 }) + } + + if (path === `/api/session/${session.id}`) return Response.json({ data: session }) + + return fallback(input, init) + } + + const platform: Platform = { + platform: "web", + openExternal() {}, + notify: async () => {}, + restart: async () => {}, + storage: createMemoryStorage(), + fetch: Object.assign(fetcher, { preconnect: fallback.preconnect }), + } + + return ( + + + + ) +} + +function RecoveryDock(props: { session: SessionInfo; directory: string }) { + const data = useData() + + onMount(() => void data.project.sync()) + + const destination = () => data.session.get(props.session.id)?.location.directory + + return ( + + + } + > + Session moved to {destination()} + + + + + ) +} + +function Replay(props: Args) { + const [revision, setRevision] = createSignal(0) + + return ( +
+ + {(args) => } + + +
+ ) +} + +export default { + title: "OpenCode/Session/Missing location", + id: "session-missing-location", + args: { directory: `${STORY_DIRECTORY}-old`, git: true, worktrees: "available", failFirstMove: false } satisfies Args, + argTypes: { worktrees: { options: ["available", "none"] } }, + render: (args: Args) => , +} + +export const MissingWorktree = {} + +export const DirectoryOnly = { args: { git: false } } + +export const NoWorktrees = { args: { worktrees: "none" } } + +export const RetryMove = { args: { failFirstMove: true } } diff --git a/packages/app/src/session/composer/queue-panel.stories.tsx b/packages/app/src/session/composer/queue-panel.stories.tsx index 8a55dd733caa..f862d5e873ea 100644 --- a/packages/app/src/session/composer/queue-panel.stories.tsx +++ b/packages/app/src/session/composer/queue-panel.stories.tsx @@ -1,3 +1,5 @@ +import { createEffect, on } from "solid-js" +import { createStore } from "solid-js/store" import { SessionQueuePanel } from "./queue-panel" import type { SessionQueueView } from "./queue" @@ -10,27 +12,58 @@ const prompts = [ "Remove the unused Alpha helper", ] -const view = (count: () => number): SessionQueueView => ({ - rows: () => prompts.slice(0, count()).map((text, index) => ({ id: `queued_${index}`, text, attachments: 0 })), - editing: () => undefined, - working: () => true, - busy: () => false, - steer: async () => undefined, - remove: async () => undefined, - undo: () => undefined, - edit: () => false, - reorder: async () => undefined, -}) +const plainRows = prompts.map((text, index) => ({ id: `queued_${index}`, text, attachments: 0 })) + +const contextRows = [ + { id: "quote", text: "Update the queue context", attachments: 1 }, + { id: "notes", text: "Compare the reference notes", attachments: 2 }, + { id: "file", text: "Keep the queue compact", attachments: 1 }, + { id: "context-only", text: "", attachments: 2 }, + ...plainRows.slice(4), +] + +type QueueArgs = { count: number; context: boolean; working: boolean; pending: boolean } + +function QueuePreview(props: QueueArgs) { + const rows = () => (props.context ? contextRows : plainRows).slice(0, props.count) + const [state, setState] = createStore<{ rows: typeof plainRows; editing?: string }>({ rows: rows() }) + const remove = (id: string) => setState("rows", (rows) => rows.filter((row) => row.id !== id)) + + createEffect(on(rows, (rows) => setState({ rows, editing: undefined }), { defer: true })) + + const queue: SessionQueueView = { + rows: () => state.rows.map((row, index) => ({ ...row, pending: props.pending && index === 0 })), + editing: () => state.editing, + working: () => props.working, + busy: () => props.pending, + steer: async (id) => remove(id), + remove: async (id) => remove(id), + undo: remove, + edit: (id) => { + if (props.pending) return false + setState("editing", id) + + return true + }, + reorder: async (ids) => + void setState( + "rows", + ids.flatMap((id) => state.rows.filter((row) => row.id === id)), + ), + } + + return ( +
+ +
+ ) +} export default { title: "OpenCode/Session/Queue panel", id: "session-queue-panel", - render: (args: { count: number }) => ( -
- args.count)} /> -
- ), - args: { count: 3 }, + render: (args: QueueArgs) => , + args: { count: 3, context: false, working: true, pending: false }, argTypes: { count: { control: { type: "range", min: 0, max: prompts.length, step: 1 } } }, parameters: { layout: "centered", @@ -46,20 +79,8 @@ export const Short = { args: { count: 3 } } export const Scrolling = { args: { count: 6 } } -export const WithContext = { - render: () => ( -
- 0), - rows: () => [ - { id: "quote", text: "Update the queue context", attachments: 1 }, - { id: "notes", text: "Compare the reference notes", attachments: 2 }, - { id: "file", text: "Keep the queue compact", attachments: 1 }, - { id: "context-only", text: "", attachments: 2 }, - ], - }} - /> -
- ), -} +export const WithContext = { args: { count: 4, context: true } } + +export const Parked = { args: { working: false } } + +export const PendingAdmission = { args: { pending: true } } diff --git a/packages/app/src/session/composer/recovery-story.tsx b/packages/app/src/session/composer/recovery-story.tsx new file mode 100644 index 000000000000..eb435beae5db --- /dev/null +++ b/packages/app/src/session/composer/recovery-story.tsx @@ -0,0 +1,38 @@ +import { CurrentSessionProviders, pendingAndQueuedDocument } from "@opencode/session-ui/storybook" +import { SessionTimeline } from "@opencode/session-ui/timeline" +import { createSignal, type ParentProps } from "solid-js" +import { Composer } from "@/composer/composer" +import { createPromptController } from "@/session/story-model" + +export function RecoverySession(props: ParentProps) { + return ( +
+
+ + + +
+ {props.children} +
+ ) +} + +export function RestoredComposer() { + const [activity, setActivity] = createSignal("") + + const prompt = createPromptController({ + initial: "Continue with the timeline fixtures.", + placeholder: "Ask anything", + status: () => ({ type: "idle" }), + onActivity: setActivity, + onSubmit: (text) => setActivity(`Sent locally: ${text}`), + onStop() {}, + }) + + return ( +
+ + {activity()} +
+ ) +} diff --git a/packages/app/src/session/composer/todo-pill.stories.tsx b/packages/app/src/session/composer/todo-pill.stories.tsx index 88b3067bd1fb..22c28ba3466b 100644 --- a/packages/app/src/session/composer/todo-pill.stories.tsx +++ b/packages/app/src/session/composer/todo-pill.stories.tsx @@ -5,7 +5,7 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { createMemo, onMount } from "solid-js" import { SessionPreview } from "@/session/story-model" import type { SessionActivityItem } from "./activity-chips" -import { sessionTodos, type Todo } from "./todos" +import { sessionTodos, todoFinished, type Todo } from "./todos" const timelineDetail = timelinePresets[2].value @@ -19,7 +19,7 @@ const plan = [ "Run the app typecheck", ] -type Scenario = "plan" | "cancelled" | "parallel" +type Scenario = "plan" | "cancelled" | "parallel" | "pending" // `progress` todos are done, the next one is in progress and the rest are pending. `cancelled` drops the last todo, // and `parallel` runs the two after `progress` at once. @@ -29,7 +29,7 @@ const todosAt = (progress: number, scenario: Scenario): Todo[] => status: index < progress ? "completed" - : index === progress || (scenario === "parallel" && index === progress + 1) + : (scenario !== "pending" && index === progress) || (scenario === "parallel" && index === progress + 1) ? "in_progress" : scenario === "cancelled" && index === plan.length - 1 ? "cancelled" @@ -100,6 +100,7 @@ type PreviewArgs = { progress: number; scenario: Scenario; open: boolean; activi function Preview(props: PreviewArgs) { const value = createMemo(() => document(todosAt(props.progress, props.scenario))) + const todos = createMemo(() => sessionTodos(value().messages)) onMount(() => setTimeout(() => { @@ -115,7 +116,7 @@ function Preview(props: PreviewArgs) { document={value()} timelineDetail={timelineDetail} activity={props.activity ? activity : undefined} - todos={{ items: sessionTodos(value().messages), open: props.open }} + todos={todos().every(todoFinished) ? undefined : { items: todos(), open: props.open }} /> ) } @@ -127,7 +128,7 @@ export default { args: { progress: 3, scenario: "plan", open: false, activity: true }, argTypes: { progress: { control: { type: "range", min: 0, max: 7, step: 1 } }, - scenario: { control: { type: "select" }, options: ["plan", "cancelled", "parallel"] }, + scenario: { control: { type: "select" }, options: ["plan", "cancelled", "parallel", "pending"] }, open: { control: { type: "boolean" } }, activity: { control: { type: "boolean" } }, }, @@ -151,3 +152,7 @@ export const WithoutActivity = { args: { activity: false } } export const Cancelled = { args: { scenario: "cancelled", open: true } } export const SeveralInProgress = { args: { scenario: "parallel", open: true } } + +export const PendingPlan = { args: { scenario: "pending", progress: 0 } } + +export const FinishedPlan = { args: { progress: plan.length } } diff --git a/packages/app/src/session/header/session-header-actions.stories.tsx b/packages/app/src/session/header/session-header-actions.stories.tsx index a436090425cb..413d6a6eaf5e 100644 --- a/packages/app/src/session/header/session-header-actions.stories.tsx +++ b/packages/app/src/session/header/session-header-actions.stories.tsx @@ -1,24 +1,33 @@ -import { createSignal } from "solid-js" -import { SessionHeaderActions } from "./session-header-actions" +import { createEffect, createSignal } from "solid-js" +import { useLanguage } from "@/runtime/i18n/language" +import { formatKeybindParts } from "@/shell/commands/command" +import { reviewGlyphFill, SessionHeaderActions } from "./session-header-actions" + +type Args = { opened: boolean; visible: boolean; label: string; keybind: string; panelGlyph: boolean } export default { title: "App/Session/Header actions", id: "app-session-header-actions", component: SessionHeaderActions, -} + args: { opened: false, visible: true, label: "Toggle review", keybind: "", panelGlyph: false }, + render: (args: Args) => { + const language = useLanguage() -export const ReviewToggle = { - render: () => { - const [opened, setOpened] = createSignal(false) + const [opened, setOpened] = createSignal(args.opened) + createEffect(() => setOpened(args.opened)) + + const glyph = (fill: SVGPathElement) => + createEffect(() => fill.setAttribute("transform", reviewGlyphFill(Number(opened())))) return (
setOpened(!opened()), }} /> @@ -26,3 +35,11 @@ export const ReviewToggle = { ) }, } + +export const ReviewToggle = {} + +export const Opened = { args: { opened: true } } + +export const PanelGlyph = { args: { panelGlyph: true, keybind: "mod+shift+r" } } + +export const Hidden = { args: { visible: false } } diff --git a/packages/app/src/session/question-switch.stories.tsx b/packages/app/src/session/question-switch.stories.tsx index aaaead6a8068..e4b27550b93e 100644 --- a/packages/app/src/session/question-switch.stories.tsx +++ b/packages/app/src/session/question-switch.stories.tsx @@ -353,3 +353,28 @@ export const LongPrompt = { /> ), } + +export const FreeResponse = { + render: () => ( + + ), +} diff --git a/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx new file mode 100644 index 000000000000..fa2210efa293 --- /dev/null +++ b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx @@ -0,0 +1,88 @@ +import { Button } from "@opencode/ui/button" +import { createSignal, Show } from "solid-js" +import { DialogStoryRuntime, STORY_LOCKED_SERVER, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { ServerProvider } from "@/runtime/server/current" +import type { ServerConnection } from "@/runtime/server/registry" +import { ServerSignedOutPanel, ServerUnavailablePanel } from "./server-unavailable-panel" + +const reasons = ["unreachable", "incompatible", "signedOutHttp", "signedOutPlugin", "signedOutManaged"] as const + +type Args = { reason: (typeof reasons)[number]; closable: boolean } + +function PanelStory(props: Args) { + const [outcome, setOutcome] = createSignal("") + + const plugin: ServerConnection.Plugin = { + type: "plugin", + key: "story:studio", + plugin: "story", + displayName: "Build workstation", + managed: true, + status: { type: props.reason === "incompatible" ? "incompatible" : "stopped" }, + authenticate: () => false, + connect: + props.reason === "signedOutManaged" + ? undefined + : async () => { + setOutcome("Signed in to the build workstation") + + return true + }, + } + + const reason = () => (props.reason === "incompatible" ? "incompatible" : "unreachable") + + return ( + +
+ + {outcome()} + +
+ } + > + } + > + + setOutcome("Session tab closed") : undefined} + /> + + + +
+ + ) +} + +export default { + title: "OpenCode/Session/Server unavailable", + id: "session-server-unavailable", + args: { reason: "unreachable", closable: true } satisfies Args, + argTypes: { reason: { options: reasons } }, + render: (args: Args) => ( + + {(reason) => } + + ), +} + +export const Unreachable = {} + +export const Incompatible = { args: { reason: "incompatible" } } + +export const Draft = { args: { closable: false } } + +export const SignedOut = { args: { reason: "signedOutHttp" } } + +export const PluginSignIn = { args: { reason: "signedOutPlugin" } } + +export const NoSignInAction = { args: { reason: "signedOutManaged" } } diff --git a/packages/app/src/session/session-screen.stories.tsx b/packages/app/src/session/session-screen.stories.tsx index 4386d68f68b4..c0b632546b5e 100644 --- a/packages/app/src/session/session-screen.stories.tsx +++ b/packages/app/src/session/session-screen.stories.tsx @@ -15,6 +15,7 @@ import { terminalPassedDocument, } from "@opencode/session-ui/storybook" import { SessionPreview } from "./story-model" +import type { SubagentStatus } from "./composer/subagent-bar" const description = "opencode · modular-session-ui" @@ -307,21 +308,33 @@ export const ChildSessionNoOutcome = { ), } -export const ChildSessionDone = { - render: () => ( +function finishedChild(title: string, status: Exclude) { + return ( - ), + ) +} + +export const ChildSessionDone = { + render: () => finishedChild("Inspect a finished child Session", "succeeded"), +} + +export const ChildSessionFailed = { + render: () => finishedChild("Inspect a failed child Session", "failed"), +} + +export const ChildSessionInterrupted = { + render: () => finishedChild("Inspect an interrupted child Session", "interrupted"), } export const MobileLayout = { diff --git a/packages/app/src/session/timeline/background-work.stories.tsx b/packages/app/src/session/timeline/background-work.stories.tsx index 8bbed9ce36cd..183cd9c8cc40 100644 --- a/packages/app/src/session/timeline/background-work.stories.tsx +++ b/packages/app/src/session/timeline/background-work.stories.tsx @@ -3,6 +3,7 @@ import { BackgroundMoveHint } from "./message-timeline" export default { title: "OpenCode/Session/Background work", id: "session-background-work", + args: { keybind: "Ctrl+B" }, parameters: { docs: { description: { @@ -13,9 +14,14 @@ export default { } export const InlineMoveHint = { - render: () => ( + render: (args: { keybind: string }) => (
- + key.trim()) + .filter(Boolean)} + />
), } diff --git a/packages/app/src/session/timeline/search-bar.stories.tsx b/packages/app/src/session/timeline/search-bar.stories.tsx new file mode 100644 index 000000000000..9ae8a2a2b6f1 --- /dev/null +++ b/packages/app/src/session/timeline/search-bar.stories.tsx @@ -0,0 +1,122 @@ +import type { SessionMessageInfo } from "@opencode/client/promise" +import type { SessionDocument } from "@opencode/session-ui/document" +import { CurrentSessionProviders, emptySessionDocument, STORY_MODEL, STORY_TIME } from "@opencode/session-ui/storybook" +import { SessionTimeline } from "@opencode/session-ui/timeline" +import { Button } from "@opencode/ui/button" +import { createEffect, createSignal, on, Show } from "solid-js" +import { TimelineSearchBar } from "./search-bar" +import { createTranscriptSearch } from "./search-controller" + +const turns = [ + [ + "Which trail is open on Saturday?", + "The lake trail opens at nine. The bridge on the north shore is closed for repairs.", + ], + [ + "Is there a way around the bridge?", + "Take the footpath past the boat house. It joins the south shore near the picnic tables.", + ], + [ + "How far is it from the station?", + "About three kilometres. There’s a drinking fountain at the entrance and a bike rack by the gate.", + ], + [ + "Where should we eat?", + "For lunch by the water, follow the trail to the orchard. The last trail marker points to a bench under the apple trees.", + ], +] + +const transcript: SessionDocument = { + ...emptySessionDocument, + messages: turns.flatMap(([question, answer], index): SessionMessageInfo[] => [ + { id: `prompt_${index}`, type: "user", text: question, time: { created: STORY_TIME + index * 60_000 } }, + { + id: `answer_${index}`, + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "text", text: answer }], + time: { created: STORY_TIME + index * 60_000 + 1000, completed: STORY_TIME + index * 60_000 + 2000 }, + }, + ]), +} + +type Args = { query: string; open: boolean; empty: boolean } + +function FindStory(props: Args) { + const document = () => (props.empty ? emptySessionDocument : transcript) + + const [scroll, setScroll] = createSignal() + + // This timeline mounts every row eagerly. The search controller can seek directly to each matching range. + const search = createTranscriptSearch({ + sessionID: () => document().sessionID, + messages: () => document().messages, + scrollRef: scroll, + revealMessage() {}, + pauseAutoScroll() {}, + }) + + createEffect( + on([() => props.open, () => props.query], ([open, query]) => { + if (!open) return search.query.close() + search.query.open() + search.query.setValue(query) + }), + ) + + return ( +
{ + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return + event.preventDefault() + search.query.open() + }} + > +
+

A walk along the south shore

+ + Find in conversation + + } + > + + +
+
+ + No messages in this session.

} + > + +
+
+
+

+ Enter for the next match · Shift+Enter for the previous match · Escape to close +

+
+ ) +} + +export default { + title: "OpenCode/Session/Find in transcript", + id: "session-transcript-find", + args: { query: "trail", open: true, empty: false } satisfies Args, + render: (args: Args) => , +} + +export const Matches = {} + +export const NoMatches = { args: { query: "waterfall" } } + +export const EmptyQuery = { args: { query: "" } } + +export const EmptyTranscript = { args: { empty: true } } + +export const Closed = { args: { open: false } } diff --git a/packages/app/src/session/timeline/search-controller.ts b/packages/app/src/session/timeline/search-controller.ts index ec869a94e2fc..b3b440b736f6 100644 --- a/packages/app/src/session/timeline/search-controller.ts +++ b/packages/app/src/session/timeline/search-controller.ts @@ -1,3 +1,4 @@ +import type { SessionMessageInfo } from "@opencode/client/promise" import { useCommand } from "@/shell/commands/command" import { useLanguage } from "@/runtime/i18n/language" import { useData } from "@/runtime/server/current" @@ -103,15 +104,36 @@ function applyHighlights( CSS.highlights.set(HIGHLIGHT_ACTIVE, new Highlight(...active)) } -export function createTimelineSearchController(input: { +type TimelineSearchInput = { sessionID: () => string | undefined scrollRef: () => HTMLDivElement | undefined revealMessage: (id: string, partID?: string) => void pauseAutoScroll: () => void -}) { +} + +export function createTimelineSearchController(input: TimelineSearchInput) { const command = useCommand() - const language = useLanguage() const data = useData() + + const controller = createTranscriptSearch({ ...input, messages: (id) => data.session.message.list(id) }) + + command.register("session.search", () => [ + { + id: "session.search", + title: controller.query.placeholder(), + keybind: "mod+f", + hidden: true, + onSelect: controller.query.open, + }, + ]) + + return controller +} + +export function createTranscriptSearch( + input: TimelineSearchInput & { messages: (id: string) => readonly SessionMessageInfo[] }, +) { + const language = useLanguage() const [searchState, setSearchState] = createSignal(createTimelineSearchState()) const view = createMemo(() => timelineSearchView(searchState())) const visible = createMemo(() => view().visible) @@ -124,7 +146,7 @@ export function createTimelineSearchController(input: { let seekFrame: number | undefined const searchableParts = (sessionID: string | undefined) => - sessionID ? extractSearchableParts(data.session.message.list(sessionID)) : NO_PARTS + sessionID ? extractSearchableParts(input.messages(sessionID)) : NO_PARTS // Reads the transcript only while a query exists, so a closed or empty Find bar costs nothing while a reply // streams, and typing reuses the lowercased parts. @@ -186,16 +208,6 @@ export function createTimelineSearchController(input: { onCleanup(() => dispatch({ type: "disposed" })) - command.register("session.search", () => [ - { - id: "session.search", - title: language.t("session.search.placeholder"), - keybind: "mod+f", - hidden: true, - onSelect: open, - }, - ]) - function open() { dispatch({ type: "open", sessionID: untrack(input.sessionID) }) } diff --git a/packages/app/src/session/timeline/sources.stories.tsx b/packages/app/src/session/timeline/sources.stories.tsx index 064904ff9792..c354caec7769 100644 --- a/packages/app/src/session/timeline/sources.stories.tsx +++ b/packages/app/src/session/timeline/sources.stories.tsx @@ -10,7 +10,7 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { Icon } from "@opencode/ui/icon" import { IconButton } from "@opencode/ui/icon-button" import { Tabs } from "@opencode/ui/tabs" -import { createEffect, createMemo, on, onMount, Show, type ParentProps } from "solid-js" +import { createEffect, createMemo, on, onCleanup, Show, type ParentProps } from "solid-js" import { createStore } from "solid-js/store" import { useLanguage } from "@/runtime/i18n/language" import { SessionPreview } from "@/session/story-model" @@ -252,7 +252,12 @@ function Sources(props: SourcesArgs) { timelineDetail={timelineDetail} side={ - setState("panel", false)}> + setState("panel", false)} + > {}} /> @@ -264,16 +269,24 @@ function Sources(props: SourcesArgs) { // The side panel's frame around the real panel: the strip with the real tab title, as the side region draws it. // `expand` opens the first search with results once it shows. -function Side(props: ParentProps<{ expand: boolean; count: number; onClose: () => void }>) { +function Side(props: ParentProps<{ turn: Turn; expand: boolean; count: number; onClose: () => void }>) { const language = useLanguage() let el: HTMLDivElement | undefined - onMount(() => { - if (!props.expand) return - requestAnimationFrame(() => - el?.querySelector('[data-slot="sources-step-row"][aria-expanded="false"]')?.click(), - ) - }) + createEffect( + on( + () => [props.turn, props.expand] as const, + ([, expand]) => { + const frame = requestAnimationFrame(() => { + const row = el?.querySelector('[data-slot="sources-step-row"][aria-expanded]') + + if (row && row.getAttribute("aria-expanded") !== String(expand)) row.click() + }) + + onCleanup(() => cancelAnimationFrame(frame)) + }, + ), + ) return ( diff --git a/packages/app/src/settings/shell.standalone.stories.tsx b/packages/app/src/settings/shell.standalone.stories.tsx index dfff34049533..c0ca4d9c26e6 100644 --- a/packages/app/src/settings/shell.standalone.stories.tsx +++ b/packages/app/src/settings/shell.standalone.stories.tsx @@ -1,15 +1,20 @@ import { createMemoryHistory, MemoryRouter, Route } from "@solidjs/router" -import { DialogStoryRuntime } from "@/components-lab/dialog-story-runtime" +import { DialogStoryRuntime, STORY_LOCKED_SERVER, STORY_SERVER } from "@/components-lab/dialog-story-runtime" +import { ServerConnection } from "@/runtime/server/registry" import { SettingsScreen } from "@/settings/shell" import { SettingsSurfaceProvider, type SettingsRootTab } from "@/settings/surface" import { LayoutProvider } from "@/shell/state/layout" -function SettingsStory(props: { tab: SettingsRootTab }) { +function SettingsStory(props: { tab: SettingsRootTab; locked?: boolean }) { const history = createMemoryHistory() - history.set({ value: `/settings?tab=${props.tab}`, replace: true, scroll: false }) + + const query = new URLSearchParams({ tab: props.tab }) + + if (props.locked) query.set("server", ServerConnection.key(STORY_LOCKED_SERVER)) + history.set({ value: `/settings?${query}`, replace: true, scroll: false }) return ( - +
, } + +export const UnavailableServer = { render: () => } diff --git a/packages/app/src/settings/timeline-detail.stories.tsx b/packages/app/src/settings/timeline-detail.stories.tsx index 1f0cc52edf36..1bf4de43ee74 100644 --- a/packages/app/src/settings/timeline-detail.stories.tsx +++ b/packages/app/src/settings/timeline-detail.stories.tsx @@ -9,32 +9,46 @@ import "./settings.css" export default { title: "OpenCode/Settings/Timeline detail", id: "settings-timeline-detail", + args: { preset: "compact" }, + argTypes: { preset: { options: [...timelinePresets.map((preset) => preset.id), "custom"] } }, + render: (args: { preset: string }) => ( + + {(preset) => } + + ), } -export const Interactive = { - render: () => { - const [state, setState] = createStore<{ value: TimelineDetail; visible: boolean }>({ - value: structuredClone(timelinePresets[2].value), - visible: true, - }) +function Preview(props: { preset: string }) { + const [state, setState] = createStore<{ value: TimelineDetail; visible: boolean }>({ + value: structuredClone( + timelinePresets.find((preset) => preset.id === props.preset)?.value ?? { + ...timelinePresets[2].value, + shell: { placement: "separate", details: "collapsed" }, + }, + ), + visible: true, + }) - return ( -
- - -
- setState("value", value)} /> -
-
-
- - - -
- ) - }, + return ( +
+ + +
+ setState("value", value)} /> +
+
+
+ + + +
+ ) } + +export const Interactive = {} + +export const Custom = { args: { preset: "custom" } } diff --git a/packages/app/src/shell/commands/dialog.standalone.stories.tsx b/packages/app/src/shell/commands/dialog.standalone.stories.tsx index 138e54a54754..68b0f6b4f8c9 100644 --- a/packages/app/src/shell/commands/dialog.standalone.stories.tsx +++ b/packages/app/src/shell/commands/dialog.standalone.stories.tsx @@ -13,7 +13,9 @@ import { useTabs } from "@/shell/tabs/tabs" import { CommandPaletteView, matchesCommandPaletteEntry } from "./dialog" import { createCommandPaletteFileEntry, type CommandPaletteEntry } from "./palette" -function CommandPaletteStory(props: { query?: string }) { +type Scenario = { query?: string; fileSearch?: "pending" | "failed" } + +function CommandPaletteStory(props: Scenario) { const dialog = useDialog() const language = useLanguage() @@ -171,27 +173,44 @@ function CommandPaletteStory(props: { query?: string }) { ] } + const findFiles = async (query: string, signal: AbortSignal): Promise => { + if (!query) return [] + + if (props.fileSearch === "failed") throw new Error("File search unavailable") + + if (props.fileSearch === "pending") { + return new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })) + } + + return files().filter((entry) => matchesCommandPaletteEntry(entry, query)) + } + const open = () => { tabs.addSessionTab({ server: serverKey, sessionId: "ses_story_1" }) - void dialog.show(() => ( - (query ? files().filter((entry) => matchesCommandPaletteEntry(entry, query)) : [])]} - highlight={() => {}} - select={() => dialog.close()} - close={() => dialog.close()} - /> - )) - - if (!props.query) return - const initial = props.query - queueMicrotask(() => { - const input = document.querySelector(".command-palette input[role='combobox']") - - if (!input) return - input.value = initial - input.dispatchEvent(new InputEvent("input", { bubbles: true })) + void dialog.show(() => { + let host!: HTMLDivElement + + onMount(() => { + if (!props.query) return + const input = host.querySelector('input[role="combobox"]') + + if (!input) return + input.value = props.query + input.dispatchEvent(new InputEvent("input", { bubbles: true })) + }) + + return ( +
+ {}} + select={() => dialog.close()} + close={() => dialog.close()} + /> +
+ ) }) } @@ -209,18 +228,20 @@ export default { id: "app-dialog-command-palette", } -export const Default = { +const story = (scenario: Scenario = {}) => ({ render: () => ( - + ), -} +}) -export const Searching = { - render: () => ( - - - - ), -} +export const Default = story() + +export const Searching = story({ query: "model" }) + +export const NoResults = story({ query: "changelog.md" }) + +export const SearchingFiles = story({ query: "changelog.md", fileSearch: "pending" }) + +export const FileSearchFailed = story({ query: "changelog.md", fileSearch: "failed" }) diff --git a/packages/app/src/shell/titlebar/inbox-card.stories.tsx b/packages/app/src/shell/titlebar/inbox-card.stories.tsx index 0a20fda4ebf9..f115f2d8e0fc 100644 --- a/packages/app/src/shell/titlebar/inbox-card.stories.tsx +++ b/packages/app/src/shell/titlebar/inbox-card.stories.tsx @@ -1,11 +1,15 @@ import { Button } from "@opencode/ui/button" +import { Menu } from "@opencode/ui/menu" import { createEffect, For, on, Show } from "solid-js" import { createStore } from "solid-js/store" +import { useLanguage } from "@/runtime/i18n/language" import { InboxSessionCard } from "./inbox" import type { InboxStatus } from "./inbox-model" const now = Date.UTC(2026, 10, 3, 12) +const statuses = ["done", "ready", "working", "approval", "input", "failed"] as const satisfies readonly InboxStatus[] + function SessionCardStory(props: { status: InboxStatus selected: boolean @@ -17,9 +21,21 @@ function SessionCardStory(props: { project: string projectKnown: boolean ageMinutes: number + ageSeconds: number + timestampKnown: boolean + readAction: boolean width: number }) { - const [state, setState] = createStore({ selected: props.selected, archived: props.archived, removed: false }) + const language = useLanguage() + + const initial = () => ({ selected: props.selected, archived: props.archived, removed: false, status: props.status }) + + const [state, setState] = createStore(initial()) + + const toggleRead = () => { + if (state.status !== "ready") return setState("status", "ready") + setState("status", props.status === "failed" ? "failed" : "done") + } createEffect( on( @@ -30,8 +46,9 @@ function SessionCardStory(props: { () => props.projectKnown, () => props.selected, () => props.archived, + () => props.readAction, ], - () => setState({ selected: props.selected, archived: props.archived, removed: false }), + () => setState(initial()), ), ) @@ -50,27 +67,34 @@ function SessionCardStory(props: { } directory={props.worktree ? "/workspace/opencode/worktrees/tooltip-status" : "/workspace/opencode"} title={props.title} - status={props.status} + status={state.status} selected={state.selected} archived={state.archived} server={props.remote ? "Build server · build.example.internal" : undefined} branch={props.branch || undefined} worktree={props.worktree} now={now} - since={now - props.ageMinutes * 60_000} + since={props.timestampKnown ? now - props.ageMinutes * 60_000 - props.ageSeconds * 1000 : undefined} onOpen={() => setState("selected", true)} + actions={ + + + {language.t(state.status === "ready" ? "session.markUnread" : "session.markRead")} + + + + } onArchive={() => setState("archived", true)} onUnarchive={() => setState("archived", false)} onDelete={() => setState("removed", true)} />
- @@ -95,12 +119,16 @@ export default { project: "opencode", projectKnown: true, ageMinutes: 41, + ageSeconds: 0, + timestampKnown: true, + readAction: false, width: 280, }, argTypes: { - status: { control: "select", options: ["done", "ready", "working", "approval", "input", "failed"] }, + status: { control: "select", options: statuses }, width: { control: { type: "range", min: 136, max: 640, step: 8 } }, ageMinutes: { control: { type: "range", min: 0, max: 10_080, step: 1 } }, + ageSeconds: { control: { type: "range", min: 0, max: 59, step: 1 } }, }, parameters: { docs: { @@ -150,7 +178,7 @@ export const Narrow = { args: { width: 136, remote: true } } export const AllStates = { render: (args: Parameters[0]) => (
- + status !== args.status)]}> {(status) => (
{status} @@ -161,3 +189,9 @@ export const AllStates = {
), } + +export const JustStarted = { args: { status: "working", ageMinutes: 0, ageSeconds: 12 } } + +export const UnknownAge = { args: { status: "working", timestampKnown: false } } + +export const MarkAsRead = { args: { readAction: true } } diff --git a/packages/app/src/shell/titlebar/inbox-list.stories.tsx b/packages/app/src/shell/titlebar/inbox-list.stories.tsx index e42ecb8f5c6c..989d9de69b98 100644 --- a/packages/app/src/shell/titlebar/inbox-list.stories.tsx +++ b/packages/app/src/shell/titlebar/inbox-list.stories.tsx @@ -29,6 +29,9 @@ function SessionListStory(props: { height: number currentArchived: boolean neverRun: boolean + loading: boolean + announcement: string + recentExpanded: boolean }) { const language = useLanguage() @@ -38,12 +41,13 @@ function SessionListStory(props: { archived: props.archived, removed: new Array(), action: "", - recentExpanded: false, + recentExpanded: props.recentExpanded, }) createEffect(() => setState("selected", props.selectedSession)) createEffect(() => setState("expanded", props.workingExpanded)) createEffect(() => setState("archived", props.archived)) + createEffect(() => setState("recentExpanded", props.recentExpanded)) const sessions = (section: "current" | "needs" | "unread" | "recent" | "working", count: number) => Array.from({ length: count }, (_, index) => { @@ -172,6 +176,8 @@ function SessionListStory(props: { style={{ width: `${props.width}px`, height: `${props.height}px` }} > @@ -236,6 +242,9 @@ export default { height: 640, currentArchived: false, neverRun: false, + loading: false, + announcement: "", + recentExpanded: false, }, argTypes: { currentCount: { control: { type: "range", min: 0, max: 1, step: 1 } }, @@ -245,7 +254,7 @@ export default { workingCount: { control: { type: "range", min: 0, max: 12, step: 1 } }, selectedSession: { control: "select", - options: ["current-0", "recent-1", "recent-0", "needs-0", "working-0", "none"], + options: ["current-0", "recent-1", "recent-0", "needs-0", "working-0", "unread-0", "none"], }, width: { control: { type: "range", min: 136, max: 640, step: 8 } }, height: { control: { type: "range", min: 240, max: 900, step: 20 } }, @@ -312,3 +321,9 @@ export const Dense = { args: { needsCount: 4, recentCount: 10, workingCount: 5 } export const Narrow = { args: { width: 136 } } export const ShortSidebar = { args: { height: 360 } } + +export const Loading = { args: { loading: true } } + +export const RecentExpanded = { args: { recentCount: 16, recentExpanded: true } } + +export const ArchivedOnly = { args: { needsCount: 0, unreadCount: 0, recentCount: 0, workingCount: 0 } } diff --git a/packages/app/src/shell/titlebar/navigation-story.tsx b/packages/app/src/shell/titlebar/navigation-story.tsx new file mode 100644 index 000000000000..63fff5e3474c --- /dev/null +++ b/packages/app/src/shell/titlebar/navigation-story.tsx @@ -0,0 +1,207 @@ +import type { ProjectListOutput, SessionInfo } from "@opencode/client/promise" +import { createMemoryHistory, MemoryRouter, Route } from "@solidjs/router" +import { createEffect, on, Show } from "solid-js" +import { + createMemoryStorage, + createStoryFetch, + DialogStoryRuntime, + STORY_DIRECTORY, + STORY_PROJECTS, + STORY_SERVER, +} from "@/components-lab/dialog-story-runtime" +import type { Platform } from "@/runtime/platform/platform" +import { ServerConnection } from "@/runtime/server/registry" +import { useGlobal } from "@/runtime/server/runtime" +import { tabHref, tabKey, useTabs, type Tab } from "@/shell/tabs/tabs" +import { createRouteTabSync } from "./route-sync" +import { SidebarCustomized, type SidebarStripGrouping } from "./sidebar-customized" +import type { SidebarViewState } from "./sidebar-view" +import { TitlebarTabStrip } from "./tab-strip" +import "./titlebar.css" + +const server = ServerConnection.key(STORY_SERVER) + +const projects = STORY_PROJECTS.map((project) => + project.id === "prj_docs" ? { ...project, name: "Developer documentation and integration guides" } : project, +) satisfies ProjectListOutput + +const idle = Date.UTC(2026, 10, 3, 12) + +function session(id: string, title: string, project: ProjectListOutput[number], unread = false): SessionInfo { + return { + id: `ses_${id}`, + title, + projectID: project.id, + location: { directory: project.canonical }, + time: { created: idle - 60_000, updated: idle, idle, viewed: unread ? undefined : idle }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + } +} + +const sessions = [ + session("restore", "Restore workspace tabs", projects[0]), + session("guide", "Review the keyboard navigation guide for switching between project sessions", projects[1], true), + session("sidebar", "Sidebar focus order", projects[0]), + session("landing", "Landing page spacing", projects[2]), + session("contrast", "Check badge contrast", projects[0]), + session("search", "Search index refresh", projects[1]), + session("redirects", "Audit redirects", projects[2]), + session("icons", "Project icons", projects[0]), + session("examples", "Update examples", projects[1]), + session("footer", "Footer links", projects[2]), +] + +// All fetches and writes belong to one mount. The rest of the server (including the event stream) +// comes from the same fixture the standalone dialog stories use. +function navigationFetch(): typeof fetch { + const fallback = createStoryFetch() + + const records = new Map(sessions.map((item) => [item.id, structuredClone(item)])) + + const handler = async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + + const url = new URL(request.url) + + if (url.pathname === "/api/project") return Response.json(projects) + + if (url.pathname === "/api/session") { + const parent = url.searchParams.get("parentID") + + return Response.json({ data: parent && parent !== "null" ? [] : [...records.values()], cursor: {} }) + } + + const match = /^\/api\/session\/(ses_[^/]+)(?:\/(\w+))?$/.exec(url.pathname) + + if (!match) return fallback(input, init) + const record = records.get(match[1]) + + if (!record) return new Response(null, { status: 404 }) + + if (match[2] === "message") return Response.json({ data: [], cursor: {} }) + + if (match[2] === "view") record.time.viewed = record.time.idle + + if (request.method === "DELETE") records.delete(record.id) + + if (request.method === "PATCH") { + const patch: { title?: string } = await request.json() + + if (patch.title !== undefined) record.title = patch.title + } + + if (request.method !== "GET") return new Response(null, { status: 204 }) + + return Response.json({ data: match[2] ? [] : record }) + } + + return Object.assign(handler, { preconnect: fallback.preconnect }) +} + +type Preset = "sessions" | "draft" | "crowded" | "projects" | "collapsed" + +export function NavigationStory(props: { preset: Preset; width: number }) { + const draft: Tab = { type: "draft", server, directory: STORY_DIRECTORY, draftID: "navigation-draft" } + + const open = props.preset === "crowded" ? sessions : sessions.slice(0, 4) + + const tabs: Tab[] = [...open.map((item): Tab => ({ type: "session", server, sessionId: item.id })), draft] + + const view: Omit = { + grouping: "project", + ordering: "manual", + show: { recent: true, subagents: false, serverLabels: true }, + collapsed: props.preset === "collapsed" ? { [`project:${projects[0].id}`]: true } : {}, + } + + const storage = createMemoryStorage() + storage("opencode.window.navigation.dat").setItem("tabs", JSON.stringify(tabs)) + storage("opencode.global.dat").setItem("sidebar.view", JSON.stringify(view)) + + const platform: Platform = { + platform: "desktop", + windowID: "navigation", + openDirectoryPickerDialog: async () => null, + openExternal() {}, + notify: async () => {}, + restart: async () => {}, + storage, + fetch: navigationFetch(), + } + + const history = createMemoryHistory() + history.set({ value: tabHref(props.preset === "draft" ? draft : tabs[0]), replace: true, scroll: false }) + + return ( + + ( + + + + )} + /> + + ) +} + +function NavigationSurface(props: { sidebar: boolean; width: number }) { + const tabs = useTabs() + + const route = createRouteTabSync() + + const global = useGlobal() + + createEffect( + on(route.currentTab, (current) => { + if (current?.type === "session") global.serverCtx(server)?.notification.session.markRead(current.sessionId) + }), + ) + + const strip = (group?: SidebarStripGrouping) => ( + { + tabs.select(tab) + element?.scrollIntoView({ block: "nearest", inline: "nearest" }) + }} + onClose={(tab) => tabs.closeTab(tabs.store.indexOf(tab))} + onCloseTabs={(items, keep) => tabs.closeTabs(items.map(tabKey), keep)} + onReorder={tabs.reorder} + /> + ) + + return ( + + {strip()} +
+ } + > +
+ void tabs.newDraft({ server, directory: STORY_DIRECTORY })} + > + {strip} + +
+ + ) +} diff --git a/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx b/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx new file mode 100644 index 000000000000..ea5bbb094c09 --- /dev/null +++ b/packages/app/src/shell/titlebar/sidebar-customized.standalone.stories.tsx @@ -0,0 +1,16 @@ +import { NavigationStory } from "./navigation-story" + +type Args = { width: number } + +export default { + title: "App/Desktop/Project sidebar", + id: "app-desktop-project-sidebar", + args: { width: 304 }, + argTypes: { width: { control: { type: "range", min: 192, max: 480, step: 8 } } }, +} + +export const ProjectGroups = { render: (args: Args) => } + +export const CollapsedCurrentProject = { + render: (args: Args) => , +} diff --git a/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx b/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx new file mode 100644 index 000000000000..478bdc9d2894 --- /dev/null +++ b/packages/app/src/shell/titlebar/tab-strip.standalone.stories.tsx @@ -0,0 +1,19 @@ +import { NavigationStory } from "./navigation-story" + +type Args = { width: number } + +export default { + title: "App/Desktop/Session tab strip", + id: "app-desktop-session-tab-strip", + args: { width: 880 }, + argTypes: { width: { control: { type: "range", min: 240, max: 1440, step: 8 } } }, +} + +export const SessionsAndDraft = { render: (args: Args) => } + +export const ActiveDraft = { render: (args: Args) => } + +export const Crowded = { + args: { width: 600 }, + render: (args: Args) => , +} diff --git a/packages/app/src/usage/dialog.standalone.stories.tsx b/packages/app/src/usage/dialog.standalone.stories.tsx index ece8f56ebc88..60c03212bfbc 100644 --- a/packages/app/src/usage/dialog.standalone.stories.tsx +++ b/packages/app/src/usage/dialog.standalone.stories.tsx @@ -2,11 +2,13 @@ import type { UsageLimitsBudget, UsageLimitsInfo } from "@opencode/client/promis import { Button } from "@opencode/ui/button" import { useDialog } from "@opencode/ui/context/dialog" import { onMount } from "solid-js" -import { DialogStoryRuntime, STORY_DIRECTORY } from "@/components-lab/dialog-story-runtime" +import { DialogStoryRuntime, STORY_DIRECTORY, STORY_LOCKED_SERVER } from "@/components-lab/dialog-story-runtime" import { DialogUsage, UsageDialogContent } from "./dialog" import type { CurrentModel } from "./limits" -const resetsAt = Date.UTC(2026, 10, 1) +const today = new Date() + +const resetsAt = Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + 1, 1) const hour = 3_600_000 @@ -33,11 +35,11 @@ const anthropic = (spent: number) => const pool = (spent: number) => budget({ id: "pool", scope: "combined", shared: true, limit: 1_000, spent }) -const info = (budgets: UsageLimitsBudget[], go = false): UsageLimitsInfo => ({ +const info = (budgets: UsageLimitsBudget[], go?: "available" | "limited"): UsageLimitsInfo => ({ workspace: { id: "wrk_1", name: "Acme", usageURL: "https://opencode.ai/wrk_1/activity/overview" }, go: go ? { - rolling: { percent: 42, limited: false, resetsAt: Date.now() + 3 * hour }, + rolling: { percent: go === "limited" ? 100 : 42, limited: go === "limited", resetsAt: Date.now() + 3 * hour }, weekly: { percent: 18, limited: false, resetsAt: Date.now() + 100 * hour }, monthly: { percent: 7, limited: false, resetsAt: Date.now() + 500 * hour }, } @@ -82,7 +84,7 @@ export default { id: "app-dialog-usage", } -export const Default = { render: () => } +export const Default = { render: () => } export const SignedOut = { render: () => ( @@ -123,3 +125,13 @@ export const WorkspaceBudgetReached = { render: () => } export const NoBudgets = { render: () => } + +export const GoLimitReached = { render: () => } + +export const LoadFailed = { + render: () => ( + + + + ), +} diff --git a/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx b/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx index 5e15c35f50fc..a78edac3e7c5 100644 --- a/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx +++ b/packages/app/src/workspaces/selection/dialog.standalone.stories.tsx @@ -5,7 +5,7 @@ import { createStore } from "solid-js/store" import { DialogStoryRuntime, STORY_DIRECTORY, STORY_SERVER } from "@/components-lab/dialog-story-runtime" import { DirectoryPickerDialog } from "./dialog" -function DirectoryPickerStory(props: { mode?: "directory" | "file" }) { +function DirectoryPickerStory(props: { mode?: "directory" | "file"; start?: string }) { const dialog = useDialog() const [store, setStore] = createStore({ selected: "No path selected" }) @@ -15,7 +15,7 @@ function DirectoryPickerStory(props: { mode?: "directory" | "file" }) { { const text = Array.isArray(result) ? result.join(", ") : (result ?? "Cancelled") @@ -56,3 +56,11 @@ export const SelectFile = {
), } + +export const MissingDirectory = { + render: () => ( + + + + ), +} diff --git a/packages/stories/index.html b/packages/stories/index.html index eacbb457aeb4..45c1b69b655b 100644 --- a/packages/stories/index.html +++ b/packages/stories/index.html @@ -7,6 +7,6 @@
- + diff --git a/packages/stories/mocks/app/context/layout.ts b/packages/stories/mocks/app/context/layout.ts index c163783a27b9..5d54cc300213 100644 --- a/packages/stories/mocks/app/context/layout.ts +++ b/packages/stories/mocks/app/context/layout.ts @@ -2,6 +2,7 @@ import { useLocation } from "../../solid-router" import { createSignal, type ParentProps } from "solid-js" import type { ServerConnection } from "@/runtime/server/registry" import type { Project } from "@/runtime/server/types" +import { requireServerKey } from "@/shell/routes/session" export type LocalProject = Partial & { worktree: string; expanded?: boolean } @@ -30,6 +31,10 @@ export function currentRoute(pathname: string, search: string): LayoutRoute { return draftID ? { type: "draft", draftID } : { type: "home" } } + if (parts[0] === "server" && parts[2] === "session" && parts[3]) { + return { type: "session", server: requireServerKey(parts[1]), sessionId: parts[3] } + } + return { type: "home" } } diff --git a/packages/stories/playwright/README.md b/packages/stories/playwright/README.md index d3b34c6d77cf..1b9a72f80798 100644 --- a/packages/stories/playwright/README.md +++ b/packages/stories/playwright/README.md @@ -2,6 +2,8 @@ Production Solid components are tested through their existing `*.stories.tsx` stories without booting the app, configuring a server, seeding browser storage, or navigating unrelated routes. +To browse the full components lab in a browser, run `bun run --cwd packages/stories dev` from the repo root and open (or the port Vite prints). The tree, grid, and inspector use the same story fixtures as the individual `/?id=…` pages. + Keep each spec in the package that owns its production component: - `packages/session-ui/component-tests/` owns timeline, tool, notice, reasoning, lifecycle, and review coverage. diff --git a/packages/stories/src/frame.tsx b/packages/stories/src/frame.tsx index 2c4086c8c4a4..f2cbac159b48 100644 --- a/packages/stories/src/frame.tsx +++ b/packages/stories/src/frame.tsx @@ -1,15 +1,11 @@ import "../../app/src/index.css" -import { createEffect, createResource, onCleanup, onMount, Show, type Component, type JSX } from "solid-js" +import { createResource, Show, type Component, type JSX } from "solid-js" import { Dynamic, render } from "solid-js/web" -import { MetaProvider } from "@solidjs/meta" -import { DialogProvider } from "@opencode/ui/context/dialog" -import { ThemeProvider, useTheme, type ColorScheme } from "@opencode/ui/theme" -import { Font } from "@opencode/ui/font" -import { LanguageProvider, UiI18nBridge, useLanguage } from "@/runtime/i18n/language" -import { SettingsProvider } from "@/settings/model" +import type { ColorScheme } from "@opencode/ui/theme" import { findStory } from "virtual:story-index" import { PluginStory } from "./plugin" +import { StoryProviders } from "./providers" type Args = { [key: string]: unknown } @@ -66,73 +62,22 @@ function Frame() { function Decorators(props: { scheme: ColorScheme; fullscreen: boolean; file: string; children: JSX.Element }) { return ( - - - - - - - - - - -
- {props.children} -
-
-
-
-
-
-
+ +
+ {props.children} +
+
) } -function Scheme(props: { value: ColorScheme }) { - const theme = useTheme() - - createEffect(() => theme.setColorScheme(props.value)) - createEffect(() => { - document.documentElement.classList.remove("light", "dark") - document.documentElement.classList.add(theme.mode()) - }) - - return null -} - -function Direction(props: { value?: string }) { - const language = useLanguage() - - createEffect(() => language.setDirection(props.value === "rtl" ? "rtl" : "ltr")) - - return null -} - -// The app derives this attribute from its reduce motion setting; stories follow the system preference. -function Motion() { - onMount(() => { - const motion = matchMedia("(prefers-reduced-motion: reduce)") - - const apply = () => (document.documentElement.dataset.motion = motion.matches ? "reduce" : "full") - - apply() - motion.addEventListener("change", apply) - onCleanup(() => motion.removeEventListener("change", apply)) - }) - - return null -} - function scheme(value: string): ColorScheme { if (value === "light" || value === "dark" || value === "system") return value diff --git a/packages/stories/src/index-plugin.ts b/packages/stories/src/index-plugin.ts index 8d8fd1bba01f..6681df70a2c6 100644 --- a/packages/stories/src/index-plugin.ts +++ b/packages/stories/src/index-plugin.ts @@ -12,6 +12,14 @@ export function storyIndex(roots: string[]): Plugin { return { name: "opencode:story-index", resolveId: (source) => (source === id ? `\0${id}` : undefined), + hotUpdate({ file }) { + if (!file.endsWith(".stories.tsx")) return + + // The index reads the export names itself. Recompute them for the next /?id=… visit. + const graph = this.environment.moduleGraph + const index = graph.getModuleById(`\0${id}`) + if (index) graph.invalidateModule(index) + }, load(source) { if (source !== `\0${id}`) return diff --git a/packages/stories/src/lab.tsx b/packages/stories/src/lab.tsx new file mode 100644 index 000000000000..673c9355a735 --- /dev/null +++ b/packages/stories/src/lab.tsx @@ -0,0 +1,54 @@ +import "../../app/src/index.css" + +import { createSignal, onCleanup } from "solid-js" +import { render } from "solid-js/web" +import { LabBrowser } from "../../app/src/components-lab/browser" +import { loadLabCatalog, type StoryModule } from "../../app/src/components-lab/catalog" +import { PluginStory } from "./plugin" +import { StoryProviders } from "./providers" + +// This origin uses the story mocks, so it can include the standalone dialog fixtures as well. +const modules = import.meta.glob("../../{app,ui,session-ui,gui-plugins}/src/**/*.stories.tsx") + +const sources = import.meta.glob("../../{app,ui,session-ui,gui-plugins}/src/**/*.stories.tsx", { + query: "?raw", + import: "default", +}) + +function StandaloneLab() { + const readParams = () => Object.fromEntries(new URLSearchParams(location.search)) + + const [params, setParams] = createSignal(readParams()) + + const sync = () => setParams(readParams()) + + window.addEventListener("popstate", sync) + onCleanup(() => window.removeEventListener("popstate", sync)) + + return ( + +
+ { + const url = new URL(location.href) + + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) url.searchParams.delete(key) + else url.searchParams.set(key, value) + } + if (url.href === location.href) return + + history.pushState(null, "", url) + sync() + }} + loadCatalog={() => loadLabCatalog(modules, sources)} + plugin={PluginStory} + /> +
+
+ ) +} + +document.title = "OpenCode Components Lab" +render(StandaloneLab, document.getElementById("story-root")!) diff --git a/packages/stories/src/main.ts b/packages/stories/src/main.ts new file mode 100644 index 000000000000..e27b868f764b --- /dev/null +++ b/packages/stories/src/main.ts @@ -0,0 +1,6 @@ +// Component tests navigate directly to an isolated story. Only the homepage loads the catalog and inspector. +if (new URLSearchParams(location.search).has("id")) { + void import("./frame") +} else { + void import("./lab") +} diff --git a/packages/stories/src/providers.tsx b/packages/stories/src/providers.tsx new file mode 100644 index 000000000000..f4a0a5e8507a --- /dev/null +++ b/packages/stories/src/providers.tsx @@ -0,0 +1,51 @@ +import { createEffect, onCleanup, onMount, type ParentProps } from "solid-js" +import { MetaProvider } from "@solidjs/meta" +import { DialogProvider } from "@opencode/ui/context/dialog" +import { Font } from "@opencode/ui/font" +import { ThemeProvider, useTheme, type ColorScheme } from "@opencode/ui/theme" +import { LanguageProvider, UiI18nBridge, useLanguage } from "@/runtime/i18n/language" +import { SettingsProvider } from "@/settings/model" + +export function StoryProviders(props: ParentProps<{ scheme?: ColorScheme; direction?: string; locale?: string }>) { + return ( + + + + + + + + {props.children} + + + + + + ) +} + +function Appearance(props: { scheme?: ColorScheme; direction?: string }) { + const theme = useTheme() + + const language = useLanguage() + + createEffect(() => props.scheme && theme.setColorScheme(props.scheme)) + createEffect(() => { + document.documentElement.classList.remove("light", "dark") + document.documentElement.classList.add(theme.mode()) + }) + createEffect(() => language.setDirection(props.direction === "rtl" ? "rtl" : "ltr")) + + // The app derives this attribute from its reduce motion setting; stories follow the system preference. + onMount(() => { + const motion = matchMedia("(prefers-reduced-motion: reduce)") + + const apply = () => (document.documentElement.dataset.motion = motion.matches ? "reduce" : "full") + + apply() + motion.addEventListener("change", apply) + onCleanup(() => motion.removeEventListener("change", apply)) + }) + + return null +} diff --git a/packages/stories/vite.config.ts b/packages/stories/vite.config.ts index 16529da36032..89dc10155a8a 100644 --- a/packages/stories/vite.config.ts +++ b/packages/stories/vite.config.ts @@ -6,8 +6,7 @@ import { defineConfig, searchForWorkspaceRoot } from "vite" import solid from "vite-plugin-solid" import { storyIndex } from "./src/index-plugin" -// Serves one story at a time for the component tests, the way Storybook's iframe did, without Storybook. The app's -// browsing UI for stories is the components lab in the app itself. +// The standalone components lab and the isolated story frames share the same mock runtime. const here = path.dirname(fileURLToPath(import.meta.url)) const packages = path.resolve(here, "..") const app = path.resolve(packages, "app/src") From b3f806c2f6b35a7712f4d7b6b508d585787bcb40 Mon Sep 17 00:00:00 2001 From: usrnk1 <7547651+usrnk1@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:58:40 +0100 Subject: [PATCH 16/43] test(gui-plugins): add interactive workspace, browser, and pairing stories (#63734) --- .../gui-plugins/src/browser/panel.fixture.tsx | 154 ++++++++--- .../gui-plugins/src/browser/panel.stories.tsx | 114 ++++++++ .../gui-plugins/src/file/browser.stories.tsx | 43 +++ .../src/pairing/dialog.stories.tsx | 18 +- .../gui-plugins/src/pairing/page.stories.tsx | 108 ++++++-- .../gui-plugins/src/review/panel.stories.tsx | 35 +++ .../stories/mocks/gui-plugins/pairing.tsx | 110 +++++--- .../mocks/gui-plugins/workspace-panel.tsx | 156 +++++++++++ .../stories/mocks/gui-plugins/workspace.ts | 246 ++++++++++++++++++ 9 files changed, 890 insertions(+), 94 deletions(-) create mode 100644 packages/gui-plugins/src/browser/panel.stories.tsx create mode 100644 packages/gui-plugins/src/file/browser.stories.tsx create mode 100644 packages/gui-plugins/src/review/panel.stories.tsx create mode 100644 packages/stories/mocks/gui-plugins/workspace-panel.tsx create mode 100644 packages/stories/mocks/gui-plugins/workspace.ts diff --git a/packages/gui-plugins/src/browser/panel.fixture.tsx b/packages/gui-plugins/src/browser/panel.fixture.tsx index b96fa780c8c9..0c8e26f63b89 100644 --- a/packages/gui-plugins/src/browser/panel.fixture.tsx +++ b/packages/gui-plugins/src/browser/panel.fixture.tsx @@ -53,7 +53,7 @@ import { createModel } from "./model" import SessionBrowserPane from "./panel" import { BrowserPane, type PaneEvent } from "./ipc" import { pageShortcut } from "./keys" -import { refusal } from "./policy" +import { normalizeURL, refusal } from "./policy" import { type BuiltinLayout } from "@opencode/plugin/gui/builtin" /** The renderer host pieces the pane runs on, passed in by `packages/app/component-tests/browser-pane.spec.ts`. */ @@ -110,6 +110,23 @@ type PaneFixtureState = { selection: string } +export type BrowserScenario = "Page" | "Empty" | "Recent" | "Loading" | "Failed" | "Suspended" + +type ElementRect = Pick + +type StoryHost = Pick & { + scenario: BrowserScenario + Page: Component<{ url: string; zoom: number; picking: boolean; pick: (rect: ElementRect) => void }> + Frame: ParentComponent<{ + loading: boolean + finish: () => void + suspended: boolean + reconnect: () => void + external: string | undefined + comments: readonly ComposerNote[] + }> +} + // A 16px blue square, as main reports a page icon. const icon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHJlY3Qgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiByeD0iMyIgZmlsbD0iIzNiODJmNiIvPjwvc3ZnPg==" @@ -137,21 +154,40 @@ export function mountBrowserPane(input: PaneHost) { host.style.cssText = "position:fixed;inset:0;z-index:1000;background:#181818;color:#eee;padding:24px" document.body.appendChild(host) - function Fixture() { + const Fixture = browserPaneFixture(input) + + return render( + () => ( + + + + + + ), + host, + ) +} + +// Both hosts exercise the real model and pane. The lab draws an in-memory document where the component tests +// measure native embed layouts and captures. +export function browserPaneFixture(input: PaneHost | StoryHost) { + return function Fixture() { const language = input.useLanguage() const messages = new Map(Object.entries(browserEn)) + const scenario = "scenario" in input ? input.scenario : undefined + const [store, setStore] = createStore({ session: "Alpha", mounted: true, visible: true, - url: undefined, - loading: false, + url: scenario === "Empty" || scenario === "Recent" ? "about:blank" : undefined, + loading: scenario === "Loading", generation: 0, delayNavigation: false, pendingURL: undefined, - loadErrors: {}, - error: undefined, + loadErrors: scenario === "Failed" ? { Alpha: "ERR_CONNECTION_REFUSED" } : {}, + error: scenario === "Suspended" ? "browser.pane.suspended" : undefined, layouts: {}, covered: false, moving: false, @@ -164,7 +200,7 @@ export function mountBrowserPane(input: PaneHost) { highlights: [], comments: [], zoom: 1, - history: { visits: [] }, + history: { visits: scenario === "Recent" ? structuredClone(visits) : [] }, external: [], cookies: 3, failSite: false, @@ -223,12 +259,30 @@ export function mountBrowserPane(input: PaneHost) { } // SAFETY: the host embeds call only `embed`, `capture` and `on` on their bridge (`runtime/plugin/embeds.tsx`). - const embeds = input.createEmbeds({ - bridge: bridge as Bridge, - zoom: () => (store.selection === "zoomed" ? 1.25 : 1), - dialog: () => store.dialog, - moving: () => store.moving || input.panelMotion.panelsMoving(), - }) + const embeds: Embeds = + "createEmbeds" in input + ? input.createEmbeds({ + bridge: bridge as Bridge, + zoom: () => (store.selection === "zoomed" ? 1.25 : 1), + dialog: () => store.dialog, + moving: () => store.moving || input.panelMotion.panelsMoving(), + }) + : { + capture: async () => undefined, + View: (props) => ( +
+ + + + {props.children} +
+ ), + } const t = (key: string, params?: Readonly>>) => (messages.get(key) ?? language.t(key)).replace(/\{\{(\w+)\}\}/g, (_, name: string) => @@ -297,6 +351,9 @@ export function mountBrowserPane(input: PaneHost) { composer: { attach: (note: ComposerNote) => setStore("comments", (items) => [...items, note]) }, } as unknown as SessionScreen + const back: string[] = [] + const forward: string[] = [] + const report = (key = store.session) => { const tab = tabs.find((item) => item.title === key) @@ -308,6 +365,8 @@ export function mountBrowserPane(input: PaneHost) { { ...tab, url: store.url ?? tab.url, + canGoBack: back.length > 0, + canGoForward: forward.length > 0, loading: store.loading, generation: store.generation, loadError: store.loadErrors[key], @@ -325,6 +384,14 @@ export function mountBrowserPane(input: PaneHost) { bindings.set(value.session, value.binding) queueMicrotask(() => { report(value.session) + + // A suspended attachment reports its retained inventory once. The next interaction can reconnect it. + if (store.error === "browser.pane.suspended") { + setStore("error", undefined) + + return + } + const tab = tabs.find((item) => item.title === value.session) if (tab) emit(value.session, { type: "embed", tabID: tab.id, embed: `embed-${tab.title}` }) @@ -342,15 +409,32 @@ export function mountBrowserPane(input: PaneHost) { if (command.type === "navigate" || command.type === "reload") setStore("loadErrors", store.session, undefined) if (command.type === "navigate") { + const url = normalizeURL(command.url) + if (store.delayNavigation) { - setStore("pendingURL", command.url) + setStore("pendingURL", url) return } - setStore({ url: command.url, loading: false, generation: store.generation + 1 }) + back.push(store.url ?? current().url) + forward.length = 0 + setStore({ url, loading: false, generation: store.generation + 1 }) + } + + if (command.type === "back" || command.type === "forward") { + const stack = command.type === "back" ? back : forward + const url = stack.pop() + + if (url) { + const other = command.type === "back" ? forward : back + other.push(store.url ?? current().url) + setStore({ url, loading: false, generation: store.generation + 1 }) + } } + if (command.type === "reload") setStore({ loading: false, generation: store.generation + 1 }) + if (command.type === "stop") setStore("loading", false) report() }, @@ -437,7 +521,7 @@ export function mountBrowserPane(input: PaneHost) { const plugin = fake as unknown as Context & SetupContext const model = createModel(plugin) - const pick = () => { + const pick = (rect?: ElementRect) => { const selector = () => { if (store.selection === "fallback") return "" @@ -458,11 +542,34 @@ export function mountBrowserPane(input: PaneHost) { label: "button.primary", role: "button", name: "Save changes", - rect: { x: 48, y: store.selection === "low" ? 180 : 40, width: 160, height: 36 }, + rect: rect ?? { x: 48, y: store.selection === "low" ? 180 : 40, width: 160, height: 36 }, }, }) } + if ("Frame" in input) + return ( + + + { + setStore("loading", false) + report() + }} + suspended={model.suspended({ key: store.session })} + reconnect={() => model.command({ key: store.session }, { type: "reload", tabID: current().id })} + comments={store.comments} + external={store.external.at(-1)} + > + + {(view) => } + + + + + ) + return ( @@ -546,7 +653,7 @@ export function mountBrowserPane(input: PaneHost) { )} - +