Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: desktop talks to the 2.0.32 engine routes

ogsamrat894b7e9542f0
diff --git a/apps/app/src/app/lib/opencode-v2-adapter.ts b/apps/app/src/app/lib/opencode-v2-adapter.ts
index 8df29397..a6872b6b 100644
--- a/apps/app/src/app/lib/opencode-v2-adapter.ts
+++ b/apps/app/src/app/lib/opencode-v2-adapter.ts
@@ -237,6 +237,8 @@ function mapV2Session(value: unknown, directory: string | undefined, eventCreate
const updated = readNumber(time, "updated") ?? readNumber(source, "updated") ?? created;
const archived = readNumber(time, "archived");
const parentID = readString(source, "parentID");
+ const revert = readRecord(source, "revert");
+ const revertMessageID = readString(revert, "messageID");
const mapped: Session = {
id,
slug: readString(source, "slug") ?? id,
@@ -251,6 +253,11 @@ function mapV2Session(value: unknown, directory: string | undefined, eventCreate
...(archived === undefined ? {} : { archived }),
},
...(parentID ? { parentID } : {}),
+ ...(revertMessageID ? { revert: {
+ messageID: revertMessageID,
+ ...(readString(revert, "partID") ? { partID: readString(revert, "partID") } : {}),
+ ...(readString(revert, "snapshot") ? { snapshot: readString(revert, "snapshot") } : {}),
+ } } : {}),
};
return mapped;
}
@@ -258,15 +265,18 @@ function mapV2Session(value: unknown, directory: string | undefined, eventCreate
function messageRole(value: Record<string, unknown>): V2MessageRole {
const raw = readString(value, "role") ?? readString(value, "type");
if (raw === "user") return "user";
- if (raw === "system" || raw === "synthetic" || raw === "compaction") return "system";
+ // Turn-end markers and context switches carry no visible conversation.
+ if (raw === "system" || raw === "synthetic" || raw === "compaction" || raw === "idle" || raw?.endsWith("-switched")) return "system";
return "assistant";
}
function parseToolInput(value: unknown, tool?: string): Record<string, unknown> {
if (isRecord(value)) {
- return tool === "subagent" && typeof value.agent === "string"
- ? { subagent_type: value.agent, ...value }
- : value;
+ // Display-only aliases for the v1 tool cards; native fields stay as sent.
+ if (tool === "subagent" && typeof value.agent === "string") return { subagent_type: value.agent, ...value };
+ if ((tool === "read" || tool === "edit" || tool === "write") && typeof value.path === "string") return { filePath: value.path, ...value };
+ if (tool === "skill" && typeof value.id === "string") return { name: value.id, ...value };
+ return value;
}
if (typeof value !== "string" || value === "") return {};
try {
@@ -278,7 +288,7 @@ function parseToolInput(value: unknown, tool?: string): Record<string, unknown>
}
function compatibleToolName(tool: string): string {
- return tool === "shell" ? "bash" : tool === "subagent" ? "task" : tool;
+ return tool === "shell" ? "bash" : tool === "subagent" ? "task" : tool === "patch" ? "apply_patch" : tool;
}
function toolMetadata(tool: string, metadata: Record<string, unknown>): Record<string, unknown> {
@@ -408,6 +418,18 @@ function mapV2MessageParts(
sessionID: string,
messageCreated: number,
): Part[] {
+ if (readString(value, "type") === "shell") {
+ const part = mapV2ToolPart({
+ id: readString(value, "shellID") ?? messageID,
+ name: "shell",
+ state: {
+ status: readString(value, "status") === "running" ? "running" : "completed",
+ input: { command: readString(value, "command") ?? "" },
+ result: readString(readRecord(value, "output"), "output") ?? "",
+ },
+ }, messageID, sessionID, messageCreated);
+ return part ? [part] : [];
+ }
if (Array.isArray(value.content)) {
const ordinals = { text: 0, reasoning: 0 };
return value.content.flatMap<Part>((entry) => {
@@ -1050,7 +1072,7 @@ export function translateV2Event(
if (type === "permission.replied" || type === "permission.v2.replied") {
const requestID = readString(properties, "requestID");
- const reply = readString(properties, "reply");
+ const reply = readString(properties, "decision") ?? readString(properties, "reply");
if (!sessionID || !requestID || (reply !== "once" && reply !== "always" && reply !== "reject")) return null;
return [{ type: "permission.replied", properties: { sessionID, requestID, reply } }];
}
@@ -1083,6 +1105,13 @@ export function translateV2Event(
return [{ type: "session.updated", properties: { info: { id: sessionID, title } } }];
}
+ if (type === "session.revert.staged" || type === "session.revert.cleared" || type === "session.revert.committed") {
+ const messageID = type === "session.revert.staged" ? readString(readRecord(properties, "revert"), "messageID") : undefined;
+ if (!sessionID) return null;
+ // A session.updated without a cursor clears it, matching a cleared or committed revert.
+ return [{ type: "session.updated", properties: { info: { id: sessionID, ...(messageID ? { revert: { messageID } } : {}) } } }];
+ }
+
if (type === "session.deleted") {
const info = mapV2Session(properties, readString(readRecord(value, "location") ?? {}, "directory"));
const deletedSessionID = sessionID || info?.id || "";
@@ -1369,7 +1398,7 @@ export function createClientV2(
"POST",
`/api/session/${encodeURIComponent(parameters.sessionID)}/permission/${encodeURIComponent(parameters.requestID)}/reply`,
{
- reply: parameters.reply ?? "once",
+ decision: parameters.reply ?? "once",
...(parameters.message ? { message: parameters.message } : {}),
},
options?.signal,
@@ -1444,7 +1473,7 @@ export function createClientV2(
const listQuestions = async (
_parameters: DirectoryParameters = {}, options?: RequestOptions,
): Promise<FieldsResult<QuestionRequest[]>> => {
- const result = await request("GET", "/api/form/request", undefined, options?.signal);
+ const result = await request("GET", "/api/form", undefined, options?.signal);
if (!result.response.ok) return failedResult(result);
const questions = responseItems(result.payload).flatMap((item) => {
const question = mapV2Question(item);
@@ -1468,7 +1497,7 @@ export function createClientV2(
const question = questionFormsByID.get(parameters.requestID);
if (!question) return {
error: { name: "QuestionNotFound", requestID: parameters.requestID },
- request: new Request(`${baseUrl}/api/form/request`),
+ request: new Request(`${baseUrl}/api/form`),
response: new Response(null, { status: 404 }),
};
const answer = parameters.answers ? Object.fromEntries(question.fields.map((field, index) => {
@@ -1476,9 +1505,10 @@ export function createClientV2(
field.options.find((option) => option.label === label)?.value ?? label);
return [field.key, field.multiple ? values : values[0] ?? ""];
})) : undefined;
- const result = await request("POST",
- `/api/session/${encodeURIComponent(question.request.sessionID)}/form/${encodeURIComponent(parameters.requestID)}/${answer ? "reply" : "cancel"}`,
- answer ? { answer } : undefined, options?.signal);
+ const formPath = `/api/session/${encodeURIComponent(question.request.sessionID)}/form/${encodeURIComponent(parameters.requestID)}`;
+ const result = answer
+ ? await request("POST", `${formPath}/reply`, { answer }, options?.signal)
+ : await request("DELETE", formPath, undefined, options?.signal);
if (!result.response.ok) return failedResult(result);
questionFormsByID.delete(parameters.requestID);
return successfulResult(result, true);
@@ -1495,6 +1525,14 @@ export function createClientV2(
return failedResult({ ...result, payload: { name: "InvalidV2SessionResponse" } });
};
+ const selectModel = (sessionID: string, model: { providerID: string; modelID: string }, options?: RequestOptions) =>
+ request("POST", `/api/session/${encodeURIComponent(sessionID)}/model`,
+ { model: { providerID: model.providerID, id: model.modelID } }, options?.signal);
+
+ // 2.x mutations answer 204 or a non-session payload; v1 callers expect the session.
+ const thenSession = async (result: TransportResult, sessionID: string, options?: RequestOptions) =>
+ result.response.ok ? getSession({ sessionID }, options) : failedResult<Session>(result);
+
const createSession = async (
parameters: SessionCreateParameters = {},
options?: RequestOptions,
@@ -1540,21 +1578,28 @@ export function createClientV2(
parameters: SessionParameters & { limit?: number; before?: string },
options?: RequestOptions,
): Promise<FieldsResult<V2MappedMessage[]>> => {
- const query = new URLSearchParams();
- if (parameters.limit !== undefined) query.set("limit", String(parameters.limit));
- const suffix = query.size ? `?${query.toString()}` : "";
- const result = await request(
- "GET",
- `/api/session/${encodeURIComponent(parameters.sessionID)}/message${suffix}`,
- undefined,
- options?.signal,
- );
- if (!result.response.ok) return failedResult(result);
- const data = responseItems(result.payload).flatMap((item) => {
- const mapped = mapV2Message(item, parameters.sessionID);
- return mapped ? [mapped] : [];
- });
- return successfulResult(result, data);
+ // 2.x pages newest first with a default page size; v1 callers expect
+ // the latest `limit` (or all) messages oldest first.
+ const path = `/api/session/${encodeURIComponent(parameters.sessionID)}/message`;
+ // The limit counts visible messages, not hidden turn markers.
+ const limit = parameters.limit ?? Infinity;
+ const data: V2MappedMessage[] = [];
+ let cursor: string | undefined;
+ let result: TransportResult;
+ for (;;) {
+ const pageSize = Math.min(200, limit - data.length);
+ const query = new URLSearchParams({ limit: String(pageSize), ...(cursor ? { cursor } : { order: "desc" }) });
+ result = await request("GET", `${path}?${query.toString()}`, undefined, options?.signal);
+ if (!result.response.ok) return failedResult(result);
+ const page = responseItems(result.payload);
+ for (const item of page) {
+ const mapped = mapV2Message(item, parameters.sessionID);
+ if (mapped && data.length < limit) data.push(mapped);
+ }
+ cursor = readString(readRecord(result.payload, "cursor"), "next");
+ if (page.length < pageSize || data.length >= limit || !cursor) break;
+ }
+ return successfulResult(result, data.reverse());
},
todo: async (parameters: SessionParameters): Promise<FieldsResult<never[]>> =>
localResult(baseUrl, `/api/session/${encodeURIComponent(parameters.sessionID)}/todo`, []),
@@ -1583,16 +1628,11 @@ export function createClientV2(
response: new Response(null, { status: 400 }),
};
}
- const modelResult = await request(
- "POST",
- `/api/session/${encodeURIComponent(parameters.sessionID)}/model`,
- { model: { providerID: parameters.model.providerID, id: parameters.model.modelID } },
- options?.signal,
- );
+ const modelResult = await selectModel(parameters.sessionID, parameters.model, options);
if (!modelResult.response.ok) return failedResult(modelResult);
if (parameters.system !== undefined) {
const instructions = await request("PUT",
- `/api/session/${encodeURIComponent(parameters.sessionID)}/instructions/entries/omnirush-context`,
+ `/api/experimental/session/${encodeURIComponent(parameters.sessionID)}/instructions/entries/omnirush-context`,
{ value: parameters.system }, options?.signal);
if (!instructions.response.ok) return failedResult(instructions);
}
@@ -1629,7 +1669,7 @@ export function createClientV2(
parameters: SessionUpdateParameters,
options?: RequestOptions,
): Promise<FieldsResult<Session>> => {
- // The native preview exposes archived state but no archive mutation.
+ // 2.x sessions expose time.archived, but PATCH /api/session/{id} cannot set it.
// Reject the entire update before a rename or read can imply success.
if (parameters.time?.archived !== undefined) {
if (options?.throwOnError) throw new Error(V2_SESSION_ARCHIVE_UNAVAILABLE);
@@ -1637,14 +1677,12 @@ export function createClientV2(
}
if (!parameters.title) return getSession(parameters, options);
const result = await request(
- "POST",
- `/api/session/${encodeURIComponent(parameters.sessionID)}/rename`,
+ "PATCH",
+ `/api/session/${encodeURIComponent(parameters.sessionID)}`,
{ title: parameters.title },
options?.signal,
);
- if (!result.response.ok) return failedResult(result);
- const mapped = mapV2Session(result.payload, directory);
- return mapped ? successfulResult(result, mapped) : getSession(parameters, options);
+ return result.response.ok ? getSession(parameters, options) : failedResult(result);
},
delete: async (
parameters: SessionParameters,
@@ -1658,24 +1696,64 @@ export function createClientV2(
);
return result.response.ok ? successfulResult(result, true) : failedResult(result);
},
- fork: async (): Promise<FieldsResult<Session>> => unsupportedResult(baseUrl, "session.fork"),
- revert: async (): Promise<FieldsResult<Session>> => unsupportedResult(baseUrl, "session.revert"),
- unrevert: async (): Promise<FieldsResult<Session>> => unsupportedResult(baseUrl, "session.unrevert"),
- summarize: async (): Promise<FieldsResult<boolean>> => unsupportedResult(baseUrl, "session.summarize"),
- shell: async (): Promise<FieldsResult<Record<string, never>>> => unsupportedResult(baseUrl, "session.shell"),
- command: async (): Promise<FieldsResult<Record<string, never>>> => unsupportedResult(baseUrl, "session.command"),
+ fork: async (
+ parameters: SessionParameters & { messageID?: string },
+ options?: RequestOptions,
+ ): Promise<FieldsResult<Session>> => {
+ // v1 forks copy the messages before messageID; 2.x calls that boundary `before`.
+ const result = await request("POST", `/api/session/${encodeURIComponent(parameters.sessionID)}/fork`,
+ parameters.messageID ? { before: parameters.messageID } : {}, options?.signal);
+ if (!result.response.ok) return failedResult(result);
+ const forked = mapV2Session(result.payload, directory);
+ return forked ? successfulResult(result, forked) : failedResult({ ...result, payload: { name: "InvalidV2SessionResponse" } });
+ },
+ // Staging restores files and hides the turns; the next prompt commits it
+ // and unrevert drops it, which is the v1 soft-revert contract. An explicit
+ // commit would make the revert permanent at once.
+ revert: async (
+ parameters: SessionParameters & { messageID: string; partID?: string },
+ options?: RequestOptions,
+ ): Promise<FieldsResult<Session>> => thenSession(await request("POST",
+ `/api/session/${encodeURIComponent(parameters.sessionID)}/revert/stage`,
+ { messageID: parameters.messageID }, options?.signal), parameters.sessionID, options),
+ unrevert: async (parameters: SessionParameters, options?: RequestOptions): Promise<FieldsResult<Session>> =>
+ thenSession(await request("DELETE", `/api/session/${encodeURIComponent(parameters.sessionID)}/revert`,
+ undefined, options?.signal), parameters.sessionID, options),
+ summarize: async (parameters: SessionParameters, options?: RequestOptions): Promise<FieldsResult<boolean>> => {
+ const result = await request("POST", `/api/session/${encodeURIComponent(parameters.sessionID)}/compact`, {}, options?.signal);
+ return result.response.ok ? successfulResult(result, true) : failedResult(result);
+ },
+ shell: async (
+ parameters: SessionParameters & { command: string },
+ options?: RequestOptions,
+ ): Promise<FieldsResult<Record<string, never>>> => {
+ const result = await request("POST", `/api/session/${encodeURIComponent(parameters.sessionID)}/shell`,
+ { command: parameters.command }, options?.signal);
+ return result.response.ok ? successfulResult(result, {}) : failedResult(result);
+ },
+ command: async (
+ parameters: SessionParameters & { command: string; arguments?: string; model?: string },
+ options?: RequestOptions,
+ ): Promise<FieldsResult<Record<string, never>>> => {
+ // v1 passes "provider/model"; 2.x commands run on the session model.
+ const slash = parameters.model?.indexOf("/") ?? -1;
+ if (parameters.model && slash > 0) {
+ const modelResult = await selectModel(parameters.sessionID,
+ { providerID: parameters.model.slice(0, slash), modelID: parameters.model.slice(slash + 1) }, options);
+ if (!modelResult.response.ok) return failedResult(modelResult);
+ }
+ const result = await request("POST", `/api/session/${encodeURIComponent(parameters.sessionID)}/command`,
+ { name: parameters.command, text: parameters.arguments ?? "" }, options?.signal);
+ return result.response.ok ? successfulResult(result, {}) : failedResult(result);
+ },
};
const adapter = {
global: {
health: async (options?: RequestOptions): Promise<FieldsResult<{ healthy: boolean; version: string }>> => {
- const result = await request("GET", "/api/health", undefined, options?.signal);
+ const result = await request("GET", "/api/info", undefined, options?.signal);
if (!result.response.ok) return failedResult(result);
- const data = responseData(result.payload);
- return successfulResult(result, {
- healthy: isRecord(data) && data.healthy === true,
- version: readString(data, "version") ?? "v2",
- });
+ return successfulResult(result, { healthy: true, version: readString(result.payload, "version") ?? "v2" });
},
},
session,
diff --git a/apps/app/tests/opencode-session-native.test.ts b/apps/app/tests/opencode-session-native.test.ts
index c349aacb..26c8e984 100644
--- a/apps/app/tests/opencode-session-native.test.ts
+++ b/apps/app/tests/opencode-session-native.test.ts
@@ -567,12 +567,13 @@ describe("native Stop and follow-up handoff", () => {
id, title: "Native turn", location: { directory: session.directory }, time: { created: 1, updated: 2 },
...(id === childID ? { parentID: rootID } : {}),
} });
+ // Native history pages are newest first.
if (action === "message") return Response.json({ data: [
- { id: "msg_user", type: "user", time: { created: 1 }, content: [] },
{ id: "msg_assistant", type: "assistant", time: { created: 2 }, content: id === rootID ? [{
type: "tool", id: "call_child", name: "subagent", time: { created: 2, ran: 2 },
state: { status: "running", input: { agent: "explore" }, metadata: { sessionID: childID } },
}] : [] },
+ { id: "msg_user", type: "user", time: { created: 1 }, content: [] },
] });
if (action === "interrupt") { events.push(`interrupt:${id}`); return Response.json({ data: { interrupted: true } }); }
if (action === "model") return Response.json({ data: {} });
diff --git a/apps/app/tests/opencode-v2-adapter.test.ts b/apps/app/tests/opencode-v2-adapter.test.ts
index a761d1e2..bb0dac2a 100644
--- a/apps/app/tests/opencode-v2-adapter.test.ts
+++ b/apps/app/tests/opencode-v2-adapter.test.ts
@@ -4,6 +4,7 @@ import {
createClientV2,
createV2EventTranslationState,
translateV2Event,
+ V2_SESSION_ARCHIVE_UNAVAILABLE,
} from "../src/app/lib/opencode-v2-adapter";
import { parseDynamicToolUIPart } from "../src/react-app/domains/session/sync/parse-tool-parts";
import { codeModeToolCalls } from "../src/lib/code-mode-tools";
@@ -676,7 +677,7 @@ describe("OpenCode v2 client compatibility", () => {
expect(result.data).toBeUndefined();
expect(result.error).toMatchObject({
name: "UnsupportedInV2Preview", operation: "session.archive",
- message: "Archiving and unarchiving are not available in the OpenCode v2 preview.",
+ message: V2_SESSION_ARCHIVE_UNAVAILABLE,
});
await expect(client.session.update(parameters, { throwOnError: true })).rejects.toThrow("Archiving and unarchiving are not available");
}
@@ -712,10 +713,12 @@ describe("OpenCode v2 client compatibility", () => {
const originalFetch = globalThis.fetch;
const notice = "New skills are available in addition to those previously listed.";
globalThis.fetch = async () => jsonResponse({ data: [
- { id: "msg_system", type: "system", text: notice, time: { created: 1 } },
- { id: "msg_synthetic", type: "synthetic", text: "Internal context", time: { created: 2 } },
- { id: "msg_user", type: "user", text: notice, time: { created: 3 } },
+ { id: "msg_idle", type: "idle", outcome: "succeeded", time: { created: 6 } },
+ { id: "msg_switch", type: "model-switched", model: { id: "m", providerID: "p" }, time: { created: 5 } },
{ id: "msg_answer", type: "assistant", content: [{ type: "text", text: "The current report code." }], time: { created: 4 } },
+ { id: "msg_user", type: "user", text: notice, time: { created: 3 } },
+ { id: "msg_synthetic", type: "synthetic", text: "Internal context", time: { created: 2 } },
+ { id: "msg_system", type: "system", text: notice, time: { created: 1 } },
] });
try {
const client = createClientV2("http://opencode.test/opencode2", "/workspace", {});
@@ -882,7 +885,7 @@ describe("OpenCode v2 client compatibility", () => {
globalThis.fetch = async () => jsonResponse({ data: states.map((state) => ({
id: "msg_parent", type: "assistant", time: { created: 5 },
content: [{ type: "tool", id: "call_child", name, state, time: { created: 10, ran: 20, completed: 30 } }],
- })) });
+ })).reverse() });
try {
const client = createClientV2("http://opencode.test/opencode2", "/workspace", {});
const result = await client.session.messages({ sessionID: "ses_parent" });
@@ -1004,7 +1007,7 @@ describe("OpenCode v2 client compatibility", () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init);
- if (request.method === "GET" && request.url.endsWith("/api/session/ses_failed/message")) {
+ if (request.method === "GET" && new URL(request.url).pathname.endsWith("/api/session/ses_failed/message")) {
return jsonResponse({ data: [{
id: "msg_failed",
type: "assistant",
@@ -1064,7 +1067,7 @@ describe("OpenCode v2 client compatibility", () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init);
- if (request.method === "GET" && request.url.endsWith("/api/session/ses_tool/message")) {
+ if (request.method === "GET" && new URL(request.url).pathname.endsWith("/api/session/ses_tool/message")) {
return jsonResponse({ data: [capturedV2ToolMessage] });
}
throw new Error(`Unexpected request: ${request.method} ${request.url}`);
@@ -1209,8 +1212,11 @@ describe("OpenCode v2 client compatibility", () => {
["GET", "/workspace/owned/opencode2/api/event"], ["GET", "/workspace/owned/opencode2/api/session/ses_fork"],
]);
expect(requests.every((request) => request.headers.get("Authorization") === "Bearer fixture-token")).toBe(true);
- expect((await client.session.fork({ sessionID: "ses_source" })).response.status).toBe(501);
- expect(requests).toHaveLength(2);
+ const fork = await client.session.fork({ sessionID: "ses_source", messageID: "msg_source" });
+ expect(fork.data?.id).toBe("ses_fork");
+ expect(fork.data?.parentID).toBeUndefined();
+ expect([requests[2]?.method, new URL(requests[2]?.url ?? "").pathname]).toEqual(["POST", "/workspace/owned/opencode2/api/session/ses_source/fork"]);
+ expect(await requests[2]?.json()).toEqual({ before: "msg_source" });
} finally { globalThis.fetch = originalFetch; }
});
@@ -1585,7 +1591,7 @@ describe("OpenCode v2 client compatibility", () => {
});
expect(reply.error).toBeUndefined();
expect(reply.response.status).toBe(204);
- expect(replyBodies).toEqual([{ reply: "always" }, { reply: "once" }]);
+ expect(replyBodies).toEqual([{ decision: "always" }, { decision: "once" }]);
} finally {
globalThis.fetch = originalFetch;
}
@@ -1647,22 +1653,22 @@ describe("v2 question forms", () => {
test("an interaction client can answer a live form it never listed, preserving values and custom text", async () => {
const originalFetch = globalThis.fetch;
- const writes: { path: string; body: unknown }[] = [];
+ const writes: { method: string; path: string; body: unknown }[] = [];
globalThis.fetch = async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init);
const path = new URL(request.url).pathname;
- if (request.method === "GET" && path.endsWith("/api/form/request")) return Response.json({ data: [form] });
- writes.push({ path, body: request.body ? await request.json() : null });
+ if (request.method === "GET" && path.endsWith("/api/form")) return Response.json({ data: [form] });
+ writes.push({ method: request.method, path, body: request.body ? await request.json() : null });
return new Response(null, { status: 204 });
};
try {
const client = createClientV2("http://owner.test/opencode2", "/workspace", {});
expect((await client.question.reply({ requestID: form.id, answers: [["Summary"], ["Facts", "Custom section"]] })).data).toBe(true);
- expect(writes).toEqual([{ path: "/opencode2/api/session/ses_side/form/frm_choice/reply", body: {
+ expect(writes).toEqual([{ method: "POST", path: "/opencode2/api/session/ses_side/form/frm_choice/reply", body: {
answer: { q0: "summary_value", q1: ["facts_value", "Custom section"] },
} }]);
expect((await client.question.reject({ requestID: form.id })).data).toBe(true);
- expect(writes.at(-1)?.path).toBe("/opencode2/api/session/ses_side/form/frm_choice/cancel");
+ expect(writes.at(-1)).toEqual({ method: "DELETE", path: "/opencode2/api/session/ses_side/form/frm_choice", body: null });
} finally { globalThis.fetch = originalFetch; }
});
@@ -1704,7 +1710,7 @@ describe("v2 question forms", () => {
system: "Main conversation reference: ses_main", parts: [{ type: "text", text: "What is happening?" }] };
expect((await client.session.promptAsync(parameters)).response.status).toBe(204);
expect(requests.map((item) => item.method)).toEqual(["POST", "PUT", "POST"]);
- expect(requests[1]).toMatchObject({ path: "/opencode2/api/session/ses_side/instructions/entries/omnirush-context", body: { value: parameters.system } });
+ expect(requests[1]).toMatchObject({ path: "/opencode2/api/experimental/session/ses_side/instructions/entries/omnirush-context", body: { value: parameters.system } });
expect(requests[2]?.body).toEqual({ text: "What is happening?" });
requests.length = 0; status = 503;
expect((await client.session.promptAsync(parameters)).response.status).toBe(503);
@@ -1712,3 +1718,146 @@ describe("v2 question forms", () => {
} finally { globalThis.fetch = originalFetch; }
});
});
+
+describe("OpenCode 2.0.32 routes", () => {
+ // Shapes captured from a stock 2.0.32 `opencode serve`.
+ const session = {
+ id: "ses_main", projectID: "project", title: "Main", cost: 0, location: { directory: "/workspace" },
+ time: { created: 1, updated: 2 }, revert: { messageID: "msg_user", snapshot: "abc", files: [] },
+ };
+
+ async function withRoutes(
+ handle: (request: Request, path: string) => Response | Promise<Response>,
+ run: (client: ReturnType<typeof createClientV2>, calls: { method: string; path: string; body: unknown }[]) => Promise<void>,
+ ) {
+ const originalFetch = globalThis.fetch;
+ const calls: { method: string; path: string; body: unknown }[] = [];
+ globalThis.fetch = async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ const url = new URL(request.url);
+ const path = url.pathname.replace("/opencode2", "") + url.search;
+ calls.push({ method: request.method, path, body: request.body ? await request.clone().json() : null });
+ return handle(request, path);
+ };
+ try { await run(createClientV2("http://owner.test/opencode2", "/workspace", {}), calls); } finally { globalThis.fetch = originalFetch; }
+ }
+
+ test("health reads /api/info and rename patches the session then rereads it", async () => {
+ await withRoutes((request, path) => path === "/api/info"
+ ? Response.json({ version: "2.0.32", pid: 1, urls: [], paths: { tmp: "/tmp" } })
+ : request.method === "PATCH" ? new Response(null, { status: 204 }) : Response.json({ data: { ...session, title: "Renamed" } }),
+ async (client, calls) => {
+ expect((await client.global.health()).data).toEqual({ healthy: true, version: "2.0.32" });
+ const renamed = await client.session.update({ sessionID: "ses_main", title: "Renamed" });
+ expect(renamed.data?.title).toBe("Renamed");
+ expect(renamed.data?.revert).toEqual({ messageID: "msg_user", snapshot: "abc" });
+ expect(calls.slice(1)).toEqual([
+ { method: "PATCH", path: "/api/session/ses_main", body: { title: "Renamed" } },
+ { method: "GET", path: "/api/session/ses_main", body: null },
+ ]);
+ });
+ });
+
+ test("revert stages without committing, unrevert clears, and compact, shell and command use native routes", async () => {
+ await withRoutes((request, path) => {
+ if (path.endsWith("/revert/stage")) return Response.json({ data: session.revert });
+ if (path.endsWith("/compact")) return Response.json({ data: { id: "msg_compact", type: "compaction" } });
+ if (request.method === "GET") return Response.json({ data: session });
+ return new Response(null, { status: 204 });
+ }, async (client, calls) => {
+ expect((await client.session.revert({ sessionID: "ses_main", messageID: "msg_user", partID: "p" })).data?.revert?.messageID).toBe("msg_user");
+ expect((await client.session.unrevert({ sessionID: "ses_main" })).data?.id).toBe("ses_main");
+ expect((await client.session.summarize({ sessionID: "ses_main", providerID: "mock", modelID: "m1" })).data).toBe(true);
+ expect((await client.session.shell({ sessionID: "ses_main", command: "echo hi", agent: "build" })).error).toBeUndefined();
+ expect((await client.session.command({ sessionID: "ses_main", command: "init", arguments: "focus", model: "mock/m1" })).error).toBeUndefined();
+ expect(calls).toEqual([
+ { method: "POST", path: "/api/session/ses_main/revert/stage", body: { messageID: "msg_user" } },
+ { method: "GET", path: "/api/session/ses_main", body: null },
+ { method: "DELETE", path: "/api/session/ses_main/revert", body: null },
+ { method: "GET", path: "/api/session/ses_main", body: null },
+ { method: "POST", path: "/api/session/ses_main/compact", body: {} },
+ { method: "POST", path: "/api/session/ses_main/shell", body: { command: "echo hi" } },
+ { method: "POST", path: "/api/session/ses_main/model", body: { model: { providerID: "mock", id: "m1" } } },
+ { method: "POST", path: "/api/session/ses_main/command", body: { name: "init", text: "focus" } },
+ ]);
+ });
+ });
+
+ test("a failed native op stays a failure", async () => {
+ await withRoutes(() => Response.json({ message: "busy" }, { status: 409 }), async (client, calls) => {
+ expect((await client.session.revert({ sessionID: "ses_main", messageID: "msg_user" })).response.status).toBe(409);
+ expect((await client.session.command({ sessionID: "ses_main", command: "init", model: "mock/m1" })).response.status).toBe(409);
+ expect(calls.map((call) => call.path)).toEqual(["/api/session/ses_main/revert/stage", "/api/session/ses_main/model"]);
+ });
+ });
+
+ test("history pages newest first through cursors and returns the latest messages oldest first", async () => {
+ const message = (n: number) => ({ id: `msg_${n}`, type: "user", text: `m${n}`, time: { created: n } });
+ await withRoutes((_request, path) => {
+ const cursor = new URL(`http://x${path}`).searchParams.get("cursor");
+ const start = cursor ? Number(cursor) : 250;
+ const limit = Number(new URL(`http://x${path}`).searchParams.get("limit"));
+ const data = Array.from({ length: Math.min(limit, start) }, (_, index) => start - index === 249
+ ? { id: "msg_idle", type: "idle", outcome: "succeeded", time: { created: 249 } } : message(start - index));
+ return Response.json({ data, cursor: { next: String(start - data.length) } });
+ }, async (client, calls) => {
+ const all = await client.session.messages({ sessionID: "ses_main" });
+ expect(all.data?.map((item) => item.info.id).slice(0, 2)).toEqual(["msg_1", "msg_2"]);
+ expect(all.data).toHaveLength(249);
+ expect(calls.map((call) => call.path)).toEqual([
+ "/api/session/ses_main/message?limit=200&order=desc",
+ "/api/session/ses_main/message?limit=200&cursor=50",
+ ]);
+ calls.length = 0;
+ const latest = await client.session.messages({ sessionID: "ses_main", limit: 3 });
+ expect(latest.data?.map((item) => item.info.id)).toEqual(["msg_247", "msg_248", "msg_250"]);
+ expect(calls.map((call) => call.path)).toEqual([
+ "/api/session/ses_main/message?limit=3&order=desc",
+ "/api/session/ses_main/message?limit=1&cursor=247",
+ ]);
+ });
+ });
+
+ test("a user shell message renders as one bash card and its synthetic notice stays hidden", async () => {
+ await withRoutes(() => Response.json({ data: [
+ { id: "msg_notice", type: "synthetic", text: "<shell id=\"sh_1\" state=\"completed\" command=\"echo hi\">\nhi\n</shell>",
+ metadata: { source: "shell", shellID: "sh_1" }, time: { created: 3 } },
+ { id: "msg_shell", type: "shell", shellID: "sh_1", command: "echo hi", status: "exited", exit: 0,
+ output: { output: "hi\n", cursor: 3, size: 3, truncated: false }, time: { created: 2, completed: 3 } },
+ ] }), async (client) => {
+ const result = await client.session.messages({ sessionID: "ses_main" });
+ expect(result.data).toHaveLength(1);
+ expect(result.data?.[0]?.info.role).toBe("assistant");
+ expect(result.data?.[0]?.parts).toMatchObject([{ type: "tool", tool: "bash", callID: "sh_1",
+ state: { status: "completed", input: { command: "echo hi" }, output: "hi\n" } }]);
+ });
+ });
+
+ test("revert events move the session cursor", () => {
+ const state = createV2EventTranslationState();
+ expect(translateV2Event({ type: "session.revert.staged", data: { sessionID: "ses_main", revert: session.revert } }, state))
+ .toEqual([{ type: "session.updated", properties: { info: { id: "ses_main", revert: { messageID: "msg_user" } } } }]);
+ for (const type of ["session.revert.cleared", "session.revert.committed"]) {
+ expect(translateV2Event({ type, data: { sessionID: "ses_main", to: "msg_user" } }, state))
+ .toEqual([{ type: "session.updated", properties: { info: { id: "ses_main" } } }]);
+ }
+ expect(translateV2Event({ type: "permission.replied", data: { sessionID: "ses_main", requestID: "per_1", decision: "always" } }, state))
+ .toEqual([{ type: "permission.replied", properties: { sessionID: "ses_main", requestID: "per_1", reply: "always" } }]);
+ });
+
+ test.each([
+ ["read", { path: "a.py" }, "read", { filePath: "a.py", path: "a.py" }],
+ ["write", { path: "b.txt", content: "x" }, "write", { filePath: "b.txt", path: "b.txt", content: "x" }],
+ ["edit", { path: "a.py", oldString: "1", newString: "2" }, "edit", { filePath: "a.py", path: "a.py" }],
+ ["skill", { id: "pdf" }, "skill", { name: "pdf", id: "pdf" }],
+ ["patch", { patchText: "*** Begin Patch" }, "apply_patch", { patchText: "*** Begin Patch" }],
+ ["websearch", { query: "news" }, "websearch", { query: "news" }],
+ ])("native %s calls render with the card's field names", (name, input, tool, expected) => {
+ const state = createV2EventTranslationState();
+ const identity = { sessionID: "ses_main", assistantMessageID: "msg_a", id: "call_1" };
+ translateV2Event({ type: "session.tool.input.started", data: { ...identity, name } }, state);
+ expect(translateV2Event({ type: "session.tool.called", created: 1, data: { ...identity, input } }, state))
+ .toMatchObject([{ properties: { part: { tool, state: { status: "running", input: expected } } } }]);
+ expect(input).not.toHaveProperty("filePath");
+ });
+});
diff --git a/apps/app/tests/session-sync-permissions.test.ts b/apps/app/tests/session-sync-permissions.test.ts
index 6546097c..5c793081 100644
--- a/apps/app/tests/session-sync-permissions.test.ts
+++ b/apps/app/tests/session-sync-permissions.test.ts
@@ -144,7 +144,7 @@ describe("session permission sync", () => {
const path = new URL(request.url).pathname;
if (path.endsWith("/api/session")) throw new Error("Unrelated session sweep must not run");
if (path.endsWith("/api/session/session-a/permission") && hold) return delayed.promise;
- if ((path.endsWith("/form/request") || path.endsWith("/question")) && hold) return delayedQuestion.promise;
+ if ((path.endsWith("/form") || path.endsWith("/question")) && hold) return delayedQuestion.promise;
if (path.endsWith("/api/session/session-child/permission")) {
return Response.json({ data: [v2Permission("perm-child", "session-child")] });
}
@@ -183,7 +183,7 @@ describe("session permission sync", () => {
hold = true;
await act(async () => render("session-a"));
const oldPermission = calls.findLast((request) => new URL(request.url).pathname.endsWith("/session-a/permission"));
- const oldQuestion = calls.findLast((request) => /\/(question|form\/request)$/.test(new URL(request.url).pathname));
+ const oldQuestion = calls.findLast((request) => /\/(question|form)$/.test(new URL(request.url).pathname));
expect(oldPermission?.signal.aborted).toBe(false);
expect(oldQuestion?.signal.aborted).toBe(false);
await act(async () => render("session-b"));