A desktop coding agent with free access to frontier models.
TypeScript
fix: chats stay listed when their folder becomes a git repo or is spelled differently
ogsamrat8e4002a1df37
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 410847f2..8689d800 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -2345,8 +2345,8 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: sbody: payload,timeoutMs: timeouts.config,}),- listWorkspaceSessionsByFolder: (workspaceId: string, limit: number) =>- requestJson<unknown[]>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/sessions/by-folder?limit=${limit}`, {+ listWorkspaceSessionsByFolder: (workspaceId: string, limit: number, engine?: "v2") =>+ requestJson<unknown[]>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/sessions/by-folder?limit=${limit}${engine ? `&engine=${engine}` : ""}`, {token,hostToken,timeoutMs: 45_000,diff --git a/apps/app/src/app/lib/opencode-v2-adapter.ts b/apps/app/src/app/lib/opencode-v2-adapter.tsindex 2c6c551b..e90efcdc 100644--- a/apps/app/src/app/lib/opencode-v2-adapter.ts+++ b/apps/app/src/app/lib/opencode-v2-adapter.ts@@ -236,7 +236,7 @@ function readMessageID(value: Record<string, unknown>): string {return readString(value, "assistantMessageID") ?? readString(value, "messageID") ?? readString(value, "messageId") ?? "";}-function mapV2Session(value: unknown, directory: string | undefined, eventCreated?: number): Session | null {+export function mapV2Session(value: unknown, directory: string | undefined, eventCreated?: number): Session | null {const data = responseData(value);if (!isRecord(data)) return null;const source = readRecord(data, "info") ?? data;diff --git a/apps/app/src/react-app/shell/route-workspaces.ts b/apps/app/src/react-app/shell/route-workspaces.tsindex 00025c7c..5d50d21a 100644--- a/apps/app/src/react-app/shell/route-workspaces.ts+++ b/apps/app/src/react-app/shell/route-workspaces.ts@@ -6,7 +6,7 @@import type { Session } from "@opencode-ai/sdk/v2/client";import { unwrap } from "@/app/lib/opencode";-import { createClientV2 } from "@/app/lib/opencode-v2-adapter";+import { createClientV2, mapV2Session } from "@/app/lib/opencode-v2-adapter";import { deleteNativeSession, unwrapNativeSessionResult } from "@/app/lib/opencode-session-native";import { OmniRushServerError, type OmniRushWorkspaceInfo } from "@/app/lib/omnirush-server";import type { ResolvedWorkspaceEndpoint } from "@/app/lib/workspace-endpoint";@@ -41,6 +41,8 @@ type RouteSessionListResult =export type RouteSessionListTransport = (input: {endpoint: ResolvedWorkspaceEndpoint;limit: number;+ /** The workspace folder, for a list that is not scoped to it yet. */+ directory?: string;}) => Promise<RouteSessionListResult>;const nativeRouteSessionList: RouteSessionListTransport = async ({ endpoint, limit }) => {@@ -83,10 +85,27 @@ export function mergeRouteSessionLists(return { data: merged.slice(0, limit), request: byProject.request, response: byProject.response ?? new Response(null, { status: 200 }) };}-export const v2RouteSessionList: RouteSessionListTransport = async ({ endpoint, limit }) =>- createClientV2(`${endpoint.mountedBaseUrl}/opencode2`, undefined, {- token: endpoint.token,- }).session.list({ limit });+/**+ * The 2.x engine's chats of this folder: its list (every folder, newest first)+ * kept to the folder, merged with the local server's by-folder list, which+ * also matches the folder by real path and scans further back.+ */+export const v2RouteSessionList: RouteSessionListTransport = async ({ endpoint, limit, directory }) => {+ const [listed, byFolder] = await Promise.all([+ createClientV2(`${endpoint.mountedBaseUrl}/opencode2`, undefined, { token: endpoint.token }).session.list({ limit }),+ endpoint.isRemote+ ? Promise.resolve(null)+ : endpoint.client.listWorkspaceSessionsByFolder(endpoint.workspaceId, limit, "v2").catch(() => null),+ ]);+ const root = normalizeDirectoryPath(directory ?? "");+ const scoped: RouteSessionListResult = root && listed.data+ ? { data: listed.data.filter((session) => normalizeDirectoryPath(session?.directory ?? "") === root), request: listed.request, response: listed.response }+ : listed as RouteSessionListResult;+ const folder = Array.isArray(byFolder)+ ? byFolder.flatMap((item) => mapV2Session(item, directory) ?? []) as RouteSession[]+ : null;+ return mergeRouteSessionLists(scoped, folder, limit);+};/** Resolve the owning server's engine even when this workspace isn't selected. */async function routeSessionEndpoint(endpoint: ResolvedWorkspaceEndpoint): Promise<ResolvedWorkspaceEndpoint> {@@ -160,8 +179,9 @@ export async function removeRouteWorkspace(input: {export async function listRouteSessions(endpoint: ResolvedWorkspaceEndpoint,transport: RouteSessionListTransport = nativeRouteSessionList,+ directory?: string,): Promise<RouteSession[]> {- return unwrapNativeSessionResult(await transport({ endpoint, limit: 200 }));+ return unwrapNativeSessionResult(await transport({ endpoint, limit: 200, ...(directory ? { directory } : {}) }));}export function mapDesktopWorkspace(workspace: WorkspaceInfo): RouteWorkspace {diff --git a/apps/app/src/react-app/shell/use-workspace-route-state.ts b/apps/app/src/react-app/shell/use-workspace-route-state.tsindex bfdb1140..9f21af4c 100644--- a/apps/app/src/react-app/shell/use-workspace-route-state.ts+++ b/apps/app/src/react-app/shell/use-workspace-route-state.ts@@ -439,13 +439,14 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {// The sidebar lists from whichever engine chat is routed to.const usesV2List = workspace.workspaceType !== "remote" && engineV2ChatRoutingRef.current;const fetchedItems = usesV2List- ? await listRouteSessions(endpoint, v2RouteSessionList)+ ? await listRouteSessions(endpoint, v2RouteSessionList, workspace.path ?? ""): await listRouteSessions(endpoint);const workspaceRoot = normalizeDirectoryPath(workspace.path ?? "");- // The local server already scopes the v1 list to this folder, also- // under its real path (symlink, junction, subst drive), which this- // string compare would drop. Other lists still need the filter.- const serverScoped = workspace.workspaceType !== "remote" && !usesV2List;+ // The local server already scopes the list to this folder (the 2.x+ // list is scoped in v2RouteSessionList), also under its real path+ // (symlink, junction, subst drive), which this string compare would+ // drop. Remote lists still need the filter.+ const serverScoped = workspace.workspaceType !== "remote";const items = workspaceRoot && !isRemoteOmniRushWorkspace && !serverScoped? fetchedItems.filter((session) =>normalizeDirectoryPath(session?.directory ?? "") === workspaceRoot,diff --git a/apps/app/tests/route-session-list.test.ts b/apps/app/tests/route-session-list.test.tsindex aa549dda..ab4e8ac4 100644--- a/apps/app/tests/route-session-list.test.ts+++ b/apps/app/tests/route-session-list.test.ts@@ -1,9 +1,42 @@import { describe, expect, test } from "bun:test";import { resolveWorkspaceEndpoint } from "../src/app/lib/workspace-endpoint";-import { classifyRouteSessionReadError, listRouteSessions, mergeRouteSessionLists, readRouteSessionsWithRetry } from "../src/react-app/shell/route-workspaces";+import { classifyRouteSessionReadError, listRouteSessions, mergeRouteSessionLists, readRouteSessionsWithRetry, v2RouteSessionList } from "../src/react-app/shell/route-workspaces";describe("workspace route native session lists", () => {+ test("2.x: the folder's chats come from the engine list and the server's by-folder list, each once", async () => {+ const resolved = resolveWorkspaceEndpoint({ id: "ws", workspaceType: "local" }, { baseUrl: "https://local.example.test", token: "t" });+ if (!resolved) throw new Error("Expected a local endpoint");+ const asked: string[] = [];+ const endpoint = { ...resolved, client: { ...resolved.client, listWorkspaceSessionsByFolder: async (id: string, limit: number, engine?: string) => {+ asked.push(`${id}:${limit}:${engine}`);+ // A chat stored under another spelling of the folder (real path, a git repo's root since), and one also in the engine list.+ return [+ { id: "ses_symlinked", title: "old", location: { directory: "/real/proj" }, time: { created: 1, updated: 9 } },+ { id: "ses_here", title: "here", location: { directory: "/home/a/proj" }, time: { created: 1, updated: 5 } },+ ];+ } } };+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input instanceof Request ? input.url : input);+ expect(url).toContain("/workspace/ws/opencode2/api/session");+ return Response.json({ data: [+ { id: "ses_here", title: "here", location: { directory: "/home/a/proj/" }, time: { created: 1, updated: 5 } },+ { id: "ses_other_folder", title: "other", location: { directory: "/home/a/other" }, time: { created: 1, updated: 7 } },+ ], cursor: {} });+ }) as typeof fetch;+ try {+ const sessions = await listRouteSessions(endpoint, v2RouteSessionList, "/home/a/proj");+ expect(sessions.map((session) => session.id)).toEqual(["ses_symlinked", "ses_here"]);+ expect(asked).toEqual(["ws:200:v2"]);+ // A server without the 2.x by-folder list: the engine list, kept to the folder.+ endpoint.client.listWorkspaceSessionsByFolder = async () => { throw new Error("503 opencode_unconfigured"); };+ expect((await listRouteSessions(endpoint, v2RouteSessionList, "/home/a/proj")).map((session) => session.id)).toEqual(["ses_here"]);+ } finally {+ globalThis.fetch = realFetch;+ }+ });+test("loads a bare session array through the local native transport input", async () => {const endpoint = resolveWorkspaceEndpoint({id: "local workspace",diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex e460052d..63f20032 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -2233,7 +2233,8 @@ export async function proxyOpencodeV2Request(input: {realpath(input.workspace.path).catch(() => input.workspace.path),directory ? realpath(directory).catch(() => directory) : null,]);- if (!actual || actual !== expected) {+ // Compared as the file system does (case on Windows and macOS), as the sidebar's by-folder list matches.+ if (!actual || directoryMatchKey(actual) !== directoryMatchKey(expected)) {throw new ApiError(404, "session_not_found", "Session not found");}}@@ -5111,6 +5112,11 @@ function createRoutes(}const requested = Number(ctx.url.searchParams.get("limit"));const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 500) : 200;+ if (ctx.url.searchParams.get("engine") === "v2") {+ const v2 = engineV2ByServer.get(config)?.connection();+ if (!v2) throw new ApiError(503, "opencode_unconfigured", "The engine is not running");+ return jsonResponse(await listEngineV2SessionsInFolder(v2, directory, limit));+ }return jsonResponse(await listEngineSessionsInFolder(config, workspace, directory, limit));});@@ -6584,6 +6590,41 @@ export async function listEngineSessionsInFolder(.slice(0, limit);}+/**+ * The 2.x engine's sessions stored for `directory`, newest first, raw: from its+ * list of every folder, matched without case (Windows, macOS), slash+ * direction, a trailing slash or the long-path prefix, or by real path+ * (symlink, junction, subst drive).+ */+export async function listEngineV2SessionsInFolder(+ v2: { url: string; password: string },+ directory: string,+ limit: number,+ fetchImpl: (input: string, init?: RequestInit) => Promise<Response> = loopbackFetch,+): Promise<unknown[]> {+ const headers = new Headers({ authorization: `Basic ${Buffer.from(`opencode:${v2.password}`).toString("base64")}` });+ const response = await fetchImpl(buildOpencodeProxyUrl(v2.url, "/api/session", `?limit=${SESSIONS_BY_FOLDER_SCAN}&order=desc`), { headers, signal: AbortSignal.timeout(45_000) });+ if (!response.ok) {+ throw new ApiError(response.status === 404 ? 404 : 502, "opencode_engine_unreachable", `The engine session list failed with status ${response.status}`);+ }+ const payload: unknown = await response.json();+ const items = isRecord(payload) && Array.isArray(payload.data) ? payload.data : Array.isArray(payload) ? payload : [];+ const real = await realpath(directory).catch(() => directory);+ const base = (value: string) => directoryMatchKey(value).split("/").pop() ?? "";+ const found: unknown[] = [];+ for (const session of items) {+ const location = isRecord(session) && isRecord(session.location) ? session.location : null;+ const folder = location && typeof location.directory === "string" ? location.directory : "";+ if (!folder) continue;+ // Real paths are read only for a folder of the same name: a scan of every chat stays cheap.+ const same = isSameSessionFolder(folder, directory) || isSameSessionFolder(folder, real)+ || ((base(folder) === base(directory) || base(folder) === base(real)) && isSameSessionFolder(await realpath(folder).catch(() => folder), real));+ if (same) found.push(session);+ if (found.length >= limit) break;+ }+ return found;+}+/*** True when the managed engine reports any non-idle session (subagent child* sessions carry their own ids and statuses, so they count too). Unknowndiff --git a/apps/server/src/sessions-by-folder.test.ts b/apps/server/src/sessions-by-folder.test.tsindex 116e8555..d1d7933c 100644--- a/apps/server/src/sessions-by-folder.test.ts+++ b/apps/server/src/sessions-by-folder.test.ts@@ -1,6 +1,9 @@import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";-import { isSameSessionFolder, listEngineSessionsInFolder } from "./server.js";+import { isSameSessionFolder, listEngineSessionsInFolder, listEngineV2SessionsInFolder } from "./server.js";import type { ServerConfig, WorkspaceInfo } from "./types.js";describe("isSameSessionFolder", () => {@@ -80,3 +83,37 @@ describe("listEngineSessionsInFolder", () => {.rejects.toMatchObject({ status: 502 });});});++describe("listEngineV2SessionsInFolder", () => {+ test("keeps this folder's 2.x chats from the engine's list of every folder, also under its real path", async () => {+ const root = mkdtempSync(join(tmpdir(), "omnirush-v2-by-folder-"));+ try {+ const real = join(root, "real", "proj");+ mkdirSync(real, { recursive: true });+ const link = join(root, "proj");+ symlinkSync(real, link);+ const requests: Request[] = [];+ const sessions = await listEngineV2SessionsInFolder({ url: "http://engine.invalid", password: "pw" }, link, 10, async (input, init) => {+ requests.push(new Request(input, init));+ return Response.json({ data: [+ { id: "ses_link", location: { directory: link } },+ { id: "ses_other", location: { directory: join(root, "other") } },+ { id: "ses_real", location: { directory: real } },+ { id: "ses_slash", location: { directory: `${link}/` } },+ { id: "ses_none" },+ ], cursor: {} });+ });+ expect(sessions.map((session) => (session as { id: string }).id)).toEqual(["ses_link", "ses_real", "ses_slash"]);+ const url = new URL(requests[0]!.url);+ expect(url.pathname).toBe("/api/session");+ expect(url.searchParams.get("directory")).toBeNull();+ expect(url.searchParams.get("limit")).toBe("2000");+ expect(requests[0]!.headers.get("authorization")).toBe(`Basic ${Buffer.from("opencode:pw").toString("base64")}`);+ expect(await listEngineV2SessionsInFolder({ url: "http://engine.invalid", password: "pw" }, link, 1, async () => Response.json({ data: [{ id: "a", location: { directory: link } }, { id: "b", location: { directory: link } }] }))).toHaveLength(1);+ await expect(listEngineV2SessionsInFolder({ url: "http://engine.invalid", password: "pw" }, link, 2, async () => new Response("no", { status: 500 })))+ .rejects.toMatchObject({ status: 502 });+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});