From 037077285ac36b8a427aa330d331e099360f1e55 Mon Sep 17 00:00:00 2001 From: Caleb Norton Date: Tue, 24 Mar 2026 11:30:39 -0500 Subject: [PATCH 01/32] fix: better nix hash detection (#18957) --- .github/workflows/nix-hashes.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/nix-hashes.yml b/.github/workflows/nix-hashes.yml index 2529c14c20..9ebdb01882 100644 --- a/.github/workflows/nix-hashes.yml +++ b/.github/workflows/nix-hashes.yml @@ -56,7 +56,7 @@ jobs: nix build ".#packages.${SYSTEM}.node_modules_updater" --no-link 2>&1 | tee "$BUILD_LOG" || true # Extract hash from build log with portability - HASH="$(grep -oE 'sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" + HASH="$(grep -oE 'got:\s*sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" if [ -z "$HASH" ]; then echo "::error::Failed to compute hash for ${SYSTEM}" From 31c4a4fb478d765d39ead26f81db9bf5ab54eb6c Mon Sep 17 00:00:00 2001 From: "opencode-agent[bot]" Date: Tue, 24 Mar 2026 16:43:24 +0000 Subject: [PATCH 02/32] chore: update nix node_modules hashes --- nix/hashes.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nix/hashes.json b/nix/hashes.json index 2065007431..944cb2c5b6 100644 --- a/nix/hashes.json +++ b/nix/hashes.json @@ -1,8 +1,8 @@ { "nodeModules": { - "x86_64-linux": "sha256-nMERinypUtIZGfLlAS5meYrvH5tTl2SkdG3GUguhOos=", - "aarch64-linux": "sha256-aQ42YVcjXSxpweA3e0SfJ8mnMWEqGeIOKg1cIhn8szA=", - "aarch64-darwin": "sha256-OGtUfhKWTRqi8bYcqkvfb1RZa3iS0DVy5bbRry47Og4=", - "x86_64-darwin": "sha256-kdzsr67cGduvGl+4UVdngiKNCaVw88WeMgx1ckVbG30=" + "x86_64-linux": "got:sha256-nMERinypUtIZGfLlAS5meYrvH5tTl2SkdG3GUguhOos=", + "aarch64-linux": "got:sha256-aQ42YVcjXSxpweA3e0SfJ8mnMWEqGeIOKg1cIhn8szA=", + "aarch64-darwin": "got:sha256-OGtUfhKWTRqi8bYcqkvfb1RZa3iS0DVy5bbRry47Og4=", + "x86_64-darwin": "got:sha256-kdzsr67cGduvGl+4UVdngiKNCaVw88WeMgx1ckVbG30=" } } From 7c5ed771c36f5acbd47a1070afc1935e8a50650b Mon Sep 17 00:00:00 2001 From: Jack Date: Wed, 25 Mar 2026 01:03:01 +0800 Subject: [PATCH 03/32] fix: update Feishu community links for zh locales (#18975) --- README.zh.md | 2 +- README.zht.md | 2 +- packages/console/app/src/routes/feishu.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.zh.md b/README.zh.md index 0859ed11d0..46d9f761cb 100644 --- a/README.zh.md +++ b/README.zh.md @@ -137,4 +137,4 @@ OpenCode 内置两种 Agent,可用 `Tab` 键快速切换: --- -**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=de8k6664-1b5e-43f2-8efd-21d6772647b5&qr_code=true) | [X.com](https://x.com/opencode) +**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=738j8655-cd59-4633-a30a-1124e0096789&qr_code=true) | [X.com](https://x.com/opencode) diff --git a/README.zht.md b/README.zht.md index b7d8b8fc47..7ef51d8fdd 100644 --- a/README.zht.md +++ b/README.zht.md @@ -137,4 +137,4 @@ OpenCode 內建了兩種 Agent,您可以使用 `Tab` 鍵快速切換。 --- -**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=de8k6664-1b5e-43f2-8efd-21d6772647b5&qr_code=true) | [X.com](https://x.com/opencode) +**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=738j8655-cd59-4633-a30a-1124e0096789&qr_code=true) | [X.com](https://x.com/opencode) diff --git a/packages/console/app/src/routes/feishu.ts b/packages/console/app/src/routes/feishu.ts index 35d2fcb0e2..3366e7208b 100644 --- a/packages/console/app/src/routes/feishu.ts +++ b/packages/console/app/src/routes/feishu.ts @@ -2,6 +2,6 @@ import { redirect } from "@solidjs/router" export async function GET() { return redirect( - "https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=de8k6664-1b5e-43f2-8efd-21d6772647b5&qr_code=true", + "https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=738j8655-cd59-4633-a30a-1124e0096789&qr_code=true", ) } From 5c1bb5de86d62bd598a89cd1ba0c1c02de103a90 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Tue, 24 Mar 2026 13:04:04 -0400 Subject: [PATCH 04/32] fix: remove flaky cross-spawn spawner tests (#18977) --- .../test/effect/cross-spawn-spawner.test.ts | 114 ------------------ 1 file changed, 114 deletions(-) diff --git a/packages/opencode/test/effect/cross-spawn-spawner.test.ts b/packages/opencode/test/effect/cross-spawn-spawner.test.ts index 7fdcb61cd4..6da0715212 100644 --- a/packages/opencode/test/effect/cross-spawn-spawner.test.ts +++ b/packages/opencode/test/effect/cross-spawn-spawner.test.ts @@ -351,122 +351,8 @@ describe("cross-spawn spawner", () => { }), ) - fx.effect( - "pipes output fd3 with { from: 'fd3' }", - Effect.gen(function* () { - const handle = yield* js('require("node:fs").writeSync(3, "hello from fd3\\n")', { - additionalFds: { fd3: { type: "output" } }, - }).pipe( - ChildProcess.pipeTo( - js( - 'process.stdin.setEncoding("utf8"); let out = ""; process.stdin.on("data", (chunk) => out += chunk); process.stdin.on("end", () => process.stdout.write(out))', - ), - { from: "fd3" }, - ), - ) - const out = yield* decodeByteStream(handle.stdout) - yield* handle.exitCode - expect(out).toBe("hello from fd3") - }), - ) - - fx.effect( - "pipes stdout to fd3", - Effect.gen(function* () { - if (process.platform === "win32") return - - const handle = yield* js('process.stdout.write("hello from stdout")').pipe( - ChildProcess.pipeTo(js('process.stdout.write(require("node:fs").readFileSync(3, "utf8"))'), { to: "fd3" }), - ) - const out = yield* decodeByteStream(handle.stdout) - yield* handle.exitCode - expect(out).toBe("hello from stdout") - }), - ) }) - describe("additional fds", () => { - fx.effect( - "reads data from output fd3", - Effect.gen(function* () { - const handle = yield* js('require("node:fs").writeSync(3, "hello from fd3\\n")', { - additionalFds: { fd3: { type: "output" } }, - }) - const out = yield* decodeByteStream(handle.getOutputFd(3)) - yield* handle.exitCode - expect(out).toBe("hello from fd3") - }), - ) - - fx.effect( - "writes data to input fd3", - Effect.gen(function* () { - if (process.platform === "win32") return - - const input = Stream.make(new TextEncoder().encode("data from parent")) - const handle = yield* js('process.stdout.write(require("node:fs").readFileSync(3, "utf8"))', { - additionalFds: { fd3: { type: "input", stream: input } }, - }) - const out = yield* decodeByteStream(handle.stdout) - yield* handle.exitCode - expect(out).toBe("data from parent") - }), - ) - - fx.effect( - "returns empty stream for unconfigured fd", - Effect.gen(function* () { - const handle = - process.platform === "win32" - ? yield* js('process.stdout.write("test")') - : yield* ChildProcess.make("echo", ["test"]) - const out = yield* decodeByteStream(handle.getOutputFd(3)) - yield* handle.exitCode - expect(out).toBe("") - }), - ) - - fx.effect( - "works alongside normal stdout and stderr", - Effect.gen(function* () { - const handle = yield* js( - 'require("node:fs").writeSync(3, "fd3\\n"); process.stdout.write("stdout\\n"); process.stderr.write("stderr\\n")', - { - additionalFds: { fd3: { type: "output" } }, - }, - ) - const stdout = yield* decodeByteStream(handle.stdout) - const stderr = yield* decodeByteStream(handle.stderr) - const fd3 = yield* decodeByteStream(handle.getOutputFd(3)) - yield* handle.exitCode - expect(stdout).toBe("stdout") - expect(stderr).toBe("stderr") - expect(fd3).toBe("fd3") - }), - ) - }) - - describe("large output", () => { - fx.effect( - "does not deadlock on large stdout", - Effect.gen(function* () { - const handle = yield* js("for (let i = 1; i <= 100000; i++) process.stdout.write(`${i}\\n`)") - const out = yield* handle.stdout.pipe( - Stream.decodeText(), - Stream.runFold( - () => "", - (acc, chunk) => acc + chunk, - ), - ) - yield* handle.exitCode - const lines = out.trim().split("\n") - expect(lines.length).toBe(100000) - expect(lines[0]).toBe("1") - expect(lines[99999]).toBe("100000") - }), - { timeout: 10_000 }, - ) - }) describe("Windows-specific", () => { fx.effect( From 1d3232b3885daa471309abab59e145d8e16f1736 Mon Sep 17 00:00:00 2001 From: "opencode-agent[bot]" Date: Tue, 24 Mar 2026 17:05:02 +0000 Subject: [PATCH 05/32] chore: generate --- packages/opencode/test/effect/cross-spawn-spawner.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/opencode/test/effect/cross-spawn-spawner.test.ts b/packages/opencode/test/effect/cross-spawn-spawner.test.ts index 6da0715212..08cae76e2f 100644 --- a/packages/opencode/test/effect/cross-spawn-spawner.test.ts +++ b/packages/opencode/test/effect/cross-spawn-spawner.test.ts @@ -350,10 +350,8 @@ describe("cross-spawn spawner", () => { expect(out).toContain("stderr") }), ) - }) - describe("Windows-specific", () => { fx.effect( "uses shell routing on Windows", From 1238d1f61acccf05330ff8fb59f3e355239b5f82 Mon Sep 17 00:00:00 2001 From: Caleb Norton Date: Tue, 24 Mar 2026 12:32:48 -0500 Subject: [PATCH 06/32] fix: nix hash update parsing (#18979) --- .github/workflows/nix-hashes.yml | 2 +- nix/hashes.json | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/nix-hashes.yml b/.github/workflows/nix-hashes.yml index 9ebdb01882..47385d20c6 100644 --- a/.github/workflows/nix-hashes.yml +++ b/.github/workflows/nix-hashes.yml @@ -56,7 +56,7 @@ jobs: nix build ".#packages.${SYSTEM}.node_modules_updater" --no-link 2>&1 | tee "$BUILD_LOG" || true # Extract hash from build log with portability - HASH="$(grep -oE 'got:\s*sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" + HASH="$(grep -oP 'got:\s*\Ksha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" if [ -z "$HASH" ]; then echo "::error::Failed to compute hash for ${SYSTEM}" diff --git a/nix/hashes.json b/nix/hashes.json index 944cb2c5b6..2065007431 100644 --- a/nix/hashes.json +++ b/nix/hashes.json @@ -1,8 +1,8 @@ { "nodeModules": { - "x86_64-linux": "got:sha256-nMERinypUtIZGfLlAS5meYrvH5tTl2SkdG3GUguhOos=", - "aarch64-linux": "got:sha256-aQ42YVcjXSxpweA3e0SfJ8mnMWEqGeIOKg1cIhn8szA=", - "aarch64-darwin": "got:sha256-OGtUfhKWTRqi8bYcqkvfb1RZa3iS0DVy5bbRry47Og4=", - "x86_64-darwin": "got:sha256-kdzsr67cGduvGl+4UVdngiKNCaVw88WeMgx1ckVbG30=" + "x86_64-linux": "sha256-nMERinypUtIZGfLlAS5meYrvH5tTl2SkdG3GUguhOos=", + "aarch64-linux": "sha256-aQ42YVcjXSxpweA3e0SfJ8mnMWEqGeIOKg1cIhn8szA=", + "aarch64-darwin": "sha256-OGtUfhKWTRqi8bYcqkvfb1RZa3iS0DVy5bbRry47Og4=", + "x86_64-darwin": "sha256-kdzsr67cGduvGl+4UVdngiKNCaVw88WeMgx1ckVbG30=" } } From 9330bc5339b3ca82975f768200450d4c9aabcd35 Mon Sep 17 00:00:00 2001 From: Vladimir Glafirov Date: Tue, 24 Mar 2026 18:33:18 +0100 Subject: [PATCH 07/32] fix: route GitLab Duo Workflow system prompt via flowConfig (#18928) --- bun.lock | 4 ++-- packages/opencode/package.json | 2 +- packages/opencode/src/session/llm.ts | 22 +++++++++++++--------- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/bun.lock b/bun.lock index 8db8852a0b..36b8f77483 100644 --- a/bun.lock +++ b/bun.lock @@ -358,7 +358,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "5.3.1", + "gitlab-ai-provider": "5.3.2", "glob": "13.0.5", "google-auth-library": "10.5.0", "gray-matter": "4.0.3", @@ -3036,7 +3036,7 @@ "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], - "gitlab-ai-provider": ["gitlab-ai-provider@5.3.1", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=2.0.0", "@ai-sdk/provider-utils": ">=3.0.0" } }, "sha512-QeNP2af/5wyOHYaLvDxn72n4xbMbJNqRiKExZJM8MnynebnqnoaJoojbtue7roCl/XcnjX6Of2+oc7hS44S45Q=="], + "gitlab-ai-provider": ["gitlab-ai-provider@5.3.2", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=2.0.0", "@ai-sdk/provider-utils": ">=3.0.0" } }, "sha512-EiAipDMa4Ngsxp4MMaua5YHWsHhc9kGXKmBxulJg1Gueb+5IZmMwxaVtgWTGWZITxC3tzKEeRt/3U4McE2vTIA=="], "glob": ["glob@13.0.5", "", { "dependencies": { "minimatch": "^10.2.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-BzXxZg24Ibra1pbQ/zE7Kys4Ua1ks7Bn6pKLkVPZ9FZe4JQS6/Q7ef3LG1H+k7lUf5l4T3PLSyYyYJVYUvfgTw=="], diff --git a/packages/opencode/package.json b/packages/opencode/package.json index 39b4e6232b..97a6457cf9 100644 --- a/packages/opencode/package.json +++ b/packages/opencode/package.json @@ -121,7 +121,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "5.3.1", + "gitlab-ai-provider": "5.3.2", "glob": "13.0.5", "google-auth-library": "10.5.0", "gray-matter": "4.0.3", diff --git a/packages/opencode/src/session/llm.ts b/packages/opencode/src/session/llm.ts index a22c6d8560..075f070e42 100644 --- a/packages/opencode/src/session/llm.ts +++ b/packages/opencode/src/session/llm.ts @@ -113,17 +113,20 @@ export namespace LLM { options.instructions = system.join("\n") } + const isWorkflow = language instanceof GitLabWorkflowLanguageModel const messages = isOpenaiOauth ? input.messages - : [ - ...system.map( - (x): ModelMessage => ({ - role: "system", - content: x, - }), - ), - ...input.messages, - ] + : isWorkflow + ? input.messages + : [ + ...system.map( + (x): ModelMessage => ({ + role: "system", + content: x, + }), + ), + ...input.messages, + ] const params = await Plugin.trigger( "chat.params", @@ -190,6 +193,7 @@ export namespace LLM { // and results sent back over the WebSocket. if (language instanceof GitLabWorkflowLanguageModel) { const workflowModel = language + workflowModel.systemPrompt = system.join("\n") workflowModel.toolExecutor = async (toolName, argsJson, _requestID) => { const t = tools[toolName] if (!t || !t.execute) { From 235a82aea97cd35c190bc95e916be5bdc0cce04a Mon Sep 17 00:00:00 2001 From: Caleb Norton Date: Tue, 24 Mar 2026 12:50:25 -0500 Subject: [PATCH 08/32] chore: update flake.lock (#18976) Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> --- flake.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flake.lock b/flake.lock index 59eb118fa4..805be8739b 100644 --- a/flake.lock +++ b/flake.lock @@ -2,11 +2,11 @@ "nodes": { "nixpkgs": { "locked": { - "lastModified": 1772091128, - "narHash": "sha256-TnrYykX8Mf/Ugtkix6V+PjW7miU2yClA6uqWl/v6KWM=", + "lastModified": 1773909469, + "narHash": "sha256-vglVrLfHjFIzIdV9A27Ugul6rh3I1qHbbitGW7dk420=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "3f0336406035444b4a24b942788334af5f906259", + "rev": "7149c06513f335be57f26fcbbbe34afda923882b", "type": "github" }, "original": { From 814a515a8a2f474585ea061a99e1058b2bb8b374 Mon Sep 17 00:00:00 2001 From: Ryan Skidmore Date: Tue, 24 Mar 2026 12:50:55 -0500 Subject: [PATCH 09/32] =?UTF-8?q?fix:=20improve=20plugin=20system=20robust?= =?UTF-8?q?ness=20=E2=80=94=20agent/command=20resolution,=20async=20errors?= =?UTF-8?q?,=20hook=20timing,=20two-phase=20init=20(#18280)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> --- packages/opencode/src/plugin/index.ts | 6 +- .../opencode/src/server/routes/session.ts | 10 ++- packages/opencode/src/session/prompt.ts | 52 ++++++++++++- .../test/plugin/auth-override.test.ts | 16 ++++ .../test/server/session-messages.test.ts | 13 ++++ packages/opencode/test/session/prompt.test.ts | 76 +++++++++++++++++++ 6 files changed, 169 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index 57dcff8f67..e519f9f350 100644 --- a/packages/opencode/src/plugin/index.ts +++ b/packages/opencode/src/plugin/index.ts @@ -136,7 +136,11 @@ export namespace Plugin { // Notify plugins of current config for (const hook of hooks) { - await (hook as any).config?.(cfg) + try { + await (hook as any).config?.(cfg) + } catch (err) { + log.error("plugin config hook failed", { error: err }) + } } }) diff --git a/packages/opencode/src/server/routes/session.ts b/packages/opencode/src/server/routes/session.ts index abc820c2af..3c9ebfdc5e 100644 --- a/packages/opencode/src/server/routes/session.ts +++ b/packages/opencode/src/server/routes/session.ts @@ -19,6 +19,8 @@ import { PermissionID } from "@/permission/schema" import { ModelID, ProviderID } from "@/provider/schema" import { errors } from "../error" import { lazy } from "../../util/lazy" +import { Bus } from "../../bus" +import { NamedError } from "@opencode-ai/util/error" const log = Log.create({ service: "server" }) @@ -846,7 +848,13 @@ export const SessionRoutes = lazy(() => return stream(c, async () => { const sessionID = c.req.valid("param").sessionID const body = c.req.valid("json") - SessionPrompt.prompt({ ...body, sessionID }) + SessionPrompt.prompt({ ...body, sessionID }).catch((err) => { + log.error("prompt_async failed", { sessionID, error: err }) + Bus.publish(Session.Event.Error, { + sessionID, + error: new NamedError.Unknown({ message: err instanceof Error ? err.message : String(err) }).toObject(), + }) + }) }) }, ) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index dca8085c5b..b3c34539e7 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -418,6 +418,16 @@ export namespace SessionPrompt { ) let executionError: Error | undefined const taskAgent = await Agent.get(task.agent) + if (!taskAgent) { + const available = await Agent.list().then((agents) => agents.filter((a) => !a.hidden).map((a) => a.name)) + const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" + const error = new NamedError.Unknown({ message: `Agent not found: "${task.agent}".${hint}` }) + Bus.publish(Session.Event.Error, { + sessionID, + error: error.toObject(), + }) + throw error + } const taskCtx: Tool.Context = { agent: task.agent, messageID: assistantMessage.id, @@ -560,6 +570,16 @@ export namespace SessionPrompt { // normal processing const agent = await Agent.get(lastUser.agent) + if (!agent) { + const available = await Agent.list().then((agents) => agents.filter((a) => !a.hidden).map((a) => a.name)) + const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" + const error = new NamedError.Unknown({ message: `Agent not found: "${lastUser.agent}".${hint}` }) + Bus.publish(Session.Event.Error, { + sessionID, + error: error.toObject(), + }) + throw error + } const maxSteps = agent.steps ?? Infinity const isLastStep = step >= maxSteps msgs = await insertReminders({ @@ -964,7 +984,18 @@ export namespace SessionPrompt { } async function createUserMessage(input: PromptInput) { - const agent = await Agent.get(input.agent ?? (await Agent.defaultAgent())) + const agentName = input.agent || (await Agent.defaultAgent()) + const agent = await Agent.get(agentName) + if (!agent) { + const available = await Agent.list().then((agents) => agents.filter((a) => !a.hidden).map((a) => a.name)) + const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" + const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` }) + Bus.publish(Session.Event.Error, { + sessionID: input.sessionID, + error: error.toObject(), + }) + throw error + } const model = input.model ?? agent.model ?? (await lastModel(input.sessionID)) const full = @@ -1531,6 +1562,16 @@ NOTE: At any point in time through this workflow you should feel free to ask the await SessionRevert.cleanup(session) } const agent = await Agent.get(input.agent) + if (!agent) { + const available = await Agent.list().then((agents) => agents.filter((a) => !a.hidden).map((a) => a.name)) + const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" + const error = new NamedError.Unknown({ message: `Agent not found: "${input.agent}".${hint}` }) + Bus.publish(Session.Event.Error, { + sessionID: input.sessionID, + error: error.toObject(), + }) + throw error + } const model = input.model ?? agent.model ?? (await lastModel(input.sessionID)) const userMsg: MessageV2.User = { id: MessageID.ascending(), @@ -1783,7 +1824,14 @@ NOTE: At any point in time through this workflow you should feel free to ask the log.info("command", input) const command = await Command.get(input.command) if (!command) { - throw new NamedError.Unknown({ message: `Command not found: "${input.command}"` }) + const available = await Command.list().then((cmds) => cmds.map((c) => c.name)) + const hint = available.length ? ` Available commands: ${available.join(", ")}` : "" + const error = new NamedError.Unknown({ message: `Command not found: "${input.command}".${hint}` }) + Bus.publish(Session.Event.Error, { + sessionID: input.sessionID, + error: error.toObject(), + }) + throw error } const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent()) diff --git a/packages/opencode/test/plugin/auth-override.test.ts b/packages/opencode/test/plugin/auth-override.test.ts index b967262254..667b7ba9aa 100644 --- a/packages/opencode/test/plugin/auth-override.test.ts +++ b/packages/opencode/test/plugin/auth-override.test.ts @@ -54,3 +54,19 @@ describe("plugin.auth-override", () => { expect(plainMethods[ProviderID.make("github-copilot")][0].label).not.toBe("Test Override Auth") }, 30000) // Increased timeout for plugin installation }) + +const file = path.join(import.meta.dir, "../../src/plugin/index.ts") + +describe("plugin.config-hook-error-isolation", () => { + test("config hooks are individually error-isolated in the layer factory", async () => { + const src = await Bun.file(file).text() + + // The config hook try/catch lives in the InstanceState factory (layer definition), + // not in init() which now just delegates to the Effect service. + expect(src).toContain("plugin config hook failed") + + const pattern = + /for\s*\(const hook of hooks\)\s*\{[\s\S]*?try\s*\{[\s\S]*?\.config\?\.\([\s\S]*?\}\s*catch\s*\(err\)\s*\{[\s\S]*?plugin config hook failed[\s\S]*?\}/ + expect(pattern.test(src)).toBe(true) + }) +}) diff --git a/packages/opencode/test/server/session-messages.test.ts b/packages/opencode/test/server/session-messages.test.ts index ee4c51646f..91e0fd9263 100644 --- a/packages/opencode/test/server/session-messages.test.ts +++ b/packages/opencode/test/server/session-messages.test.ts @@ -117,3 +117,16 @@ describe("session messages endpoint", () => { }) }) }) + +describe("session.prompt_async error handling", () => { + test("prompt_async route has error handler for detached prompt call", async () => { + const src = await Bun.file(path.join(import.meta.dir, "../../src/server/routes/session.ts")).text() + const start = src.indexOf('"/:sessionID/prompt_async"') + const end = src.indexOf('"/:sessionID/command"', start) + expect(start).toBeGreaterThan(-1) + expect(end).toBeGreaterThan(start) + const route = src.slice(start, end) + expect(route).toContain(".catch(") + expect(route).toContain("Bus.publish(Session.Event.Error") + }) +}) diff --git a/packages/opencode/test/session/prompt.test.ts b/packages/opencode/test/session/prompt.test.ts index 3986271dab..7d1d429057 100644 --- a/packages/opencode/test/session/prompt.test.ts +++ b/packages/opencode/test/session/prompt.test.ts @@ -1,5 +1,6 @@ import path from "path" import { describe, expect, test } from "bun:test" +import { NamedError } from "@opencode-ai/util/error" import { fileURLToPath } from "url" import { Instance } from "../../src/project/instance" import { ModelID, ProviderID } from "../../src/provider/schema" @@ -210,3 +211,78 @@ describe("session.prompt agent variant", () => { } }) }) + +describe("session.agent-resolution", () => { + test("unknown agent throws typed error", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({}) + const err = await SessionPrompt.prompt({ + sessionID: session.id, + agent: "nonexistent-agent-xyz", + noReply: true, + parts: [{ type: "text", text: "hello" }], + }).then( + () => undefined, + (e) => e, + ) + expect(err).toBeDefined() + expect(err).not.toBeInstanceOf(TypeError) + expect(NamedError.Unknown.isInstance(err)).toBe(true) + if (NamedError.Unknown.isInstance(err)) { + expect(err.data.message).toContain('Agent not found: "nonexistent-agent-xyz"') + } + }, + }) + }, 30000) + + test("unknown agent error includes available agent names", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({}) + const err = await SessionPrompt.prompt({ + sessionID: session.id, + agent: "nonexistent-agent-xyz", + noReply: true, + parts: [{ type: "text", text: "hello" }], + }).then( + () => undefined, + (e) => e, + ) + expect(NamedError.Unknown.isInstance(err)).toBe(true) + if (NamedError.Unknown.isInstance(err)) { + expect(err.data.message).toContain("build") + } + }, + }) + }, 30000) + + test("unknown command throws typed error with available names", async () => { + await using tmp = await tmpdir({ git: true }) + await Instance.provide({ + directory: tmp.path, + fn: async () => { + const session = await Session.create({}) + const err = await SessionPrompt.command({ + sessionID: session.id, + command: "nonexistent-command-xyz", + arguments: "", + }).then( + () => undefined, + (e) => e, + ) + expect(err).toBeDefined() + expect(err).not.toBeInstanceOf(TypeError) + expect(NamedError.Unknown.isInstance(err)).toBe(true) + if (NamedError.Unknown.isInstance(err)) { + expect(err.data.message).toContain('Command not found: "nonexistent-command-xyz"') + expect(err.data.message).toContain("init") + } + }, + }) + }, 30000) +}) From 539b01f20fc3677155b3bdbb428c69423a805578 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Tue, 24 Mar 2026 14:04:22 -0400 Subject: [PATCH 10/32] effectify Project service (#18808) --- packages/opencode/specs/effect-migration.md | 2 +- packages/opencode/src/project/project.ts | 728 ++++++++++-------- .../opencode/src/server/routes/project.ts | 2 +- .../opencode/test/project/project.test.ts | 302 +++++--- 4 files changed, 578 insertions(+), 456 deletions(-) diff --git a/packages/opencode/specs/effect-migration.md b/packages/opencode/specs/effect-migration.md index 12017b0e45..cf217871da 100644 --- a/packages/opencode/specs/effect-migration.md +++ b/packages/opencode/specs/effect-migration.md @@ -173,6 +173,6 @@ Still open and likely worth migrating: - [ ] `SessionPrompt` - [ ] `SessionCompaction` - [ ] `Provider` -- [ ] `Project` +- [x] `Project` - [ ] `LSP` - [ ] `MCP` diff --git a/packages/opencode/src/project/project.ts b/packages/opencode/src/project/project.ts index 1cef41c85c..3d20f58d45 100644 --- a/packages/opencode/src/project/project.ts +++ b/packages/opencode/src/project/project.ts @@ -1,36 +1,23 @@ import z from "zod" -import { Filesystem } from "../util/filesystem" -import path from "path" import { and, Database, eq } from "../storage/db" import { ProjectTable } from "./project.sql" import { SessionTable } from "../session/session.sql" import { Log } from "../util/log" import { Flag } from "@/flag/flag" -import { fn } from "@opencode-ai/util/fn" import { BusEvent } from "@/bus/bus-event" -import { iife } from "@/util/iife" import { GlobalBus } from "@/bus/global" -import { existsSync } from "fs" -import { git } from "../util/git" -import { Glob } from "../util/glob" import { which } from "../util/which" import { ProjectID } from "./schema" +import { Effect, Layer, Path, Scope, ServiceMap, Stream } from "effect" +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" +import { NodeFileSystem, NodePath } from "@effect/platform-node" +import { makeRunPromise } from "@/effect/run-service" +import { AppFileSystem } from "@/filesystem" +import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner" export namespace Project { const log = Log.create({ service: "project" }) - function gitpath(cwd: string, name: string) { - if (!name) return cwd - // git output includes trailing newlines; keep path whitespace intact. - name = name.replace(/[\r\n]+$/, "") - if (!name) return cwd - - name = Filesystem.windowsPath(name) - - if (path.isAbsolute(name)) return path.normalize(name) - return path.resolve(cwd, name) - } - export const Info = z .object({ id: ProjectID.zod, @@ -73,7 +60,7 @@ export namespace Project { ? { url: row.icon_url ?? undefined, color: row.icon_color ?? undefined } : undefined return { - id: ProjectID.make(row.id), + id: row.id, worktree: row.worktree, vcs: row.vcs ? Info.shape.vcs.parse(row.vcs) : undefined, name: row.name ?? undefined, @@ -88,245 +75,401 @@ export namespace Project { } } - function readCachedId(dir: string) { - return Filesystem.readText(path.join(dir, "opencode")) - .then((x) => x.trim()) - .then(ProjectID.make) - .catch(() => undefined) + export const UpdateInput = z.object({ + projectID: ProjectID.zod, + name: z.string().optional(), + icon: Info.shape.icon.optional(), + commands: Info.shape.commands.optional(), + }) + export type UpdateInput = z.infer + + // --------------------------------------------------------------------------- + // Effect service + // --------------------------------------------------------------------------- + + export interface Interface { + readonly fromDirectory: (directory: string) => Effect.Effect<{ project: Info; sandbox: string }> + readonly discover: (input: Info) => Effect.Effect + readonly list: () => Effect.Effect + readonly get: (id: ProjectID) => Effect.Effect + readonly update: (input: UpdateInput) => Effect.Effect + readonly initGit: (input: { directory: string; project: Info }) => Effect.Effect + readonly setInitialized: (id: ProjectID) => Effect.Effect + readonly sandboxes: (id: ProjectID) => Effect.Effect + readonly addSandbox: (id: ProjectID, directory: string) => Effect.Effect + readonly removeSandbox: (id: ProjectID, directory: string) => Effect.Effect } - export async function fromDirectory(directory: string) { - log.info("fromDirectory", { directory }) + export class Service extends ServiceMap.Service()("@opencode/Project") {} - const data = await iife(async () => { - const matches = Filesystem.up({ targets: [".git"], start: directory }) - const dotgit = await matches.next().then((x) => x.value) - await matches.return() - if (dotgit) { - let sandbox = path.dirname(dotgit) + type GitResult = { code: number; text: string; stderr: string } - const gitBinary = which("git") + export const layer: Layer.Layer< + Service, + never, + AppFileSystem.Service | Path.Path | ChildProcessSpawner.ChildProcessSpawner + > = Layer.effect( + Service, + Effect.gen(function* () { + const fsys = yield* AppFileSystem.Service + const pathSvc = yield* Path.Path + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner - // cached id calculation - let id = await readCachedId(dotgit) + const git = Effect.fnUntraced( + function* (args: string[], opts?: { cwd?: string }) { + const handle = yield* spawner.spawn( + ChildProcess.make("git", args, { cwd: opts?.cwd, extendEnv: true, stdin: "ignore" }), + ) + const [text, stderr] = yield* Effect.all( + [Stream.mkString(Stream.decodeText(handle.stdout)), Stream.mkString(Stream.decodeText(handle.stderr))], + { concurrency: 2 }, + ) + const code = yield* handle.exitCode + return { code, text, stderr } satisfies GitResult + }, + Effect.scoped, + Effect.catch(() => Effect.succeed({ code: 1, text: "", stderr: "" } satisfies GitResult)), + ) - if (!gitBinary) { - return { - id: id ?? ProjectID.global, - worktree: sandbox, - sandbox, - vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS), - } - } + const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => + Effect.sync(() => Database.use(fn)) - const worktree = await git(["rev-parse", "--git-common-dir"], { - cwd: sandbox, - }) - .then(async (result) => { - const common = gitpath(sandbox, await result.text()) - // Avoid going to parent of sandbox when git-common-dir is empty. - return common === sandbox ? sandbox : path.dirname(common) - }) - .catch(() => undefined) + const emitUpdated = (data: Info) => + Effect.sync(() => + GlobalBus.emit("event", { + payload: { type: Event.Updated.type, properties: data }, + }), + ) - if (!worktree) { - return { - id: id ?? ProjectID.global, - worktree: sandbox, - sandbox, - vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS), - } - } + const fakeVcs = Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS) - // In the case of a git worktree, it can't cache the id - // because `.git` is not a folder, but it always needs the - // same project id as the common dir, so we resolve it now - if (id == null) { - id = await readCachedId(path.join(worktree, ".git")) - } + const resolveGitPath = (cwd: string, name: string) => { + if (!name) return cwd + name = name.replace(/[\r\n]+$/, "") + if (!name) return cwd + name = AppFileSystem.windowsPath(name) + if (pathSvc.isAbsolute(name)) return pathSvc.normalize(name) + return pathSvc.resolve(cwd, name) + } - // generate id from root commit - if (!id) { - const roots = await git(["rev-list", "--max-parents=0", "HEAD"], { - cwd: sandbox, - }) - .then(async (result) => - (await result.text()) - .split("\n") - .filter(Boolean) - .map((x) => x.trim()) - .toSorted(), - ) - .catch(() => undefined) + const scope = yield* Scope.Scope - if (!roots) { + const readCachedProjectId = Effect.fnUntraced(function* (dir: string) { + return yield* fsys.readFileString(pathSvc.join(dir, "opencode")).pipe( + Effect.map((x) => x.trim()), + Effect.map(ProjectID.make), + Effect.catch(() => Effect.succeed(undefined)), + ) + }) + + const fromDirectory = Effect.fn("Project.fromDirectory")(function* (directory: string) { + log.info("fromDirectory", { directory }) + + // Phase 1: discover git info + type DiscoveryResult = { id: ProjectID; worktree: string; sandbox: string; vcs: Info["vcs"] } + + const data: DiscoveryResult = yield* Effect.gen(function* () { + const dotgitMatches = yield* fsys.up({ targets: [".git"], start: directory }).pipe(Effect.orDie) + const dotgit = dotgitMatches[0] + + if (!dotgit) { return { id: ProjectID.global, - worktree: sandbox, - sandbox, - vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS), + worktree: "/", + sandbox: "/", + vcs: fakeVcs, } } - id = roots[0] ? ProjectID.make(roots[0]) : undefined - if (id) { - // Write to common dir so the cache is shared across worktrees. - await Filesystem.write(path.join(worktree, ".git", "opencode"), id).catch(() => undefined) - } - } + let sandbox = pathSvc.dirname(dotgit) + const gitBinary = yield* Effect.sync(() => which("git")) + let id = yield* readCachedProjectId(dotgit) - if (!id) { - return { - id: ProjectID.global, - worktree: sandbox, - sandbox, - vcs: "git", + if (!gitBinary) { + return { + id: id ?? ProjectID.global, + worktree: sandbox, + sandbox, + vcs: fakeVcs, + } } - } - const top = await git(["rev-parse", "--show-toplevel"], { - cwd: sandbox, + const commonDir = yield* git(["rev-parse", "--git-common-dir"], { cwd: sandbox }) + if (commonDir.code !== 0) { + return { + id: id ?? ProjectID.global, + worktree: sandbox, + sandbox, + vcs: fakeVcs, + } + } + const worktree = (() => { + const common = resolveGitPath(sandbox, commonDir.text.trim()) + return common === sandbox ? sandbox : pathSvc.dirname(common) + })() + + if (id == null) { + id = yield* readCachedProjectId(pathSvc.join(worktree, ".git")) + } + + if (!id) { + const revList = yield* git(["rev-list", "--max-parents=0", "HEAD"], { cwd: sandbox }) + const roots = revList.text + .split("\n") + .filter(Boolean) + .map((x) => x.trim()) + .toSorted() + + id = roots[0] ? ProjectID.make(roots[0]) : undefined + if (id) { + yield* fsys.writeFileString(pathSvc.join(worktree, ".git", "opencode"), id).pipe(Effect.ignore) + } + } + + if (!id) { + return { id: ProjectID.global, worktree: sandbox, sandbox, vcs: "git" as const } + } + + const topLevel = yield* git(["rev-parse", "--show-toplevel"], { cwd: sandbox }) + if (topLevel.code !== 0) { + return { + id, + worktree: sandbox, + sandbox, + vcs: fakeVcs, + } + } + sandbox = resolveGitPath(sandbox, topLevel.text.trim()) + + return { id, sandbox, worktree, vcs: "git" as const } }) - .then(async (result) => gitpath(sandbox, await result.text())) - .catch(() => undefined) - if (!top) { - return { - id, - worktree: sandbox, - sandbox, - vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS), - } - } + // Phase 2: upsert + const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, data.id)).get()) + const existing = row + ? fromRow(row) + : { + id: data.id, + worktree: data.worktree, + vcs: data.vcs, + sandboxes: [] as string[], + time: { created: Date.now(), updated: Date.now() }, + } - sandbox = top + if (Flag.OPENCODE_EXPERIMENTAL_ICON_DISCOVERY) + yield* discover(existing).pipe(Effect.ignore, Effect.forkIn(scope)) - return { - id, - sandbox, - worktree, - vcs: "git", - } - } - - return { - id: ProjectID.global, - worktree: "/", - sandbox: "/", - vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS), - } - }) - - const row = Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, data.id)).get()) - const existing = row - ? fromRow(row) - : { - id: data.id, + const result: Info = { + ...existing, worktree: data.worktree, - vcs: data.vcs as Info["vcs"], - sandboxes: [] as string[], - time: { - created: Date.now(), - updated: Date.now(), - }, + vcs: data.vcs, + time: { ...existing.time, updated: Date.now() }, + } + if (data.sandbox !== result.worktree && !result.sandboxes.includes(data.sandbox)) + result.sandboxes.push(data.sandbox) + result.sandboxes = yield* Effect.forEach( + result.sandboxes, + (s) => + fsys.exists(s).pipe( + Effect.orDie, + Effect.map((exists) => (exists ? s : undefined)), + ), + { concurrency: "unbounded" }, + ).pipe(Effect.map((arr) => arr.filter((x): x is string => x !== undefined))) + + yield* db((d) => + d + .insert(ProjectTable) + .values({ + id: result.id, + worktree: result.worktree, + vcs: result.vcs ?? null, + name: result.name, + icon_url: result.icon?.url, + icon_color: result.icon?.color, + time_created: result.time.created, + time_updated: result.time.updated, + time_initialized: result.time.initialized, + sandboxes: result.sandboxes, + commands: result.commands, + }) + .onConflictDoUpdate({ + target: ProjectTable.id, + set: { + worktree: result.worktree, + vcs: result.vcs ?? null, + name: result.name, + icon_url: result.icon?.url, + icon_color: result.icon?.color, + time_updated: result.time.updated, + time_initialized: result.time.initialized, + sandboxes: result.sandboxes, + commands: result.commands, + }, + }) + .run(), + ) + + if (data.id !== ProjectID.global) { + yield* db((d) => + d + .update(SessionTable) + .set({ project_id: data.id }) + .where(and(eq(SessionTable.project_id, ProjectID.global), eq(SessionTable.directory, data.worktree))) + .run(), + ) } - if (Flag.OPENCODE_EXPERIMENTAL_ICON_DISCOVERY) discover(existing) + yield* emitUpdated(result) + return { project: result, sandbox: data.sandbox } + }) - const result: Info = { - ...existing, - worktree: data.worktree, - vcs: data.vcs as Info["vcs"], - time: { - ...existing.time, - updated: Date.now(), - }, - } - if (data.sandbox !== result.worktree && !result.sandboxes.includes(data.sandbox)) - result.sandboxes.push(data.sandbox) - result.sandboxes = result.sandboxes.filter((x) => existsSync(x)) - const insert = { - id: result.id, - worktree: result.worktree, - vcs: result.vcs ?? null, - name: result.name, - icon_url: result.icon?.url, - icon_color: result.icon?.color, - time_created: result.time.created, - time_updated: result.time.updated, - time_initialized: result.time.initialized, - sandboxes: result.sandboxes, - commands: result.commands, - } - const updateSet = { - worktree: result.worktree, - vcs: result.vcs ?? null, - name: result.name, - icon_url: result.icon?.url, - icon_color: result.icon?.color, - time_updated: result.time.updated, - time_initialized: result.time.initialized, - sandboxes: result.sandboxes, - commands: result.commands, - } - Database.use((db) => - db.insert(ProjectTable).values(insert).onConflictDoUpdate({ target: ProjectTable.id, set: updateSet }).run(), - ) - // Runs after upsert so the target project row exists (FK constraint). - // Runs on every startup because sessions created before git init - // accumulate under "global" and need migrating whenever they appear. - if (data.id !== ProjectID.global) { - Database.use((db) => - db - .update(SessionTable) - .set({ project_id: data.id }) - .where(and(eq(SessionTable.project_id, ProjectID.global), eq(SessionTable.directory, data.worktree))) - .run(), - ) - } - GlobalBus.emit("event", { - payload: { - type: Event.Updated.type, - properties: result, - }, - }) - return { project: result, sandbox: data.sandbox } + const discover = Effect.fn("Project.discover")(function* (input: Info) { + if (input.vcs !== "git") return + if (input.icon?.override) return + if (input.icon?.url) return + + const matches = yield* fsys + .glob("**/favicon.{ico,png,svg,jpg,jpeg,webp}", { + cwd: input.worktree, + absolute: true, + include: "file", + }) + .pipe(Effect.orDie) + const shortest = matches.sort((a, b) => a.length - b.length)[0] + if (!shortest) return + + const buffer = yield* fsys.readFile(shortest).pipe(Effect.orDie) + const base64 = Buffer.from(buffer).toString("base64") + const mime = AppFileSystem.mimeType(shortest) + const url = `data:${mime};base64,${base64}` + yield* update({ projectID: input.id, icon: { url } }) + }) + + const list = Effect.fn("Project.list")(function* () { + return yield* db((d) => d.select().from(ProjectTable).all().map(fromRow)) + }) + + const get = Effect.fn("Project.get")(function* (id: ProjectID) { + const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + return row ? fromRow(row) : undefined + }) + + const update = Effect.fn("Project.update")(function* (input: UpdateInput) { + const result = yield* db((d) => + d + .update(ProjectTable) + .set({ + name: input.name, + icon_url: input.icon?.url, + icon_color: input.icon?.color, + commands: input.commands, + time_updated: Date.now(), + }) + .where(eq(ProjectTable.id, input.projectID)) + .returning() + .get(), + ) + if (!result) throw new Error(`Project not found: ${input.projectID}`) + const data = fromRow(result) + yield* emitUpdated(data) + return data + }) + + const initGit = Effect.fn("Project.initGit")(function* (input: { directory: string; project: Info }) { + if (input.project.vcs === "git") return input.project + if (!(yield* Effect.sync(() => which("git")))) throw new Error("Git is not installed") + const result = yield* git(["init", "--quiet"], { cwd: input.directory }) + if (result.code !== 0) { + throw new Error(result.stderr.trim() || result.text.trim() || "Failed to initialize git repository") + } + const { project } = yield* fromDirectory(input.directory) + return project + }) + + const setInitialized = Effect.fn("Project.setInitialized")(function* (id: ProjectID) { + yield* db((d) => + d.update(ProjectTable).set({ time_initialized: Date.now() }).where(eq(ProjectTable.id, id)).run(), + ) + }) + + const sandboxes = Effect.fn("Project.sandboxes")(function* (id: ProjectID) { + const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + if (!row) return [] + const data = fromRow(row) + return yield* Effect.forEach( + data.sandboxes, + (dir) => fsys.isDir(dir).pipe(Effect.orDie, Effect.map((ok) => (ok ? dir : undefined))), + { concurrency: "unbounded" }, + ).pipe(Effect.map((arr) => arr.filter((x): x is string => x !== undefined))) + }) + + const addSandbox = Effect.fn("Project.addSandbox")(function* (id: ProjectID, directory: string) { + const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + if (!row) throw new Error(`Project not found: ${id}`) + const sboxes = [...row.sandboxes] + if (!sboxes.includes(directory)) sboxes.push(directory) + const result = yield* db((d) => + d + .update(ProjectTable) + .set({ sandboxes: sboxes, time_updated: Date.now() }) + .where(eq(ProjectTable.id, id)) + .returning() + .get(), + ) + if (!result) throw new Error(`Project not found: ${id}`) + yield* emitUpdated(fromRow(result)) + }) + + const removeSandbox = Effect.fn("Project.removeSandbox")(function* (id: ProjectID, directory: string) { + const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + if (!row) throw new Error(`Project not found: ${id}`) + const sboxes = row.sandboxes.filter((s) => s !== directory) + const result = yield* db((d) => + d + .update(ProjectTable) + .set({ sandboxes: sboxes, time_updated: Date.now() }) + .where(eq(ProjectTable.id, id)) + .returning() + .get(), + ) + if (!result) throw new Error(`Project not found: ${id}`) + yield* emitUpdated(fromRow(result)) + }) + + return Service.of({ + fromDirectory, + discover, + list, + get, + update, + initGit, + setInitialized, + sandboxes, + addSandbox, + removeSandbox, + }) + }), + ) + + export const defaultLayer = layer.pipe( + Layer.provide(CrossSpawnSpawner.layer), + Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(NodeFileSystem.layer), + Layer.provide(NodePath.layer), + ) + const runPromise = makeRunPromise(Service, defaultLayer) + + // --------------------------------------------------------------------------- + // Promise-based API (delegates to Effect service via runPromise) + // --------------------------------------------------------------------------- + + export function fromDirectory(directory: string) { + return runPromise((svc) => svc.fromDirectory(directory)) } - export async function discover(input: Info) { - if (input.vcs !== "git") return - if (input.icon?.override) return - if (input.icon?.url) return - const matches = await Glob.scan("**/favicon.{ico,png,svg,jpg,jpeg,webp}", { - cwd: input.worktree, - absolute: true, - include: "file", - }) - const shortest = matches.sort((a, b) => a.length - b.length)[0] - if (!shortest) return - const buffer = await Filesystem.readBytes(shortest) - const base64 = buffer.toString("base64") - const mime = Filesystem.mimeType(shortest) || "image/png" - const url = `data:${mime};base64,${base64}` - await update({ - projectID: input.id, - icon: { - url, - }, - }) - return - } - - export function setInitialized(id: ProjectID) { - Database.use((db) => - db - .update(ProjectTable) - .set({ - time_initialized: Date.now(), - }) - .where(eq(ProjectTable.id, id)) - .run(), - ) + export function discover(input: Info) { + return runPromise((svc) => svc.discover(input)) } export function list() { @@ -345,112 +488,29 @@ export namespace Project { return fromRow(row) } - export async function initGit(input: { directory: string; project: Info }) { - if (input.project.vcs === "git") return input.project - if (!which("git")) throw new Error("Git is not installed") - - const result = await git(["init", "--quiet"], { - cwd: input.directory, - }) - if (result.exitCode !== 0) { - const text = result.stderr.toString().trim() || result.text().trim() - throw new Error(text || "Failed to initialize git repository") - } - - return (await fromDirectory(input.directory)).project - } - - export const update = fn( - z.object({ - projectID: ProjectID.zod, - name: z.string().optional(), - icon: Info.shape.icon.optional(), - commands: Info.shape.commands.optional(), - }), - async (input) => { - const id = ProjectID.make(input.projectID) - const result = Database.use((db) => - db - .update(ProjectTable) - .set({ - name: input.name, - icon_url: input.icon?.url, - icon_color: input.icon?.color, - commands: input.commands, - time_updated: Date.now(), - }) - .where(eq(ProjectTable.id, id)) - .returning() - .get(), - ) - if (!result) throw new Error(`Project not found: ${input.projectID}`) - const data = fromRow(result) - GlobalBus.emit("event", { - payload: { - type: Event.Updated.type, - properties: data, - }, - }) - return data - }, - ) - - export async function sandboxes(id: ProjectID) { - const row = Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) - if (!row) return [] - const data = fromRow(row) - const valid: string[] = [] - for (const dir of data.sandboxes) { - const s = Filesystem.stat(dir) - if (s?.isDirectory()) valid.push(dir) - } - return valid - } - - export async function addSandbox(id: ProjectID, directory: string) { - const row = Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) - if (!row) throw new Error(`Project not found: ${id}`) - const sandboxes = [...row.sandboxes] - if (!sandboxes.includes(directory)) sandboxes.push(directory) - const result = Database.use((db) => - db - .update(ProjectTable) - .set({ sandboxes, time_updated: Date.now() }) - .where(eq(ProjectTable.id, id)) - .returning() - .get(), + export function setInitialized(id: ProjectID) { + Database.use((db) => + db.update(ProjectTable).set({ time_initialized: Date.now() }).where(eq(ProjectTable.id, id)).run(), ) - if (!result) throw new Error(`Project not found: ${id}`) - const data = fromRow(result) - GlobalBus.emit("event", { - payload: { - type: Event.Updated.type, - properties: data, - }, - }) - return data } - export async function removeSandbox(id: ProjectID, directory: string) { - const row = Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) - if (!row) throw new Error(`Project not found: ${id}`) - const sandboxes = row.sandboxes.filter((s) => s !== directory) - const result = Database.use((db) => - db - .update(ProjectTable) - .set({ sandboxes, time_updated: Date.now() }) - .where(eq(ProjectTable.id, id)) - .returning() - .get(), - ) - if (!result) throw new Error(`Project not found: ${id}`) - const data = fromRow(result) - GlobalBus.emit("event", { - payload: { - type: Event.Updated.type, - properties: data, - }, - }) - return data + export function initGit(input: { directory: string; project: Info }) { + return runPromise((svc) => svc.initGit(input)) + } + + export function update(input: UpdateInput) { + return runPromise((svc) => svc.update(input)) + } + + export function sandboxes(id: ProjectID) { + return runPromise((svc) => svc.sandboxes(id)) + } + + export function addSandbox(id: ProjectID, directory: string) { + return runPromise((svc) => svc.addSandbox(id, directory)) + } + + export function removeSandbox(id: ProjectID, directory: string) { + return runPromise((svc) => svc.removeSandbox(id, directory)) } } diff --git a/packages/opencode/src/server/routes/project.ts b/packages/opencode/src/server/routes/project.ts index 6cd51ac958..e5dd5782d6 100644 --- a/packages/opencode/src/server/routes/project.ts +++ b/packages/opencode/src/server/routes/project.ts @@ -107,7 +107,7 @@ export const ProjectRoutes = lazy(() => }, }), validator("param", z.object({ projectID: ProjectID.zod })), - validator("json", Project.update.schema.omit({ projectID: true })), + validator("json", Project.UpdateInput.omit({ projectID: true })), async (c) => { const projectID = c.req.valid("param").projectID const body = c.req.valid("json") diff --git a/packages/opencode/test/project/project.test.ts b/packages/opencode/test/project/project.test.ts index a71fe0528f..523f0711fd 100644 --- a/packages/opencode/test/project/project.test.ts +++ b/packages/opencode/test/project/project.test.ts @@ -1,78 +1,69 @@ -import { describe, expect, mock, test } from "bun:test" +import { describe, expect, test } from "bun:test" import { Project } from "../../src/project/project" import { Log } from "../../src/util/log" import { $ } from "bun" import path from "path" import { tmpdir } from "../fixture/fixture" -import { Filesystem } from "../../src/util/filesystem" import { GlobalBus } from "../../src/bus/global" import { ProjectID } from "../../src/project/schema" +import { Effect, Layer, Stream } from "effect" +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" +import { NodeFileSystem, NodePath } from "@effect/platform-node" +import { AppFileSystem } from "../../src/filesystem" +import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner" Log.init({ print: false }) -const gitModule = await import("../../src/util/git") -const originalGit = gitModule.git +const encoder = new TextEncoder() -type Mode = "none" | "rev-list-fail" | "top-fail" | "common-dir-fail" -let mode: Mode = "none" - -mock.module("../../src/util/git", () => ({ - git: (args: string[], opts: { cwd: string; env?: Record }) => { - const cmd = ["git", ...args].join(" ") - if ( - mode === "rev-list-fail" && - cmd.includes("git rev-list") && - cmd.includes("--max-parents=0") && - cmd.includes("HEAD") - ) { - return Promise.resolve({ - exitCode: 128, - text: () => Promise.resolve(""), - stdout: Buffer.from(""), - stderr: Buffer.from("fatal"), - }) - } - if (mode === "top-fail" && cmd.includes("git rev-parse") && cmd.includes("--show-toplevel")) { - return Promise.resolve({ - exitCode: 128, - text: () => Promise.resolve(""), - stdout: Buffer.from(""), - stderr: Buffer.from("fatal"), - }) - } - if (mode === "common-dir-fail" && cmd.includes("git rev-parse") && cmd.includes("--git-common-dir")) { - return Promise.resolve({ - exitCode: 128, - text: () => Promise.resolve(""), - stdout: Buffer.from(""), - stderr: Buffer.from("fatal"), - }) - } - return originalGit(args, opts) - }, -})) - -async function withMode(next: Mode, run: () => Promise) { - const prev = mode - mode = next - try { - await run() - } finally { - mode = prev - } +/** + * Creates a mock ChildProcessSpawner layer that intercepts git subcommands + * matching `failArg` and returns exit code 128, while delegating everything + * else to the real CrossSpawnSpawner. + */ +function mockGitFailure(failArg: string) { + return Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.gen(function* () { + const real = yield* ChildProcessSpawner.ChildProcessSpawner + return ChildProcessSpawner.make( + Effect.fnUntraced(function* (command) { + const std = ChildProcess.isStandardCommand(command) ? command : undefined + if (std?.command === "git" && std.args.some((a) => a === failArg)) { + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(0), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: { [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") } as any, + stdout: Stream.empty, + stderr: Stream.make(encoder.encode("fatal: simulated failure\n")), + all: Stream.empty, + getInputFd: () => ({ [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") }) as any, + getOutputFd: () => Stream.empty, + }) + } + return yield* real.spawn(command) + }), + ) + }), + ).pipe(Layer.provide(CrossSpawnSpawner.layer), Layer.provide(NodeFileSystem.layer), Layer.provide(NodePath.layer)) } -async function loadProject() { - return (await import("../../src/project/project")).Project +function projectLayerWithFailure(failArg: string) { + return Project.layer.pipe( + Layer.provide(mockGitFailure(failArg)), + Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(NodePath.layer), + ) } describe("Project.fromDirectory", () => { test("should handle git repository with no commits", async () => { - const p = await loadProject() await using tmp = await tmpdir() await $`git init`.cwd(tmp.path).quiet() - const { project } = await p.fromDirectory(tmp.path) + const { project } = await Project.fromDirectory(tmp.path) expect(project).toBeDefined() expect(project.id).toBe(ProjectID.global) @@ -80,15 +71,13 @@ describe("Project.fromDirectory", () => { expect(project.worktree).toBe(tmp.path) const opencodeFile = path.join(tmp.path, ".git", "opencode") - const fileExists = await Filesystem.exists(opencodeFile) - expect(fileExists).toBe(false) + expect(await Bun.file(opencodeFile).exists()).toBe(false) }) test("should handle git repository with commits", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) - const { project } = await p.fromDirectory(tmp.path) + const { project } = await Project.fromDirectory(tmp.path) expect(project).toBeDefined() expect(project.id).not.toBe(ProjectID.global) @@ -96,54 +85,63 @@ describe("Project.fromDirectory", () => { expect(project.worktree).toBe(tmp.path) const opencodeFile = path.join(tmp.path, ".git", "opencode") - const fileExists = await Filesystem.exists(opencodeFile) - expect(fileExists).toBe(true) + expect(await Bun.file(opencodeFile).exists()).toBe(true) }) - test("keeps git vcs when rev-list exits non-zero with empty output", async () => { - const p = await loadProject() + test("returns global for non-git directory", async () => { + await using tmp = await tmpdir() + const { project } = await Project.fromDirectory(tmp.path) + expect(project.id).toBe(ProjectID.global) + }) + + test("derives stable project ID from root commit", async () => { + await using tmp = await tmpdir({ git: true }) + const { project: a } = await Project.fromDirectory(tmp.path) + const { project: b } = await Project.fromDirectory(tmp.path) + expect(b.id).toBe(a.id) + }) +}) + +describe("Project.fromDirectory git failure paths", () => { + test("keeps vcs when rev-list exits non-zero (no commits)", async () => { await using tmp = await tmpdir() await $`git init`.cwd(tmp.path).quiet() - await withMode("rev-list-fail", async () => { - const { project } = await p.fromDirectory(tmp.path) - expect(project.vcs).toBe("git") - expect(project.id).toBe(ProjectID.global) - expect(project.worktree).toBe(tmp.path) - }) + // rev-list fails because HEAD doesn't exist yet — this is the natural scenario + const { project } = await Project.fromDirectory(tmp.path) + expect(project.vcs).toBe("git") + expect(project.id).toBe(ProjectID.global) + expect(project.worktree).toBe(tmp.path) }) - test("keeps git vcs when show-toplevel exits non-zero with empty output", async () => { - const p = await loadProject() + test("handles show-toplevel failure gracefully", async () => { await using tmp = await tmpdir({ git: true }) + const layer = projectLayerWithFailure("--show-toplevel") - await withMode("top-fail", async () => { - const { project, sandbox } = await p.fromDirectory(tmp.path) - expect(project.vcs).toBe("git") - expect(project.worktree).toBe(tmp.path) - expect(sandbox).toBe(tmp.path) - }) + const { project, sandbox } = await Effect.runPromise( + Project.Service.use((svc) => svc.fromDirectory(tmp.path)).pipe(Effect.provide(layer)), + ) + expect(project.worktree).toBe(tmp.path) + expect(sandbox).toBe(tmp.path) }) - test("keeps git vcs when git-common-dir exits non-zero with empty output", async () => { - const p = await loadProject() + test("handles git-common-dir failure gracefully", async () => { await using tmp = await tmpdir({ git: true }) + const layer = projectLayerWithFailure("--git-common-dir") - await withMode("common-dir-fail", async () => { - const { project, sandbox } = await p.fromDirectory(tmp.path) - expect(project.vcs).toBe("git") - expect(project.worktree).toBe(tmp.path) - expect(sandbox).toBe(tmp.path) - }) + const { project, sandbox } = await Effect.runPromise( + Project.Service.use((svc) => svc.fromDirectory(tmp.path)).pipe(Effect.provide(layer)), + ) + expect(project.worktree).toBe(tmp.path) + expect(sandbox).toBe(tmp.path) }) }) describe("Project.fromDirectory with worktrees", () => { test("should set worktree to root when called from root", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) - const { project, sandbox } = await p.fromDirectory(tmp.path) + const { project, sandbox } = await Project.fromDirectory(tmp.path) expect(project.worktree).toBe(tmp.path) expect(sandbox).toBe(tmp.path) @@ -151,14 +149,13 @@ describe("Project.fromDirectory with worktrees", () => { }) test("should set worktree to root when called from a worktree", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) const worktreePath = path.join(tmp.path, "..", path.basename(tmp.path) + "-worktree") try { await $`git worktree add ${worktreePath} -b test-branch-${Date.now()}`.cwd(tmp.path).quiet() - const { project, sandbox } = await p.fromDirectory(worktreePath) + const { project, sandbox } = await Project.fromDirectory(worktreePath) expect(project.worktree).toBe(tmp.path) expect(sandbox).toBe(worktreePath) @@ -173,22 +170,21 @@ describe("Project.fromDirectory with worktrees", () => { }) test("worktree should share project ID with main repo", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) - const { project: main } = await p.fromDirectory(tmp.path) + const { project: main } = await Project.fromDirectory(tmp.path) const worktreePath = path.join(tmp.path, "..", path.basename(tmp.path) + "-wt-shared") try { await $`git worktree add ${worktreePath} -b shared-${Date.now()}`.cwd(tmp.path).quiet() - const { project: wt } = await p.fromDirectory(worktreePath) + const { project: wt } = await Project.fromDirectory(worktreePath) expect(wt.id).toBe(main.id) // Cache should live in the common .git dir, not the worktree's .git file const cache = path.join(tmp.path, ".git", "opencode") - const exists = await Filesystem.exists(cache) + const exists = await Bun.file(cache).exists() expect(exists).toBe(true) } finally { await $`git worktree remove ${worktreePath}` @@ -199,7 +195,6 @@ describe("Project.fromDirectory with worktrees", () => { }) test("separate clones of the same repo should share project ID", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) // Create a bare remote, push, then clone into a second directory @@ -209,8 +204,8 @@ describe("Project.fromDirectory with worktrees", () => { await $`git clone --bare ${tmp.path} ${bare}`.quiet() await $`git clone ${bare} ${clone}`.quiet() - const { project: a } = await p.fromDirectory(tmp.path) - const { project: b } = await p.fromDirectory(clone) + const { project: a } = await Project.fromDirectory(tmp.path) + const { project: b } = await Project.fromDirectory(clone) expect(b.id).toBe(a.id) } finally { @@ -219,7 +214,6 @@ describe("Project.fromDirectory with worktrees", () => { }) test("should accumulate multiple worktrees in sandboxes", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) const worktree1 = path.join(tmp.path, "..", path.basename(tmp.path) + "-wt1") @@ -228,8 +222,8 @@ describe("Project.fromDirectory with worktrees", () => { await $`git worktree add ${worktree1} -b branch-${Date.now()}`.cwd(tmp.path).quiet() await $`git worktree add ${worktree2} -b branch-${Date.now() + 1}`.cwd(tmp.path).quiet() - await p.fromDirectory(worktree1) - const { project } = await p.fromDirectory(worktree2) + await Project.fromDirectory(worktree1) + const { project } = await Project.fromDirectory(worktree2) expect(project.worktree).toBe(tmp.path) expect(project.sandboxes).toContain(worktree1) @@ -250,14 +244,13 @@ describe("Project.fromDirectory with worktrees", () => { describe("Project.discover", () => { test("should discover favicon.png in root", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) - const { project } = await p.fromDirectory(tmp.path) + const { project } = await Project.fromDirectory(tmp.path) const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) await Bun.write(path.join(tmp.path, "favicon.png"), pngData) - await p.discover(project) + await Project.discover(project) const updated = Project.get(project.id) expect(updated).toBeDefined() @@ -268,13 +261,12 @@ describe("Project.discover", () => { }) test("should not discover non-image files", async () => { - const p = await loadProject() await using tmp = await tmpdir({ git: true }) - const { project } = await p.fromDirectory(tmp.path) + const { project } = await Project.fromDirectory(tmp.path) await Bun.write(path.join(tmp.path, "favicon.txt"), "not an image") - await p.discover(project) + await Project.discover(project) const updated = Project.get(project.id) expect(updated).toBeDefined() @@ -344,8 +336,6 @@ describe("Project.update", () => { }) test("should throw error when project not found", async () => { - await using tmp = await tmpdir({ git: true }) - await expect( Project.update({ projectID: ProjectID.make("nonexistent-project-id"), @@ -358,22 +348,22 @@ describe("Project.update", () => { await using tmp = await tmpdir({ git: true }) const { project } = await Project.fromDirectory(tmp.path) - let eventFired = false let eventPayload: any = null + const on = (data: any) => { eventPayload = data } + GlobalBus.on("event", on) - GlobalBus.on("event", (data) => { - eventFired = true - eventPayload = data - }) + try { + await Project.update({ + projectID: project.id, + name: "Updated Name", + }) - await Project.update({ - projectID: project.id, - name: "Updated Name", - }) - - expect(eventFired).toBe(true) - expect(eventPayload.payload.type).toBe("project.updated") - expect(eventPayload.payload.properties.name).toBe("Updated Name") + expect(eventPayload).not.toBeNull() + expect(eventPayload.payload.type).toBe("project.updated") + expect(eventPayload.payload.properties.name).toBe("Updated Name") + } finally { + GlobalBus.off("event", on) + } }) test("should update multiple fields at once", async () => { @@ -393,3 +383,75 @@ describe("Project.update", () => { expect(updated.commands?.start).toBe("make start") }) }) + +describe("Project.list and Project.get", () => { + test("list returns all projects", async () => { + await using tmp = await tmpdir({ git: true }) + const { project } = await Project.fromDirectory(tmp.path) + + const all = Project.list() + expect(all.length).toBeGreaterThan(0) + expect(all.find((p) => p.id === project.id)).toBeDefined() + }) + + test("get returns project by id", async () => { + await using tmp = await tmpdir({ git: true }) + const { project } = await Project.fromDirectory(tmp.path) + + const found = Project.get(project.id) + expect(found).toBeDefined() + expect(found!.id).toBe(project.id) + }) + + test("get returns undefined for unknown id", () => { + const found = Project.get(ProjectID.make("nonexistent")) + expect(found).toBeUndefined() + }) +}) + +describe("Project.setInitialized", () => { + test("sets time_initialized on project", async () => { + await using tmp = await tmpdir({ git: true }) + const { project } = await Project.fromDirectory(tmp.path) + + expect(project.time.initialized).toBeUndefined() + + Project.setInitialized(project.id) + + const updated = Project.get(project.id) + expect(updated?.time.initialized).toBeDefined() + }) +}) + +describe("Project.addSandbox and Project.removeSandbox", () => { + test("addSandbox adds directory and removeSandbox removes it", async () => { + await using tmp = await tmpdir({ git: true }) + const { project } = await Project.fromDirectory(tmp.path) + const sandboxDir = path.join(tmp.path, "sandbox-test") + + await Project.addSandbox(project.id, sandboxDir) + + let found = Project.get(project.id) + expect(found?.sandboxes).toContain(sandboxDir) + + await Project.removeSandbox(project.id, sandboxDir) + + found = Project.get(project.id) + expect(found?.sandboxes).not.toContain(sandboxDir) + }) + + test("addSandbox emits GlobalBus event", async () => { + await using tmp = await tmpdir({ git: true }) + const { project } = await Project.fromDirectory(tmp.path) + const sandboxDir = path.join(tmp.path, "sandbox-event") + + const events: any[] = [] + const on = (evt: any) => events.push(evt) + GlobalBus.on("event", on) + + await Project.addSandbox(project.id, sandboxDir) + + GlobalBus.off("event", on) + expect(events.some((e) => e.payload.type === Project.Event.Updated.type)).toBe(true) + }) +}) From 42a773481e4d50a59784d514d81257330de38ca9 Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Tue, 24 Mar 2026 13:03:55 -0500 Subject: [PATCH 11/32] fix(app): sidebar truncation --- .../app/src/pages/layout/sidebar-items.tsx | 179 +++++++++--------- 1 file changed, 92 insertions(+), 87 deletions(-) diff --git a/packages/app/src/pages/layout/sidebar-items.tsx b/packages/app/src/pages/layout/sidebar-items.tsx index a9627c5dbc..75dada05f0 100644 --- a/packages/app/src/pages/layout/sidebar-items.tsx +++ b/packages/app/src/pages/layout/sidebar-items.tsx @@ -104,7 +104,7 @@ const SessionRow = (props: { }): JSX.Element => ( -
-
- }> - - - - -
- - -
- - 0}> -
- - -
- - {props.session.title} - +
+ }> + + + + +
+ + +
+ + 0}> +
+ +
+ {props.session.title}
) @@ -167,7 +163,11 @@ const SessionHoverPreview = (props: { placement="right-start" gutter={16} shift={-2} - trigger={
{props.trigger}
} + trigger={ +
+ {props.trigger} +
+ } open={props.hoverSession() === props.session.id} onOpenChange={(open) => { if (!open) { @@ -309,62 +309,71 @@ export const SessionItem = (props: SessionItemProps): JSX.Element => { return (
- - {item} - - } - > - { - if (!isActive()) - layout.pendingMessage.set(`${base64Encode(props.session.directory)}/${props.session.id}`, message.id) +
+
+ + {item} + + } + > + { + if (!isActive()) + layout.pendingMessage.set(`${base64Encode(props.session.directory)}/${props.session.id}`, message.id) - navigate(`${props.slug}/session/${props.session.id}#message-${message.id}`) + navigate(`${props.slug}/session/${props.session.id}#message-${message.id}`) + }} + trigger={item} + /> + +
+ +
- - -
- - { - event.preventDefault() - event.stopPropagation() - void props.archiveSession(props.session) - }} - /> - + > + + { + event.preventDefault() + event.stopPropagation() + void props.archiveSession(props.session) + }} + /> + +
) @@ -386,30 +395,26 @@ export const NewSessionItem = (props: { { props.setHoverSession(undefined) if (layout.sidebar.opened()) return props.clearHoverProjectSoon() }} > -
-
- -
- - {label} - +
+
+ {label}
) return ( -
+
+ {item} } From 8994cbfc0f57aede5a34a202f778d3a4385908af Mon Sep 17 00:00:00 2001 From: "opencode-agent[bot]" Date: Tue, 24 Mar 2026 18:05:43 +0000 Subject: [PATCH 12/32] chore: generate --- packages/opencode/src/project/project.ts | 6 +++++- packages/opencode/test/project/project.test.ts | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/project/project.ts b/packages/opencode/src/project/project.ts index 3d20f58d45..256be36959 100644 --- a/packages/opencode/src/project/project.ts +++ b/packages/opencode/src/project/project.ts @@ -399,7 +399,11 @@ export namespace Project { const data = fromRow(row) return yield* Effect.forEach( data.sandboxes, - (dir) => fsys.isDir(dir).pipe(Effect.orDie, Effect.map((ok) => (ok ? dir : undefined))), + (dir) => + fsys.isDir(dir).pipe( + Effect.orDie, + Effect.map((ok) => (ok ? dir : undefined)), + ), { concurrency: "unbounded" }, ).pipe(Effect.map((arr) => arr.filter((x): x is string => x !== undefined))) }) diff --git a/packages/opencode/test/project/project.test.ts b/packages/opencode/test/project/project.test.ts index 523f0711fd..b030e6cbcd 100644 --- a/packages/opencode/test/project/project.test.ts +++ b/packages/opencode/test/project/project.test.ts @@ -349,7 +349,9 @@ describe("Project.update", () => { const { project } = await Project.fromDirectory(tmp.path) let eventPayload: any = null - const on = (data: any) => { eventPayload = data } + const on = (data: any) => { + eventPayload = data + } GlobalBus.on("event", on) try { From 2c1d8a90d567d65ac044b2feaf2ee886318247ec Mon Sep 17 00:00:00 2001 From: Caleb Norton Date: Tue, 24 Mar 2026 13:06:46 -0500 Subject: [PATCH 13/32] fix: nix hash update parsing... again (#18989) --- .github/workflows/nix-hashes.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/nix-hashes.yml b/.github/workflows/nix-hashes.yml index 47385d20c6..9d94682f11 100644 --- a/.github/workflows/nix-hashes.yml +++ b/.github/workflows/nix-hashes.yml @@ -56,7 +56,7 @@ jobs: nix build ".#packages.${SYSTEM}.node_modules_updater" --no-link 2>&1 | tee "$BUILD_LOG" || true # Extract hash from build log with portability - HASH="$(grep -oP 'got:\s*\Ksha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" + HASH="$(nix run --inputs-from . nixpkgs#gnugrep -- -oP 'got:\s*\Ksha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)" if [ -z "$HASH" ]; then echo "::error::Failed to compute hash for ${SYSTEM}" From 5e684c6e80d30a77ba02db013c61b8ecfe420f7f Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 24 Mar 2026 13:15:23 -0500 Subject: [PATCH 14/32] chore: effectify agent.ts (#18971) Co-authored-by: Kit Langton --- packages/opencode/src/agent/agent.ts | 609 +++++++++++++++------------ 1 file changed, 340 insertions(+), 269 deletions(-) diff --git a/packages/opencode/src/agent/agent.ts b/packages/opencode/src/agent/agent.ts index 30d0986144..72b2869641 100644 --- a/packages/opencode/src/agent/agent.ts +++ b/packages/opencode/src/agent/agent.ts @@ -3,7 +3,6 @@ import z from "zod" import { Provider } from "../provider/provider" import { ModelID, ProviderID } from "../provider/schema" import { generateObject, streamObject, type ModelMessage } from "ai" -import { SystemPrompt } from "../session/system" import { Instance } from "../project/instance" import { Truncate } from "../tool/truncate" import { Auth } from "../auth" @@ -20,6 +19,9 @@ import { Global } from "@/global" import path from "path" import { Plugin } from "@/plugin" import { Skill } from "../skill" +import { Effect, ServiceMap, Layer } from "effect" +import { InstanceState } from "@/effect/instance-state" +import { makeRunPromise } from "@/effect/run-service" export namespace Agent { export const Info = z @@ -49,295 +51,364 @@ export namespace Agent { }) export type Info = z.infer - const state = Instance.state(async () => { - const cfg = await Config.get() + export interface Interface { + readonly get: (agent: string) => Effect.Effect + readonly list: () => Effect.Effect + readonly defaultAgent: () => Effect.Effect + readonly generate: (input: { + description: string + model?: { providerID: ProviderID; modelID: ModelID } + }) => Effect.Effect<{ + identifier: string + whenToUse: string + systemPrompt: string + }> + } - const skillDirs = await Skill.dirs() - const whitelistedDirs = [Truncate.GLOB, ...skillDirs.map((dir) => path.join(dir, "*"))] - const defaults = Permission.fromConfig({ - "*": "allow", - doom_loop: "ask", - external_directory: { - "*": "ask", - ...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])), - }, - question: "deny", - plan_enter: "deny", - plan_exit: "deny", - // mirrors github.com/github/gitignore Node.gitignore pattern for .env files - read: { - "*": "allow", - "*.env": "ask", - "*.env.*": "ask", - "*.env.example": "allow", - }, - }) - const user = Permission.fromConfig(cfg.permission ?? {}) + type State = Omit - const result: Record = { - build: { - name: "build", - description: "The default agent. Executes tools based on configured permissions.", - options: {}, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - question: "allow", - plan_enter: "allow", - }), - user, - ), - mode: "primary", - native: true, - }, - plan: { - name: "plan", - description: "Plan mode. Disallows all edit tools.", - options: {}, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - question: "allow", - plan_exit: "allow", - external_directory: { - [path.join(Global.Path.data, "plans", "*")]: "allow", - }, - edit: { - "*": "deny", - [path.join(".opencode", "plans", "*.md")]: "allow", - [path.relative(Instance.worktree, path.join(Global.Path.data, path.join("plans", "*.md")))]: "allow", - }, - }), - user, - ), - mode: "primary", - native: true, - }, - general: { - name: "general", - description: `General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.`, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - todoread: "deny", - todowrite: "deny", - }), - user, - ), - options: {}, - mode: "subagent", - native: true, - }, - explore: { - name: "explore", - permission: Permission.merge( - defaults, - Permission.fromConfig({ - "*": "deny", - grep: "allow", - glob: "allow", - list: "allow", - bash: "allow", - webfetch: "allow", - websearch: "allow", - codesearch: "allow", - read: "allow", + export class Service extends ServiceMap.Service()("@opencode/Agent") {} + + export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const config = () => Effect.promise(() => Config.get()) + const auth = yield* Auth.Service + + const state = yield* InstanceState.make( + Effect.fn("Agent.state")(function* (ctx) { + const cfg = yield* config() + const skillDirs = yield* Effect.promise(() => Skill.dirs()) + const whitelistedDirs = [Truncate.GLOB, ...skillDirs.map((dir) => path.join(dir, "*"))] + + const defaults = Permission.fromConfig({ + "*": "allow", + doom_loop: "ask", external_directory: { "*": "ask", ...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])), }, - }), - user, - ), - description: `Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.`, - prompt: PROMPT_EXPLORE, - options: {}, - mode: "subagent", - native: true, - }, - compaction: { - name: "compaction", - mode: "primary", - native: true, - hidden: true, - prompt: PROMPT_COMPACTION, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - "*": "deny", - }), - user, - ), - options: {}, - }, - title: { - name: "title", - mode: "primary", - options: {}, - native: true, - hidden: true, - temperature: 0.5, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - "*": "deny", - }), - user, - ), - prompt: PROMPT_TITLE, - }, - summary: { - name: "summary", - mode: "primary", - options: {}, - native: true, - hidden: true, - permission: Permission.merge( - defaults, - Permission.fromConfig({ - "*": "deny", - }), - user, - ), - prompt: PROMPT_SUMMARY, - }, - } + question: "deny", + plan_enter: "deny", + plan_exit: "deny", + // mirrors github.com/github/gitignore Node.gitignore pattern for .env files + read: { + "*": "allow", + "*.env": "ask", + "*.env.*": "ask", + "*.env.example": "allow", + }, + }) - for (const [key, value] of Object.entries(cfg.agent ?? {})) { - if (value.disable) { - delete result[key] - continue - } - let item = result[key] - if (!item) - item = result[key] = { - name: key, - mode: "all", - permission: Permission.merge(defaults, user), - options: {}, - native: false, - } - if (value.model) item.model = Provider.parseModel(value.model) - item.variant = value.variant ?? item.variant - item.prompt = value.prompt ?? item.prompt - item.description = value.description ?? item.description - item.temperature = value.temperature ?? item.temperature - item.topP = value.top_p ?? item.topP - item.mode = value.mode ?? item.mode - item.color = value.color ?? item.color - item.hidden = value.hidden ?? item.hidden - item.name = value.name ?? item.name - item.steps = value.steps ?? item.steps - item.options = mergeDeep(item.options, value.options ?? {}) - item.permission = Permission.merge(item.permission, Permission.fromConfig(value.permission ?? {})) - } + const user = Permission.fromConfig(cfg.permission ?? {}) - // Ensure Truncate.GLOB is allowed unless explicitly configured - for (const name in result) { - const agent = result[name] - const explicit = agent.permission.some((r) => { - if (r.permission !== "external_directory") return false - if (r.action !== "deny") return false - return r.pattern === Truncate.GLOB - }) - if (explicit) continue + const agents: Record = { + build: { + name: "build", + description: "The default agent. Executes tools based on configured permissions.", + options: {}, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + question: "allow", + plan_enter: "allow", + }), + user, + ), + mode: "primary", + native: true, + }, + plan: { + name: "plan", + description: "Plan mode. Disallows all edit tools.", + options: {}, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + question: "allow", + plan_exit: "allow", + external_directory: { + [path.join(Global.Path.data, "plans", "*")]: "allow", + }, + edit: { + "*": "deny", + [path.join(".opencode", "plans", "*.md")]: "allow", + [path.relative(Instance.worktree, path.join(Global.Path.data, path.join("plans", "*.md")))]: + "allow", + }, + }), + user, + ), + mode: "primary", + native: true, + }, + general: { + name: "general", + description: `General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.`, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + todoread: "deny", + todowrite: "deny", + }), + user, + ), + options: {}, + mode: "subagent", + native: true, + }, + explore: { + name: "explore", + permission: Permission.merge( + defaults, + Permission.fromConfig({ + "*": "deny", + grep: "allow", + glob: "allow", + list: "allow", + bash: "allow", + webfetch: "allow", + websearch: "allow", + codesearch: "allow", + read: "allow", + external_directory: { + "*": "ask", + ...Object.fromEntries(whitelistedDirs.map((dir) => [dir, "allow"])), + }, + }), + user, + ), + description: `Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.`, + prompt: PROMPT_EXPLORE, + options: {}, + mode: "subagent", + native: true, + }, + compaction: { + name: "compaction", + mode: "primary", + native: true, + hidden: true, + prompt: PROMPT_COMPACTION, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + "*": "deny", + }), + user, + ), + options: {}, + }, + title: { + name: "title", + mode: "primary", + options: {}, + native: true, + hidden: true, + temperature: 0.5, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + "*": "deny", + }), + user, + ), + prompt: PROMPT_TITLE, + }, + summary: { + name: "summary", + mode: "primary", + options: {}, + native: true, + hidden: true, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + "*": "deny", + }), + user, + ), + prompt: PROMPT_SUMMARY, + }, + } - result[name].permission = Permission.merge( - result[name].permission, - Permission.fromConfig({ external_directory: { [Truncate.GLOB]: "allow" } }), + for (const [key, value] of Object.entries(cfg.agent ?? {})) { + if (value.disable) { + delete agents[key] + continue + } + let item = agents[key] + if (!item) + item = agents[key] = { + name: key, + mode: "all", + permission: Permission.merge(defaults, user), + options: {}, + native: false, + } + if (value.model) item.model = Provider.parseModel(value.model) + item.variant = value.variant ?? item.variant + item.prompt = value.prompt ?? item.prompt + item.description = value.description ?? item.description + item.temperature = value.temperature ?? item.temperature + item.topP = value.top_p ?? item.topP + item.mode = value.mode ?? item.mode + item.color = value.color ?? item.color + item.hidden = value.hidden ?? item.hidden + item.name = value.name ?? item.name + item.steps = value.steps ?? item.steps + item.options = mergeDeep(item.options, value.options ?? {}) + item.permission = Permission.merge(item.permission, Permission.fromConfig(value.permission ?? {})) + } + + // Ensure Truncate.GLOB is allowed unless explicitly configured + for (const name in agents) { + const agent = agents[name] + const explicit = agent.permission.some((r) => { + if (r.permission !== "external_directory") return false + if (r.action !== "deny") return false + return r.pattern === Truncate.GLOB + }) + if (explicit) continue + + agents[name].permission = Permission.merge( + agents[name].permission, + Permission.fromConfig({ external_directory: { [Truncate.GLOB]: "allow" } }), + ) + } + + const get = Effect.fnUntraced(function* (agent: string) { + return agents[agent] + }) + + const list = Effect.fnUntraced(function* () { + const cfg = yield* config() + return pipe( + agents, + values(), + sortBy( + [(x) => (cfg.default_agent ? x.name === cfg.default_agent : x.name === "build"), "desc"], + [(x) => x.name, "asc"], + ), + ) + }) + + const defaultAgent = Effect.fnUntraced(function* () { + const c = yield* config() + if (c.default_agent) { + const agent = agents[c.default_agent] + if (!agent) throw new Error(`default agent "${c.default_agent}" not found`) + if (agent.mode === "subagent") throw new Error(`default agent "${c.default_agent}" is a subagent`) + if (agent.hidden === true) throw new Error(`default agent "${c.default_agent}" is hidden`) + return agent.name + } + const visible = Object.values(agents).find((a) => a.mode !== "subagent" && a.hidden !== true) + if (!visible) throw new Error("no primary visible agent found") + return visible.name + }) + + return { + get, + list, + defaultAgent, + } satisfies State + }), ) - } - return result - }) + return Service.of({ + get: Effect.fn("Agent.get")(function* (agent: string) { + return yield* InstanceState.useEffect(state, (s) => s.get(agent)) + }), + list: Effect.fn("Agent.list")(function* () { + return yield* InstanceState.useEffect(state, (s) => s.list()) + }), + defaultAgent: Effect.fn("Agent.defaultAgent")(function* () { + return yield* InstanceState.useEffect(state, (s) => s.defaultAgent()) + }), + generate: Effect.fn("Agent.generate")(function* (input: { + description: string + model?: { providerID: ProviderID; modelID: ModelID } + }) { + const cfg = yield* config() + const model = input.model ?? (yield* Effect.promise(() => Provider.defaultModel())) + const resolved = yield* Effect.promise(() => Provider.getModel(model.providerID, model.modelID)) + const language = yield* Effect.promise(() => Provider.getLanguage(resolved)) + + const system = [PROMPT_GENERATE] + yield* Effect.promise(() => + Plugin.trigger("experimental.chat.system.transform", { model: resolved }, { system }), + ) + const existing = yield* InstanceState.useEffect(state, (s) => s.list()) + + const params = { + experimental_telemetry: { + isEnabled: cfg.experimental?.openTelemetry, + metadata: { + userId: cfg.username ?? "unknown", + }, + }, + temperature: 0.3, + messages: [ + ...system.map( + (item): ModelMessage => ({ + role: "system", + content: item, + }), + ), + { + role: "user", + content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`, + }, + ], + model: language, + schema: z.object({ + identifier: z.string(), + whenToUse: z.string(), + systemPrompt: z.string(), + }), + } satisfies Parameters[0] + + // TODO: clean this up so provider specific logic doesnt bleed over + const authInfo = yield* auth.get(model.providerID).pipe(Effect.orDie) + if (model.providerID === "openai" && authInfo?.type === "oauth") { + return yield* Effect.promise(async () => { + const result = streamObject({ + ...params, + providerOptions: ProviderTransform.providerOptions(resolved, { + store: false, + }), + onError: () => {}, + }) + for await (const part of result.fullStream) { + if (part.type === "error") throw part.error + } + return result.object + }) + } + + return yield* Effect.promise(() => generateObject(params).then((r) => r.object)) + }), + }) + }), + ) + + export const defaultLayer = layer.pipe(Layer.provide(Auth.layer)) + + const runPromise = makeRunPromise(Service, defaultLayer) export async function get(agent: string) { - return state().then((x) => x[agent]) + return runPromise((svc) => svc.get(agent)) } export async function list() { - const cfg = await Config.get() - return pipe( - await state(), - values(), - sortBy( - [(x) => (cfg.default_agent ? x.name === cfg.default_agent : x.name === "build"), "desc"], - [(x) => x.name, "asc"], - ), - ) + return runPromise((svc) => svc.list()) } export async function defaultAgent() { - const cfg = await Config.get() - const agents = await state() - - if (cfg.default_agent) { - const agent = agents[cfg.default_agent] - if (!agent) throw new Error(`default agent "${cfg.default_agent}" not found`) - if (agent.mode === "subagent") throw new Error(`default agent "${cfg.default_agent}" is a subagent`) - if (agent.hidden === true) throw new Error(`default agent "${cfg.default_agent}" is hidden`) - return agent.name - } - - const primaryVisible = Object.values(agents).find((a) => a.mode !== "subagent" && a.hidden !== true) - if (!primaryVisible) throw new Error("no primary visible agent found") - return primaryVisible.name + return runPromise((svc) => svc.defaultAgent()) } export async function generate(input: { description: string; model?: { providerID: ProviderID; modelID: ModelID } }) { - const cfg = await Config.get() - const defaultModel = input.model ?? (await Provider.defaultModel()) - const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID) - const language = await Provider.getLanguage(model) - - const system = [PROMPT_GENERATE] - await Plugin.trigger("experimental.chat.system.transform", { model }, { system }) - const existing = await list() - - const params = { - experimental_telemetry: { - isEnabled: cfg.experimental?.openTelemetry, - metadata: { - userId: cfg.username ?? "unknown", - }, - }, - temperature: 0.3, - messages: [ - ...system.map( - (item): ModelMessage => ({ - role: "system", - content: item, - }), - ), - { - role: "user", - content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`, - }, - ], - model: language, - schema: z.object({ - identifier: z.string(), - whenToUse: z.string(), - systemPrompt: z.string(), - }), - } satisfies Parameters[0] - - // TODO: clean this up so provider specific logic doesnt bleed over - if (defaultModel.providerID === "openai" && (await Auth.get(defaultModel.providerID))?.type === "oauth") { - const result = streamObject({ - ...params, - providerOptions: ProviderTransform.providerOptions(model, { - store: false, - }), - onError: () => {}, - }) - for await (const part of result.fullStream) { - if (part.type === "error") throw part.error - } - return result.object - } - - const result = await generateObject(params) - return result.object + return runPromise((svc) => svc.generate(input)) } } From 98b3340ceeb6928d0d57898d02665d763ef1ea9c Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Tue, 24 Mar 2026 13:23:41 -0500 Subject: [PATCH 15/32] fix(app): more startup efficiency (#18985) --- packages/app/src/components/prompt-input.tsx | 1 + .../app/src/context/global-sync/bootstrap.ts | 308 +++++++++++------- packages/app/src/context/settings.tsx | 7 +- packages/app/src/context/sync.tsx | 7 +- packages/app/src/pages/home.tsx | 8 + packages/app/src/pages/session.tsx | 7 +- .../pages/session/use-session-hash-scroll.ts | 18 + packages/app/vite.js | 12 + 8 files changed, 240 insertions(+), 128 deletions(-) diff --git a/packages/app/src/components/prompt-input.tsx b/packages/app/src/components/prompt-input.tsx index f523671ec9..ee98e68cd5 100644 --- a/packages/app/src/components/prompt-input.tsx +++ b/packages/app/src/components/prompt-input.tsx @@ -572,6 +572,7 @@ export const PromptInput: Component = (props) => { const open = recent() const seen = new Set(open) const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true })) + if (!query.trim()) return [...agents, ...pinned] const paths = await files.searchFilesAndDirectories(query) const fileOptions: AtOption[] = paths .filter((path) => !seen.has(path)) diff --git a/packages/app/src/context/global-sync/bootstrap.ts b/packages/app/src/context/global-sync/bootstrap.ts index c795ab471c..47be3abcb3 100644 --- a/packages/app/src/context/global-sync/bootstrap.ts +++ b/packages/app/src/context/global-sync/bootstrap.ts @@ -31,6 +31,47 @@ type GlobalStore = { reload: undefined | "pending" | "complete" } +function waitForPaint() { + return new Promise((resolve) => { + let done = false + const finish = () => { + if (done) return + done = true + resolve() + } + const timer = setTimeout(finish, 50) + if (typeof requestAnimationFrame !== "function") return + requestAnimationFrame(() => { + clearTimeout(timer) + finish() + }) + }) +} + +function errors(list: PromiseSettledResult[]) { + return list.filter((item): item is PromiseRejectedResult => item.status === "rejected").map((item) => item.reason) +} + +function runAll(list: Array<() => Promise>) { + return Promise.allSettled(list.map((item) => item())) +} + +function showErrors(input: { + errors: unknown[] + title: string + translate: (key: string, vars?: Record) => string + formatMoreCount: (count: number) => string +}) { + if (input.errors.length === 0) return + const message = formatServerError(input.errors[0], input.translate) + const more = input.errors.length > 1 ? input.formatMoreCount(input.errors.length - 1) : "" + showToast({ + variant: "error", + title: input.title, + description: message + more, + }) +} + export async function bootstrapGlobal(input: { globalSDK: OpencodeClient requestFailedTitle: string @@ -38,45 +79,54 @@ export async function bootstrapGlobal(input: { formatMoreCount: (count: number) => string setGlobalStore: SetStoreFunction }) { - const tasks = [ - retry(() => - input.globalSDK.path.get().then((x) => { - input.setGlobalStore("path", x.data!) - }), - ), - retry(() => - input.globalSDK.global.config.get().then((x) => { - input.setGlobalStore("config", x.data!) - }), - ), - retry(() => - input.globalSDK.project.list().then((x) => { - const projects = (x.data ?? []) - .filter((p) => !!p?.id) - .filter((p) => !!p.worktree && !p.worktree.includes("opencode-test")) - .slice() - .sort((a, b) => cmp(a.id, b.id)) - input.setGlobalStore("project", projects) - }), - ), - retry(() => - input.globalSDK.provider.list().then((x) => { - input.setGlobalStore("provider", normalizeProviderList(x.data!)) - }), - ), + const fast = [ + () => + retry(() => + input.globalSDK.path.get().then((x) => { + input.setGlobalStore("path", x.data!) + }), + ), + () => + retry(() => + input.globalSDK.global.config.get().then((x) => { + input.setGlobalStore("config", x.data!) + }), + ), + () => + retry(() => + input.globalSDK.provider.list().then((x) => { + input.setGlobalStore("provider", normalizeProviderList(x.data!)) + }), + ), ] - const results = await Promise.allSettled(tasks) - const errors = results.filter((r): r is PromiseRejectedResult => r.status === "rejected").map((r) => r.reason) - if (errors.length) { - const message = formatServerError(errors[0], input.translate) - const more = errors.length > 1 ? input.formatMoreCount(errors.length - 1) : "" - showToast({ - variant: "error", - title: input.requestFailedTitle, - description: message + more, - }) - } + const slow = [ + () => + retry(() => + input.globalSDK.project.list().then((x) => { + const projects = (x.data ?? []) + .filter((p) => !!p?.id) + .filter((p) => !!p.worktree && !p.worktree.includes("opencode-test")) + .slice() + .sort((a, b) => cmp(a.id, b.id)) + input.setGlobalStore("project", projects) + }), + ), + ] + + showErrors({ + errors: errors(await runAll(fast)), + title: input.requestFailedTitle, + translate: input.translate, + formatMoreCount: input.formatMoreCount, + }) + await waitForPaint() + showErrors({ + errors: errors(await runAll(slow)), + title: input.requestFailedTitle, + translate: input.translate, + formatMoreCount: input.formatMoreCount, + }) input.setGlobalStore("ready", true) } @@ -119,95 +169,113 @@ export async function bootstrapDirectory(input: { } if (loading) input.setStore("status", "partial") - const results = await Promise.allSettled([ - seededProject - ? Promise.resolve() - : retry(() => input.sdk.project.current()).then((x) => input.setStore("project", x.data!.id)), - retry(() => - input.sdk.provider.list().then((x) => { - input.setStore("provider", normalizeProviderList(x.data!)) - }), - ), - retry(() => input.sdk.app.agents().then((x) => input.setStore("agent", x.data ?? []))), - retry(() => input.sdk.config.get().then((x) => input.setStore("config", x.data!))), - retry(() => - input.sdk.path.get().then((x) => { - input.setStore("path", x.data!) - const next = projectID(x.data?.directory ?? input.directory, input.global.project) - if (next) input.setStore("project", next) - }), - ), - retry(() => input.sdk.command.list().then((x) => input.setStore("command", x.data ?? []))), - retry(() => input.sdk.session.status().then((x) => input.setStore("session_status", x.data!))), - input.loadSessions(input.directory), - retry(() => input.sdk.mcp.status().then((x) => input.setStore("mcp", x.data!))), - retry(() => input.sdk.lsp.status().then((x) => input.setStore("lsp", x.data!))), - retry(() => - input.sdk.vcs.get().then((x) => { - const next = x.data ?? input.store.vcs - input.setStore("vcs", next) - if (next?.branch) input.vcsCache.setStore("value", next) - }), - ), - retry(() => - input.sdk.permission.list().then((x) => { - const grouped = groupBySession( - (x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID), - ) - batch(() => { - for (const sessionID of Object.keys(input.store.permission)) { - if (grouped[sessionID]) continue - input.setStore("permission", sessionID, []) - } - for (const [sessionID, permissions] of Object.entries(grouped)) { - input.setStore( - "permission", - sessionID, - reconcile( - permissions.filter((p) => !!p?.id).sort((a, b) => cmp(a.id, b.id)), - { key: "id" }, - ), - ) - } - }) - }), - ), - retry(() => - input.sdk.question.list().then((x) => { - const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID)) - batch(() => { - for (const sessionID of Object.keys(input.store.question)) { - if (grouped[sessionID]) continue - input.setStore("question", sessionID, []) - } - for (const [sessionID, questions] of Object.entries(grouped)) { - input.setStore( - "question", - sessionID, - reconcile( - questions.filter((q) => !!q?.id).sort((a, b) => cmp(a.id, b.id)), - { key: "id" }, - ), - ) - } - }) - }), - ), - ]) + const fast = [ + () => + seededProject + ? Promise.resolve() + : retry(() => input.sdk.project.current()).then((x) => input.setStore("project", x.data!.id)), + () => retry(() => input.sdk.app.agents().then((x) => input.setStore("agent", x.data ?? []))), + () => retry(() => input.sdk.config.get().then((x) => input.setStore("config", x.data!))), + () => + retry(() => + input.sdk.path.get().then((x) => { + input.setStore("path", x.data!) + const next = projectID(x.data?.directory ?? input.directory, input.global.project) + if (next) input.setStore("project", next) + }), + ), + () => retry(() => input.sdk.session.status().then((x) => input.setStore("session_status", x.data!))), + () => + retry(() => + input.sdk.vcs.get().then((x) => { + const next = x.data ?? input.store.vcs + input.setStore("vcs", next) + if (next?.branch) input.vcsCache.setStore("value", next) + }), + ), + () => retry(() => input.sdk.command.list().then((x) => input.setStore("command", x.data ?? []))), + () => + retry(() => + input.sdk.permission.list().then((x) => { + const grouped = groupBySession( + (x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID), + ) + batch(() => { + for (const sessionID of Object.keys(input.store.permission)) { + if (grouped[sessionID]) continue + input.setStore("permission", sessionID, []) + } + for (const [sessionID, permissions] of Object.entries(grouped)) { + input.setStore( + "permission", + sessionID, + reconcile( + permissions.filter((p) => !!p?.id).sort((a, b) => cmp(a.id, b.id)), + { key: "id" }, + ), + ) + } + }) + }), + ), + () => + retry(() => + input.sdk.question.list().then((x) => { + const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID)) + batch(() => { + for (const sessionID of Object.keys(input.store.question)) { + if (grouped[sessionID]) continue + input.setStore("question", sessionID, []) + } + for (const [sessionID, questions] of Object.entries(grouped)) { + input.setStore( + "question", + sessionID, + reconcile( + questions.filter((q) => !!q?.id).sort((a, b) => cmp(a.id, b.id)), + { key: "id" }, + ), + ) + } + }) + }), + ), + ] - const errors = results - .filter((item): item is PromiseRejectedResult => item.status === "rejected") - .map((item) => item.reason) - if (errors.length > 0) { - console.error("Failed to bootstrap instance", errors[0]) + const slow = [ + () => + retry(() => + input.sdk.provider.list().then((x) => { + input.setStore("provider", normalizeProviderList(x.data!)) + }), + ), + () => Promise.resolve(input.loadSessions(input.directory)), + () => retry(() => input.sdk.mcp.status().then((x) => input.setStore("mcp", x.data!))), + () => retry(() => input.sdk.lsp.status().then((x) => input.setStore("lsp", x.data!))), + ] + + const errs = errors(await runAll(fast)) + if (errs.length > 0) { + console.error("Failed to bootstrap instance", errs[0]) const project = getFilename(input.directory) showToast({ variant: "error", title: input.translate("toast.project.reloadFailed.title", { project }), - description: formatServerError(errors[0], input.translate), + description: formatServerError(errs[0], input.translate), }) - return } - if (loading) input.setStore("status", "complete") + await waitForPaint() + const slowErrs = errors(await runAll(slow)) + if (slowErrs.length > 0) { + console.error("Failed to finish bootstrap instance", slowErrs[0]) + const project = getFilename(input.directory) + showToast({ + variant: "error", + title: input.translate("toast.project.reloadFailed.title", { project }), + description: formatServerError(slowErrs[0], input.translate), + }) + } + + if (loading && errs.length === 0 && slowErrs.length === 0) input.setStore("status", "complete") } diff --git a/packages/app/src/context/settings.tsx b/packages/app/src/context/settings.tsx index 247d36dd36..eddd752eb4 100644 --- a/packages/app/src/context/settings.tsx +++ b/packages/app/src/context/settings.tsx @@ -118,8 +118,11 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont createEffect(() => { if (typeof document === "undefined") return - void loadFont().then((x) => x.ensureMonoFont(store.appearance?.font)) - document.documentElement.style.setProperty("--font-family-mono", monoFontFamily(store.appearance?.font)) + const id = store.appearance?.font ?? defaultSettings.appearance.font + if (id !== defaultSettings.appearance.font) { + void loadFont().then((x) => x.ensureMonoFont(id)) + } + document.documentElement.style.setProperty("--font-family-mono", monoFontFamily(id)) }) return { diff --git a/packages/app/src/context/sync.tsx b/packages/app/src/context/sync.tsx index 66b889e2ad..bbf4fc5ec4 100644 --- a/packages/app/src/context/sync.tsx +++ b/packages/app/src/context/sync.tsx @@ -180,7 +180,8 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({ return globalSync.child(directory) } const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/") - const messagePageSize = 200 + const initialMessagePageSize = 80 + const historyMessagePageSize = 200 const inflight = new Map>() const inflightDiff = new Map>() const inflightTodo = new Map>() @@ -463,7 +464,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({ const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined if (cached && hasSession && !opts?.force) return - const limit = meta.limit[key] ?? messagePageSize + const limit = meta.limit[key] ?? initialMessagePageSize const sessionReq = hasSession && !opts?.force ? Promise.resolve() @@ -560,7 +561,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({ const [, setStore] = globalSync.child(directory) touch(directory, setStore, sessionID) const key = keyFor(directory, sessionID) - const step = count ?? messagePageSize + const step = count ?? historyMessagePageSize if (meta.loading[key]) return if (meta.complete[key]) return const before = meta.cursor[key] diff --git a/packages/app/src/pages/home.tsx b/packages/app/src/pages/home.tsx index ba3a2b9427..4c795b9683 100644 --- a/packages/app/src/pages/home.tsx +++ b/packages/app/src/pages/home.tsx @@ -113,6 +113,14 @@ export default function Home() {
+ +
+
{language.t("common.loading")}
+ +
+
diff --git a/packages/app/src/pages/session.tsx b/packages/app/src/pages/session.tsx index 19dcba58ee..722a688bba 100644 --- a/packages/app/src/pages/session.tsx +++ b/packages/app/src/pages/session.tsx @@ -1179,8 +1179,6 @@ export default function Page() { on( () => sdk.directory, () => { - void file.tree.list("") - const tab = activeFileTab() if (!tab) return const path = file.pathFromTab(tab) @@ -1635,6 +1633,9 @@ export default function Page() { sessionID: () => params.id, messagesReady, visibleUserMessages, + historyMore, + historyLoading, + loadMore: (sessionID) => sync.session.history.loadMore(sessionID), turnStart: historyWindow.turnStart, currentMessageId: () => store.messageId, pendingMessage: () => ui.pendingMessage, @@ -1706,7 +1707,7 @@ export default function Page() {
- + string | undefined messagesReady: () => boolean visibleUserMessages: () => UserMessage[] + historyMore: () => boolean + historyLoading: () => boolean + loadMore: (sessionID: string) => Promise turnStart: () => number currentMessageId: () => string | undefined pendingMessage: () => string | undefined @@ -181,6 +184,21 @@ export const useSessionHashScroll = (input: { queue(() => scrollToMessage(msg, "auto")) }) + createEffect(() => { + const sessionID = input.sessionID() + if (!sessionID || !input.messagesReady()) return + + visibleUserMessages() + + let targetId = input.pendingMessage() + if (!targetId && !clearing) targetId = messageIdFromHash(location.hash) + if (!targetId) return + if (messageById().has(targetId)) return + if (!input.historyMore() || input.historyLoading()) return + + void input.loadMore(sessionID) + }) + onMount(() => { if (typeof window !== "undefined" && "scrollRestoration" in window.history) { window.history.scrollRestoration = "manual" diff --git a/packages/app/vite.js b/packages/app/vite.js index 6b8fd61376..f65a68a1cb 100644 --- a/packages/app/vite.js +++ b/packages/app/vite.js @@ -1,7 +1,10 @@ +import { readFileSync } from "node:fs" import solidPlugin from "vite-plugin-solid" import tailwindcss from "@tailwindcss/vite" import { fileURLToPath } from "url" +const theme = fileURLToPath(new URL("./public/oc-theme-preload.js", import.meta.url)) + /** * @type {import("vite").PluginOption} */ @@ -21,6 +24,15 @@ export default [ } }, }, + { + name: "opencode-desktop:theme-preload", + transformIndexHtml(html) { + return html.replace( + '', + ``, + ) + }, + }, tailwindcss(), solidPlugin(), ] From 9838f56a6f8598ae5d9b587067e4de20adfb303d Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Tue, 24 Mar 2026 13:35:15 -0500 Subject: [PATCH 16/32] fix(app): sidebar ux --- packages/app/src/pages/layout.tsx | 54 ++++++++++++++++++------------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/packages/app/src/pages/layout.tsx b/packages/app/src/pages/layout.tsx index d01c7d3ceb..731f0fe5b2 100644 --- a/packages/app/src/pages/layout.tsx +++ b/packages/app/src/pages/layout.tsx @@ -1818,6 +1818,9 @@ export default function Layout(props: ParentProps) { document.documentElement.style.setProperty("--dialog-left-margin", `${sidebarWidth}px`) }) + const side = createMemo(() => Math.max(layout.sidebar.width(), 244)) + const panel = createMemo(() => Math.max(side() - 64, 0)) + const loadedSessionDirs = new Set() createEffect( @@ -2094,7 +2097,7 @@ export default function Layout(props: ParentProps) { "max-w-full overflow-hidden": panelProps.mobile, }} style={{ - width: panelProps.mobile ? undefined : `${Math.max(Math.max(layout.sidebar.width(), 244) - 64, 0)}px`, + width: panelProps.mobile ? undefined : `${panel()}px`, }} > @@ -2384,7 +2389,7 @@ export default function Layout(props: ParentProps) { "absolute inset-y-0 left-0": true, "z-10": true, }} - style={{ width: `${Math.max(layout.sidebar.width(), 244)}px` }} + style={{ width: `${side()}px` }} ref={(el) => { setState("nav", el) }} @@ -2399,24 +2404,29 @@ export default function Layout(props: ParentProps) { }} >
{sidebarContent()}
- -
setState("sizing", true)}> - { - setState("sizing", true) - if (sizet !== undefined) clearTimeout(sizet) - sizet = window.setTimeout(() => setState("sizing", false), 120) - layout.sidebar.resize(w) - }} - /> -
-
+ + + +