A desktop coding agent with free access to frontier models.
TypeScript
fix: list work tools again after a source connects on the 2.x engine
ogsamrat5eec82d3ebc0
diff --git a/apps/server/src/engine-v2-mcp.ts b/apps/server/src/engine-v2-mcp.tsindex fb5c5688..e5361a6b 100644--- a/apps/server/src/engine-v2-mcp.ts+++ b/apps/server/src/engine-v2-mcp.ts@@ -106,7 +106,7 @@ export async function desiredV2Mcp(stateDir: string, root: string, engineEnv: Reout[CLOUD_MCP_NAME] = { type: "remote", url: cloud.url, headers, ...(cloud.oauth === false ? { oauth: false } : {}), codemode: false, ...timeout };}// Work mode: the account's Work folder gets the hosted connector server (through the app's local API).- const work = gate.includes(FIRST_PARTY_REMOTE.work.id) && isV2WorkRoot(workDir(stateDir), root) ? v2WorkMcp(engineEnv) : null;+ const work = gate.includes(FIRST_PARTY_REMOTE.work.id) && isV2WorkRoot(workDir(stateDir), root) ? v2WorkMcp(engineEnv, workDir(stateDir)) : null;if (work) out[FIRST_PARTY_REMOTE.work.id] = work;return out;} catch {diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.tsindex 67d8c435..c650e667 100644--- a/apps/server/src/engine-v2-preview.ts+++ b/apps/server/src/engine-v2-preview.ts@@ -80,6 +80,8 @@ export interface EngineV2Preview {refreshProviders(): Promise<void>;ensureWorkspaceReady(directory: string): Promise<void>;syncWorkspaceMcp(workspaceId: string, directory: string): Promise<void>;+ /** Applies a location's MCP servers again (they changed outside the runtime config: Work's connected sources). */+ refreshWorkspaceMcp(directory: string): void;/** Whether a chat came from the 1.x store (engine-v2-migration.ts). */migratedFromV1(sessionId: string): boolean;stop(): Promise<void>;@@ -710,5 +712,13 @@ export function createEngineV2Preview(options: {if (enabled) void start().catch(recordStartError);}if (!options.deferStart) startWhenReady();- return { start: startWhenReady, status, setEnabled, setChatRouting, connection, awaitConnection, refreshProviders, ensureWorkspaceReady, syncWorkspaceMcp, migratedFromV1: (id) => migrated.has(id), stop };+ function refreshWorkspaceMcp(directory: string): void {+ mcpCleaned.delete(directory);+ const id = mcpWorkspaces.get(directory);+ if (id && sidecar) void syncWorkspaceMcp(id, directory).catch((error) => {+ if (sidecar) lastError = `MCP: ${errorMessage(error)}`;+ });+ }++ return { start: startWhenReady, status, setEnabled, setChatRouting, connection, awaitConnection, refreshProviders, ensureWorkspaceReady, syncWorkspaceMcp, refreshWorkspaceMcp, migratedFromV1: (id) => migrated.has(id), stop };}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 0798e361..110485c6 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -192,7 +192,7 @@ import { rememberWebSearchSwitch, userWebSearchEnabled, webSearchAllowed, watchWimport { askSideQuestion, brokerSideCall } from "./side-question.js";import { createChatTracker, rememberComputerUseSwitch } from "./computer-use/desktop.js";import { registerComputerUseRoutes } from "./computer-use/routes.js";-import { forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./work/routes.js";+import { findWorkWorkspace, forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./work/routes.js";import { rememberWorkSwitch, workDir } from "./work/work.js";import { isV2WorkRoot, withV2WorkPermissions } from "./work/engine.js";import { WORK_PROMPT } from "./work/prompt.js";@@ -5500,6 +5500,10 @@ function createRoutes(return workspace;},applyEngine: () => applyComputerUseEngine(config, "work"),+ refreshMcp: () => {+ const workspace = findWorkWorkspace(config.workspaces);+ if (workspace) engineV2ByServer.get(config)?.refreshWorkspaceMcp(workspace.path);+ },});// Computer use (computer-use/routes.ts): for Electron main, which runs the host.diff --git a/apps/server/src/work/engine.ts b/apps/server/src/work/engine.tsindex c82e1fe8..089d0f3d 100644--- a/apps/server/src/work/engine.ts+++ b/apps/server/src/work/engine.ts@@ -1,7 +1,7 @@// Work chats' engine config (Work mode), applied by the MCP plugin (opencode-plugins/omnirush-mcp-policy.ts).import { FIRST_PARTY_REMOTE, firstPartyRemote, toolPrefix } from "../mcp-allow/mcp-allow.mjs";import { WORK_PROMPT } from "./prompt.js";-import { isWorkRoot, rememberedWorkSwitch, WORK_DIR_ENV, WORK_DISABLED_TOOLS, WORK_READ_TOOLS } from "./work.js";+import { isWorkRoot, rememberedWorkConnectors, rememberedWorkSwitch, WORK_DIR_ENV, WORK_DISABLED_TOOLS, WORK_READ_TOOLS } from "./work.js";function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);@@ -48,11 +48,16 @@ export function isV2WorkRoot(dir: string, root: string): boolean {return isWorkRoot(dir, root) && rememberedWorkSwitch(dir).enabled;}-/** The hosted server as a 2.x runtime MCP entry, through the app's local API with the engine's own token; null without either. */-export function v2WorkMcp(engineEnv: Record<string, string | undefined>): Record<string, unknown> | null {+/**+ * The hosted server as a 2.x runtime MCP entry, through the app's local API with the engine's own token; null without either.+ * Its tools follow the connected sources, and the engine lists them only when the entry changes: the sources as last+ * listed go in a header (the local API does not forward it), so connecting or disconnecting one reconnects the server.+ */+export function v2WorkMcp(engineEnv: Record<string, string | undefined>, dir?: string): Record<string, unknown> | null {const origin = String(engineEnv.OMNIRUSH_SERVER_URL ?? "").trim();const token = String(engineEnv.OMNIRUSH_ACCESS_TOKEN ?? "").trim();- const entry = token ? firstPartyRemote("work", origin, `${origin.replace(/\/+$/, "")}${FIRST_PARTY_REMOTE.work.path}`, { Authorization: `Bearer ${token}` }) : null;+ const sources = dir ? rememberedWorkConnectors(dir).map((row) => row.id).sort().join(",") : "";+ const entry = token ? firstPartyRemote("work", origin, `${origin.replace(/\/+$/, "")}${FIRST_PARTY_REMOTE.work.path}`, { Authorization: `Bearer ${token}`, "X-OmniRush-Work-Sources": sources || "none" }) : null;if (!entry) return null;return { type: "remote", url: entry.url, headers: entry.headers, oauth: false, codemode: false, timeout: { startup: 60_000, catalog: 60_000, execution: 60_000 } };}diff --git a/apps/server/src/work/routes.ts b/apps/server/src/work/routes.tsindex 9572dd65..12e2e465 100644--- a/apps/server/src/work/routes.ts+++ b/apps/server/src/work/routes.ts@@ -18,7 +18,7 @@ import { mkdir } from "node:fs/promises";import { addRoute, type Route } from "../routes/registry.js";import type { ServerConfig, WorkspaceInfo } from "../types.js";-import { rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PRESET, WORK_SOURCE_ID, workHome } from "./work.js";+import { rememberedWorkConnectors, rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PRESET, WORK_SOURCE_ID, workHome } from "./work.js";export type WorkBroker = {workRequest: (path: string, init: { method: "GET" | "POST" | "PATCH"; body?: string; headers?: Record<string, string>; signal?: AbortSignal }) => Promise<Response>;@@ -36,6 +36,8 @@ export type WorkRouteDeps = {addWorkspace: (folderPath: string) => Promise<WorkspaceInfo>;/** The engine picks up a changed switch (the Work folder's server comes or goes). */applyEngine: () => Promise<unknown>;+ /** The engine lists the hosted server's tools again (a source was connected or disconnected). */+ refreshMcp?: () => void;};const WORK_ERRORS: Record<string, string> = {@@ -108,7 +110,11 @@ export function registerWorkRoutes(deps: WorkRouteDeps): void {const found = deps.broker();if (!found) return signedOut();const answer = await passThrough(await found.workRequest("connectors", { method: "GET" }), jsonResponse);- if (answer.status === 200) rememberWorkConnectors(deps.workDir(), answer.data);+ if (answer.status === 200) {+ const ids = (rows: { id: string }[]) => rows.map((row) => row.id).sort().join(",");+ const before = ids(rememberedWorkConnectors(deps.workDir()));+ if (ids(rememberWorkConnectors(deps.workDir(), answer.data)) !== before) deps.refreshMcp?.();+ }return answer.response;});diff --git a/apps/server/src/work/work.test.ts b/apps/server/src/work/work.test.tsindex 972ddf98..ce61cbd1 100644--- a/apps/server/src/work/work.test.ts+++ b/apps/server/src/work/work.test.ts@@ -107,8 +107,14 @@ describe("work on the 2.x engine", () => {expect(await desiredV2Mcp(state, root, engineEnv, v2McpGate(state))).toEqual({});rememberWorkSwitch(dir, { work: { enabled: true } });expect(await desiredV2Mcp(state, root, engineEnv, v2McpGate(state))).toEqual({- "omnirush-work": { type: "remote", url: "http://127.0.0.1:8787/omnirush/work/mcp", headers: { Authorization: "Bearer engine-token" }, oauth: false, codemode: false, timeout: { startup: 60_000, catalog: 60_000, execution: 60_000 } },+ "omnirush-work": { type: "remote", url: "http://127.0.0.1:8787/omnirush/work/mcp", headers: { Authorization: "Bearer engine-token", "X-OmniRush-Work-Sources": "none" }, oauth: false, codemode: false, timeout: { startup: 60_000, catalog: 60_000, execution: 60_000 } },});+ // A source connected (or gone) changes the entry, so the engine reconnects and lists that source's tools.+ rememberWorkConnectors(dir, [{ id: "slack", status: "connected", sync_enabled: false }, { id: "mock", status: "connected", sync_enabled: true }]);+ const sources = async () => ((await desiredV2Mcp(state, root, engineEnv, v2McpGate(state)))["omnirush-work"]?.headers as Record<string, string>)["X-OmniRush-Work-Sources"];+ expect(await sources()).toBe("mock,slack");+ rememberWorkConnectors(dir, [{ id: "mock", status: "disconnected", sync_enabled: true }]);+ expect(await sources()).toBe("none");expect(await desiredV2Mcp(state, join(state, "project"), engineEnv, v2McpGate(state))).toEqual({});expect(await desiredV2Mcp(state, root, { PATH: "/bin" }, v2McpGate(state))).toEqual({});});@@ -150,7 +156,8 @@ describe("work routes", () => {capabilities: async () => ({ work: { enabled: true, sources: ["mock"] } }),};const config = { workspaces: [] } as unknown as ServerConfig;- registerWorkRoutes({ routes, config, workDir: () => dir, broker: () => broker, jsonResponse: json, readJsonBody: (r) => r.json(), addWorkspace: async (folderPath) => ({ id: "ws_work", name: "Work", path: folderPath, preset: "work", workspaceType: "local" }), applyEngine: async () => undefined });+ const refreshed: number[] = [];+ registerWorkRoutes({ routes, config, workDir: () => dir, broker: () => broker, jsonResponse: json, readJsonBody: (r) => r.json(), addWorkspace: async (folderPath) => ({ id: "ws_work", name: "Work", path: folderPath, preset: "work", workspaceType: "local" }), applyEngine: async () => undefined, refreshMcp: () => refreshed.push(1) });const call = async (method: string, path: string, body?: unknown) => {const pathname = path.split("?")[0] ?? "";const route = routes.find((r) => r.method === method && r.regex.test(pathname));@@ -161,22 +168,25 @@ describe("work routes", () => {const request = new Request(`http://x${path}`, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });return route.handler({ request, url: new URL(request.url), params } as never);};- return { dir, calls, call };+ return { dir, calls, call, refreshed };}test("state, workspace and the connector calls go to /omnirush/work with the contract's shapes", async () => {- const { dir, calls, call } = setup((path) => path === "connectors"+ const { dir, calls, call, refreshed } = setup((path) => path === "connectors"? json([{ id: "mock", label: "Mock", status: "connected", sync_enabled: true, records: 3, last_sync_at: null, scopes: [] }]): path.endsWith("/start") ? json({ auth_url: "https://auth.example/x" }) : json({ ok: true, sync_enabled: false }));expect(await (await call("GET", "/work/state")).json()).toEqual({ enabled: true, sources: ["mock"], message: null, workspaceId: null });expect(await (await call("POST", "/work/workspace")).json()).toEqual({ workspaceId: "ws_work", path: join(dir, "user_1") });expect((await (await call("GET", "/work/connectors")).json())[0].id).toBe("mock");expect(workEnvironment(dir, join(dir, "user_1"))?.work.connectors).toEqual([{ id: "mock", enabled: true }]);+ // A newly connected source makes the engine list the server's tools again; the same sources do not.+ await call("GET", "/work/connectors");+ expect(refreshed.length).toBe(1);expect(await (await call("POST", "/work/connectors/mock/start")).json()).toEqual({ auth_url: "https://auth.example/x" });expect((await call("PATCH", "/work/connectors/mock", { sync_enabled: false })).status).toBe(200);expect((await call("PATCH", "/work/connectors/mock", { sync_enabled: "no" })).status).toBe(400);expect((await call("POST", "/work/connectors/Bad.Id/start")).status).toBe(404);- expect(calls).toEqual(["GET connectors ", "POST connectors/mock/start {}", "PATCH connectors/mock {\"sync_enabled\":false}"]);+ expect(calls).toEqual(["GET connectors ", "GET connectors ", "POST connectors/mock/start {}", "PATCH connectors/mock {\"sync_enabled\":false}"]);});test("health, entities and facts are forwarded with only their own parameters, and checked first", async () => {diff --git a/apps/server/src/work/work.ts b/apps/server/src/work/work.tsindex 76ec046d..31628908 100644--- a/apps/server/src/work/work.ts+++ b/apps/server/src/work/work.ts@@ -124,9 +124,13 @@ export function rememberWorkConnectors(dir: string, listed: unknown): WorkConnec*/export function workEnvironment(dir: string | null | undefined, root: string): { mode: "work"; work: { connectors: WorkConnectorUse[] } } | null {if (!dir || !isWorkRoot(dir, root)) return null;+ return { mode: "work", work: { connectors: rememberedWorkConnectors(dir) } };+}++/** The account's connectors as last listed (rememberWorkConnectors). */+export function rememberedWorkConnectors(dir: string): WorkConnectorUse[] {const saved = readJson(join(dir, "connectors.json"));- const connectors = isRecord(saved) && Array.isArray(saved.connectors)+ return isRecord(saved) && Array.isArray(saved.connectors)? saved.connectors.filter((row): row is WorkConnectorUse => isRecord(row) && typeof row.id === "string" && typeof row.enabled === "boolean").map((row) => ({ id: row.id, enabled: row.enabled })): [];- return { mode: "work", work: { connectors } };}