diff --git a/packages/cli/src/commands/commands.ts b/packages/cli/src/commands/commands.ts index 12188859cfb..f5622d215fa 100644 --- a/packages/cli/src/commands/commands.ts +++ b/packages/cli/src/commands/commands.ts @@ -51,7 +51,7 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME ), session: Flag.string("session").pipe( Flag.withAlias("s"), - Flag.withDescription("Session ID to continue"), + Flag.withDescription("Session ID to continue, or to create if it does not exist"), Flag.optional, ), prompt: Flag.string("prompt").pipe(Flag.withDescription("Prompt to use"), Flag.optional), @@ -328,7 +328,7 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME ), session: Flag.string("session").pipe( Flag.withAlias("s"), - Flag.withDescription("Session ID to continue"), + Flag.withDescription("Session ID to continue, or to create if it does not exist"), Flag.optional, ), fork: Flag.boolean("fork").pipe( @@ -368,7 +368,7 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME ), session: Flag.string("session").pipe( Flag.withAlias("s"), - Flag.withDescription("Session ID to continue"), + Flag.withDescription("Session ID to continue, or to create if it does not exist"), Flag.optional, ), fork: Flag.boolean("fork").pipe( diff --git a/packages/cli/src/commands/handlers/default.ts b/packages/cli/src/commands/handlers/default.ts index 8bf7410615f..0ba72099a76 100644 --- a/packages/cli/src/commands/handlers/default.ts +++ b/packages/cli/src/commands/handlers/default.ts @@ -11,6 +11,10 @@ import { UpdatePreflight } from "../../services/update-preflight" import { Npm } from "@opencode/util/npm" import { OPENCODE_ARTIFACT, OPENCODE_CHANNEL, OPENCODE_VERSION } from "../../version" import { Env } from "../../env" +import { Service } from "@opencode/client/effect/service" +import { OpenCode } from "@opencode/client/promise" +import { findSession } from "../../session-target" +import { errorMessage } from "../../util/error" export default Runtime.handler(Commands, (input) => Effect.gen(function* () { @@ -46,6 +50,15 @@ export default Runtime.handler(Commands, (input) => Effect.promise(() => preflight.fail("OpenCode update could not start the new background service")), ), ) + const session = Option.getOrUndefined(input.session) + // A missing --session ID becomes the ID of the session the first prompt creates. + const sessionExists = + session !== undefined && + (yield* Effect.tryPromise({ + try: () => + findSession(OpenCode.make({ baseUrl: server.endpoint.url, headers: Service.headers(server.endpoint) }), session), + catch: (cause) => new Error(errorMessage(cause)), + })) !== undefined const updater = yield* Updater.Service let installing: string | undefined const updateListeners = new Set<(version: string) => void>() @@ -81,7 +94,8 @@ export default Runtime.handler(Commands, (input) => }, args: { continue: input.continue, - sessionID: Option.getOrUndefined(input.session), + sessionID: sessionExists ? session : undefined, + newSessionID: sessionExists ? undefined : session, prompt: Option.getOrUndefined(input.prompt), auto: input.auto || input.yolo || input.dangerouslySkipPermissions, }, diff --git a/packages/cli/src/session-target.ts b/packages/cli/src/session-target.ts index 3d56ad0a1cb..67d255533e4 100644 --- a/packages/cli/src/session-target.ts +++ b/packages/cli/src/session-target.ts @@ -63,6 +63,7 @@ export async function resolveSessionTarget(input: { (await input.client.session .create( { + id: input.session, agent: prepared.agent, model: prepared.model, location: { directory: location.directory }, @@ -101,14 +102,11 @@ async function selectSession(input: { fork?: boolean signal?: AbortSignal }) { - const explicit = input.session - ? await input.client.session.get({ sessionID: input.session }, ...requestOptions(input.signal)).catch((error) => { - if (error && typeof error === "object" && "_tag" in error && error._tag === "SessionNotFoundError") - return undefined - throw error - }) - : undefined - if (input.session && !explicit) throw new Error("Session not found") + const explicit = input.session ? await findSession(input.client, input.session, input.signal) : undefined + if (input.session && !explicit) { + if (input.fork) throw new Error("Session not found") + return { session: undefined } + } if (explicit) return { session: input.fork @@ -133,6 +131,13 @@ async function selectSession(input: { } } +export function findSession(client: OpenCodeClient, sessionID: string, signal?: AbortSignal) { + return client.session.get({ sessionID }, ...requestOptions(signal)).catch((error) => { + if (error && typeof error === "object" && "_tag" in error && error._tag === "SessionNotFoundError") return undefined + throw error + }) +} + async function latestSession( client: OpenCodeClient, location: LocationGetOutput, diff --git a/packages/cli/test/session-target.test.ts b/packages/cli/test/session-target.test.ts index 00a5b30e670..eeef3896920 100644 --- a/packages/cli/test/session-target.test.ts +++ b/packages/cli/test/session-target.test.ts @@ -42,6 +42,28 @@ describe("session target resolver", () => { }) }) + test("creates a missing explicit Session with its ID", async () => { + const client = OpenCode.make({ baseUrl: "https://opencode.test" }) + spyOn(client.session, "get").mockRejectedValue({ _tag: "SessionNotFoundError" }) + spyOn(client.location, "get").mockResolvedValue(location("/project")) + const create = spyOn(client.session, "create").mockResolvedValue(session("ses_chosen", "/project")) + + const target = await resolveSessionTarget({ client, session: "ses_chosen", prepare }) + expect(create).toHaveBeenCalledWith(expect.objectContaining({ id: "ses_chosen" })) + expect(target).toMatchObject({ session: { id: "ses_chosen" }, resume: false }) + }) + + test("does not create a missing explicit Session to fork", async () => { + const client = OpenCode.make({ baseUrl: "https://opencode.test" }) + spyOn(client.session, "get").mockRejectedValue({ _tag: "SessionNotFoundError" }) + const create = spyOn(client.session, "create") + + await expect(resolveSessionTarget({ client, session: "ses_chosen", fork: true, prepare })).rejects.toThrow( + "Session not found", + ) + expect(create).not.toHaveBeenCalled() + }) + test("paginates to continue the exact directory", async () => { const client = OpenCode.make({ baseUrl: "https://opencode.test" }) spyOn(client.location, "get").mockResolvedValue(location("/project")) diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index db549661ad5..ad21de04cfd 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -53,6 +53,7 @@ import { usePromptMove } from "./move" import { resolvePastedAttachments } from "./local-attachment" import { locationKey, useData } from "../../context/data" import { useLocation } from "../../context/location" +import { useArgs } from "../../context/args" import { Keymap, type KeymapCommand } from "../../context/keymap" import { useInteractivity } from "../../context/interactivity" import { abbreviateHome } from "../../runtime" @@ -206,6 +207,7 @@ export function Prompt(props: PromptProps) { const directoryRecents = useDirectoryRecents() const keymapCommands = Keymap.useCommands() const currentLocation = useLocation() + const args = useArgs() const config = useConfig().data const dialog = useDialog() const toast = useToast() @@ -1229,7 +1231,9 @@ export function Prompt(props: PromptProps) { // a local session record synchronously, so the navigation below happens // immediately — enter feels sent even while the create round-trip is in // flight. Sends against the new session gate on the request. + const newSessionID = args.takeNewSessionID() const created = data.session.create({ + id: newSessionID, location: directory ? { directory } : location, agent: agent.id, model: { @@ -1238,6 +1242,7 @@ export function Prompt(props: PromptProps) { variant, }, }) + if (newSessionID !== undefined) created.request.catch(() => args.restoreNewSessionID(newSessionID)) sessionID = created.id session = data.session.get(created.id) newSession = { diff --git a/packages/tui/src/context/args.tsx b/packages/tui/src/context/args.tsx index 9a528f2f0ec..8a9a8528a9a 100644 --- a/packages/tui/src/context/args.tsx +++ b/packages/tui/src/context/args.tsx @@ -1,3 +1,4 @@ +import { mergeProps } from "solid-js" import { createSimpleContext } from "./helper" export interface Args { @@ -6,11 +7,25 @@ export interface Args { prompt?: string continue?: boolean sessionID?: string + newSessionID?: string fork?: boolean auto?: boolean } export const { use: useArgs, provider: ArgsProvider } = createSimpleContext({ name: "Args", - init: (props: Args) => props, + init: (props: Args) => { + // The first new session created from home takes this ID; later ones mint their own. + let pending = props.newSessionID + return mergeProps(props, { + takeNewSessionID() { + const id = pending + pending = undefined + return id + }, + restoreNewSessionID(id: string) { + pending ??= id + }, + }) + }, }) diff --git a/packages/tui/test/new-session-id.test.tsx b/packages/tui/test/new-session-id.test.tsx new file mode 100644 index 00000000000..e0d8d5f0ce0 --- /dev/null +++ b/packages/tui/test/new-session-id.test.tsx @@ -0,0 +1,100 @@ +import { expect, test } from "bun:test" +import { createAppFixture } from "./fixture/app" +import { json } from "./fixture/tui-client" + +type SessionInput = { id?: string; location?: { directory: string } } + +const location = { + directory: "/tmp/opencode/packages/tui", + project: { id: "project", directory: "/tmp/opencode", canonical: "/tmp/opencode" }, +} + +function sessionInfo(record: SessionInput) { + return { + ...record, + location: record.location ?? { directory: location.directory }, + projectID: "project", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, + } +} + +async function launch(options: { failCreates?: number } = {}) { + const attempts: (string | undefined)[] = [] + const created: SessionInput[] = [] + const prompts: string[] = [] + let failures = options.failCreates ?? 0 + const setup = await createAppFixture({ + args: { newSessionID: "ses_chosen" }, + config: { animations: false, keybinds: { "session.new": "f6" } }, + fetch: async (url, request) => { + if (url.pathname === "/api/agent") + return json({ location, data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }] }) + if (url.pathname === "/api/provider") return json({ location, data: [{ id: "demo", name: "Demo" }] }) + if (url.pathname === "/api/model") + return json({ location, data: [{ id: "model", providerID: "demo", name: "Demo Model", variants: [] }] }) + if (url.pathname === "/api/session" && request.method === "POST") { + const record: SessionInput = await request.json() + attempts.push(record.id) + if (failures > 0) { + failures-- + return json({ message: "create failed" }, { status: 500 }) + } + created.push(record) + return json({ data: sessionInfo(record) }) + } + if (/^\/api\/session\/[^/]+\/prompt$/.test(url.pathname)) { + prompts.push(url.pathname.split("/")[3] ?? "") + return json({ data: {} }) + } + if (/^\/api\/session\/[^/]+\/(message|inbox|permission)$/.test(url.pathname)) + return json({ data: [], cursor: {} }) + if (/^\/api\/session\/[^/]+\/(agent|model)$/.test(url.pathname)) return new Response(null, { status: 204 }) + if (/^\/api\/session\/[^/]+$/.test(url.pathname)) { + const record = created.find((item) => item.id === url.pathname.split("/")[3]) + if (!record) return json({ message: "not found" }, { status: 404 }) + return json({ data: sessionInfo(record) }) + } + return undefined + }, + }) + return { setup, attempts, created, prompts } +} + +test("the first new session uses the launch session ID and later ones mint their own", async () => { + const run = await launch() + await using setup = run.setup + + await setup.ready + await setup.waitForFrame((frame) => frame.includes("Demo Model")) + await setup.mockInput.typeText("hello") + setup.mockInput.pressEnter() + await setup.waitForFrame(() => run.prompts.length === 1) + expect(run.prompts[0]).toBe("ses_chosen") + expect(run.created.map((item) => item.id)).toEqual(["ses_chosen"]) + + setup.mockInput.pressKey("F6") + await setup.renderOnce() + await setup.mockInput.typeText("again") + setup.mockInput.pressEnter() + await setup.waitForFrame(() => run.created.length === 2) + expect(run.created[1]?.id).toMatch(/^ses/) + expect(run.created[1]?.id).not.toBe("ses_chosen") +}) + +test("a failed first create keeps the launch session ID for the retry", async () => { + const run = await launch({ failCreates: 1 }) + await using setup = run.setup + + await setup.ready + await setup.waitForFrame((frame) => frame.includes("Demo Model")) + await setup.mockInput.typeText("hello") + setup.mockInput.pressEnter() + await setup.waitForFrame((frame) => frame.includes("Creating a session failed") && frame.includes("hello")) + expect(run.attempts).toEqual(["ses_chosen"]) + + setup.mockInput.pressEnter() + await setup.waitForFrame(() => run.created.length === 1) + expect(run.attempts).toEqual(["ses_chosen", "ses_chosen"]) +})