A desktop coding agent with free access to frontier models.
TypeScript
feat: archive chats on the new engine
ogsamrate57aa22e719c
diff --git a/apps/app/src/app/lib/opencode-v2-adapter.ts b/apps/app/src/app/lib/opencode-v2-adapter.tsindex cf92c065..ce6e3cf3 100644--- a/apps/app/src/app/lib/opencode-v2-adapter.ts+++ b/apps/app/src/app/lib/opencode-v2-adapter.ts@@ -68,7 +68,6 @@ type SessionUpdateParameters = SessionParameters & {time?: { archived?: number };};-export const V2_SESSION_ARCHIVE_UNAVAILABLE = "Archiving and unarchiving are not available in the OmniRush v2 preview.";type PermissionReply = "once" | "always" | "reject";@@ -1696,17 +1695,14 @@ export function createClientV2(parameters: SessionUpdateParameters,options?: RequestOptions,): Promise<FieldsResult<Session>> => {- // 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);- return unsupportedResult(baseUrl, "session.archive", V2_SESSION_ARCHIVE_UNAVAILABLE);- }- if (!parameters.title) return getSession(parameters, options);+ // Archiving is the app's own flag (the server keeps it; it never reaches the engine): `archived` on the+ // same PATCH, a time to archive, 0 or null to unarchive.+ const archived = parameters.time?.archived;+ if (!parameters.title && archived === undefined) return getSession(parameters, options);const result = await request("PATCH",`/api/session/${encodeURIComponent(parameters.sessionID)}`,- { title: parameters.title },+ { ...(parameters.title ? { title: parameters.title } : {}), ...(archived === undefined ? {} : { archived: archived || null }) },options?.signal,);return result.response.ok ? getSession(parameters, options) : failedResult(result);diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex b88c0f13..adcf333d 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -24,7 +24,7 @@ import { downloadTextAsFile } from "@/app/lib/download";import { canCreateWorkspaces } from "@/app/lib/workspace-creation-policy";import { useQueryClient } from "@tanstack/react-query";import { isPromptAdmissionUnknown, unwrap } from "@/app/lib/opencode";-import { createClientV2, isOpencodeV2BaseUrl, V2_SESSION_ARCHIVE_UNAVAILABLE } from "@/app/lib/opencode-v2-adapter";+import { createClientV2 } from "@/app/lib/opencode-v2-adapter";import { abortSessionSafe, forkSession, listCommands, revertSession, setSessionArchived, shellInSession, unrevertSession } from "@/app/lib/opencode-session";import { getNativeSessionMessages } from "@/app/lib/opencode-session-native";import { copySessionId } from "@/react-app/domains/session/sidebar/copy-session-id";@@ -561,7 +561,8 @@ export function SessionRoute() {locationKey: location.key,navigationGeneration: routeNavigationRef.current.generation,};- const archiveDisabledReason = isOpencodeV2BaseUrl(opencodeBaseUrl) ? V2_SESSION_ARCHIVE_UNAVAILABLE : undefined;+ // Archiving is the app's own flag on 2.x (the server keeps it): always available.+ const archiveDisabledReason: string | undefined = undefined;// The dashboard is user-scoped while MCP servers are workspace-scoped: the// selected workspace's runtime is primary, and every other available one is// a per-tile fallback so tiles keep working when the selected workspace doesdiff --git a/apps/app/tests/opencode-v2-adapter.test.ts b/apps/app/tests/opencode-v2-adapter.test.tsindex 09ecac5e..8862189b 100644--- a/apps/app/tests/opencode-v2-adapter.test.ts+++ b/apps/app/tests/opencode-v2-adapter.test.ts@@ -4,7 +4,6 @@ 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";@@ -661,27 +660,19 @@ describe("OpenCode v2 event translation", () => {});describe("OpenCode v2 client compatibility", () => {- test.each([0, 1_788_548_737_221])("rejects archived=%i without reading, renaming, or deleting the session", async (archived) => {+ test.each([0, 1_788_548_737_221])("archives (archived=%i) through the server's own flag on the session PATCH", async (archived) => {const originalFetch = globalThis.fetch;- const requests: Request[] = [];+ const sent: Array<{ method: string; path: string; body: unknown }> = [];globalThis.fetch = async (input, init) => {- requests.push(input instanceof Request ? input : new Request(input, init));- return jsonResponse({ data: { id: "ses_archive", title: "Keep this session", time: { created: 1 } } });+ const request = input instanceof Request ? input : new Request(input, init);+ sent.push({ method: request.method, path: new URL(request.url).pathname, body: request.method === "PATCH" ? await request.json() : null });+ return jsonResponse({ data: { id: "ses_archive", title: "Keep", time: { created: 1, ...(archived ? { archived } : {}) } } });};try {const client = createClientV2("http://opencode.test/opencode2", "/workspace", {});- for (const title of [undefined, "Do not partially rename"]) {- const parameters = { sessionID: "ses_archive", title, time: { archived } };- const result = await client.session.update(parameters);- expect(result.response.status).toBe(501);- expect(result.data).toBeUndefined();- expect(result.error).toMatchObject({- name: "UnsupportedInV2Preview", operation: "session.archive",- message: V2_SESSION_ARCHIVE_UNAVAILABLE,- });- await expect(client.session.update(parameters, { throwOnError: true })).rejects.toThrow("Archiving and unarchiving are not available");- }- expect(requests).toEqual([]);+ const result = await client.session.update({ sessionID: "ses_archive", title: "Renamed", time: { archived } });+ expect(result.data?.time.archived).toBe(archived || undefined);+ expect(sent[0]).toEqual({ method: "PATCH", path: "/opencode2/api/session/ses_archive", body: { title: "Renamed", archived: archived || null } });} finally {globalThis.fetch = originalFetch;}diff --git a/apps/server/src/archived-chats.ts b/apps/server/src/archived-chats.tsnew file mode 100644index 00000000..5d9bc9ee--- /dev/null+++ b/apps/server/src/archived-chats.ts@@ -0,0 +1,52 @@+/**+ * Archived chats on the 2.x engine: the app's own flag (the engine has no way to set it). Kept in the server's+ * runtime storage only; it never reaches the engine or an upload. The engine's v2 mount (server.ts) applies it:+ * a session PATCH's `archived` sets or clears it, and session reads carry it as `time.archived`.+ */+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++const FILE = "archived-chats.json";+const MAX = 20_000;++function read(dir: string): Record<string, number> {+ try {+ const parsed: unknown = JSON.parse(readFileSync(join(dir, FILE), "utf8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, number] => typeof entry[1] === "number" && entry[1] > 0));+ } catch {+ return {};+ }+}++/** When `sessionId` was archived, or undefined. */+export function archivedAt(dir: string, sessionId: string): number | undefined {+ return read(dir)[sessionId];+}++/** Sets (a time) or clears (null) a chat's archived flag. */+export function setArchived(dir: string, sessionId: string, at: number | null): void {+ const all = read(dir);+ if (at) all[sessionId] = at;+ else delete all[sessionId];+ const entries = Object.entries(all).slice(-MAX);+ const file = join(dir, FILE);+ mkdirSync(dirname(file), { recursive: true });+ const temp = `${file}.${process.pid}.tmp`;+ writeFileSync(temp, JSON.stringify(Object.fromEntries(entries)), { mode: 0o600 });+ renameSync(temp, file);+}++/** A session record (2.x `{id, time}`) with the app's archived flag applied. */+export function withArchived(dir: string, session: unknown, flags = read(dir)): unknown {+ if (!session || typeof session !== "object" || Array.isArray(session)) return session;+ const record = session as Record<string, unknown>;+ const id = typeof record.id === "string" ? record.id : null;+ if (!id) return session;+ const time = record.time && typeof record.time === "object" && !Array.isArray(record.time) ? { ...(record.time as Record<string, unknown>) } : {};+ if (flags[id]) time.archived = flags[id];+ else delete time.archived;+ return { ...record, time };+}++export const readArchivedChats = read;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex f808c6b6..c9b559d1 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -235,6 +235,7 @@ import { createEngineV2Preview, resolveInitialEngineV2PreviewState, type EngineVimport { MIGRATED_FROM } from "./engine-v2-migration.js";import { createV2BudgetWrap } from "./engine-v2-budget-wrap.js";import { convertOfficeAttachments } from "./engine-v2-attachments.js";+import { readArchivedChats, setArchived, withArchived } from "./archived-chats.js";import { createEditorLsp, LSP_OPS, type LspOp, type LspPayload } from "./editor-lsp.js";import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";@@ -2229,6 +2230,27 @@ export async function proxyOpencodeV2Request(input: {headers.delete("content-length");headers.set("content-type", "application/json");}+ // Archiving (archived-chats.ts): the app's own flag, taken off the PATCH before the engine sees it.+ if (method === "PATCH" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath) && requestBody) {+ let patch: unknown = null;+ try { patch = JSON.parse(new TextDecoder().decode(requestBody)); } catch { patch = null; }+ if (isRecord(patch) && Object.hasOwn(patch, "archived")) {+ const at = typeof patch.archived === "number" && patch.archived > 0 ? patch.archived : null;+ setArchived(runtimeStorageDir(input.config), sessionId, at);+ const { archived: _archived, ...rest } = patch;+ if (Object.keys(rest).length === 0) {+ const read = new URL(target);+ const answer = await loopbackFetch(read.toString(), { headers: new Headers({ authorization: headers.get("authorization") ?? "" }), signal: AbortSignal.timeout(10_000) });+ if (!answer.ok) return sanitizeProxyResponse(answer);+ const payload: unknown = await answer.json();+ const data = isRecord(payload) && "data" in payload ? payload.data : payload;+ return jsonResponse({ data: withArchived(runtimeStorageDir(input.config), data) });+ }+ body = JSON.stringify(rest);+ headers.delete("content-length");+ headers.set("content-type", "application/json");+ }+ }if (method === "POST" && /^\/api\/session\/[^/]+\/prompt$/.test(routePath) && requestBody) {// Office files the engine would drop go in as their text (engine-v2-attachments.ts).let promptInput: unknown = null;@@ -2400,13 +2422,17 @@ export async function proxyOpencodeV2Request(input: {const items = Array.isArray(data) ? data : isRecord(data) && Array.isArray(data.items) ? data.items : null;if (!items) throw new ApiError(502, "invalid_engine_response", "Invalid session list response");const expected = await realpath(input.workspace.path).catch(() => input.workspace.path);+ const flags = readArchivedChats(runtimeStorageDir(input.config));const scoped = (await Promise.all(items.map(async (item: unknown) => {const session = isRecord(item) && isRecord(item.info) ? item.info : item;const location = isRecord(session) && isRecord(session.location) ? session.location : null;const directory = location && typeof location.directory === "string" ? location.directory : null;if (!directory) return null;const actual = await realpath(directory).catch(() => directory);- return actual === expected ? item : null;+ if (actual !== expected) return null;+ return isRecord(item) && isRecord(item.info)+ ? { ...item, info: withArchived(runtimeStorageDir(input.config), item.info, flags) }+ : withArchived(runtimeStorageDir(input.config), item, flags);}))).filter((item) => item !== null);const scopedData = isRecord(data) ? { ...data, items: scoped } : scoped;const scopedPayload = isRecord(payload) && "data" in payload ? { ...payload, data: scopedData } : scopedData;@@ -2415,6 +2441,12 @@ export async function proxyOpencodeV2Request(input: {responseHeaders.delete("content-encoding");return sanitizeProxyResponse(new Response(JSON.stringify(scopedPayload), { status: response.status, headers: responseHeaders }));}+ if (method === "GET" && /^\/api\/session\/[^/]+$/.test(routePath) && response.ok) {+ const payload: unknown = await response.json();+ const data = isRecord(payload) && "data" in payload ? payload.data : payload;+ const shaped = isRecord(data) && isRecord(data.info) ? { ...data, info: withArchived(runtimeStorageDir(input.config), data.info) } : withArchived(runtimeStorageDir(input.config), data);+ return jsonResponse(isRecord(payload) && "data" in payload ? { ...payload, data: shaped } : shaped, response.status);+ }return sanitizeProxyResponse(response);}