Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,16 @@ export function Prompt(props: PromptProps) {
command: inputText,
})
setStore("mode", "normal")
} else if (
inputText.startsWith("/") &&
iife(() => {
const name = inputText.split("\n")[0].split(" ")[0].slice(1)
const match = command.slashes().find((s) => s.display === "/" + name || s.aliases?.includes("/" + name))
if (match) match.onSelect()
return !!match
})
) {
// slash command dispatched inside the iife above
} else if (
inputText.startsWith("/") &&
iife(() => {
Expand Down
34 changes: 34 additions & 0 deletions packages/opencode/src/cli/cmd/tui/routes/session/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,40 @@ export function Session() {
})
},
},
{
title: "Continue interrupted session",
value: "session.continue",
category: "Session",
slash: {
name: "continue",
},
onSelect: (dialog) => {
const status = sync.data.session_status?.[route.sessionID]
if (status?.type !== "idle" && status?.type !== undefined) {
toast.show({ message: "Session is busy", variant: "warning", duration: 3000 })
dialog.clear()
return
}
// Uses raw fetch because the SDK has not been regenerated yet
sdk
.fetch(`${sdk.url}/session/${route.sessionID}/continue`, {
method: "POST",
})
.then(async (r) => {
if (!r.ok) {
const body = await r.json().catch(() => null)
throw new Error(body?.data?.message ?? `Continue failed: ${r.status}`)
}
})
.catch((e) =>
toast.show({
message: e instanceof Error ? e.message : "Failed to continue session",
variant: "error",
}),
)
dialog.clear()
},
},
{
title: sidebarVisible() ? "Hide sidebar" : "Show sidebar",
value: "session.sidebar.toggle",
Expand Down
2 changes: 1 addition & 1 deletion packages/opencode/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function errorHandler(log: Log.Logger): ErrorHandler {
else status = 500
return c.json(err.toObject(), { status })
}
if (err instanceof Session.BusyError) {
if (err instanceof Session.BusyError || err instanceof Session.NothingToContinueError) {
return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 })
}
if (err instanceof HTTPException) return err.getResponse()
Expand Down
28 changes: 28 additions & 0 deletions packages/opencode/src/server/routes/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,34 @@ export const SessionRoutes = lazy(() =>
return c.json(true)
},
)
.post(
"/:sessionID/continue",
describeRoute({
summary: "Continue session",
description: "Continue an interrupted session from where it left off without creating a new user message.",
operationId: "session.continue",
responses: {
200: {
description: "Continued session",
content: {
"application/json": {
schema: resolver(
z.object({
info: MessageV2.Assistant,
parts: MessageV2.Part.array(),
}),
),
},
},
},
...errors(400, 404),
},
}),
validator("param", z.object({ sessionID: SessionID.zod })),
async (c) => {
return c.json(await SessionPrompt.continue_(c.req.valid("param").sessionID))
},
)
.post(
"/:sessionID/share",
describeRoute({
Expand Down
6 changes: 6 additions & 0 deletions packages/opencode/src/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@ export namespace Session {
}
}

export class NothingToContinueError extends Error {
constructor(public readonly sessionID: string) {
super(`Nothing to continue in session ${sessionID}`)
}
}

export interface Interface {
readonly create: (input?: {
parentID?: SessionID
Expand Down
38 changes: 38 additions & 0 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export namespace SessionPrompt {
readonly loop: (input: z.infer<typeof LoopInput>) => Effect.Effect<MessageV2.WithParts>
readonly shell: (input: ShellInput) => Effect.Effect<MessageV2.WithParts>
readonly command: (input: CommandInput) => Effect.Effect<MessageV2.WithParts>
readonly continue: (sessionID: SessionID) => Effect.Effect<MessageV2.WithParts>
readonly resolvePromptParts: (template: string) => Effect.Effect<PromptInput["parts"]>
}

Expand Down Expand Up @@ -1323,6 +1324,38 @@ NOTE: At any point in time through this workflow you should feel free to ask the
},
)

const continue_ = Effect.fn("SessionPrompt.continue")(function* (sessionID: SessionID) {
const s = yield* InstanceState.get(state)
if (s.runners.get(sessionID)?.busy) throw new Session.BusyError(sessionID)

const last = (yield* MessageV2.filterCompactedEffect(sessionID)).findLast(
(m): m is MessageV2.WithParts & { info: MessageV2.Assistant } => m.info.role === "assistant",
)
if (!last) throw new Session.NothingToContinueError(sessionID)

if (
last.info.finish &&
last.info.finish !== "tool-calls" &&
!last.parts.some(
(p) => p.type === "tool" && (p.state.status === "pending" || p.state.status === "running"),
) &&
!last.info.error
) {
return yield* prompt({
sessionID,
parts: [{ type: "text", text: "continue" }],
})
}

last.info.error = undefined
last.info.finish = "tool-calls"
last.info.time.completed ??= Date.now()
yield* sessions.updateMessage(last.info)

yield* sessions.touch(sessionID)
return yield* getRunner(s.runners, sessionID).ensureRunning(runLoop(sessionID))
})

const lastAssistant = (sessionID: SessionID) =>
Effect.promise(async () => {
let latest: MessageV2.WithParts | undefined
Expand Down Expand Up @@ -1704,6 +1737,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
loop,
shell,
command,
continue: continue_,
resolvePromptParts,
})
}),
Expand Down Expand Up @@ -1818,6 +1852,10 @@ NOTE: At any point in time through this workflow you should feel free to ask the
return runPromise((svc) => svc.cancel(SessionID.zod.parse(sessionID)))
}

export async function continue_(sessionID: SessionID) {
return runPromise((svc) => svc.continue(SessionID.zod.parse(sessionID)))
}

export const LoopInput = z.object({
sessionID: SessionID.zod,
})
Expand Down
Loading
Loading