mirror of
https://github.com/anomalyco/opencode.git
synced 2026-09-06 08:56:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2cecc6350 | ||
|
|
63a1074c6c | ||
|
|
31ee07e3ae | ||
|
|
370b9965d3 | ||
|
|
8ea99ef9ad | ||
|
|
e64b2bc137 | ||
|
|
cf1923c238 | ||
|
|
bfcb388dd7 | ||
|
|
ec46439ef5 | ||
|
|
1be3b32a47 | ||
|
|
2823b886d7 | ||
|
|
99651b2d50 | ||
|
|
33ef66746b | ||
|
|
cf212a4235 | ||
|
|
768e3d45a2 | ||
|
|
0674ddf043 | ||
|
|
41b66bc560 | ||
|
|
49a5baa059 | ||
|
|
1cf576ab55 | ||
|
|
f7d0f69e6c | ||
|
|
a66e6cd55e | ||
|
|
93b3725b14 | ||
|
|
371e344ba6 | ||
|
|
6559dcb01b | ||
|
|
35dbdfe287 | ||
|
|
cd504dc66a | ||
|
|
c4f2926ffb | ||
|
|
aa48433fa0 | ||
|
|
8da7526616 | ||
|
|
7a4ad68af6 | ||
|
|
2960c61f9c | ||
|
|
7ad705225e | ||
|
|
5045b3ce18 | ||
|
|
4306c07b34 | ||
|
|
7de1e86b5d | ||
|
|
a6fd1f8b22 |
@@ -91,7 +91,7 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/setup-bun
|
||||
with:
|
||||
bun-version: 1.4.1
|
||||
bun-version: 1.4.2
|
||||
|
||||
- name: Setup git committer
|
||||
id: committer
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
id: build
|
||||
run: ./packages/cli/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }}
|
||||
env:
|
||||
BUN_COMPILE_RELEASE: bun-v1.4.1
|
||||
BUN_COMPILE_RELEASE: bun-v1.4.2
|
||||
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
|
||||
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
|
||||
GH_REPO: ${{ needs.version.outputs.repo }}
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"name": "@opencode-ai/ai",
|
||||
"version": "1.17.20",
|
||||
"dependencies": {
|
||||
"@aws-sdk/credential-providers": "3.1057.0",
|
||||
"@opencode-ai/schema": "workspace:*",
|
||||
"@smithy/eventstream-codec": "4.2.14",
|
||||
"@smithy/util-utf8": "4.2.2",
|
||||
@@ -338,7 +339,6 @@
|
||||
"version": "1.18.4",
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "1.0.17",
|
||||
"@ai-sdk/amazon-bedrock": "4.0.112",
|
||||
"@ai-sdk/anthropic": "3.0.82",
|
||||
"@ai-sdk/azure": "3.0.88",
|
||||
"@ai-sdk/cohere": "3.0.27",
|
||||
@@ -350,7 +350,6 @@
|
||||
"@ai-sdk/provider": "3.0.8",
|
||||
"@ai-sdk/provider-utils": "4.0.23",
|
||||
"@ai-sdk/vercel": "2.0.39",
|
||||
"@aws-sdk/credential-providers": "3.1057.0",
|
||||
"@ff-labs/fff-bun": "0.10.5",
|
||||
"@ff-labs/fff-node": "0.10.5",
|
||||
"@lydell/node-pty": "catalog:",
|
||||
@@ -1067,7 +1066,7 @@
|
||||
"@opentui/solid": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"bun-types": "1.4.1",
|
||||
"bun-types": "1.4.2",
|
||||
"effect": "catalog:",
|
||||
"solid-js": "catalog:",
|
||||
},
|
||||
@@ -1189,7 +1188,7 @@
|
||||
|
||||
"@ai-sdk/mistral": ["@ai-sdk/mistral@3.0.51", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.40" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-83eXY6p0lUFhSuMvNDmTKDuMciK5XDAWDlNh5c0L80tKjmtCFRItA1MZHp4IKe1r7eK8Rb5nN7qtxqMLUFRIRw=="],
|
||||
|
||||
"@ai-sdk/openai": ["@ai-sdk/openai@3.0.67", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-oAiGC9eWG7IgtdsdS74bOCnAAHarAfTJhWN9x5INwnWPekL802AvF+0I5DvLzIF1MIRmNw4N8mPSL/GUVbX9Mw=="],
|
||||
"@ai-sdk/openai": ["@ai-sdk/openai@3.0.84", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.38" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-cmgbeJL0bbY0yTJH4/AdmP5E7MjWRL9G8UdhIi0JlV/So03o82ORJofW8OzwCZPTORVQblFbpZXYGDcUd9NdUQ=="],
|
||||
|
||||
"@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@2.0.41", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-kNAGINk71AlOXx10Dq/PXw4t/9XjdK8uxfpVElRwtSFMdeSiLVt58p9TPx4/FJD+hxZuVhvxYj9r42osxWq79g=="],
|
||||
|
||||
@@ -3487,7 +3486,7 @@
|
||||
|
||||
"bun-pty": ["bun-pty@0.4.8", "", {}, "sha512-rO70Mrbr13+jxHHHu2YBkk2pNqrJE5cJn29WE++PUr+GFA0hq/VgtQPZANJ8dJo6d7XImvBk37Innt8GM7O28w=="],
|
||||
|
||||
"bun-types": ["bun-types@1.4.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA=="],
|
||||
"bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
|
||||
|
||||
"bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
|
||||
@@ -5867,6 +5866,8 @@
|
||||
|
||||
"@ai-sdk/amazon-bedrock/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.81", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-B1JDd9Ugq9R5AgIaW3674lhGCMMYJcPUxnrZh8fzbGojgg4QvHFRv6eZahGQAUsmGHbcf74G9bdSBDLWQGY2GA=="],
|
||||
|
||||
"@ai-sdk/amazon-bedrock/@ai-sdk/openai": ["@ai-sdk/openai@3.0.67", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-oAiGC9eWG7IgtdsdS74bOCnAAHarAfTJhWN9x5INwnWPekL802AvF+0I5DvLzIF1MIRmNw4N8mPSL/GUVbX9Mw=="],
|
||||
|
||||
"@ai-sdk/amazon-bedrock/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="],
|
||||
|
||||
"@ai-sdk/amazon-bedrock/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="],
|
||||
@@ -5875,8 +5876,6 @@
|
||||
|
||||
"@ai-sdk/anthropic/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="],
|
||||
|
||||
"@ai-sdk/azure/@ai-sdk/openai": ["@ai-sdk/openai@3.0.84", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.38" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-cmgbeJL0bbY0yTJH4/AdmP5E7MjWRL9G8UdhIi0JlV/So03o82ORJofW8OzwCZPTORVQblFbpZXYGDcUd9NdUQ=="],
|
||||
|
||||
"@ai-sdk/azure/@ai-sdk/provider": ["@ai-sdk/provider@3.0.14", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA=="],
|
||||
|
||||
"@ai-sdk/azure/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.38", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-/HHGmtKllqjg1OLc023v9w9kK3laW7Z6TzfZukYQWCsGBbzB9p60zTvvpXFVcs44NZBVXL3viOa1HRKUbeee8g=="],
|
||||
@@ -5923,9 +5922,9 @@
|
||||
|
||||
"@ai-sdk/mistral/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.40", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OL5IrpUm9Y8Dwy+w/vvFwPotS6m52O9W0op2oXgXdCROMJIBalBI0oro6OIBYkPxvm5Xg02GSkoQN25RlR0bnw=="],
|
||||
|
||||
"@ai-sdk/openai/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="],
|
||||
"@ai-sdk/openai/@ai-sdk/provider": ["@ai-sdk/provider@3.0.14", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA=="],
|
||||
|
||||
"@ai-sdk/openai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="],
|
||||
"@ai-sdk/openai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.38", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-/HHGmtKllqjg1OLc023v9w9kK3laW7Z6TzfZukYQWCsGBbzB9p60zTvvpXFVcs44NZBVXL3viOa1HRKUbeee8g=="],
|
||||
|
||||
"@ai-sdk/perplexity/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="],
|
||||
|
||||
@@ -6385,8 +6384,6 @@
|
||||
|
||||
"ai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.27", "", { "dependencies": { "@ai-sdk/provider": "4.0.7", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8", "undici": "^7.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-EzAn4pdgG5g0xXtH6lE2zyNmfjDQIDjATkfqzuidEI35g++hh4+07vnjzkT/RmGmIClPZiRj/Q2GMPV2V7mkHw=="],
|
||||
|
||||
"ai-gateway-provider/@ai-sdk/openai": ["@ai-sdk/openai@3.0.84", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.38" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-cmgbeJL0bbY0yTJH4/AdmP5E7MjWRL9G8UdhIi0JlV/So03o82ORJofW8OzwCZPTORVQblFbpZXYGDcUd9NdUQ=="],
|
||||
|
||||
"ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
|
||||
@@ -7247,10 +7244,6 @@
|
||||
|
||||
"@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="],
|
||||
|
||||
"ai-gateway-provider/@ai-sdk/openai/@ai-sdk/provider": ["@ai-sdk/provider@3.0.14", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA=="],
|
||||
|
||||
"ai-gateway-provider/@ai-sdk/openai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.38", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-/HHGmtKllqjg1OLc023v9w9kK3laW7Z6TzfZukYQWCsGBbzB9p60zTvvpXFVcs44NZBVXL3viOa1HRKUbeee8g=="],
|
||||
|
||||
"ai/@ai-sdk/provider-utils/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
|
||||
|
||||
"ansi-align/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"nodeModules": {
|
||||
"x86_64-linux": "sha256-IDORw4Nup1Yj+RZSLGo0pDnwrkveYA8GvYQVNTJUnMM=",
|
||||
"aarch64-linux": "sha256-jxjyAI2imF7csdZNUqvs9mFj8SnYqGg1CapEEk15rxA=",
|
||||
"aarch64-darwin": "sha256-Hbh+cw2DPOJpYCDjasK6m0SLqznyAw1ODKSb7w87GG8=",
|
||||
"x86_64-darwin": "sha256-Aj0/MtMPoeccrN36mu2wUM6gyRKaTF2AbjZ0/wZtKnA="
|
||||
"x86_64-linux": "sha256-bWKV3fV8Yc+3ILaNRChIYajsRcvEG2OkydsD2KMUXCM=",
|
||||
"aarch64-linux": "sha256-zIavB09LW+BU3GOq0PO7Lqfc3MVchkiOUf3trnAjhRM=",
|
||||
"aarch64-darwin": "sha256-Jlvz7QsXsb8GS9Ty4TmUIfGOawiueZWWEYmyEPms3dc=",
|
||||
"x86_64-darwin": "sha256-TzTDtcDtj1c3+eP2WZAHOfkszxIS06J6QUwlnscLaUM="
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -5,9 +5,9 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "bun@1.4.1",
|
||||
"packageManager": "bun@1.4.2",
|
||||
"scripts": {
|
||||
"dev": "bun run --cwd packages/cli --conditions=browser src/index.ts",
|
||||
"dev": "bun run --cwd packages/cli src/index.ts",
|
||||
"dev:live": "sh -c 'OPENCODE_TUI_CHANNEL=dev OPENCODE_PASSWORD=\"$(opencode2 service get password)\" exec bun run dev \"$@\" --server \"$(opencode2 service status)\"' --",
|
||||
"dev:desktop": "bun --cwd packages/desktop dev",
|
||||
"dev:web": "bun --cwd packages/app dev",
|
||||
@@ -159,7 +159,7 @@
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"bun-types": "1.4.1",
|
||||
"bun-types": "1.4.2",
|
||||
"effect": "catalog:",
|
||||
"solid-js": "catalog:"
|
||||
},
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/credential-providers": "3.1057.0",
|
||||
"@smithy/eventstream-codec": "4.2.14",
|
||||
"@smithy/util-utf8": "4.2.2",
|
||||
"@opencode-ai/schema": "workspace:*",
|
||||
|
||||
@@ -2,13 +2,12 @@ import { AwsV4Signer } from "aws4fetch"
|
||||
import { Effect } from "effect"
|
||||
import { Headers } from "effect/unstable/http"
|
||||
import { Auth, type AuthInput } from "../../route/auth.js"
|
||||
import { AIError, AuthenticationError } from "../../schema/index.js"
|
||||
import { ProviderShared } from "../shared.js"
|
||||
|
||||
/**
|
||||
* AWS credentials for SigV4 signing. Bedrock also supports Bearer API key auth,
|
||||
* which provider facades configure as route auth instead of SigV4. STS-vended
|
||||
* credentials should be refreshed by the consumer (rebuild the model) before
|
||||
* they expire; the route does not refresh.
|
||||
* which provider facades configure as route auth instead of SigV4.
|
||||
*/
|
||||
export interface Credentials {
|
||||
readonly region: string
|
||||
@@ -17,6 +16,44 @@ export interface Credentials {
|
||||
readonly sessionToken?: string
|
||||
}
|
||||
|
||||
/** Static credentials or an effect resolved before every request. */
|
||||
export type CredentialSource = Credentials | Effect.Effect<Credentials, AIError>
|
||||
|
||||
export interface DefaultChainOptions {
|
||||
readonly region: string
|
||||
/** Shared config profile passed to the AWS default chain. */
|
||||
readonly profile?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve credentials through the AWS default provider chain: environment
|
||||
* variables, shared config and SSO caches, web identity tokens, process
|
||||
* credentials, and container or instance metadata. A fresh chain runs on every
|
||||
* request so credentials rotated on disk without an expiration (for example
|
||||
* shared-config keys rewritten by a corporate SSO tool) are always re-read;
|
||||
* the SDK's own memoization would otherwise pin them for the process lifetime.
|
||||
*/
|
||||
export const defaultChain = (options: DefaultChainOptions): Effect.Effect<Credentials, AIError> =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers")
|
||||
const identity = await fromNodeProviderChain(options.profile === undefined ? {} : { profile: options.profile })()
|
||||
return {
|
||||
region: options.region,
|
||||
accessKeyId: identity.accessKeyId,
|
||||
secretAccessKey: identity.secretAccessKey,
|
||||
...(identity.sessionToken === undefined ? {} : { sessionToken: identity.sessionToken }),
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
new AIError({
|
||||
reason: new AuthenticationError({
|
||||
message: `AWS default credential chain failed: ${ProviderShared.errorText(error)}`,
|
||||
cause: error,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
|
||||
const signRequest = (input: {
|
||||
readonly url: string
|
||||
readonly body: string
|
||||
@@ -48,16 +85,17 @@ const signRequest = (input: {
|
||||
|
||||
/** Sign the exact JSON bytes with SigV4 using credentials configured on the route. */
|
||||
export const sigV4 = (
|
||||
credentials: Credentials | undefined,
|
||||
source: CredentialSource | undefined,
|
||||
options: { readonly service?: string; readonly name?: string } = {},
|
||||
) =>
|
||||
Auth.custom((input: AuthInput) => {
|
||||
return Effect.gen(function* () {
|
||||
if (!credentials) {
|
||||
if (!source) {
|
||||
return yield* ProviderShared.invalidRequest(
|
||||
`${options.name ?? "Bedrock Converse"} requires either route bearer auth or AWS credentials configured on the route`,
|
||||
)
|
||||
}
|
||||
const credentials = Effect.isEffect(source) ? yield* source : source
|
||||
const headersForSigning = Headers.set(input.headers, "content-type", "application/json")
|
||||
const signed = yield* signRequest({
|
||||
url: input.url,
|
||||
@@ -74,4 +112,35 @@ export const sigV4 = (
|
||||
/** Bedrock route auth defaults to SigV4 and expects credentials from route configuration. */
|
||||
export const auth = sigV4(undefined)
|
||||
|
||||
export const resolveRegion = (input: {
|
||||
readonly region?: string
|
||||
readonly credentials?: { readonly region: string }
|
||||
}) =>
|
||||
input.region ?? input.credentials?.region ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? "us-east-1"
|
||||
|
||||
export interface ResolveAuthInput {
|
||||
readonly apiKey?: string
|
||||
readonly credentials?: Credentials
|
||||
readonly profile?: string
|
||||
}
|
||||
|
||||
export interface ResolveAuthOptions {
|
||||
readonly service?: string
|
||||
readonly name?: string
|
||||
/** `sigv4` ignores an ambient `AWS_BEARER_TOKEN_BEDROCK`; `bearer` is validated by the caller. */
|
||||
readonly mode?: "bearer" | "sigv4"
|
||||
}
|
||||
|
||||
/**
|
||||
* Bearer wins over SigV4 and explicit static credentials win over the default
|
||||
* chain, matching the AWS SDK's own precedence for `AWS_BEARER_TOKEN_BEDROCK`.
|
||||
* The region is applied to the SigV4 scope so it always matches the endpoint host.
|
||||
*/
|
||||
export const resolveAuth = (input: ResolveAuthInput, region: string, options: ResolveAuthOptions = {}) => {
|
||||
const apiKey = options.mode === "sigv4" ? undefined : (input.apiKey ?? process.env.AWS_BEARER_TOKEN_BEDROCK)
|
||||
if (apiKey !== undefined) return Auth.bearer(apiKey)
|
||||
if (input.credentials !== undefined) return sigV4({ ...input.credentials, region }, options)
|
||||
return sigV4(defaultChain({ region, profile: input.profile }), options)
|
||||
}
|
||||
|
||||
export * as BedrockAuth from "./bedrock-auth.js"
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Auth } from "../route/auth.js"
|
||||
import { Route, type RouteDefaultsInput } from "../route/client.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { OpenAIChat } from "../protocols/openai-chat.js"
|
||||
@@ -10,9 +9,15 @@ import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-opt
|
||||
export const id = ProviderID.make("amazon-bedrock")
|
||||
|
||||
export type Config = RouteDefaultsInput & {
|
||||
/** Bedrock API key. Falls back to `AWS_BEARER_TOKEN_BEDROCK`; bearer auth takes precedence over SigV4. */
|
||||
readonly apiKey?: string
|
||||
/** `sigv4` ignores `apiKey` fallbacks from the environment; `bearer` requires a token. */
|
||||
readonly auth?: "bearer" | "sigv4"
|
||||
readonly baseURL?: string
|
||||
/** Static SigV4 credentials. When omitted the AWS default credential chain resolves them per request. */
|
||||
readonly credentials?: Credentials
|
||||
/** Shared config profile for the default credential chain. */
|
||||
readonly profile?: string
|
||||
readonly region?: string
|
||||
readonly providerOptions?: OpenAIProviderOptionsInput
|
||||
}
|
||||
@@ -22,6 +27,7 @@ export interface Settings extends ProviderPackage.Settings {
|
||||
readonly auth?: "bearer" | "sigv4"
|
||||
readonly baseURL?: string
|
||||
readonly credentials?: Credentials
|
||||
readonly profile?: string
|
||||
readonly region?: string
|
||||
readonly topP?: number
|
||||
readonly providerOptions?: OpenAIProviderOptionsInput
|
||||
@@ -47,23 +53,35 @@ const chatRoute = OpenAIChat.route.with({
|
||||
export const routes = [responsesRoute, chatRoute]
|
||||
|
||||
const configuredRoute = <Body, Prepared>(route: Route<Body, Prepared>, input: Config) => {
|
||||
const region = input.region ?? input.credentials?.region ?? "us-east-1"
|
||||
const credentials = input.credentials === undefined ? undefined : { ...input.credentials, region }
|
||||
const region = BedrockAuth.resolveRegion(input)
|
||||
return route.with({
|
||||
endpoint: { baseURL: input.baseURL ?? `https://bedrock-mantle.${region}.api.aws/v1` },
|
||||
auth:
|
||||
input.apiKey === undefined
|
||||
? BedrockAuth.sigV4(credentials, { service: "bedrock-mantle", name: "Bedrock Mantle" })
|
||||
: Auth.bearer(input.apiKey),
|
||||
auth: BedrockAuth.resolveAuth(input, region, {
|
||||
service: "bedrock-mantle",
|
||||
name: "Bedrock Mantle",
|
||||
mode: input.auth,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
const defaults = (input: Config) => {
|
||||
const { apiKey: _, baseURL: _baseURL, credentials: _credentials, region: _region, ...rest } = input
|
||||
const {
|
||||
apiKey: _,
|
||||
auth: _auth,
|
||||
baseURL: _baseURL,
|
||||
credentials: _credentials,
|
||||
profile: _profile,
|
||||
region: _region,
|
||||
...rest
|
||||
} = input
|
||||
return rest
|
||||
}
|
||||
|
||||
export const configure = (input: Config = {}) => {
|
||||
if (input.auth === "bearer" && input.apiKey === undefined && process.env.AWS_BEARER_TOKEN_BEDROCK === undefined)
|
||||
throw new Error("Amazon Bedrock Mantle bearer auth requires apiKey")
|
||||
if (input.auth === "sigv4" && input.apiKey !== undefined)
|
||||
throw new Error("Amazon Bedrock Mantle SigV4 auth does not accept apiKey")
|
||||
const configuredResponsesRoute = configuredRoute(responsesRoute, input)
|
||||
const configuredChatRoute = configuredRoute(chatRoute, input)
|
||||
const modelDefaults = defaults(input)
|
||||
@@ -87,29 +105,26 @@ export const configure = (input: Config = {}) => {
|
||||
|
||||
export const provider = configure()
|
||||
|
||||
const config = (settings: Settings): Config => {
|
||||
if (settings.auth === "bearer" && settings.apiKey === undefined)
|
||||
throw new Error("Amazon Bedrock Mantle bearer auth requires apiKey")
|
||||
if (settings.auth === "sigv4" && settings.apiKey !== undefined)
|
||||
throw new Error("Amazon Bedrock Mantle SigV4 auth does not accept apiKey")
|
||||
return {
|
||||
apiKey: settings.auth === "sigv4" ? undefined : settings.apiKey,
|
||||
const fromSettings = (settings: Settings) =>
|
||||
configure({
|
||||
apiKey: settings.apiKey,
|
||||
auth: settings.auth,
|
||||
baseURL: settings.baseURL,
|
||||
credentials: settings.credentials,
|
||||
generation: settings.topP === undefined ? undefined : { topP: settings.topP },
|
||||
headers: settings.headers === undefined ? undefined : { ...settings.headers },
|
||||
http: settings.body === undefined ? undefined : { body: { ...settings.body } },
|
||||
profile: settings.profile,
|
||||
providerOptions: settings.providerOptions,
|
||||
region: settings.region,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const chatModel: ProviderPackage.Definition<Settings, OpenAIProviderOptionsInput>["model"] = (
|
||||
modelID,
|
||||
settings,
|
||||
) => configure(config(settings)).chat(modelID)
|
||||
) => fromSettings(settings).chat(modelID)
|
||||
export const responsesModel: ProviderPackage.Definition<Settings, OpenAIProviderOptionsInput>["model"] = (
|
||||
modelID,
|
||||
settings,
|
||||
) => configure(config(settings)).responses(modelID)
|
||||
) => fromSettings(settings).responses(modelID)
|
||||
export const model = responsesModel
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import type { RouteDefaultsInput } from "../route/client.js"
|
||||
import { Auth } from "../route/auth.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { ProviderID, type ModelID } from "../schema/index.js"
|
||||
import * as BedrockConverse from "../protocols/bedrock-converse.js"
|
||||
import type { BedrockCredentials } from "../protocols/bedrock-converse.js"
|
||||
import { BedrockAuth } from "../protocols/utils/bedrock-auth.js"
|
||||
|
||||
export const id = ProviderID.make("amazon-bedrock")
|
||||
|
||||
export type Config = RouteDefaultsInput & {
|
||||
/** Bedrock API key. Falls back to `AWS_BEARER_TOKEN_BEDROCK`; bearer auth takes precedence over SigV4. */
|
||||
readonly apiKey?: string
|
||||
/** `sigv4` ignores `apiKey` fallbacks from the environment; `bearer` requires a token. */
|
||||
readonly auth?: "bearer" | "sigv4"
|
||||
readonly headers?: Record<string, string>
|
||||
/** Static SigV4 credentials. When omitted the AWS default credential chain resolves them per request. */
|
||||
readonly credentials?: BedrockCredentials
|
||||
/** AWS region. Defaults to `us-east-1` when neither this nor `credentials.region` is set. */
|
||||
/** Shared config profile for the default credential chain. */
|
||||
readonly profile?: string
|
||||
/** AWS region. Falls back to `credentials.region`, `AWS_REGION`, `AWS_DEFAULT_REGION`, then `us-east-1`. */
|
||||
readonly region?: string
|
||||
/** Override the computed `https://bedrock-runtime.<region>.amazonaws.com` URL. */
|
||||
readonly baseURL?: string
|
||||
@@ -22,6 +28,7 @@ export interface Settings extends ProviderPackage.Settings {
|
||||
readonly auth?: "bearer" | "sigv4"
|
||||
readonly baseURL?: string
|
||||
readonly credentials?: BedrockCredentials
|
||||
readonly profile?: string
|
||||
readonly region?: string
|
||||
readonly topP?: number
|
||||
}
|
||||
@@ -30,14 +37,17 @@ export const routes = [BedrockConverse.route]
|
||||
const bedrockBaseURL = (region: string) => `https://bedrock-runtime.${region}.amazonaws.com`
|
||||
|
||||
const configuredRoute = (input: Config) => {
|
||||
const { apiKey, credentials, region, baseURL, ...rest } = input
|
||||
const resolvedRegion = region ?? credentials?.region ?? "us-east-1"
|
||||
const { apiKey, auth, credentials, profile, region, baseURL, ...rest } = input
|
||||
if (auth === "bearer" && apiKey === undefined && process.env.AWS_BEARER_TOKEN_BEDROCK === undefined)
|
||||
throw new Error("Amazon Bedrock bearer auth requires apiKey")
|
||||
if (auth === "sigv4" && apiKey !== undefined) throw new Error("Amazon Bedrock SigV4 auth does not accept apiKey")
|
||||
const resolvedRegion = BedrockAuth.resolveRegion(input)
|
||||
return BedrockConverse.route.with({
|
||||
...rest,
|
||||
provider: id,
|
||||
providerMetadataKey: "bedrock",
|
||||
endpoint: { baseURL: baseURL ?? bedrockBaseURL(resolvedRegion) },
|
||||
auth: apiKey === undefined ? BedrockConverse.sigV4Auth(credentials) : Auth.bearer(apiKey),
|
||||
auth: BedrockAuth.resolveAuth({ apiKey, credentials, profile }, resolvedRegion, { mode: auth }),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -51,18 +61,15 @@ export const configure = (input: Config = {}) => {
|
||||
}
|
||||
|
||||
export const provider = configure()
|
||||
export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, settings) => {
|
||||
if (settings.auth === "bearer" && settings.apiKey === undefined)
|
||||
throw new Error("Amazon Bedrock bearer auth requires apiKey")
|
||||
if (settings.auth === "sigv4" && settings.apiKey !== undefined)
|
||||
throw new Error("Amazon Bedrock SigV4 auth does not accept apiKey")
|
||||
return configure({
|
||||
apiKey: settings.auth === "sigv4" ? undefined : settings.apiKey,
|
||||
export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, settings) =>
|
||||
configure({
|
||||
apiKey: settings.apiKey,
|
||||
auth: settings.auth,
|
||||
baseURL: settings.baseURL,
|
||||
credentials: settings.credentials,
|
||||
generation: settings.topP === undefined ? undefined : { topP: settings.topP },
|
||||
headers: settings.headers === undefined ? undefined : { ...settings.headers },
|
||||
http: settings.body === undefined ? undefined : { body: { ...settings.body } },
|
||||
profile: settings.profile,
|
||||
region: settings.region,
|
||||
}).model(modelID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Effect } from "effect"
|
||||
|
||||
/**
|
||||
* Run an effect with `process.env` overrides, restoring the previous values
|
||||
* afterwards. Use for code that reads `process.env` directly, such as AWS SDK
|
||||
* credential providers, where Effect `ConfigProvider` layers do not apply.
|
||||
* `undefined` removes a variable for the duration of the effect.
|
||||
*/
|
||||
export const withProcessEnv =
|
||||
(env: Record<string, string | undefined>) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const previous = Object.fromEntries(Object.keys(env).map((name) => [name, process.env[name]]))
|
||||
apply(env)
|
||||
return previous
|
||||
}),
|
||||
() => effect,
|
||||
(previous) => Effect.sync(() => apply(previous)),
|
||||
)
|
||||
|
||||
const apply = (env: Record<string, string | undefined>) => {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[name]
|
||||
continue
|
||||
}
|
||||
process.env[name] = value
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@ import { EventStreamCodec } from "@smithy/eventstream-codec"
|
||||
import { fromUtf8, toUtf8 } from "@smithy/util-utf8"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Encoding, Ref, Stream } from "effect"
|
||||
import { HttpClientRequest } from "effect/unstable/http"
|
||||
import {
|
||||
CacheHint,
|
||||
GenerationOptions,
|
||||
type LanguageModel,
|
||||
LLM,
|
||||
LLMEvent,
|
||||
LLMRequest,
|
||||
@@ -18,7 +20,8 @@ import { compileRequest } from "../../src/route/client.js"
|
||||
import { AmazonBedrock } from "../../src/providers.js"
|
||||
import * as BedrockConverse from "../../src/protocols/bedrock-converse.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
import { fixedResponse } from "../lib/http.js"
|
||||
import { withProcessEnv } from "../lib/env.js"
|
||||
import { dynamicResponse, fixedResponse } from "../lib/http.js"
|
||||
import {
|
||||
eventSummary,
|
||||
expectWeatherToolLoop,
|
||||
@@ -95,6 +98,41 @@ const fixedByteChunks = (...chunks: ReadonlyArray<Uint8Array>) =>
|
||||
{ headers: { "content-type": "application/vnd.amazon.eventstream" } },
|
||||
)
|
||||
|
||||
// Clears every input the AWS default chain reads so tests do not pick up the
|
||||
// developer's profiles, SSO cache, or instance metadata.
|
||||
const noAmbientAWS = {
|
||||
AWS_ACCESS_KEY_ID: undefined,
|
||||
AWS_SECRET_ACCESS_KEY: undefined,
|
||||
AWS_SESSION_TOKEN: undefined,
|
||||
AWS_BEARER_TOKEN_BEDROCK: undefined,
|
||||
AWS_PROFILE: undefined,
|
||||
AWS_REGION: undefined,
|
||||
AWS_DEFAULT_REGION: undefined,
|
||||
AWS_WEB_IDENTITY_TOKEN_FILE: undefined,
|
||||
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI: undefined,
|
||||
AWS_CONTAINER_CREDENTIALS_FULL_URI: undefined,
|
||||
AWS_EC2_METADATA_DISABLED: "true",
|
||||
}
|
||||
|
||||
const captureHeaders = (target: LanguageModel) =>
|
||||
Effect.gen(function* () {
|
||||
const seen: Array<Headers> = []
|
||||
yield* LLMClient.generate(LLMRequest.update(baseRequest, { model: target })).pipe(
|
||||
Effect.provide(
|
||||
dynamicResponse((input) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpClientRequest.toWeb(input.request)
|
||||
seen.push(request.headers)
|
||||
return input.respond(eventStreamBody(["messageStop", { stopReason: "end_turn" }]), {
|
||||
headers: { "content-type": "application/vnd.amazon.eventstream" },
|
||||
})
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
return seen[0]!
|
||||
})
|
||||
|
||||
const model = AmazonBedrock.configure({
|
||||
baseURL: "https://bedrock-runtime.test",
|
||||
apiKey: "test-bearer",
|
||||
@@ -1311,35 +1349,137 @@ describe("Bedrock Converse route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects requests with no auth path", () =>
|
||||
it.effect("fails with an authentication error when the default chain cannot resolve credentials", () =>
|
||||
Effect.gen(function* () {
|
||||
const unsignedModel = AmazonBedrock.configure({
|
||||
baseURL: "https://bedrock-runtime.test",
|
||||
profile: "opencode-test-missing-profile",
|
||||
}).model("anthropic.claude-3-5-sonnet-20240620-v1:0")
|
||||
const error = yield* LLMClient.generate(LLMRequest.update(baseRequest, { model: unsignedModel })).pipe(
|
||||
Effect.provide(fixedBytes(eventStreamBody(["messageStop", { stopReason: "end_turn" }]))),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error.message).toContain("Bedrock Converse requires either route bearer auth or AWS credentials")
|
||||
}),
|
||||
expect(error.reason._tag).toBe("Authentication")
|
||||
expect(error.message).toContain("AWS default credential chain failed")
|
||||
}).pipe(withProcessEnv(noAmbientAWS)),
|
||||
)
|
||||
|
||||
it.effect("signs requests with SigV4 when AWS credentials are provided (deterministic plumbing check)", () =>
|
||||
it.effect("signs with static credentials using the configured region for the SigV4 scope", () =>
|
||||
Effect.gen(function* () {
|
||||
const signed = AmazonBedrock.configure({
|
||||
baseURL: "https://bedrock-runtime.test",
|
||||
region: "eu-west-1",
|
||||
credentials: {
|
||||
region: "us-east-1",
|
||||
accessKeyId: "AKIAIOSFODNN7EXAMPLE",
|
||||
secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||
},
|
||||
}).model("anthropic.claude-3-5-sonnet-20240620-v1:0")
|
||||
const prepared = yield* compileRequest(LLMRequest.update(baseRequest, { model: signed }))
|
||||
const headers = yield* captureHeaders(signed)
|
||||
|
||||
expect(prepared.route).toBe("bedrock-converse")
|
||||
expect(prepared.model).toBe(signed)
|
||||
}),
|
||||
expect(headers.get("authorization")).toContain("Credential=AKIAIOSFODNN7EXAMPLE/")
|
||||
expect(headers.get("authorization")).toContain("/eu-west-1/bedrock/aws4_request")
|
||||
expect(headers.get("x-amz-security-token")).toBeNull()
|
||||
}).pipe(withProcessEnv(noAmbientAWS)),
|
||||
)
|
||||
|
||||
it.effect("resolves SigV4 credentials through the AWS default chain on every request", () =>
|
||||
Effect.gen(function* () {
|
||||
const chained = AmazonBedrock.configure({ baseURL: "https://bedrock-runtime.test", region: "us-west-2" }).model(
|
||||
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
)
|
||||
const headers = yield* captureHeaders(chained)
|
||||
|
||||
expect(headers.get("authorization")).toContain("Credential=AKIACHAINEXAMPLE/")
|
||||
expect(headers.get("authorization")).toContain("/us-west-2/bedrock/aws4_request")
|
||||
expect(headers.get("x-amz-security-token")).toBe("chain-session-token")
|
||||
}).pipe(
|
||||
withProcessEnv({
|
||||
...noAmbientAWS,
|
||||
AWS_ACCESS_KEY_ID: "AKIACHAINEXAMPLE",
|
||||
AWS_SECRET_ACCESS_KEY: "chain-secret",
|
||||
AWS_SESSION_TOKEN: "chain-session-token",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("re-resolves rotated chain credentials on the next request without rebuilding the model", () =>
|
||||
Effect.gen(function* () {
|
||||
const chained = AmazonBedrock.configure({ baseURL: "https://bedrock-runtime.test", region: "us-west-2" }).model(
|
||||
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
)
|
||||
const first = yield* captureHeaders(chained)
|
||||
const second = yield* captureHeaders(chained).pipe(
|
||||
withProcessEnv({ AWS_ACCESS_KEY_ID: "AKIAROTATEDEXAMPLE", AWS_SECRET_ACCESS_KEY: "rotated-secret" }),
|
||||
)
|
||||
|
||||
expect(first.get("authorization")).toContain("Credential=AKIACHAINEXAMPLE/")
|
||||
expect(second.get("authorization")).toContain("Credential=AKIAROTATEDEXAMPLE/")
|
||||
}).pipe(
|
||||
withProcessEnv({
|
||||
...noAmbientAWS,
|
||||
AWS_ACCESS_KEY_ID: "AKIACHAINEXAMPLE",
|
||||
AWS_SECRET_ACCESS_KEY: "chain-secret",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("prefers AWS_BEARER_TOKEN_BEDROCK over the credential chain", () =>
|
||||
Effect.gen(function* () {
|
||||
const bearer = AmazonBedrock.configure({ baseURL: "https://bedrock-runtime.test" }).model(
|
||||
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
)
|
||||
const headers = yield* captureHeaders(bearer)
|
||||
|
||||
expect(headers.get("authorization")).toBe("Bearer env-bearer-token")
|
||||
}).pipe(
|
||||
withProcessEnv({
|
||||
...noAmbientAWS,
|
||||
AWS_BEARER_TOKEN_BEDROCK: "env-bearer-token",
|
||||
AWS_ACCESS_KEY_ID: "AKIACHAINEXAMPLE",
|
||||
AWS_SECRET_ACCESS_KEY: "chain-secret",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("auth: sigv4 ignores an ambient bearer token from configure and settings", () =>
|
||||
Effect.gen(function* () {
|
||||
const configured = AmazonBedrock.configure({ auth: "sigv4", baseURL: "https://bedrock-runtime.test" }).model(
|
||||
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
)
|
||||
const fromSettings = AmazonBedrock.model("anthropic.claude-3-5-sonnet-20240620-v1:0", {
|
||||
auth: "sigv4",
|
||||
baseURL: "https://bedrock-runtime.test",
|
||||
})
|
||||
|
||||
for (const target of [configured, fromSettings]) {
|
||||
const headers = yield* captureHeaders(target)
|
||||
expect(headers.get("authorization")).toContain("Credential=AKIACHAINEXAMPLE/")
|
||||
expect(headers.get("authorization")).toContain("/ap-southeast-2/bedrock/aws4_request")
|
||||
}
|
||||
expect(() => AmazonBedrock.configure({ auth: "sigv4", apiKey: "k" })).toThrow("does not accept apiKey")
|
||||
}).pipe(
|
||||
withProcessEnv({
|
||||
...noAmbientAWS,
|
||||
AWS_BEARER_TOKEN_BEDROCK: "env-bearer-token",
|
||||
AWS_REGION: "ap-southeast-2",
|
||||
AWS_ACCESS_KEY_ID: "AKIACHAINEXAMPLE",
|
||||
AWS_SECRET_ACCESS_KEY: "chain-secret",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("derives the endpoint region from AWS_REGION then AWS_DEFAULT_REGION", () =>
|
||||
Effect.gen(function* () {
|
||||
const fromRegion = AmazonBedrock.configure({ apiKey: "k" }).model("anthropic.claude-3-5-sonnet-20240620-v1:0")
|
||||
expect(fromRegion.route.endpoint.baseURL).toBe("https://bedrock-runtime.eu-central-1.amazonaws.com")
|
||||
|
||||
const fromDefault = yield* Effect.sync(() =>
|
||||
AmazonBedrock.configure({ apiKey: "k" }).model("anthropic.claude-3-5-sonnet-20240620-v1:0"),
|
||||
).pipe(withProcessEnv({ AWS_REGION: undefined }))
|
||||
expect(fromDefault.route.endpoint.baseURL).toBe("https://bedrock-runtime.us-gov-west-1.amazonaws.com")
|
||||
}).pipe(withProcessEnv({ ...noAmbientAWS, AWS_REGION: "eu-central-1", AWS_DEFAULT_REGION: "us-gov-west-1" })),
|
||||
)
|
||||
|
||||
it.effect("emits cachePoint markers after system, user-text, and assistant-text with cache hints", () =>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { model } from "../../src/providers/amazon-bedrock/mantle.js"
|
||||
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
|
||||
import { compileRequest, LLMClient } from "../../src/route/client.js"
|
||||
import { it } from "../lib/effect.js"
|
||||
import { withProcessEnv } from "../lib/env.js"
|
||||
import { dynamicResponse, fixedResponse } from "../lib/http.js"
|
||||
import { sseEvents } from "../lib/sse.js"
|
||||
import { recordedTests } from "../recorded-test.js"
|
||||
@@ -82,6 +83,36 @@ describe("Amazon Bedrock Mantle provider", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("signs with the Mantle service using default-chain credentials", () =>
|
||||
Effect.gen(function* () {
|
||||
const seen: Array<string | undefined> = []
|
||||
const model = AmazonBedrockMantle.configure({ region: "us-west-1" }).responses("openai.gpt-oss-120b")
|
||||
yield* LLMClient.generate(LLM.request({ model, prompt: "Hi" })).pipe(
|
||||
Effect.provide(
|
||||
dynamicResponse((input) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpClientRequest.toWeb(input.request)
|
||||
seen.push(request.headers.get("authorization") ?? undefined)
|
||||
return input.respond("", { headers: { "content-type": "text/event-stream" } })
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(seen[0]).toContain("Credential=AKIACHAINEXAMPLE/")
|
||||
expect(seen[0]).toContain("/us-west-1/bedrock-mantle/aws4_request")
|
||||
}).pipe(
|
||||
withProcessEnv({
|
||||
AWS_BEARER_TOKEN_BEDROCK: undefined,
|
||||
AWS_PROFILE: undefined,
|
||||
AWS_ACCESS_KEY_ID: "AKIACHAINEXAMPLE",
|
||||
AWS_SECRET_ACCESS_KEY: "chain-secret",
|
||||
AWS_SESSION_TOKEN: undefined,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("supports bearer authentication and custom base URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
const seen: Array<{ readonly url: string; readonly authorization: string | undefined }> = []
|
||||
|
||||
@@ -1,16 +1,139 @@
|
||||
import { expect, story } from "../../storybook/playwright/story"
|
||||
|
||||
story("raises the docked composer only in dark mode", async ({ mount, page }) => {
|
||||
const component = await mount("opencode-composer-flow--empty-draft")
|
||||
const composer = component.locator('[data-component="composer"]')
|
||||
for (const direction of ["ltr", "rtl"]) {
|
||||
for (const alternate of ["none", "queue", "steer"]) {
|
||||
story(`scrolls overflowing controls beside fixed ${alternate} actions in ${direction}`, async ({ mount, page }) => {
|
||||
const component = await mount("opencode-composer-flow--toolbar-overflow", {
|
||||
args: { alternate },
|
||||
globals: { direction },
|
||||
})
|
||||
const controls = component.locator('[data-slot="composer-controls"]')
|
||||
const actions = component.locator('[data-slot="composer-actions"]')
|
||||
const submit = component.locator('[data-action="composer-submit"]')
|
||||
const add = component.locator('[data-action="composer-attach"]')
|
||||
const agent = controls.getByRole("button", { name: "Choose agent" })
|
||||
const variant = controls.getByRole("button", { name: "Choose model variant" })
|
||||
await expect(controls).toHaveCSS("overflow-x", "auto")
|
||||
await expect(controls).toHaveCSS("overscroll-behavior-x", "contain")
|
||||
await expect(controls).toHaveCSS("direction", direction)
|
||||
await expect(controls).toHaveCSS("padding-inline-start", "0px")
|
||||
await expect(controls).toHaveCSS("padding-inline-end", "0px")
|
||||
await expect(component.locator('[data-action="composer-alternate-delivery"]')).toHaveCount(
|
||||
alternate === "none" ? 0 : 1,
|
||||
)
|
||||
|
||||
await page.locator("html").evaluate((root) => root.setAttribute("data-color-scheme", "light"))
|
||||
await expect(composer).toHaveCSS("background-color", "rgb(255, 255, 255)")
|
||||
for (const width of [1024, 360]) {
|
||||
await page.setViewportSize({ width, height: 720 })
|
||||
await expect
|
||||
.poll(() => controls.evaluate((element) => element.scrollWidth - element.clientWidth))
|
||||
.toBeGreaterThan(0)
|
||||
const fixed = await submit.boundingBox()
|
||||
const fixedAdd = await add.boundingBox()
|
||||
const viewport = await controls.boundingBox()
|
||||
const action = await actions.boundingBox()
|
||||
expect(fixed).not.toBeNull()
|
||||
expect(viewport).not.toBeNull()
|
||||
expect(action).not.toBeNull()
|
||||
expect(fixedAdd).not.toBeNull()
|
||||
if (!fixed || !viewport || !action || !fixedAdd) return
|
||||
expect(direction === "ltr" ? fixedAdd.x + fixedAdd.width : viewport.x + viewport.width).toBeCloseTo(
|
||||
direction === "ltr" ? viewport.x - 4 : fixedAdd.x - 4,
|
||||
1,
|
||||
)
|
||||
expect(direction === "ltr" ? viewport.x + viewport.width : action.x + action.width).toBeCloseTo(
|
||||
direction === "ltr" ? action.x - 12 : viewport.x - 12,
|
||||
1,
|
||||
)
|
||||
|
||||
await page.locator("html").evaluate((root) => root.setAttribute("data-color-scheme", "dark"))
|
||||
await expect(composer).toHaveCSS("background-color", "rgb(36, 36, 36)")
|
||||
await controls.evaluate((element) => {
|
||||
element.scrollLeft = 0
|
||||
})
|
||||
await expect(controls).toHaveAttribute("data-overflow-start", "false")
|
||||
await expect(controls).toHaveAttribute("data-overflow-end", "true")
|
||||
await expect(controls).toHaveCSS(
|
||||
"mask-image",
|
||||
`linear-gradient(to ${direction === "ltr" ? "right" : "left"}, rgba(0, 0, 0, 0), rgb(0, 0, 0) 0px, rgb(0, 0, 0) calc(100% - 16px), rgba(0, 0, 0, 0))`,
|
||||
)
|
||||
const first = await agent.boundingBox()
|
||||
if (!first) throw new Error("Missing agent control")
|
||||
expect(
|
||||
direction === "ltr" ? first.x - viewport.x : viewport.x + viewport.width - first.x - first.width,
|
||||
).toBeCloseTo(0, 0)
|
||||
await controls.evaluate((element) => {
|
||||
element.scrollLeft =
|
||||
((getComputedStyle(element).direction === "rtl" ? -1 : 1) * (element.scrollWidth - element.clientWidth)) / 2
|
||||
})
|
||||
await expect(controls).toHaveAttribute("data-overflow-start", "true")
|
||||
await expect(controls).toHaveAttribute("data-overflow-end", "true")
|
||||
const scrolled = (await controls.boundingBox())!
|
||||
expect(scrolled.x).toBeCloseTo(viewport.x, 1)
|
||||
expect(scrolled.width).toBeCloseTo(viewport.width, 1)
|
||||
await controls.hover()
|
||||
await page.mouse.wheel(direction === "ltr" ? 1000 : -1000, 0)
|
||||
await expect.poll(() => controls.evaluate((element) => Math.abs(element.scrollLeft))).toBeGreaterThan(0)
|
||||
expect(await submit.boundingBox()).toEqual(fixed)
|
||||
expect(await add.boundingBox()).toEqual(fixedAdd)
|
||||
|
||||
// The fade disappears at the endpoint instead of reserving padding.
|
||||
await variant.focus()
|
||||
await controls.evaluate((element) => {
|
||||
element.scrollLeft =
|
||||
getComputedStyle(element).direction === "rtl" ? -element.scrollWidth : element.scrollWidth
|
||||
})
|
||||
await expect(controls).toHaveAttribute("data-overflow-start", "true")
|
||||
await expect(controls).toHaveAttribute("data-overflow-end", "false")
|
||||
const last = await variant.boundingBox()
|
||||
if (!last) throw new Error("Missing variant control")
|
||||
expect(
|
||||
Math.abs(direction === "ltr" ? viewport.x + viewport.width - last.x - last.width : last.x - viewport.x),
|
||||
).toBeLessThan(1)
|
||||
expect(
|
||||
Math.abs((direction === "ltr" ? action.x - last.x - last.width : last.x - action.x - action.width) - 12),
|
||||
).toBeLessThan(1)
|
||||
await page.keyboard.press("Enter")
|
||||
await expect(page.getByRole("menuitemradio", { name: "high", exact: true })).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(variant).toBeFocused()
|
||||
await expect(submit).toBeInViewport()
|
||||
await expect(add).toBeInViewport()
|
||||
await add.click()
|
||||
await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
expect(await add.boundingBox()).toEqual(fixedAdd)
|
||||
}
|
||||
|
||||
if (alternate !== "none") {
|
||||
const width = (await controls.boundingBox())!.width
|
||||
await component.getByRole("textbox", { name: "Prompt", exact: true }).fill("")
|
||||
await expect(component.locator('[data-action="composer-alternate-delivery"]')).toHaveCount(0)
|
||||
await expect.poll(async () => (await controls.boundingBox())!.width).toBeGreaterThan(width)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
story("does not mask or pad controls when they fit", async ({ mount }) => {
|
||||
const component = await mount("opencode-composer-flow--model-and-variant")
|
||||
const controls = component.locator('[data-slot="composer-controls"]')
|
||||
await expect(controls).toHaveAttribute("data-overflow-start", "false")
|
||||
await expect(controls).toHaveAttribute("data-overflow-end", "false")
|
||||
await expect(controls).toHaveCSS("mask-image", "none")
|
||||
await expect(controls).toHaveCSS("padding-inline-start", "0px")
|
||||
await expect(controls).toHaveCSS("padding-inline-end", "0px")
|
||||
})
|
||||
|
||||
// ThemeProvider writes resolved token values into a <style> block, so toggling data-color-scheme by hand
|
||||
// leaves every --v2-* variable at its previous value. Switch themes through the Storybook global instead.
|
||||
for (const [theme, background] of [
|
||||
["light", "rgb(255, 255, 255)"],
|
||||
["dark", "rgb(36, 36, 36)"],
|
||||
] as const) {
|
||||
story(`raises the docked composer only in dark mode (${theme})`, async ({ mount }) => {
|
||||
const component = await mount("opencode-composer-flow--empty-draft", { globals: { theme } })
|
||||
await expect(component.locator('[data-component="composer"]')).toHaveCSS("background-color", background)
|
||||
})
|
||||
}
|
||||
|
||||
story("centers add menu shortcuts in a consistent column", async ({ mount, page }) => {
|
||||
const component = await mount("opencode-composer-flow--empty-draft")
|
||||
await component.locator('[data-action="composer-attach"]').click()
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { expect, story } from "../../storybook/playwright/story"
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
for (const direction of ["ltr", "rtl"]) {
|
||||
story(`shimmers once over the visible wordmark (${theme}, ${direction})`, async ({ mount, page }, testInfo) => {
|
||||
await page.emulateMedia({ reducedMotion: "no-preference" })
|
||||
const component = await mount("app-new-session-wordmark--reveal", { globals: { theme, direction } })
|
||||
const logo = component.locator('[data-component="new-session-wordmark"]')
|
||||
const reveal = logo.locator('[data-slot="wordmark-reveal"]')
|
||||
const shimmer = logo.locator(".wordmark-shimmer")
|
||||
const base = logo.locator("svg").first()
|
||||
await expect(base).toHaveCSS("opacity", theme === "dark" ? "0.5" : "0.6")
|
||||
await expect(shimmer).toHaveCSS("animation-iteration-count", "1")
|
||||
await expect(logo.locator("g[mask]")).toHaveCount(0)
|
||||
await expect(shimmer).toHaveCSS("color", "rgb(255, 255, 255)")
|
||||
await expect(shimmer).toHaveCSS("mix-blend-mode", "screen")
|
||||
await expect(base.locator("g[fill]")).toHaveAttribute("fill", "currentColor")
|
||||
|
||||
await logo.evaluate((element) => {
|
||||
element.getAnimations({ subtree: true }).forEach((animation) => {
|
||||
animation.pause()
|
||||
animation.currentTime = 0
|
||||
})
|
||||
})
|
||||
await expect(reveal).toHaveCSS("opacity", "1")
|
||||
await expect(reveal).toHaveCSS("animation-name", "none")
|
||||
await expect(shimmer).toHaveCSS("mask-position", "100% 0px")
|
||||
|
||||
await logo.evaluate((element) => {
|
||||
element.getAnimations({ subtree: true }).forEach((animation) => (animation.currentTime = 400))
|
||||
})
|
||||
await expect(shimmer).toHaveCSS("mask-position", "50% 0px")
|
||||
await expect(shimmer).toHaveCSS("opacity", theme === "dark" ? "0.0672" : "0.45")
|
||||
const swept = await logo.screenshot({ path: testInfo.outputPath("wordmark-shimmer.png") })
|
||||
|
||||
await logo.evaluate((element) => {
|
||||
element.getAnimations({ subtree: true }).forEach((animation) => animation.finish())
|
||||
})
|
||||
await expect(reveal).toHaveCSS("opacity", "1")
|
||||
await expect(shimmer).toHaveCSS("opacity", "0")
|
||||
await expect(shimmer).toHaveCSS("mask-position", "0% 0px")
|
||||
const settled = await logo.screenshot({ path: testInfo.outputPath("wordmark-settled.png") })
|
||||
const brightness = await page.evaluate(
|
||||
async (screenshots) => {
|
||||
const pixels = await Promise.all(
|
||||
screenshots.map(async (screenshot) => {
|
||||
const image = new Image()
|
||||
image.src = `data:image/png;base64,${screenshot}`
|
||||
await image.decode()
|
||||
const canvas = new OffscreenCanvas(image.width, image.height)
|
||||
const context = canvas.getContext("2d")
|
||||
if (!context) throw new Error("Cannot read screenshot pixels")
|
||||
context.drawImage(image, 0, 0)
|
||||
return context.getImageData(0, 0, image.width, image.height).data
|
||||
}),
|
||||
)
|
||||
return {
|
||||
min: pixels[0].reduce(
|
||||
(min, value, index) => (index % 4 === 3 ? min : Math.min(min, value - pixels[1][index])),
|
||||
0,
|
||||
),
|
||||
max: pixels[0].reduce(
|
||||
(max, value, index) => (index % 4 === 3 ? max : Math.max(max, value - pixels[1][index])),
|
||||
0,
|
||||
),
|
||||
}
|
||||
},
|
||||
[swept.toString("base64"), settled.toString("base64")],
|
||||
)
|
||||
expect(brightness.min).toBeGreaterThanOrEqual(0)
|
||||
expect(brightness.max).toBeGreaterThanOrEqual(5)
|
||||
})
|
||||
}
|
||||
|
||||
story(`shows a static wordmark with reduced motion (${theme})`, async ({ mount, page }) => {
|
||||
await page.emulateMedia({ reducedMotion: "reduce" })
|
||||
await page.setViewportSize({ width: 360, height: 640 })
|
||||
const component = await mount("app-new-session-wordmark--reveal", { globals: { theme } })
|
||||
const logo = component.locator('[data-component="new-session-wordmark"]')
|
||||
await expect(logo.locator("svg").first()).toHaveCSS("opacity", theme === "dark" ? "0.5" : "0.6")
|
||||
await expect(logo.locator('[data-slot="wordmark-reveal"]')).toHaveCSS("opacity", "1")
|
||||
await expect(logo.locator(".wordmark-shimmer")).toHaveCSS("opacity", "0")
|
||||
expect(await logo.evaluate((element) => element.getAnimations({ subtree: true }).length)).toBe(0)
|
||||
expect(await logo.evaluate((element) => element.getBoundingClientRect().right <= innerWidth)).toBe(true)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { expect, story } from "../../storybook/playwright/story"
|
||||
|
||||
story("enables Any only after confirmation and supports resetting the preview", async ({ mount }) => {
|
||||
const component = await mount("app-current-session-surface--web-search-request")
|
||||
const card = component.getByRole("region", { name: "Third-party web search" })
|
||||
await expect(card.getByRole("button", { name: "Enable", exact: true })).toBeEnabled()
|
||||
await expect(card.getByRole("button", { name: "Search provider Any", exact: true })).toBeVisible()
|
||||
await card.getByRole("button", { name: "Enable", exact: true }).click()
|
||||
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): random")
|
||||
await expect(card).toHaveCount(0)
|
||||
await component.getByRole("button", { name: "Reset", exact: true }).click()
|
||||
await expect(card.getByRole("button", { name: "Enable", exact: true })).toBeEnabled()
|
||||
})
|
||||
|
||||
story("declining search is an explicit disabled selection", async ({ mount }) => {
|
||||
const component = await mount("app-current-session-surface--web-search-request")
|
||||
const card = component.getByRole("region", { name: "Third-party web search" })
|
||||
await card.getByRole("button", { name: "Don’t use search", exact: true }).click()
|
||||
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): false")
|
||||
await expect(card).toHaveCount(0)
|
||||
})
|
||||
|
||||
story("sizes provider options to their content", async ({ mount, page }) => {
|
||||
const component = await mount("app-current-session-surface--web-search-request")
|
||||
await component.getByRole("button", { name: "Search provider Any", exact: true }).click()
|
||||
const menu = page.getByRole("listbox", { name: "Search provider", exact: true })
|
||||
await expect(menu).toBeVisible()
|
||||
const metrics = await menu.evaluate((listbox) => {
|
||||
const items = Array.from(listbox.querySelectorAll('[data-component="menu-v2-item"]'))
|
||||
const longest = items
|
||||
.flatMap((item) => {
|
||||
const label = item.querySelector('[data-slot="menu-v2-item-content"]')?.getBoundingClientRect()
|
||||
const check = item.querySelector('[data-slot="menu-v2-item-indicator"]')?.getBoundingClientRect()
|
||||
return label && check ? [{ label, check }] : []
|
||||
})
|
||||
.toSorted((a, b) => b.label.width - a.label.width)[0]
|
||||
return {
|
||||
width: listbox.getBoundingClientRect().width,
|
||||
gap: longest ? longest.check.left - longest.label.right : 0,
|
||||
}
|
||||
})
|
||||
expect(metrics.width).toBeLessThan(160)
|
||||
expect(metrics.gap).toBe(24)
|
||||
})
|
||||
|
||||
for (const width of [360, 1200]) {
|
||||
for (const direction of ["ltr", "rtl"]) {
|
||||
for (const theme of ["light", "dark"]) {
|
||||
story(`selects and confirms a provider at ${width}px in ${direction} ${theme}`, async ({ mount, page }) => {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
const component = await mount("app-current-session-surface--web-search-request", {
|
||||
globals: { theme, direction },
|
||||
})
|
||||
const card = component.getByRole("region", { name: "Third-party web search" })
|
||||
const select = card.getByRole("button", { name: /^Search provider/ })
|
||||
await expect(select).toBeEnabled()
|
||||
await expect(card).toHaveCSS("direction", direction)
|
||||
expect(await card.evaluate((node) => node.scrollWidth <= node.clientWidth)).toBe(true)
|
||||
await select.focus()
|
||||
await select.press("Enter")
|
||||
const list = page.getByRole("listbox", { name: "Search provider", exact: true })
|
||||
await expect(list).toHaveCSS("direction", direction)
|
||||
await list.getByRole("option", { name: "Parallel", exact: true }).click()
|
||||
await expect(select).toHaveText("Parallel")
|
||||
await expect(card).toBeVisible()
|
||||
await expect(component.getByRole("status")).toHaveText("Ready")
|
||||
await expect(select).toBeFocused()
|
||||
await select.press("Tab")
|
||||
await expect(card.getByRole("button", { name: "Don’t use search", exact: true })).toBeFocused()
|
||||
await page.keyboard.press("Tab")
|
||||
const enable = card.getByRole("button", { name: "Enable", exact: true })
|
||||
await expect(enable).toBeFocused()
|
||||
await enable.press("Enter")
|
||||
await expect(component.getByRole("status")).toHaveText("Web search selection (local only): parallel")
|
||||
await expect(card).toHaveCount(0)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ The suite contains:
|
||||
- home-session click timing split between content and titlebar-tab paint
|
||||
- single-session tab close timing through stable home restoration
|
||||
- cached session repaint and mutation tracing
|
||||
- large-session search scan, first-result reveal, and highlight stabilization
|
||||
- streaming timeline throughput, RAF-gap, long-task, geometry, and remount diagnostics
|
||||
- retained renderer heap with a large model catalog across repeated session navigation
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { benchmark, expect } from "../benchmark"
|
||||
import { buildInitialStreamEvent, setupTimelineBenchmark, textPartID } from "./session-timeline-benchmark.fixture"
|
||||
import {
|
||||
collectTimelineSearchMetrics,
|
||||
installTimelineSearchProbe,
|
||||
waitForStableTimelineSearch,
|
||||
} from "./session-timeline-search-probe"
|
||||
|
||||
benchmark("searches a large virtualized session and reveals the first result", async ({ page, report }) => {
|
||||
benchmark.setTimeout(180_000)
|
||||
const historyTurns = Number(process.env.TIMELINE_SEARCH_HISTORY_TURNS ?? 320)
|
||||
const completionTimeout = Number(process.env.TIMELINE_SEARCH_COMPLETION_TIMEOUT_MS ?? 60_000)
|
||||
const query = "Historical prompt"
|
||||
const targetPartID = "msg_0000_0000_a_user:text:0"
|
||||
const expectedCounter = `1/${historyTurns}`
|
||||
const fixture = await setupTimelineBenchmark(page, {
|
||||
historyTurns,
|
||||
eventBatch: 1,
|
||||
})
|
||||
|
||||
fixture.transport.enqueue(buildInitialStreamEvent(1))
|
||||
await expect(fixture.text).toContainText("Implementation plan")
|
||||
await fixture.scrollToBottom()
|
||||
await fixture.waitForStableGeometry()
|
||||
// Chromium reserves the physical shortcut for its native find overlay, so request the same controller path directly.
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("opencode:timeline-search-open")))
|
||||
|
||||
const search = page.locator('[data-component="timeline-search-bar"]')
|
||||
const field = search.getByRole("searchbox", { name: "Find..." })
|
||||
const count = search.locator('[data-slot="timeline-search-count"]')
|
||||
const target = page.locator(`[data-timeline-part-id="${targetPartID}"]`)
|
||||
await expect(field).toBeVisible()
|
||||
await expect(field).toBeFocused()
|
||||
await installTimelineSearchProbe(page, { targetPartID })
|
||||
|
||||
await field.fill(query)
|
||||
await expect(count).toHaveText(expectedCounter)
|
||||
await expect(target).toBeVisible({ timeout: completionTimeout })
|
||||
await waitForStableTimelineSearch(page, { counter: expectedCounter, targetPartID, timeout: completionTimeout })
|
||||
const metrics = await collectTimelineSearchMetrics(page, { counter: expectedCounter, targetPartID })
|
||||
|
||||
expect(metrics.summary.handlerDurationMs).toBeDefined()
|
||||
expect(metrics.summary.firstCountObservedMs).toBeDefined()
|
||||
expect(metrics.summary.firstTargetVisibleMs).toBeDefined()
|
||||
expect(metrics.summary.firstActiveHighlightObservedMs).toBeDefined()
|
||||
expect(metrics.summary.stableResultObservedMs).toBeDefined()
|
||||
expect(metrics.summary.activeHighlightRanges).toBe(1)
|
||||
report(metrics, { historyTurns, query, expectedMatches: historyTurns })
|
||||
|
||||
// Check navigation and the V2 assistant content IDs outside the measured interval.
|
||||
await field.press("Enter")
|
||||
await expect(count).toHaveText(`2/${historyTurns}`)
|
||||
await field.press("Shift+Enter")
|
||||
await expect(count).toHaveText(expectedCounter)
|
||||
await field.fill("Implementation plan")
|
||||
await expect(count).toHaveText("1/1")
|
||||
await expect(fixture.text).toBeInViewport()
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(() => {
|
||||
const range = [...(CSS.highlights.get("timeline-search-hit-active") ?? [])][0]
|
||||
return range?.startContainer.parentElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset
|
||||
.timelinePartId
|
||||
}),
|
||||
)
|
||||
.toBe(textPartID)
|
||||
await field.press("Escape")
|
||||
await expect(search).toBeHidden()
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { Page } from "@playwright/test"
|
||||
|
||||
export type TimelineSearchSample = {
|
||||
observedAtMs: number
|
||||
counter: string
|
||||
targetMounted: boolean
|
||||
targetVisible: boolean
|
||||
targetTopPx?: number
|
||||
activeRanges: number
|
||||
activePartID?: string
|
||||
activeVisible: boolean
|
||||
scrollTopPx: number
|
||||
}
|
||||
|
||||
type TimelineSearchProbe = {
|
||||
samples: TimelineSearchSample[]
|
||||
handlerDurationMs?: number
|
||||
initialScrollTopPx: number
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
export async function installTimelineSearchProbe(page: Page, input: { targetPartID: string }) {
|
||||
await page.evaluate(({ targetPartID }) => {
|
||||
const search = document.querySelector<HTMLElement>('[data-component="timeline-search-bar"]')
|
||||
const field = search?.querySelector<HTMLInputElement>('[data-slot="text-input-v2-input"]')
|
||||
const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
|
||||
element.querySelector("[data-timeline-row]"),
|
||||
)
|
||||
if (!search || !field || !root) throw new Error("missing timeline search benchmark nodes")
|
||||
|
||||
const samples: TimelineSearchSample[] = []
|
||||
const initialScrollTopPx = root.scrollTop
|
||||
let startedAt: number | undefined
|
||||
let handlerDurationMs: number | undefined
|
||||
let frame: number | undefined
|
||||
let running = true
|
||||
|
||||
const visibleInRoot = (rect: DOMRect) => {
|
||||
const viewport = root.getBoundingClientRect()
|
||||
return rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom
|
||||
}
|
||||
const sample = () => {
|
||||
if (!running || startedAt === undefined) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
setTimeout(() => {
|
||||
if (!running || startedAt === undefined) return
|
||||
const target = root.querySelector<HTMLElement>(`[data-timeline-part-id="${targetPartID}"]`)
|
||||
const targetRect = target?.getBoundingClientRect()
|
||||
const highlight = CSS.highlights.get("timeline-search-hit-active")
|
||||
const ranges = highlight ? [...highlight] : []
|
||||
const active = ranges.find((range): range is Range => range instanceof Range)
|
||||
const activeRect = active?.getBoundingClientRect()
|
||||
const activeElement =
|
||||
active?.startContainer instanceof Element ? active.startContainer : active?.startContainer.parentElement
|
||||
|
||||
samples.push({
|
||||
observedAtMs: performance.now() - startedAt,
|
||||
counter:
|
||||
search.querySelector<HTMLElement>('[data-slot="timeline-search-count"]')?.textContent?.trim() ?? "",
|
||||
targetMounted: !!target,
|
||||
targetVisible: !!targetRect && visibleInRoot(targetRect),
|
||||
targetTopPx: targetRect?.top,
|
||||
activeRanges: ranges.length,
|
||||
activePartID: activeElement?.closest<HTMLElement>("[data-timeline-part-id]")?.dataset.timelinePartId,
|
||||
activeVisible: !!activeRect && visibleInRoot(activeRect),
|
||||
scrollTopPx: root.scrollTop,
|
||||
})
|
||||
sample()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
const onInputCapture = (event: Event) => {
|
||||
if (event.target !== field || startedAt !== undefined) return
|
||||
startedAt = performance.now()
|
||||
sample()
|
||||
}
|
||||
const onInput = (event: Event) => {
|
||||
if (event.target !== field || startedAt === undefined || handlerDurationMs !== undefined) return
|
||||
handlerDurationMs = performance.now() - startedAt
|
||||
}
|
||||
document.addEventListener("input", onInputCapture, { capture: true })
|
||||
document.addEventListener("input", onInput)
|
||||
;(window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark = {
|
||||
samples,
|
||||
initialScrollTopPx,
|
||||
get handlerDurationMs() {
|
||||
return handlerDurationMs
|
||||
},
|
||||
stop: () => {
|
||||
running = false
|
||||
document.removeEventListener("input", onInputCapture, { capture: true })
|
||||
document.removeEventListener("input", onInput)
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
},
|
||||
}
|
||||
}, input)
|
||||
}
|
||||
|
||||
export async function waitForStableTimelineSearch(
|
||||
page: Page,
|
||||
input: { counter: string; targetPartID: string; timeout: number },
|
||||
) {
|
||||
await page.waitForFunction(
|
||||
({ counter, targetPartID }) => {
|
||||
const samples = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
|
||||
?.samples
|
||||
if (!samples) return false
|
||||
return samples.some((_, index) => {
|
||||
const stable = samples.slice(index, index + 3)
|
||||
if (stable.length !== 3) return false
|
||||
return stable.every(
|
||||
(sample, sampleIndex) =>
|
||||
sample.counter === counter &&
|
||||
sample.targetVisible &&
|
||||
sample.activeRanges === 1 &&
|
||||
sample.activePartID === targetPartID &&
|
||||
sample.activeVisible &&
|
||||
(sampleIndex === 0 ||
|
||||
(Math.abs(sample.scrollTopPx - stable[sampleIndex - 1]!.scrollTopPx) <= 1 &&
|
||||
Math.abs((sample.targetTopPx ?? Infinity) - (stable[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
|
||||
)
|
||||
})
|
||||
},
|
||||
{ counter: input.counter, targetPartID: input.targetPartID },
|
||||
{ timeout: input.timeout },
|
||||
)
|
||||
}
|
||||
|
||||
export async function collectTimelineSearchMetrics(page: Page, input: { counter: string; targetPartID: string }) {
|
||||
const result = await page.evaluate(() => {
|
||||
const probe = (window as Window & { __timelineSearchBenchmark?: TimelineSearchProbe }).__timelineSearchBenchmark
|
||||
if (!probe) throw new Error("missing timeline search benchmark probe")
|
||||
probe.stop()
|
||||
return {
|
||||
samples: probe.samples,
|
||||
handlerDurationMs: probe.handlerDurationMs,
|
||||
initialScrollTopPx: probe.initialScrollTopPx,
|
||||
}
|
||||
})
|
||||
const first = (predicate: (sample: TimelineSearchSample) => boolean) => result.samples.find(predicate)?.observedAtMs
|
||||
const stable = result.samples.findIndex((_, index) => {
|
||||
const samples = result.samples.slice(index, index + 3)
|
||||
if (samples.length !== 3) return false
|
||||
return samples.every(
|
||||
(sample, sampleIndex) =>
|
||||
sample.counter === input.counter &&
|
||||
sample.targetVisible &&
|
||||
sample.activeRanges === 1 &&
|
||||
sample.activePartID === input.targetPartID &&
|
||||
sample.activeVisible &&
|
||||
(sampleIndex === 0 ||
|
||||
(Math.abs(sample.scrollTopPx - samples[sampleIndex - 1]!.scrollTopPx) <= 1 &&
|
||||
Math.abs((sample.targetTopPx ?? Infinity) - (samples[sampleIndex - 1]!.targetTopPx ?? -Infinity)) <= 1)),
|
||||
)
|
||||
})
|
||||
const final = result.samples.at(-1)
|
||||
|
||||
return {
|
||||
summary: {
|
||||
handlerDurationMs: result.handlerDurationMs,
|
||||
firstCountObservedMs: first((sample) => sample.counter === input.counter),
|
||||
firstTargetMountedMs: first((sample) => sample.targetMounted),
|
||||
firstTargetVisibleMs: first((sample) => sample.targetVisible),
|
||||
firstActiveHighlightObservedMs: first(
|
||||
(sample) => sample.activeRanges === 1 && sample.activePartID === input.targetPartID && sample.activeVisible,
|
||||
),
|
||||
stableResultObservedMs: stable >= 0 ? result.samples[stable + 2]?.observedAtMs : undefined,
|
||||
initialScrollTopPx: result.initialScrollTopPx,
|
||||
finalScrollTopPx: final?.scrollTopPx,
|
||||
scrollDistancePx: final === undefined ? undefined : Math.abs(result.initialScrollTopPx - final.scrollTopPx),
|
||||
activeHighlightRanges: final?.activeRanges,
|
||||
},
|
||||
samples: result.samples,
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,13 @@ const directory = "C:/OpenCode/OpenFileExpand"
|
||||
const projectID = "proj_open_file_expand"
|
||||
const sessionID = "ses_open_file_expand"
|
||||
const title = "Open file expand"
|
||||
const longFilename = "a-very-long-file-name-that-must-overflow-the-file-sidebar-instead-of-being-truncated.ts"
|
||||
const longPath = `frontend/${longFilename}`
|
||||
const server = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
|
||||
|
||||
test.use({ viewport: { width: 1440, height: 900 } })
|
||||
|
||||
test("expands a folder whose path has a trailing Windows separator", async ({ page }) => {
|
||||
test("expands Windows paths and horizontally scrolls long filenames", async ({ page }) => {
|
||||
await mockOpenCodeServer(page, {
|
||||
directory,
|
||||
project: {
|
||||
@@ -44,7 +46,17 @@ test("expands a folder whose path has a trailing Windows separator", async ({ pa
|
||||
time: { created: 1700000000000, updated: 1700000000000 },
|
||||
},
|
||||
],
|
||||
vcsDiff: [],
|
||||
vcsDiff: [
|
||||
{
|
||||
file: longPath,
|
||||
before: "",
|
||||
after: "export const added = true\n",
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
status: "added",
|
||||
patch: "@@ -0,0 +1 @@\n+export const added = true\n",
|
||||
},
|
||||
],
|
||||
fileList: (path) => {
|
||||
if (path === "frontend\\" || path === "frontend") {
|
||||
return [
|
||||
@@ -55,6 +67,13 @@ test("expands a folder whose path has a trailing Windows separator", async ({ pa
|
||||
type: "file" as const,
|
||||
ignored: false,
|
||||
},
|
||||
{
|
||||
name: longFilename,
|
||||
path: `frontend\\${longFilename}`,
|
||||
absolute: `${directory}/${longPath}`,
|
||||
type: "file" as const,
|
||||
ignored: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
if (path) return []
|
||||
@@ -75,6 +94,7 @@ test("expands a folder whose path has a trailing Windows separator", async ({ pa
|
||||
},
|
||||
]
|
||||
},
|
||||
findFiles: ({ query }) => (longPath.includes(query) ? [longPath] : []),
|
||||
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
@@ -119,6 +139,93 @@ test("expands a folder whose path has a trailing Windows separator", async ({ pa
|
||||
await frontendRow.click()
|
||||
await expect(frontendRow).toHaveAttribute("aria-expanded", "true")
|
||||
|
||||
const viewport = sidebar.locator('[data-slot="session-review-v2-sidebar-tree"] .scroll-view__viewport')
|
||||
const longRow = panel.getByRole("button", { name: longFilename })
|
||||
await expect(longRow).toBeVisible()
|
||||
await expect.poll(() => viewport.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeGreaterThan(0)
|
||||
expect(
|
||||
await longRow.evaluate((element) => getComputedStyle(element.querySelector("bdi")!.parentElement!).textOverflow),
|
||||
).toBe("clip")
|
||||
expect(await longRow.evaluate((element) => element.getBoundingClientRect().width)).toBeGreaterThanOrEqual(
|
||||
await viewport.evaluate((element) => element.clientWidth),
|
||||
)
|
||||
await expect
|
||||
.poll(() =>
|
||||
panel.locator('[data-slot="file-tree-v2-row"]').evaluateAll((rows) => {
|
||||
const widths = rows.map((row) => row.getBoundingClientRect().width)
|
||||
return Math.max(...widths) - Math.min(...widths)
|
||||
}),
|
||||
)
|
||||
.toBeLessThanOrEqual(0.5)
|
||||
await expect(longRow.locator('[data-slot="file-tree-v2-label"]')).toHaveCSS("margin-inline-end", "12px")
|
||||
const status = longRow.locator('[data-slot="file-tree-v2-change"]')
|
||||
await expect(status).toHaveText("A")
|
||||
const statusBox = await status.boundingBox()
|
||||
if (!statusBox) throw new Error("File status has no bounding box")
|
||||
const viewportBox = await viewport.boundingBox()
|
||||
if (!viewportBox) throw new Error("File tree viewport has no bounding box")
|
||||
expect(viewportBox.x + viewportBox.width - statusBox.x - statusBox.width).toBeLessThanOrEqual(24)
|
||||
|
||||
await viewport.hover()
|
||||
const horizontalThumb = sidebar.locator('.scroll-view__thumb[data-orientation="horizontal"]')
|
||||
await expect(horizontalThumb).toHaveCSS("opacity", "1")
|
||||
await page.mouse.wheel(1_000, 0)
|
||||
await expect.poll(() => viewport.evaluate((element) => Math.abs(element.scrollLeft))).toBeGreaterThan(0)
|
||||
await expect(horizontalThumb).toHaveAttribute("data-visible", "true")
|
||||
await expect
|
||||
.poll(() =>
|
||||
status.evaluate((element) => {
|
||||
const viewport = element.closest<HTMLElement>(".scroll-view__viewport")!.getBoundingClientRect()
|
||||
return viewport.right - element.getBoundingClientRect().right
|
||||
}),
|
||||
)
|
||||
.toBeLessThanOrEqual(24)
|
||||
|
||||
const beforeDrag = await viewport.evaluate((element) => Math.abs(element.scrollLeft))
|
||||
const thumbBox = await horizontalThumb.boundingBox()
|
||||
if (!thumbBox) throw new Error("Horizontal scrollbar thumb has no bounding box")
|
||||
await page.mouse.move(thumbBox.x + thumbBox.width / 2, thumbBox.y + thumbBox.height / 2)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(thumbBox.x + thumbBox.width / 2 - 40, thumbBox.y + thumbBox.height / 2)
|
||||
await page.mouse.up()
|
||||
await expect.poll(() => viewport.evaluate((element) => Math.abs(element.scrollLeft))).toBeLessThan(beforeDrag)
|
||||
|
||||
const filter = panel.getByRole("combobox", { name: "Filter files" })
|
||||
await filter.fill(longFilename)
|
||||
const filteredRow = panel.getByRole("option", { name: longFilename })
|
||||
await expect(filteredRow).toBeVisible()
|
||||
const filteredStatus = filteredRow.locator('[data-slot="file-tree-v2-change"]')
|
||||
await expect(filteredStatus).toHaveText("A")
|
||||
await expect.poll(() => viewport.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeGreaterThan(0)
|
||||
|
||||
await viewport.evaluate((element) => {
|
||||
element.setAttribute("dir", "rtl")
|
||||
element.scrollLeft = 0
|
||||
element.dispatchEvent(new Event("scroll"))
|
||||
})
|
||||
await expect
|
||||
.poll(() =>
|
||||
filteredStatus.evaluate((element) => {
|
||||
const viewport = element.closest<HTMLElement>(".scroll-view__viewport")!.getBoundingClientRect()
|
||||
return element.getBoundingClientRect().left - viewport.left
|
||||
}),
|
||||
)
|
||||
.toBeLessThanOrEqual(24)
|
||||
const rtlThumbBox = await horizontalThumb.boundingBox()
|
||||
if (!rtlThumbBox) throw new Error("RTL horizontal scrollbar thumb has no bounding box")
|
||||
await page.mouse.move(rtlThumbBox.x + rtlThumbBox.width / 2, rtlThumbBox.y + rtlThumbBox.height / 2)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(rtlThumbBox.x + rtlThumbBox.width / 2 - 40, rtlThumbBox.y + rtlThumbBox.height / 2)
|
||||
await page.mouse.up()
|
||||
await expect.poll(() => viewport.evaluate((element) => element.scrollLeft)).toBeLessThan(0)
|
||||
await viewport.evaluate((element) => {
|
||||
element.removeAttribute("dir")
|
||||
element.scrollLeft = 0
|
||||
element.dispatchEvent(new Event("scroll"))
|
||||
})
|
||||
|
||||
await filter.fill("")
|
||||
|
||||
const appRow = panel.locator('[data-slot="file-tree-v2-row"][data-path="frontend/app.ts"]')
|
||||
await expect(appRow).toBeVisible()
|
||||
await appRow.click()
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { createTwoFilesPatch } from "diff"
|
||||
import { assistantMessage, setupTimeline, toolPart, userMessage } from "../performance/timeline-stability/fixture"
|
||||
|
||||
test.use({
|
||||
deviceScaleFactor: 2,
|
||||
// Emulating DPR alone does not exercise Chromium's native hairline border rounding.
|
||||
launchOptions: { args: ["--force-device-scale-factor=2"] },
|
||||
})
|
||||
|
||||
for (const width of [1400, 390]) {
|
||||
test(`patch file borders retain a full CSS pixel at ${width}px on high-density displays`, async ({ page }) => {
|
||||
const file = `src/${"long-directory/".repeat(12)}patch-border.ts`
|
||||
await setupTimeline(page, {
|
||||
messages: [
|
||||
userMessage(),
|
||||
assistantMessage([
|
||||
toolPart(
|
||||
"prt_border_patch",
|
||||
"patch",
|
||||
"completed",
|
||||
{ patchText: "Update file" },
|
||||
{
|
||||
metadata: {
|
||||
files: [
|
||||
{
|
||||
file,
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
patch: createTwoFilesPatch(file, file, "const value = 1\n", "const value = 2\n"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
]),
|
||||
],
|
||||
reducedMotion: true,
|
||||
viewport: { width, height: 900 },
|
||||
})
|
||||
await page.getByRole("button", { name: "Used 1 Patch", exact: true }).click()
|
||||
const patch = page.locator('[data-component="apply-patch-tool"]')
|
||||
const trigger = patch.getByRole("button", { name: /patch-border.ts/ })
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(trigger).toHaveCSS("height", "32px")
|
||||
for (const side of ["top", "right", "bottom", "left"]) {
|
||||
await expect(trigger).toHaveCSS(`border-${side}-width`, "1px")
|
||||
}
|
||||
|
||||
const box = await trigger.boundingBox()
|
||||
await trigger.hover()
|
||||
expect(await trigger.boundingBox()).toEqual(box)
|
||||
await page.mouse.move(0, 0)
|
||||
expect(await trigger.boundingBox()).toEqual(box)
|
||||
|
||||
await trigger.click()
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "true")
|
||||
const content = patch.locator('[data-slot="accordion-content"]')
|
||||
await expect(content).toBeVisible()
|
||||
for (const side of ["left", "right", "bottom"]) {
|
||||
await expect(content).toHaveCSS(`border-${side}-width`, "1px")
|
||||
}
|
||||
await expect(content).toHaveCSS("border-top-width", "0px")
|
||||
await trigger.press("Enter")
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "false")
|
||||
})
|
||||
}
|
||||
@@ -301,11 +301,14 @@ for (const count of [0, 26]) {
|
||||
}
|
||||
|
||||
for (const direction of ["ltr", "rtl"]) {
|
||||
test(`vertical tabs keep Settings pinned while scrolling in ${direction}`, async ({ page }, testInfo) => {
|
||||
test(`vertical tabs keep Status pinned without Settings in ${direction}`, async ({ page }, testInfo) => {
|
||||
await mockServer(page)
|
||||
await page.addInitScript(
|
||||
({ server, sessionA, sessionB, directory }) => {
|
||||
localStorage.setItem("settings.v3", JSON.stringify({ appearance: { tabLayout: "vertical" } }))
|
||||
localStorage.setItem(
|
||||
"settings.v3",
|
||||
JSON.stringify({ appearance: { tabLayout: "vertical" }, general: { showStatus: true } }),
|
||||
)
|
||||
localStorage.setItem(
|
||||
"opencode.window.browser.dat:tabs",
|
||||
JSON.stringify([
|
||||
@@ -322,23 +325,27 @@ for (const direction of ["ltr", "rtl"]) {
|
||||
},
|
||||
{ server, sessionA: sessionA.id, sessionB: sessionB.id, directory: sessionA.directory },
|
||||
)
|
||||
await page.goto("/")
|
||||
await page.goto(`/server/${base64Encode(server)}/session/${sessionA.id}`)
|
||||
|
||||
const sidebar = page.locator('[data-slot="vertical-tabs-sidebar"]')
|
||||
const settings = sidebar.getByRole("button", { name: "Settings", exact: true })
|
||||
const status = sidebar.getByRole("button", { name: "Status", exact: true })
|
||||
const scroll = sidebar.locator('[data-slot="vertical-tabs-scroll"]')
|
||||
const hrefB = `/server/${base64Encode(server)}/session/${sessionB.id}`
|
||||
const tabB = sidebar.locator(`[data-titlebar-tab-link][href="${hrefB}"]`)
|
||||
await expect(sidebar.locator("[data-titlebar-tab-slot]")).toHaveCount(26)
|
||||
await expect(settings).toHaveText("Settings")
|
||||
await expect(status).toHaveText("Status")
|
||||
await expect(settings).toHaveCount(0)
|
||||
await expect(status.locator('[data-slot="status-indicator"]')).toBeVisible()
|
||||
await page.evaluate((direction) => document.documentElement.setAttribute("dir", direction), direction)
|
||||
|
||||
for (const width of [1280, 800]) {
|
||||
await page.setViewportSize({ width, height: 360 })
|
||||
await expect(settings).toBeInViewport({ ratio: 1 })
|
||||
await expect(sidebar).toHaveCSS("padding-inline-start", "10px")
|
||||
await expect(sidebar).toHaveCSS("padding-bottom", "10px")
|
||||
await expect(settings).toHaveCSS("margin-top", "8px")
|
||||
await expect(sidebar.locator('[data-slot="vertical-tabs-footer"]')).toHaveCSS("margin-top", "8px")
|
||||
await expect(status).toBeInViewport({ ratio: 1 })
|
||||
await expect(status).toHaveCSS("height", "28px")
|
||||
await expect
|
||||
.poll(() =>
|
||||
sidebar.locator('[data-slot="vertical-tabs-footer"]').evaluate((element) => {
|
||||
@@ -353,12 +360,12 @@ for (const direction of ["ltr", "rtl"]) {
|
||||
await expect(scroll).toHaveCSS("mask-image", /linear-gradient/)
|
||||
await scroll.evaluate((element) => element.scrollTo(0, 0))
|
||||
await expect(scroll).toHaveJSProperty("scrollTop", 0)
|
||||
const pinned = await settings.boundingBox()
|
||||
const pinnedStatus = await status.boundingBox()
|
||||
await scroll.hover()
|
||||
await page.mouse.wheel(0, 200)
|
||||
await expect.poll(() => scroll.evaluate((element) => element.scrollTop)).toBeGreaterThan(0)
|
||||
await expect.poll(() => settings.boundingBox()).toEqual(pinned)
|
||||
await testInfo.attach(`vertical-tabs-settings-${width}`, {
|
||||
await expect.poll(() => status.boundingBox()).toEqual(pinnedStatus)
|
||||
await testInfo.attach(`vertical-tabs-status-${width}`, {
|
||||
body: await sidebar.screenshot(),
|
||||
contentType: "image/png",
|
||||
})
|
||||
@@ -372,17 +379,14 @@ for (const direction of ["ltr", "rtl"]) {
|
||||
return !!tab && !!viewport && tab.y + tab.height <= viewport.y + viewport.height - 16
|
||||
})
|
||||
.toBe(true)
|
||||
await expect.poll(() => settings.boundingBox()).toEqual(pinned)
|
||||
await expect.poll(() => status.boundingBox()).toEqual(pinnedStatus)
|
||||
await expect(settings).toHaveCount(0)
|
||||
}
|
||||
|
||||
await settings.click()
|
||||
await expect(page.getByTestId("settings-screen")).toBeVisible()
|
||||
await expect(settings).toHaveAttribute("aria-pressed", "true")
|
||||
await sidebar.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await expect(page.getByTestId("settings-screen")).toBeHidden()
|
||||
await settings.focus()
|
||||
await settings.press("Enter")
|
||||
await expect(page.getByTestId("settings-screen")).toBeVisible()
|
||||
await status.click()
|
||||
await expect(status).toHaveAttribute("aria-expanded", "true")
|
||||
await status.press("Escape")
|
||||
await expect(status).toHaveAttribute("aria-expanded", "false")
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -67,12 +67,12 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await testInfo.attach("workspace-accent", { path, contentType: "image/png" })
|
||||
}
|
||||
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await view.send.hover()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await view.composer.locator('[data-action="composer-model"]').press("Tab")
|
||||
await expect(view.send).toBeFocused()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
const message = page.locator('[data-slot="user-message-text"]')
|
||||
await expect(message).toHaveText("Check this fixture workspace.")
|
||||
await expectToken(
|
||||
@@ -92,7 +92,7 @@ for (const theme of ["light", "dark"] as const) {
|
||||
const view = await openSession(page, workspace, [{ directory: root }])
|
||||
await view.input.fill("Keep this draft while the inventory changes.")
|
||||
await expect(view.send).toBeEnabled()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
const url = page.url()
|
||||
|
||||
const refreshed = page.waitForResponse(
|
||||
@@ -109,14 +109,14 @@ for (const theme of ["light", "dark"] as const) {
|
||||
data: { projectID },
|
||||
})
|
||||
expect((await refreshed).ok()).toBe(true)
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await expect(page).toHaveURL(url)
|
||||
await expect(view.input).toHaveText("Keep this draft while the inventory changes.")
|
||||
await expect(view.send).toBeEnabled()
|
||||
|
||||
await view.input.fill("")
|
||||
await expect(view.send).toBeDisabled()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
|
||||
view.events.push({
|
||||
id: "evt_workspace_accent_running",
|
||||
@@ -127,29 +127,29 @@ for (const theme of ["light", "dark"] as const) {
|
||||
})
|
||||
const stop = view.composer.getByRole("button", { name: "Stop", exact: true })
|
||||
await expect(stop).toBeEnabled()
|
||||
await expectBackground(stop, "contrast")
|
||||
await expectBackground(stop, "icon-button-contrast")
|
||||
|
||||
await view.input.fill("Send a follow-up instead of stopping.")
|
||||
await expect(view.send).toBeEnabled()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await expect(page).toHaveURL(url)
|
||||
})
|
||||
|
||||
test("new workspace send button stays neutral", async ({ page }) => {
|
||||
const view = await openSession(page, root, [...inventory], true)
|
||||
await expect(view.send).toBeDisabled()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await page.getByRole("button", { name: "Local", exact: true }).click()
|
||||
await page.getByRole("menuitem", { name: "New worktree", exact: true }).click()
|
||||
await expect(page.getByRole("button", { name: "New worktree", exact: true })).toBeVisible()
|
||||
await view.input.fill("Inspect this fixture workspace.")
|
||||
await expect(view.send).toBeEnabled()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await view.send.hover()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
await view.composer.locator('[data-action="composer-model"]').press("Tab")
|
||||
await expect(view.send).toBeFocused()
|
||||
await expectBackground(view.send, "contrast")
|
||||
await expectBackground(view.send, "icon-button-contrast")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ function ComposerStory(props: {
|
||||
label?: string
|
||||
inspectRequest?: boolean
|
||||
continueOnStop?: boolean
|
||||
longLabels?: boolean
|
||||
alternate?: "queue" | "steer"
|
||||
}) {
|
||||
const [draft, setDraft] = createStore<ComposerPersistedState>({
|
||||
prompt: props.prompt ?? [{ type: "text", content: "", start: 0, end: 0 }],
|
||||
@@ -66,11 +68,15 @@ function ComposerStory(props: {
|
||||
activity: props.label ?? "Ready",
|
||||
variant: STORY_MODEL.variant,
|
||||
})
|
||||
const modelOption = createMemo(() => ({
|
||||
...selectedModel,
|
||||
name: props.longLabels ? "Claude Sonnet with an unusually long model name" : selectedModel.name,
|
||||
}))
|
||||
const modelSelection = {
|
||||
ready: Object.assign(() => true, { promise: undefined }),
|
||||
current: () => selectedModel,
|
||||
recent: () => [selectedModel],
|
||||
list: () => [selectedModel],
|
||||
current: () => modelOption(),
|
||||
recent: () => [modelOption()],
|
||||
list: () => [modelOption()],
|
||||
cycle() {},
|
||||
set() {},
|
||||
visible: () => true,
|
||||
@@ -126,7 +132,7 @@ function ComposerStory(props: {
|
||||
placeholder: () => "Ask anything, / for commands, @ for context...",
|
||||
agent: {
|
||||
options: () => [
|
||||
{ id: "build", label: "build" },
|
||||
{ id: "build", label: props.longLabels ? "Build agent with an unusually long name" : "build" },
|
||||
{ id: "review", label: "review" },
|
||||
],
|
||||
current: () => "build",
|
||||
@@ -135,7 +141,7 @@ function ComposerStory(props: {
|
||||
variant: {
|
||||
options: () => [
|
||||
{ id: "default", label: "default" },
|
||||
{ id: "balanced", label: "balanced" },
|
||||
{ id: "balanced", label: props.longLabels ? "Balanced reasoning with an extended label" : "balanced" },
|
||||
{ id: "high", label: "high" },
|
||||
],
|
||||
current: () => story.variant,
|
||||
@@ -144,6 +150,17 @@ function ComposerStory(props: {
|
||||
submit: {
|
||||
stopping: () => !!props.stopping,
|
||||
working: () => !!props.working,
|
||||
queue: props.alternate
|
||||
? {
|
||||
count: () => 0,
|
||||
delivery: () => (props.alternate === "queue" ? "steer" : "queue"),
|
||||
alternate: () => props.alternate,
|
||||
editing: () => undefined,
|
||||
confirmEdit() {},
|
||||
cancelEdit() {},
|
||||
editFirst: () => false,
|
||||
}
|
||||
: undefined,
|
||||
onSubmit: () => {
|
||||
const value = draft.prompt.map((part) => ("content" in part ? part.content : `[${part.filename}]`)).join("")
|
||||
const request = props.inspectRequest
|
||||
@@ -290,6 +307,21 @@ export const NarrowLayout = {
|
||||
),
|
||||
}
|
||||
|
||||
export const ToolbarOverflow = {
|
||||
args: { alternate: "queue" },
|
||||
argTypes: { alternate: { control: "select", options: ["none", "queue", "steer"] } },
|
||||
render: (args: { alternate: "none" | "queue" | "steer" }) => (
|
||||
<div class="w-[min(420px,calc(100vw-80px))]">
|
||||
<ComposerStory
|
||||
longLabels
|
||||
working
|
||||
prompt={text("Keep all controls reachable when the toolbar overflows")}
|
||||
alternate={args.alternate === "none" ? undefined : args.alternate}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const DemoFirstClassSkillIDs = {
|
||||
name: "Demo: First-class skill IDs",
|
||||
render: () => (
|
||||
|
||||
@@ -2,6 +2,29 @@
|
||||
content: "\200B";
|
||||
}
|
||||
|
||||
/* Masks only cover hidden content; they do not reserve space in the toolbar. */
|
||||
[data-slot="composer-controls"][data-overflow-start="true"] {
|
||||
--mask-start: 16px;
|
||||
}
|
||||
|
||||
[data-slot="composer-controls"][data-overflow-end="true"] {
|
||||
--mask-end: 16px;
|
||||
}
|
||||
|
||||
[data-slot="composer-controls"]:dir(rtl) {
|
||||
--mask-direction: to left;
|
||||
}
|
||||
|
||||
[data-slot="composer-controls"]:is([data-overflow-start="true"], [data-overflow-end="true"]) {
|
||||
mask-image: linear-gradient(
|
||||
var(--mask-direction, to right),
|
||||
transparent,
|
||||
black var(--mask-start, 0px),
|
||||
black calc(100% - var(--mask-end, 0px)),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
[data-component="composer"]:not(:hover) .composer-variant-default:not(:focus-visible, [data-expanded]) {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createEffect, createMemo, createSignal, For, Show, type JSX } from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { FileIcon } from "@opencode-ai/ui/file-icon"
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||
@@ -56,6 +57,23 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
const view = props.controller.view
|
||||
let editor: HTMLDivElement | undefined
|
||||
let viewport: HTMLDivElement | undefined
|
||||
let controlsViewport!: HTMLDivElement
|
||||
let controlsContent!: HTMLDivElement
|
||||
const [overflow, setOverflow] = createStore({ start: false, end: false })
|
||||
const updateOverflow = () => {
|
||||
const offset = Math.abs(controlsViewport.scrollLeft)
|
||||
setOverflow({
|
||||
start: offset > 1,
|
||||
end: controlsViewport.scrollWidth - controlsViewport.clientWidth - offset > 1,
|
||||
})
|
||||
}
|
||||
onMount(() => {
|
||||
const observer = new ResizeObserver(updateOverflow)
|
||||
observer.observe(controlsViewport)
|
||||
observer.observe(controlsContent)
|
||||
updateOverflow()
|
||||
onCleanup(() => observer.disconnect())
|
||||
})
|
||||
let localInput = false
|
||||
const updateCursor = () => {
|
||||
if (!editor || !window.getSelection()?.isCollapsed) return
|
||||
@@ -226,7 +244,7 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
|
||||
<div class="flex h-11 items-center px-2">
|
||||
<div
|
||||
class="flex min-w-0 flex-1 items-center gap-1"
|
||||
class="flex shrink-0 items-center"
|
||||
aria-hidden={state.mode === "shell"}
|
||||
inert={state.mode === "shell" ? true : undefined}
|
||||
style={buttons()}
|
||||
@@ -245,64 +263,80 @@ export function ComposerEditor(props: ComposerEditorProps) {
|
||||
onContext={props.controller.openContext}
|
||||
onShell={props.controller.openShell}
|
||||
/>
|
||||
<Show when={view.agent} keyed>
|
||||
{(control) => (
|
||||
<ComposerEditorConfiguredSelect
|
||||
title={i18n.t("ui.promptInput.chooseAgent")}
|
||||
keybind={["Mod", "."]}
|
||||
control={control}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={props.modelControlsVisible ?? true}>
|
||||
{props.modelControl}
|
||||
<Show when={view.variant} keyed>
|
||||
</div>
|
||||
<div
|
||||
ref={controlsViewport}
|
||||
data-slot="composer-controls"
|
||||
data-overflow-start={overflow.start}
|
||||
data-overflow-end={overflow.end}
|
||||
class="ms-1 me-3 h-full min-w-0 flex-1 overflow-x-auto overscroll-x-contain no-scrollbar"
|
||||
onScroll={updateOverflow}
|
||||
aria-hidden={state.mode === "shell"}
|
||||
inert={state.mode === "shell" ? true : undefined}
|
||||
style={buttons()}
|
||||
>
|
||||
<div ref={controlsContent} class="flex h-full w-max min-w-full items-center gap-1">
|
||||
<Show when={view.agent} keyed>
|
||||
{(control) => (
|
||||
<Show when={control.options().length > 1}>
|
||||
<ComposerEditorConfiguredSelect
|
||||
title={i18n.t("ui.promptInput.chooseVariant")}
|
||||
keybind={["Shift", "Mod", "D"]}
|
||||
control={control}
|
||||
class={control.current() === "default" ? "composer-variant-default" : undefined}
|
||||
/>
|
||||
</Show>
|
||||
<ComposerEditorConfiguredSelect
|
||||
title={i18n.t("ui.promptInput.chooseAgent")}
|
||||
keybind={["Mod", "."]}
|
||||
control={control}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
<Show when={props.modelControlsVisible ?? true}>
|
||||
{props.modelControl}
|
||||
<Show when={view.variant} keyed>
|
||||
{(control) => (
|
||||
<Show when={control.options().length > 1}>
|
||||
<ComposerEditorConfiguredSelect
|
||||
title={i18n.t("ui.promptInput.chooseVariant")}
|
||||
keybind={["Shift", "Mod", "D"]}
|
||||
control={control}
|
||||
class={control.current() === "default" ? "composer-variant-default" : undefined}
|
||||
/>
|
||||
</Show>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
<Show when={state.mode === "normal"}>
|
||||
<ComposerEditorAlternateDelivery
|
||||
controller={props.controller}
|
||||
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
|
||||
<div data-slot="composer-actions" class="flex shrink-0 items-center">
|
||||
<Show when={state.mode === "normal"}>
|
||||
<ComposerEditorAlternateDelivery
|
||||
controller={props.controller}
|
||||
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
|
||||
/>
|
||||
</Show>
|
||||
<Show when={state.mode === "shell"}>
|
||||
<Button
|
||||
data-action="composer-exit-shell"
|
||||
type="button"
|
||||
variant="ghost-faint"
|
||||
size="small"
|
||||
class="me-3 gap-1.5 px-1.5"
|
||||
onClick={() => {
|
||||
props.controller.dispatch({ type: "mode.normal" })
|
||||
props.controller.restoreFocus()
|
||||
}}
|
||||
>
|
||||
{i18n.t("ui.promptInput.exitShell")}
|
||||
<span class="hidden sm:block">
|
||||
<Keybind keys={props.exitShellKeybind ?? ["ESC"]} variant="neutral" />
|
||||
</span>
|
||||
</Button>
|
||||
</Show>
|
||||
<ComposerEditorSubmitButton
|
||||
mode={state.mode}
|
||||
stopping={view.submit.stopping()}
|
||||
disabled={!props.controller.canSubmit()}
|
||||
sendLabel={i18n.t("ui.promptInput.send")}
|
||||
stopLabel={i18n.t("ui.promptInput.stop")}
|
||||
onSubmit={() => props.controller.submit()}
|
||||
onStop={props.controller.stop}
|
||||
/>
|
||||
</Show>
|
||||
<Show when={state.mode === "shell"}>
|
||||
<Button
|
||||
data-action="composer-exit-shell"
|
||||
type="button"
|
||||
variant="ghost-faint"
|
||||
size="small"
|
||||
class="me-3 gap-1.5 px-1.5"
|
||||
onClick={() => {
|
||||
props.controller.dispatch({ type: "mode.normal" })
|
||||
props.controller.restoreFocus()
|
||||
}}
|
||||
>
|
||||
{i18n.t("ui.promptInput.exitShell")}
|
||||
<span class="hidden sm:block">
|
||||
<Keybind keys={props.exitShellKeybind ?? ["ESC"]} variant="neutral" />
|
||||
</span>
|
||||
</Button>
|
||||
</Show>
|
||||
<ComposerEditorSubmitButton
|
||||
mode={state.mode}
|
||||
stopping={view.submit.stopping()}
|
||||
disabled={!props.controller.canSubmit()}
|
||||
sendLabel={i18n.t("ui.promptInput.send")}
|
||||
stopLabel={i18n.t("ui.promptInput.stop")}
|
||||
onSubmit={() => props.controller.submit()}
|
||||
onStop={props.controller.stop}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -808,11 +842,7 @@ export function ComposerEditorSubmitButton(props: {
|
||||
tabIndex={props.mode === "normal" ? undefined : -1}
|
||||
icon={<Icon name={props.stopping ? "stop" : props.mode === "shell" ? "arrow-undo-down" : "arrow-up"} />}
|
||||
variant="contrast"
|
||||
class="size-7 rounded-md p-[6px] text-v2-icon-icon-muted shadow-[var(--v2-elevation-button-contrast)] disabled:opacity-50"
|
||||
style={{
|
||||
"background-image":
|
||||
"linear-gradient(180deg,var(--v2-alpha-light-20) 0%,var(--v2-alpha-light-0) 100%),linear-gradient(90deg,var(--v2-background-bg-contrast) 0%,var(--v2-background-bg-contrast) 100%)",
|
||||
}}
|
||||
class="size-7 rounded-md p-[6px] disabled:opacity-50"
|
||||
aria-label={props.stopping ? props.stopLabel : props.sendLabel}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
|
||||
@@ -165,6 +165,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
::highlight(timeline-search-hit) {
|
||||
background-color: color-mix(in srgb, var(--v2-icon-icon-accent) 28%, transparent);
|
||||
}
|
||||
|
||||
::highlight(timeline-search-hit-active) {
|
||||
background-color: var(--v2-icon-icon-accent);
|
||||
color: var(--v2-background-bg-deep);
|
||||
}
|
||||
|
||||
[data-component="getting-started"] {
|
||||
container-type: inline-size;
|
||||
container-name: getting-started;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
/** Inline new-session content width — keep in sync with session composer `placement === "inline"`. */
|
||||
export const NEW_SESSION_CONTENT_WIDTH = "w-full max-w-[720px] px-0"
|
||||
/** Allows the prompt to extend 80px beyond each side of the 720px wordmark. */
|
||||
export const NEW_SESSION_CONTENT_WIDTH = "w-full max-w-[880px] px-0"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { Wordmark } from "@opencode-ai/ui/wordmark"
|
||||
import { Show, createMemo, createSignal } from "solid-js"
|
||||
import { Schema } from "effect"
|
||||
import createPresence from "solid-presence"
|
||||
@@ -23,6 +22,7 @@ import { NEW_SESSION_CONTENT_WIDTH } from "@/new-session/layout"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
import type { NewSessionWorkspaceController } from "./workspace/controller"
|
||||
import { NewSessionWordmark } from "./wordmark"
|
||||
|
||||
const providerTipDismissalDuration = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
@@ -61,7 +61,7 @@ export function NewSessionView(props: {
|
||||
/>
|
||||
<div class="absolute inset-x-0 top-[25.375%] flex justify-center px-6">
|
||||
<div class={NEW_SESSION_CONTENT_WIDTH}>
|
||||
<Wordmark class="h-auto w-full text-v2-background-bg-inverse" />
|
||||
<NewSessionWordmark />
|
||||
<div class="mt-8 flex flex-col gap-8">
|
||||
<Composer model={props.composer} />
|
||||
<Show when={props.project.empty()}>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
[data-component="new-session-wordmark"] {
|
||||
--wordmark-shimmer-opacity: 0.45;
|
||||
|
||||
.wordmark-shimmer {
|
||||
/* Blend above the base logo's opacity so the sweep only adds light in either theme. */
|
||||
color: white;
|
||||
mix-blend-mode: screen;
|
||||
opacity: 0;
|
||||
mask-image: linear-gradient(to right, transparent 40%, black 50%, transparent 60%);
|
||||
mask-size: 300% 100%;
|
||||
mask-repeat: no-repeat;
|
||||
animation: new-session-wordmark-shimmer 800ms linear both;
|
||||
}
|
||||
}
|
||||
|
||||
[data-color-scheme="dark"] [data-component="new-session-wordmark"] {
|
||||
/* Preserve the previous dark highlight strength: 0.16 × 0.7 × 0.6. */
|
||||
--wordmark-shimmer-opacity: 0.0672;
|
||||
}
|
||||
|
||||
/* Oversizing the mask moves its highlight physically left to right, including in RTL. */
|
||||
@keyframes new-session-wordmark-shimmer {
|
||||
0% {
|
||||
mask-position: 100% 0;
|
||||
opacity: 0;
|
||||
}
|
||||
20%,
|
||||
80% {
|
||||
opacity: var(--wordmark-shimmer-opacity);
|
||||
}
|
||||
100% {
|
||||
mask-position: 0% 0;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-component="new-session-wordmark"] {
|
||||
.wordmark-shimmer {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { NewSessionWordmark } from "./wordmark"
|
||||
|
||||
export default {
|
||||
title: "App/New Session/Wordmark",
|
||||
id: "app-new-session-wordmark",
|
||||
component: NewSessionWordmark,
|
||||
}
|
||||
|
||||
export const Reveal = {
|
||||
render: () => <NewSessionWordmark />,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Wordmark } from "@opencode-ai/ui/wordmark"
|
||||
import "./wordmark.css"
|
||||
|
||||
export function NewSessionWordmark() {
|
||||
return (
|
||||
<div
|
||||
data-component="new-session-wordmark"
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none mx-auto w-full max-w-[720px] text-v2-background-bg-inverse"
|
||||
>
|
||||
<div data-slot="wordmark-reveal" class="relative">
|
||||
<Wordmark fade={false} class="block h-auto w-full opacity-60 [[data-color-scheme=dark]_&]:opacity-50" />
|
||||
<Wordmark fade={false} muted={false} class="wordmark-shimmer absolute inset-0 h-auto w-full" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -676,7 +676,7 @@ export const dict = {
|
||||
"session.error.incompatible.description":
|
||||
"{{server}} is running OpenCode {{version}}, which isn't compatible with this app. Upgrade the server to OpenCode V2 to continue.",
|
||||
"session.background.moveTasks": "Move {{tasks}} to background",
|
||||
"session.background.moveRunning": "Move running work to background",
|
||||
"session.background.moveRunning": "Move to background",
|
||||
"session.background.inBackground": "Running {{tasks}} in background",
|
||||
"session.background.moveInline": "Press {{keybind}} to move running work to the background",
|
||||
"session.background.running": "Running work in background",
|
||||
@@ -736,6 +736,16 @@ export const dict = {
|
||||
"session.todo.expand": "Expand",
|
||||
"session.todo.progress": "{{done}} of {{total}} todos completed",
|
||||
"session.question.progress": "{{current}} of {{total}} questions",
|
||||
"session.websearch.title": "Third-party web search",
|
||||
"session.websearch.description": "Select the search provider agents use to search the web",
|
||||
"session.websearch.provider": "Search provider",
|
||||
"session.websearch.any": "Any",
|
||||
"session.websearch.disable": "Don’t use search",
|
||||
"session.websearch.enable": "Enable",
|
||||
"session.websearch.loadFailed": "Could not load search providers.",
|
||||
"session.websearch.empty": "No search providers available.",
|
||||
"session.websearch.failed": "Could not save your choice. Please try again.",
|
||||
"session.websearch.retry": "Retry",
|
||||
"session.question.minimize": "Minimize question",
|
||||
"session.question.restore": "Restore question",
|
||||
"session.question.pending.one": "{{count}} pending question",
|
||||
@@ -759,6 +769,8 @@ export const dict = {
|
||||
|
||||
"session.header.search.placeholder": "Search {{project}}",
|
||||
"session.header.searchFiles": "Search files",
|
||||
"session.search.placeholder": "Find...",
|
||||
"session.search.noResults": "No matches",
|
||||
"session.header.openIn": "Open in",
|
||||
"session.header.open.action": "Open {{app}}",
|
||||
"session.header.open.ariaLabel": "Open in {{app}}",
|
||||
@@ -1045,8 +1057,8 @@ export const dict = {
|
||||
"settings.general.row.showTerminal.description": "Show the terminal button in the desktop title bar",
|
||||
"settings.general.row.showStatus.title": "Server status",
|
||||
"settings.general.row.showStatus.description": "Show the server status button in the title bar",
|
||||
"settings.general.row.showProjectIcon.title": "Project icon",
|
||||
"settings.general.row.showProjectIcon.description": "Show the project icon in the session header",
|
||||
"settings.general.row.showProjectIcon.title": "Show project icon",
|
||||
"settings.general.row.showProjectIcon.description": "Show project icon in session header",
|
||||
"settings.general.row.mobileTitlebarBottom.title": "Bottom navigation",
|
||||
"settings.general.row.mobileTitlebarBottom.description": "Place the title bar at the bottom of the screen on mobile",
|
||||
"settings.general.row.mobileDiffWrap.description":
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { createRequestQueue } from "./request-queue"
|
||||
import { createRequestQueue, isSlowRequest } from "./request-queue"
|
||||
|
||||
function setup(input?: { limit?: number; stallMs?: number }) {
|
||||
const pending: Array<{ url: string; resolve: () => void }> = []
|
||||
function setup(input?: { limit?: number; slowLimit?: number; stallMs?: number; headersTimeoutMs?: number }) {
|
||||
const pending: Array<{ url: string; signal: AbortSignal; resolve: () => void }> = []
|
||||
const logs: Array<{ message: string; data: Record<string, unknown> }> = []
|
||||
let clock = 0
|
||||
const queue = createRequestQueue({
|
||||
limit: input?.limit ?? 2,
|
||||
slowLimit: input?.slowLimit,
|
||||
stallMs: input?.stallMs,
|
||||
headersTimeoutMs: input?.headersTimeoutMs,
|
||||
now: () => clock,
|
||||
log: (message, data) => logs.push({ message, data }),
|
||||
fetch: Object.assign(
|
||||
(resource: RequestInfo | URL) =>
|
||||
new Promise<Response>((resolve) => {
|
||||
pending.push({ url: new Request(resource).url, resolve: () => resolve(new Response("ok")) })
|
||||
new Promise<Response>((resolve, reject) => {
|
||||
const request = new Request(resource)
|
||||
request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true })
|
||||
pending.push({ url: request.url, signal: request.signal, resolve: () => resolve(new Response("ok")) })
|
||||
}),
|
||||
{ preconnect() {} },
|
||||
),
|
||||
@@ -37,6 +41,36 @@ describe("createRequestQueue", () => {
|
||||
expect(input.queue.inflight()).toBe(0)
|
||||
})
|
||||
|
||||
test("slow endpoints hold at most their share of slots so small reads go first", async () => {
|
||||
const input = setup({ limit: 4, slowLimit: 2 })
|
||||
const paths = ["/api/vcs?location[directory]=%2Fa", "/api/vcs/diff?location[directory]=%2Fa", "/api/worktree", "/api/session/ses_1"]
|
||||
const responses = paths.map((path) => input.queue.fetch(`http://server${path}`))
|
||||
await input.settle()
|
||||
const started = () => input.pending.map((item) => new URL(item.url).pathname)
|
||||
// Two slow requests fill the slow share; the worktree read waits while the session read jumps ahead.
|
||||
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1"])
|
||||
expect(input.queue.inflight()).toBe(3)
|
||||
expect(input.queue.queued()).toBe(1)
|
||||
// A fast request finishing does not free a slow slot.
|
||||
input.pending[2]!.resolve()
|
||||
await input.settle()
|
||||
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1"])
|
||||
input.pending[0]!.resolve()
|
||||
await input.settle()
|
||||
expect(started()).toEqual(["/api/vcs", "/api/vcs/diff", "/api/session/ses_1", "/api/worktree"])
|
||||
input.pending.forEach((item) => item.resolve())
|
||||
await Promise.all(responses)
|
||||
expect(input.queue.inflight()).toBe(0)
|
||||
})
|
||||
|
||||
test("classifies git and worktree endpoints as slow", () => {
|
||||
expect(isSlowRequest("/api/vcs")).toBe(true)
|
||||
expect(isSlowRequest("/api/vcs/branches")).toBe(true)
|
||||
expect(isSlowRequest("/api/worktree")).toBe(true)
|
||||
expect(isSlowRequest("/api/vcsx")).toBe(false)
|
||||
expect(isSlowRequest("/api/session")).toBe(false)
|
||||
})
|
||||
|
||||
test("never counts the event stream against the budget", async () => {
|
||||
const input = setup({ limit: 1 })
|
||||
void input.queue.fetch("http://server/api/session")
|
||||
@@ -59,6 +93,34 @@ describe("createRequestQueue", () => {
|
||||
expect(input.queue.inflight()).toBe(0)
|
||||
})
|
||||
|
||||
test("a request the server never answers times out and frees its slot", async () => {
|
||||
const input = setup({ limit: 1, headersTimeoutMs: 10 })
|
||||
const dead = input.queue.fetch("http://server/api/dead")
|
||||
const next = input.queue.fetch("http://server/api/next")
|
||||
await input.settle()
|
||||
expect(input.queue.queued()).toBe(1)
|
||||
const error = await dead.catch((cause: unknown) => cause)
|
||||
expect(error).toBeInstanceOf(DOMException)
|
||||
expect((error as DOMException).name).toBe("TimeoutError")
|
||||
await input.settle()
|
||||
expect(input.pending.map((item) => new URL(item.url).pathname)).toEqual(["/api/dead", "/api/next"])
|
||||
input.pending[1]!.resolve()
|
||||
await expect(next).resolves.toBeInstanceOf(Response)
|
||||
expect(input.queue.inflight()).toBe(0)
|
||||
})
|
||||
|
||||
test("caller aborts still reach the underlying request", async () => {
|
||||
const input = setup({ limit: 1 })
|
||||
const controller = new AbortController()
|
||||
const request = input.queue.fetch("http://server/api/slow", { signal: controller.signal })
|
||||
await input.settle()
|
||||
expect(input.pending[0]!.signal.aborted).toBe(false)
|
||||
controller.abort()
|
||||
expect(input.pending[0]!.signal.aborted).toBe(true)
|
||||
await expect(request).rejects.toBeInstanceOf(DOMException)
|
||||
expect(input.queue.inflight()).toBe(0)
|
||||
})
|
||||
|
||||
test("a burst that drains promptly is not thrashing", async () => {
|
||||
const input = setup({ stallMs: 5 })
|
||||
const responses = Array.from({ length: 12 }, (_, index) => input.queue.fetch(`http://server/api/${index}`))
|
||||
|
||||
@@ -1,23 +1,41 @@
|
||||
type Entry = { method: string; url: string; at: number }
|
||||
type Entry = { method: string; url: string; at: number; slow: boolean }
|
||||
|
||||
// Chromium allows six connections per origin. The event stream holds one for the life of the
|
||||
// connection and health probes use their own fetch, so the app's API calls stay below that or
|
||||
// a burst stalls probes and user actions inside the browser where nothing can observe it.
|
||||
export const requestQueueLimit = 4
|
||||
|
||||
// Endpoints that shell out to git or walk the filesystem take seconds on a large repository. They
|
||||
// may hold at most this many slots, so a session mount's small reads never queue behind them.
|
||||
export const requestQueueSlowLimit = 2
|
||||
export const slowRequestPaths = ["/api/vcs", "/api/worktree"]
|
||||
|
||||
// A mount legitimately fires a dozen requests at once; only a request that has waited this long
|
||||
// for a slot indicates the server is not keeping up.
|
||||
export const requestStallMs = 2_000
|
||||
|
||||
// A socket that dies while the device sleeps can leave fetch waiting for response headers until the
|
||||
// OS gives up on TCP retransmits, which takes minutes. Bound that so a dead request frees its slot
|
||||
// instead of wedging every later API call; the body may still stream for as long as it needs.
|
||||
export const requestHeadersTimeoutMs = 60_000
|
||||
|
||||
export function isSlowRequest(pathname: string) {
|
||||
return slowRequestPaths.some((path) => pathname === path || pathname.startsWith(`${path}/`))
|
||||
}
|
||||
|
||||
export function createRequestQueue(input: {
|
||||
fetch: typeof globalThis.fetch
|
||||
limit?: number
|
||||
slowLimit?: number
|
||||
stallMs?: number
|
||||
headersTimeoutMs?: number
|
||||
log?: (message: string, data: Record<string, unknown>) => void
|
||||
now?: () => number
|
||||
}) {
|
||||
const limit = input.limit ?? requestQueueLimit
|
||||
const slowLimit = input.slowLimit ?? requestQueueSlowLimit
|
||||
const stallMs = input.stallMs ?? requestStallMs
|
||||
const headersTimeoutMs = input.headersTimeoutMs ?? requestHeadersTimeoutMs
|
||||
// Call the browser fetch unbound; `input.fetch(...)` would make `this` the options object.
|
||||
const base = input.fetch
|
||||
const now = input.now ?? Date.now
|
||||
@@ -43,9 +61,17 @@ export function createRequestQueue(input: {
|
||||
}
|
||||
watcher = setTimeout(watch, stallMs)
|
||||
}
|
||||
const canStart = (entry: Entry) => {
|
||||
if (inflight.size >= limit) return false
|
||||
if (!entry.slow) return true
|
||||
return [...inflight].filter((item) => item.slow).length < slowLimit
|
||||
}
|
||||
// FIFO, except a slow request waits its turn behind faster ones while the slow slots are full.
|
||||
const release = (entry: Entry) => {
|
||||
inflight.delete(entry)
|
||||
waiting.shift()?.start()
|
||||
const index = waiting.findIndex((item) => canStart(item.entry))
|
||||
if (index === -1) return
|
||||
waiting.splice(index, 1)[0]?.start()
|
||||
}
|
||||
const acquire = (entry: Entry) =>
|
||||
new Promise<void>((resolve) => {
|
||||
@@ -54,7 +80,7 @@ export function createRequestQueue(input: {
|
||||
inflight.add(entry)
|
||||
resolve()
|
||||
}
|
||||
if (inflight.size < limit) return start()
|
||||
if (canStart(entry)) return start()
|
||||
waiting.push({ entry, start })
|
||||
watcher ??= setTimeout(watch, stallMs)
|
||||
})
|
||||
@@ -62,15 +88,25 @@ export function createRequestQueue(input: {
|
||||
const fetch: typeof globalThis.fetch = Object.assign(
|
||||
async (resource: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(resource, init)
|
||||
const pathname = new URL(request.url).pathname
|
||||
// The event stream is long-lived; never count it against the request budget.
|
||||
if (new URL(request.url).pathname === "/api/event") return base(request)
|
||||
const entry = { method: request.method, url: request.url, at: now() }
|
||||
if (pathname === "/api/event") return base(request)
|
||||
const entry = { method: request.method, url: request.url, at: now(), slow: isSlowRequest(pathname) }
|
||||
await acquire(entry)
|
||||
if (request.signal.aborted) {
|
||||
release(entry)
|
||||
throw request.signal.reason ?? new DOMException("The operation was aborted.", "AbortError")
|
||||
}
|
||||
return base(request).finally(() => release(entry))
|
||||
const controller = new AbortController()
|
||||
request.signal.addEventListener("abort", () => controller.abort(request.signal.reason), { once: true })
|
||||
const timer = setTimeout(
|
||||
() => controller.abort(new DOMException("Timed out waiting for the server to respond", "TimeoutError")),
|
||||
headersTimeoutMs,
|
||||
)
|
||||
return base(new Request(request, { signal: controller.signal })).finally(() => {
|
||||
clearTimeout(timer)
|
||||
release(entry)
|
||||
})
|
||||
},
|
||||
// Bun's fetch type carries preconnect; the browser never calls it.
|
||||
{ preconnect: () => {} },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createRoot, createSignal } from "solid-js"
|
||||
import { createConnectionSync } from "./connection"
|
||||
import { createConnectionSync, reconnectOrder } from "./connection"
|
||||
|
||||
test("invalidates disconnected data and synchronizes after the handshake", () => {
|
||||
const calls: string[] = []
|
||||
@@ -19,3 +19,9 @@ test("invalidates disconnected data and synchronizes after the handshake", () =>
|
||||
})
|
||||
dispose()
|
||||
})
|
||||
|
||||
test("held directories refresh before the rest, otherwise keeping their order", () => {
|
||||
const held = new Set(["/b", "/d"])
|
||||
expect(reconnectOrder(["/a", "/b", "/c", "/d"], (directory) => held.has(directory))).toEqual(["/b", "/d", "/a", "/c"])
|
||||
expect(reconnectOrder(["/a", "/c"], (directory) => held.has(directory))).toEqual(["/a", "/c"])
|
||||
})
|
||||
|
||||
@@ -20,3 +20,8 @@ export function createConnectionSync(input: {
|
||||
|
||||
return { handleEvent }
|
||||
}
|
||||
|
||||
// Directories a mounted view holds refresh first; the rest keep their existing order behind them.
|
||||
export function reconnectOrder(directories: string[], held: (directory: string) => boolean) {
|
||||
return [...directories.filter(held), ...directories.filter((directory) => !held(directory))]
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import type { ServerScope } from "@/runtime/server/scope"
|
||||
import { persisted } from "@/runtime/persistence/storage"
|
||||
import type { ServerApi } from "@/runtime/server/api"
|
||||
import { toggleMcp } from "./global-sync/mcp"
|
||||
import { createConnectionSync } from "./server-sync/connection"
|
||||
import { createConnectionSync, reconnectOrder } from "./server-sync/connection"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import type { Data } from "@opencode-ai/client/solid"
|
||||
import { createWorktreeInventory, withWorktreeInventory } from "@/workspaces/inventory"
|
||||
@@ -162,12 +162,11 @@ export function createServerSyncContextInner(serverSDK: ServerSDK, data: Data) {
|
||||
},
|
||||
connected: (info) => {
|
||||
if (bootstrap.data !== undefined && !bootstrap.isFetching) void bootstrap.refetch()
|
||||
Object.keys(children.children)
|
||||
.filter(children.active)
|
||||
.forEach((directory) => {
|
||||
queue.push(directory)
|
||||
void data.location.sync({ directory }).catch(() => undefined)
|
||||
})
|
||||
// The refresh queue re-syncs two directories at a time, held ones first. Syncing every active
|
||||
// directory here as well sent the whole catalog fan-out for all of them at once.
|
||||
reconnectOrder(Object.keys(children.children).filter(children.active), children.pinned).forEach(
|
||||
(directory) => queue.push(directory),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -2,11 +2,12 @@ import { Show, type JSX } from "solid-js"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { SessionPermissionDock } from "@/session/requests/session-permission-dock"
|
||||
import { SessionQuestionDock } from "@/session/requests/session-question-dock"
|
||||
import { SessionWebSearchDock } from "@/session/requests/session-websearch-dock"
|
||||
import type { SessionComposerRegionController } from "./session-composer-region-controller"
|
||||
|
||||
type SessionComposerRegionState = Pick<
|
||||
SessionComposerRegionController["state"],
|
||||
"questionRequest" | "permissionRequest" | "permissionResponding" | "decide" | "blocked"
|
||||
"questionRequest" | "websearch" | "permissionRequest" | "permissionResponding" | "decide" | "blocked"
|
||||
>
|
||||
|
||||
export type SessionComposerRegionViewController = Pick<
|
||||
@@ -32,6 +33,9 @@ export function SessionComposerRegion(props: {
|
||||
"md:max-w-[1000px] md:mx-auto": controller.centered(),
|
||||
}}
|
||||
>
|
||||
<Show when={controller.state.websearch.request()}>
|
||||
<SessionWebSearchDock model={controller.state.websearch} onSubmit={controller.onResponseSubmit} />
|
||||
</Show>
|
||||
<Show when={controller.state.questionRequest()} keyed>
|
||||
{(request) => (
|
||||
<div>
|
||||
|
||||
@@ -24,6 +24,11 @@ import {
|
||||
type FileTreeV2Node,
|
||||
} from "@/session/files/file-tree-v2-model"
|
||||
import { virtualScrollElement } from "@/session/files/virtual-scroll"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { useOpenInApp } from "@/session/files/open-in-app"
|
||||
import { OpenInAppContextMenuV2 } from "@/session/files/open-in-app-button"
|
||||
import { resolveOpenInAppPath } from "@/session/files/open-in-app-path"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
|
||||
export type { Kind } from "@/session/files/file-tree"
|
||||
|
||||
@@ -99,7 +104,7 @@ const FileTreeNodeV2 = (
|
||||
{...rest}
|
||||
>
|
||||
{local.children}
|
||||
<span class="flex-1 min-w-0 text-start text-12-medium whitespace-nowrap truncate">
|
||||
<span data-slot="file-tree-v2-label" class="flex-1 shrink-0 text-start text-12-medium whitespace-nowrap">
|
||||
<bdi dir="auto">
|
||||
{local.node.type === "directory"
|
||||
? normalizeFileTreeV2Path(local.node.path).split("/").at(-1)
|
||||
@@ -136,6 +141,9 @@ export default function FileTreeV2(props: {
|
||||
onFileDoubleClick?: (file: FileNode) => void
|
||||
}) {
|
||||
const file = useFile()
|
||||
const location = useWorkspaceLocation()
|
||||
const platform = usePlatform()
|
||||
const openIn = platform.platform === "desktop" ? useOpenInApp({ path: () => location().directory }) : undefined
|
||||
const live = () => props.allowed === undefined
|
||||
const draggable = () => props.draggable ?? true
|
||||
const active = () => normalizeFileTreeV2Path(props.active ?? "")
|
||||
@@ -217,6 +225,19 @@ export default function FileTreeV2(props: {
|
||||
)
|
||||
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => item.key))
|
||||
|
||||
createEffect(() => {
|
||||
rows()
|
||||
const element = root()
|
||||
if (!element) return
|
||||
element.style.removeProperty("width")
|
||||
syncFileTreeV2Width(element)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
virtualRowKeys()
|
||||
syncFileTreeV2Width(root())
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setRoot}
|
||||
@@ -235,6 +256,7 @@ export default function FileTreeV2(props: {
|
||||
top: "0",
|
||||
"inset-inline-start": "0",
|
||||
width: "100%",
|
||||
"min-width": "max-content",
|
||||
height: `${item().size}px`,
|
||||
transform: `translateY(${item().start}px)`,
|
||||
}}
|
||||
@@ -244,29 +266,36 @@ export default function FileTreeV2(props: {
|
||||
<Show
|
||||
when={row().node.type === "directory"}
|
||||
fallback={
|
||||
<FileTreeNodeV2
|
||||
node={row().node}
|
||||
level={row().level}
|
||||
active={active()}
|
||||
draggable={draggable()}
|
||||
kinds={props.kinds}
|
||||
as="button"
|
||||
type="button"
|
||||
class="relative"
|
||||
onFocus={() => setFocused(row().node.path)}
|
||||
onBlur={() => setFocused(undefined)}
|
||||
onClick={() => selectFile(row().node, props.onFileClick)}
|
||||
onDblClick={() => selectFile(row().node, props.onFileDoubleClick)}
|
||||
<OpenInAppContextMenuV2
|
||||
state={openIn}
|
||||
path={() =>
|
||||
resolveOpenInAppPath(location().directory, row().node.absolute || row().node.originalPath)
|
||||
}
|
||||
>
|
||||
<GuideLines level={row().level} />
|
||||
<Show when={row().level > 0}>
|
||||
<div class="w-4 shrink-0" />
|
||||
</Show>
|
||||
<span class="filetree-iconpair size-4">
|
||||
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--color" />
|
||||
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--mono" mono />
|
||||
</span>
|
||||
</FileTreeNodeV2>
|
||||
<FileTreeNodeV2
|
||||
node={row().node}
|
||||
level={row().level}
|
||||
active={active()}
|
||||
draggable={draggable()}
|
||||
kinds={props.kinds}
|
||||
as="button"
|
||||
type="button"
|
||||
class="relative"
|
||||
onFocus={() => setFocused(row().node.path)}
|
||||
onBlur={() => setFocused(undefined)}
|
||||
onClick={() => selectFile(row().node, props.onFileClick)}
|
||||
onDblClick={() => selectFile(row().node, props.onFileDoubleClick)}
|
||||
>
|
||||
<GuideLines level={row().level} />
|
||||
<Show when={row().level > 0}>
|
||||
<div class="w-4 shrink-0" />
|
||||
</Show>
|
||||
<span class="filetree-iconpair size-4">
|
||||
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--color" />
|
||||
<FileIcon node={row().node} class="size-4 filetree-icon filetree-icon--mono" mono />
|
||||
</span>
|
||||
</FileTreeNodeV2>
|
||||
</OpenInAppContextMenuV2>
|
||||
}
|
||||
>
|
||||
<FileTreeNodeV2
|
||||
@@ -303,3 +332,13 @@ export default function FileTreeV2(props: {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function syncFileTreeV2Width(element?: HTMLDivElement) {
|
||||
if (!element) return
|
||||
queueMicrotask(() => {
|
||||
if (!element.isConnected) return
|
||||
const width = Math.max(element.clientWidth, ...Array.from(element.children, (child) => child.scrollWidth))
|
||||
if (width <= element.clientWidth) return
|
||||
element.style.width = `${width}px`
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,10 +2,15 @@ import { FileIcon } from "@opencode-ai/ui/file-icon"
|
||||
import "@opencode-ai/ui/file-tree.css"
|
||||
import { getDirectory, getFilename } from "@opencode-ai/util/path"
|
||||
import { createEffect, createMemo, createSignal, For, Show } from "solid-js"
|
||||
import { kindChange, kindLabel, type Kind } from "@/session/files/file-tree-v2"
|
||||
import { kindChange, kindLabel, syncFileTreeV2Width, type Kind } from "@/session/files/file-tree-v2"
|
||||
import { normalizePath } from "@/session/review/review-diff-kinds"
|
||||
import { createVirtualizer, defaultRangeExtractor } from "@tanstack/solid-virtual"
|
||||
import { virtualScrollElement } from "@/session/files/virtual-scroll"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { useOpenInApp } from "@/session/files/open-in-app"
|
||||
import { OpenInAppContextMenuV2 } from "@/session/files/open-in-app-button"
|
||||
import { resolveOpenInAppPath } from "@/session/files/open-in-app-path"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
|
||||
// Drives the highlight/selection of the flat search-result list from the filter
|
||||
// input's keyboard events.
|
||||
@@ -49,6 +54,9 @@ export function SessionFileList(props: {
|
||||
onFileClick: (path: string) => void
|
||||
onFileDoubleClick?: (path: string) => void
|
||||
}) {
|
||||
const location = useWorkspaceLocation()
|
||||
const platform = usePlatform()
|
||||
const openIn = platform.platform === "desktop" ? useOpenInApp({ path: () => location().directory }) : undefined
|
||||
const active = () => normalizePath(props.active ?? "")
|
||||
const highlighted = () => normalizePath(props.highlighted ?? "")
|
||||
const normalized = createMemo(() => props.files.map(normalizePath))
|
||||
@@ -89,6 +97,19 @@ export function SessionFileList(props: {
|
||||
)
|
||||
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => item.key))
|
||||
|
||||
createEffect(() => {
|
||||
normalized()
|
||||
const element = root()
|
||||
if (!element) return
|
||||
element.style.removeProperty("width")
|
||||
syncFileTreeV2Width(element)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
virtualRowKeys()
|
||||
syncFileTreeV2Width(root())
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setRoot}
|
||||
@@ -114,47 +135,48 @@ export function SessionFileList(props: {
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: "0",
|
||||
left: "0",
|
||||
"inset-inline-start": "0",
|
||||
width: "100%",
|
||||
"min-width": "max-content",
|
||||
height: `${item().size}px`,
|
||||
transform: `translateY(${item().start}px)`,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
id={props.optionID?.(path)}
|
||||
role={props.role ? "option" : undefined}
|
||||
aria-selected={props.role ? selected() : undefined}
|
||||
data-slot="file-tree-v2-row"
|
||||
data-path={path}
|
||||
data-selected={selected() ? "" : undefined}
|
||||
data-highlighted={highlightedRow() ? "" : undefined}
|
||||
style="padding-left: 8px"
|
||||
onFocus={() => setFocused(path)}
|
||||
onBlur={() => setFocused(undefined)}
|
||||
onClick={() => props.onFileClick(path)}
|
||||
onDblClick={() => props.onFileDoubleClick?.(path)}
|
||||
>
|
||||
<span class="filetree-iconpair size-4">
|
||||
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--color" />
|
||||
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--mono" mono />
|
||||
</span>
|
||||
<span class="flex min-w-0 flex-1 items-center overflow-hidden whitespace-nowrap">
|
||||
<Show when={directory()}>
|
||||
<OpenInAppContextMenuV2 state={openIn} path={() => resolveOpenInAppPath(location().directory, path)}>
|
||||
<button
|
||||
type="button"
|
||||
id={props.optionID?.(path)}
|
||||
role={props.role ? "option" : undefined}
|
||||
aria-selected={props.role ? selected() : undefined}
|
||||
data-slot="file-tree-v2-row"
|
||||
data-path={path}
|
||||
data-selected={selected() ? "" : undefined}
|
||||
data-highlighted={highlightedRow() ? "" : undefined}
|
||||
style="padding-inline-start: 8px"
|
||||
onFocus={() => setFocused(path)}
|
||||
onBlur={() => setFocused(undefined)}
|
||||
onClick={() => props.onFileClick(path)}
|
||||
onDblClick={() => props.onFileDoubleClick?.(path)}
|
||||
>
|
||||
<span class="filetree-iconpair size-4">
|
||||
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--color" />
|
||||
<FileIcon node={{ path, type: "file" }} class="size-4 filetree-icon filetree-icon--mono" mono />
|
||||
</span>
|
||||
<span data-slot="file-tree-v2-label" class="flex flex-1 shrink-0 items-center whitespace-nowrap">
|
||||
<Show when={directory()}>
|
||||
{(value) => <span class="text-12-medium text-text-muted shrink-0">{value()}</span>}
|
||||
</Show>
|
||||
<span class="text-12-medium text-text-base shrink-0">{filename()}</span>
|
||||
</span>
|
||||
<Show when={kind()}>
|
||||
{(value) => (
|
||||
<span class="text-12-medium text-text-muted truncate min-w-0 shrink">{value()}</span>
|
||||
<span data-slot="file-tree-v2-change" data-change={kindChange(value())}>
|
||||
{kindLabel(value())}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
<span class="text-12-medium text-text-base truncate min-w-0 shrink-0">{filename()}</span>
|
||||
</span>
|
||||
<Show when={kind()}>
|
||||
{(value) => (
|
||||
<span data-slot="file-tree-v2-change" data-change={kindChange(value())}>
|
||||
{kindLabel(value())}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</button>
|
||||
</button>
|
||||
</OpenInAppContextMenuV2>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { For, Show } from "solid-js"
|
||||
import { createSignal, For, Show, type ParentProps } from "solid-js"
|
||||
import { AppIcon } from "@opencode-ai/ui/app-icon"
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import { Spinner } from "@opencode-ai/ui/spinner"
|
||||
@@ -10,7 +10,7 @@ import { type OpenApp, useOpenInApp } from "@/session/files/open-in-app"
|
||||
|
||||
export function OpenInAppButton(props: { directory: () => string }) {
|
||||
const language = useLanguage()
|
||||
const state = useOpenInApp(props)
|
||||
const state = useOpenInApp({ path: props.directory })
|
||||
|
||||
return (
|
||||
<Show when={props.directory() && state.canOpen()}>
|
||||
@@ -25,7 +25,7 @@ export function OpenInAppButton(props: { directory: () => string }) {
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
if (state.opening()) return
|
||||
state.openDir(state.current().id)
|
||||
state.openPath(state.current().id)
|
||||
}}
|
||||
disabled={state.opening()}
|
||||
aria-label={language.t("session.header.open.ariaLabel", { app: state.current().label })}
|
||||
@@ -52,42 +52,7 @@ export function OpenInAppButton(props: { directory: () => string }) {
|
||||
</Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Content class="open-in-app-v2-menu">
|
||||
<Menu.Group>
|
||||
<Menu.GroupLabel>{language.t("session.header.openIn")}</Menu.GroupLabel>
|
||||
<Menu.RadioGroup
|
||||
value={state.current().id}
|
||||
onChange={(value) => {
|
||||
state.selectApp(value as OpenApp)
|
||||
}}
|
||||
>
|
||||
<For each={state.options()}>
|
||||
{(option) => (
|
||||
<Menu.RadioItem
|
||||
value={option.id}
|
||||
disabled={state.opening()}
|
||||
onSelect={() => {
|
||||
state.selectApp(option.id)
|
||||
state.setMenu("open", false)
|
||||
state.openDir(option.id)
|
||||
}}
|
||||
>
|
||||
<AppIcon id={option.icon} />
|
||||
{option.label}
|
||||
</Menu.RadioItem>
|
||||
)}
|
||||
</For>
|
||||
</Menu.RadioGroup>
|
||||
</Menu.Group>
|
||||
<Menu.Separator />
|
||||
<Menu.Item
|
||||
onSelect={() => {
|
||||
state.setMenu("open", false)
|
||||
state.copyPath()
|
||||
}}
|
||||
>
|
||||
<Icon name="copy" size="small" class="text-icon-weak" />
|
||||
{language.t("session.header.open.copyPath")}
|
||||
</Menu.Item>
|
||||
<OpenInAppMenuItemsV2 state={state} close={() => state.setMenu("open", false)} />
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu>
|
||||
@@ -95,3 +60,116 @@ export function OpenInAppButton(props: { directory: () => string }) {
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
type OpenInAppState = ReturnType<typeof useOpenInApp>
|
||||
|
||||
function OpenInAppMenuItemsV2(props: {
|
||||
state: OpenInAppState
|
||||
path?: () => string
|
||||
reveal?: boolean
|
||||
selection?: boolean
|
||||
close?: () => void
|
||||
}) {
|
||||
const language = useLanguage()
|
||||
const path = () => props.path?.()
|
||||
|
||||
return (
|
||||
<>
|
||||
<Menu.Group>
|
||||
<Menu.GroupLabel>{language.t("session.header.openIn")}</Menu.GroupLabel>
|
||||
<Show
|
||||
when={props.selection !== false}
|
||||
fallback={
|
||||
<For each={props.state.options()}>
|
||||
{(option) => (
|
||||
<Menu.Item
|
||||
disabled={props.state.opening()}
|
||||
onSelect={() => {
|
||||
props.state.selectApp(option.id)
|
||||
props.close?.()
|
||||
props.state.openPath(option.id, path(), props.reveal)
|
||||
}}
|
||||
>
|
||||
<AppIcon id={option.icon} />
|
||||
{option.label}
|
||||
</Menu.Item>
|
||||
)}
|
||||
</For>
|
||||
}
|
||||
>
|
||||
<Menu.RadioGroup
|
||||
value={props.state.current().id}
|
||||
onChange={(value) => {
|
||||
props.state.selectApp(value as OpenApp)
|
||||
}}
|
||||
>
|
||||
<For each={props.state.options()}>
|
||||
{(option) => (
|
||||
<Menu.RadioItem
|
||||
value={option.id}
|
||||
closeOnSelect
|
||||
disabled={props.state.opening()}
|
||||
onSelect={() => {
|
||||
props.state.selectApp(option.id)
|
||||
props.close?.()
|
||||
props.state.openPath(option.id, path(), props.reveal)
|
||||
}}
|
||||
>
|
||||
<AppIcon id={option.icon} />
|
||||
{option.label}
|
||||
</Menu.RadioItem>
|
||||
)}
|
||||
</For>
|
||||
</Menu.RadioGroup>
|
||||
</Show>
|
||||
</Menu.Group>
|
||||
<Menu.Separator />
|
||||
<Menu.Item
|
||||
onSelect={() => {
|
||||
props.close?.()
|
||||
props.state.copyPath(path())
|
||||
}}
|
||||
>
|
||||
<Icon name="copy" size="small" class="text-icon-weak" />
|
||||
{language.t("session.header.open.copyPath")}
|
||||
</Menu.Item>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function OpenInAppContextMenuV2(
|
||||
props: ParentProps<{
|
||||
state?: OpenInAppState
|
||||
path: () => string
|
||||
}>,
|
||||
) {
|
||||
const state = props.state
|
||||
if (!state) return props.children
|
||||
const [open, setOpen] = createSignal(false)
|
||||
|
||||
return (
|
||||
<Show when={state.canOpen() && props.path()} fallback={props.children}>
|
||||
<Menu.Context modal={false} onOpenChange={setOpen}>
|
||||
<Menu.Context.Trigger
|
||||
as="div"
|
||||
class="h-full w-full min-w-max"
|
||||
data-slot="file-tree-v2-context-trigger"
|
||||
data-context-menu-open={open() ? "" : undefined}
|
||||
>
|
||||
{props.children}
|
||||
</Menu.Context.Trigger>
|
||||
<Menu.Context.Portal>
|
||||
<Menu.Context.Content class="open-in-app-v2-menu">
|
||||
<OpenInAppMenuItemsV2
|
||||
state={state}
|
||||
path={props.path}
|
||||
reveal
|
||||
selection={false}
|
||||
close={() => setOpen(false)}
|
||||
/>
|
||||
</Menu.Context.Content>
|
||||
</Menu.Context.Portal>
|
||||
</Menu.Context>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { openInAppParentPath, resolveOpenInAppPath } from "./open-in-app-path"
|
||||
|
||||
describe("resolveOpenInAppPath", () => {
|
||||
test("joins relative paths using the workspace separator", () => {
|
||||
expect(resolveOpenInAppPath("/workspace/project", "src/file.ts")).toBe("/workspace/project/src/file.ts")
|
||||
expect(resolveOpenInAppPath("C:\\workspace\\project", "src/file.ts")).toBe("C:\\workspace\\project\\src\\file.ts")
|
||||
})
|
||||
|
||||
test("does not duplicate root separators", () => {
|
||||
expect(resolveOpenInAppPath("/workspace/project/", "src/file.ts")).toBe("/workspace/project/src/file.ts")
|
||||
expect(resolveOpenInAppPath("C:/workspace/project/", "src\\file.ts")).toBe("C:/workspace/project/src/file.ts")
|
||||
})
|
||||
|
||||
test("preserves backslashes in POSIX filenames", () => {
|
||||
expect(resolveOpenInAppPath("/workspace", "src\\file.ts")).toBe("/workspace/src\\file.ts")
|
||||
expect(resolveOpenInAppPath("/workspace", "\\file.ts")).toBe("/workspace/\\file.ts")
|
||||
})
|
||||
|
||||
test("preserves absolute POSIX, Windows, and UNC paths", () => {
|
||||
expect(resolveOpenInAppPath("/workspace", "/tmp/file.ts")).toBe("/tmp/file.ts")
|
||||
expect(resolveOpenInAppPath("C:/workspace", "D:\\src\\file.ts")).toBe("D:\\src\\file.ts")
|
||||
expect(resolveOpenInAppPath("C:/workspace", "\\\\server\\share\\file.ts")).toBe("\\\\server\\share\\file.ts")
|
||||
expect(resolveOpenInAppPath("C:/workspace", "\\src\\file.ts")).toBe("\\src\\file.ts")
|
||||
})
|
||||
})
|
||||
|
||||
describe("openInAppParentPath", () => {
|
||||
test("preserves POSIX and Windows roots", () => {
|
||||
expect(openInAppParentPath("/file.ts")).toBe("/")
|
||||
expect(openInAppParentPath("/workspace/file.ts")).toBe("/workspace")
|
||||
expect(openInAppParentPath("C:\\file.ts")).toBe("C:\\")
|
||||
expect(openInAppParentPath("C:\\workspace\\file.ts")).toBe("C:\\workspace")
|
||||
expect(openInAppParentPath("\\\\server\\share\\file.ts")).toBe("\\\\server\\share")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
export function resolveOpenInAppPath(root: string, path: string) {
|
||||
if (!path) return root
|
||||
const windowsRoot = root.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(root)
|
||||
if (path.startsWith("/") || (windowsRoot && path.startsWith("\\")) || /^[A-Za-z]:[\\/]/.test(path)) return path
|
||||
if (!root) return path
|
||||
|
||||
const separator = root.includes("\\") ? "\\" : "/"
|
||||
const relative = windowsRoot ? path.replace(/^[\\/]+/, "") : path
|
||||
return `${root.replace(/[\\/]+$/, "")}${separator}${windowsRoot ? relative.replaceAll(separator === "\\" ? "/" : "\\", separator) : relative}`
|
||||
}
|
||||
|
||||
export function openInAppParentPath(path: string) {
|
||||
const value = path.replace(/[\\/]+$/, "")
|
||||
const index = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"))
|
||||
if (index < 0) return path
|
||||
if (index === 0) return value.slice(0, 1)
|
||||
if (index === 2 && /^[A-Za-z]:/.test(value)) return value.slice(0, 3)
|
||||
return value.slice(0, index)
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import { showToast } from "@/shell/notifications/toast"
|
||||
import { useServer } from "@/runtime/server/current"
|
||||
import { Schema } from "effect"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
import { fileManagerApp } from "@/home/projects/file-manager"
|
||||
import { openInAppParentPath } from "@/session/files/open-in-app-path"
|
||||
|
||||
export const OPEN_APPS = [
|
||||
"vscode",
|
||||
@@ -32,6 +34,8 @@ export const OpenAppPreferences = Persistence.struct({
|
||||
app: Schema.Literals(OPEN_APPS),
|
||||
})
|
||||
|
||||
const appExistence = new Map<string, Promise<boolean>>()
|
||||
|
||||
export const MAC_OPEN_APPS = [
|
||||
{
|
||||
id: "vscode",
|
||||
@@ -108,9 +112,7 @@ export function detectOpenAppOS(platform: ReturnType<typeof usePlatform>): OpenA
|
||||
}
|
||||
|
||||
export function openAppFileManager(os: OpenAppOS) {
|
||||
if (os === "macos") return { label: "session.header.open.finder", icon: "finder" as const }
|
||||
if (os === "windows") return { label: "session.header.open.fileExplorer", icon: "file-explorer" as const }
|
||||
return { label: "session.header.open.fileManager", icon: "finder" as const }
|
||||
return fileManagerApp(os)
|
||||
}
|
||||
|
||||
export function openAppsForOS(os: OpenAppOS) {
|
||||
@@ -127,7 +129,7 @@ const showRequestError = (language: ReturnType<typeof useLanguage>, err: unknown
|
||||
})
|
||||
}
|
||||
|
||||
export function useOpenInApp(input: { directory: () => string }) {
|
||||
export function useOpenInApp(input: { path: () => string }) {
|
||||
const platform = usePlatform()
|
||||
const server = useServer()
|
||||
const language = useLanguage()
|
||||
@@ -149,12 +151,7 @@ export function useOpenInApp(input: { directory: () => string }) {
|
||||
setExists(Object.fromEntries(list.map((app) => [app.id, undefined])) as Partial<Record<OpenApp, boolean>>)
|
||||
|
||||
void Promise.all(
|
||||
list.map((app) =>
|
||||
Promise.resolve(platform.checkAppExists?.(app.openWith))
|
||||
.then((value) => Boolean(value))
|
||||
.catch(() => false)
|
||||
.then((ok) => [app.id, ok] as const),
|
||||
),
|
||||
list.map((app) => checkAppExists(platform, app.openWith).then((ok) => [app.id, ok] as const)),
|
||||
).then((entries) => {
|
||||
setExists(Object.fromEntries(entries) as Partial<Record<OpenApp, boolean>>)
|
||||
})
|
||||
@@ -189,33 +186,35 @@ export function useOpenInApp(input: { directory: () => string }) {
|
||||
setPrefs("app", app)
|
||||
}
|
||||
|
||||
const openDir = (app: OpenApp | "finder") => {
|
||||
const openPath = (app: OpenApp | "finder", target = input.path(), reveal = false) => {
|
||||
if (opening() || !canOpen() || !platform.openPath) return
|
||||
const directory = input.directory()
|
||||
if (!directory) return
|
||||
if (!target) return
|
||||
|
||||
const open = (path: string, openWith?: string) => platform.openPath!(path, openWith)
|
||||
const item = options().find((o) => o.id === app)
|
||||
const openWith = item && "openWith" in item ? item.openWith : undefined
|
||||
setOpenRequest("app", app)
|
||||
platform
|
||||
.openPath(directory, openWith)
|
||||
const request =
|
||||
app === "finder" && reveal && platform.revealPath
|
||||
? platform.revealPath(target).then((revealed) => (revealed ? undefined : open(openInAppParentPath(target))))
|
||||
: open(target, openWith)
|
||||
request
|
||||
.catch((err: unknown) => showRequestError(language, err))
|
||||
.finally(() => {
|
||||
setOpenRequest("app", undefined)
|
||||
})
|
||||
}
|
||||
|
||||
const copyPath = () => {
|
||||
const directory = input.directory()
|
||||
if (!directory) return
|
||||
const copyPath = (target = input.path()) => {
|
||||
if (!target) return
|
||||
navigator.clipboard
|
||||
.writeText(directory)
|
||||
.writeText(target)
|
||||
.then(() => {
|
||||
showToast({
|
||||
variant: "success",
|
||||
icon: "circle-check",
|
||||
title: language.t("common.copied"),
|
||||
description: directory,
|
||||
description: target,
|
||||
})
|
||||
})
|
||||
.catch((err: unknown) => showRequestError(language, err))
|
||||
@@ -228,8 +227,18 @@ export function useOpenInApp(input: { directory: () => string }) {
|
||||
options,
|
||||
menu,
|
||||
setMenu,
|
||||
openDir,
|
||||
openPath,
|
||||
selectApp,
|
||||
copyPath,
|
||||
}
|
||||
}
|
||||
|
||||
function checkAppExists(platform: ReturnType<typeof usePlatform>, app: string) {
|
||||
const cached = appExistence.get(app)
|
||||
if (cached) return cached
|
||||
const request = Promise.resolve(platform.checkAppExists?.(app))
|
||||
.then(Boolean)
|
||||
.catch(() => false)
|
||||
appExistence.set(app, request)
|
||||
return request
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ import { useServerSDK } from "@/runtime/server/client"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useSettings } from "@/settings/model"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
|
||||
import { sessionPermissionRequest, sessionFormRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import { createWebSearchRequest } from "./websearch"
|
||||
import { createSessionBackground } from "@/session/requests/background"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
|
||||
@@ -24,12 +25,40 @@ export function createSessionRequestModel() {
|
||||
void Promise.all([
|
||||
data.shell.sync({ directory: sdk().directory }),
|
||||
data.session.permission.sync(id),
|
||||
data.session.form.sync(id),
|
||||
]).catch(() => undefined)
|
||||
})
|
||||
createEffect(() => {
|
||||
const id = params.id
|
||||
if (!id || serverSDK.connection.status() !== "connected") return
|
||||
void Promise.all(
|
||||
sessionTreeIDs(data.session.list(), id).map((sessionID) => data.session.form.sync(sessionID)),
|
||||
).catch(() => undefined)
|
||||
})
|
||||
|
||||
const questionRequest = createMemo((): FormInfo | undefined => {
|
||||
return sessionQuestionForm(data.session.list(), data.session.form.list, params.id)
|
||||
const formRequest = createMemo((): FormInfo | undefined => {
|
||||
return sessionFormRequest(data.session.list(), data.session.form.list, params.id)
|
||||
})
|
||||
const websearch = createWebSearchRequest({
|
||||
owner: () => params.id,
|
||||
connected: () => serverSDK.connection.status() === "connected",
|
||||
request: () => {
|
||||
const form = formRequest()
|
||||
return form?.metadata?.kind === "websearch.provider" ? form : undefined
|
||||
},
|
||||
providers: async (sessionID) => {
|
||||
const session = data.session.get(sessionID) ?? (await serverSDK.api.session.get({ sessionID }))
|
||||
const result = await serverSDK.api.websearch.providers({
|
||||
location: { directory: session.location.directory, workspace: session.location.workspaceID },
|
||||
})
|
||||
return result.data.map((provider) => ({ value: provider.id, label: provider.name }))
|
||||
},
|
||||
reply: (input) => data.session.form.reply(input),
|
||||
events: serverSDK.event,
|
||||
})
|
||||
const questionRequest = createMemo(() => {
|
||||
if (websearch.request()) return
|
||||
const form = formRequest()
|
||||
return form?.metadata?.kind === "question" ? form : undefined
|
||||
})
|
||||
|
||||
const permissionRequest = createMemo((): PermissionRequest | undefined => {
|
||||
@@ -40,7 +69,7 @@ export function createSessionRequestModel() {
|
||||
const blocked = createMemo(() => {
|
||||
const id = params.id
|
||||
if (!id) return false
|
||||
return !!permissionRequest() || !!questionRequest()
|
||||
return !!permissionRequest() || !!questionRequest() || !!websearch.request()
|
||||
})
|
||||
|
||||
const primary = () => {
|
||||
@@ -96,6 +125,7 @@ export function createSessionRequestModel() {
|
||||
return {
|
||||
blocked,
|
||||
questionRequest,
|
||||
websearch,
|
||||
permissionRequest,
|
||||
permissionResponding,
|
||||
background: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { FormInfo, PermissionRequest, SessionInfo } from "@opencode-ai/client/promise"
|
||||
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
|
||||
import { sessionPermissionRequest, sessionFormRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
|
||||
const session = (input: { id: string; parentID?: string }) =>
|
||||
({
|
||||
@@ -23,6 +23,22 @@ const question = (id: string, sessionID: string) =>
|
||||
fields: [{ key: "q0", type: "string" }],
|
||||
}) as FormInfo
|
||||
|
||||
describe("sessionTreeIDs", () => {
|
||||
test("returns only the current session and its descendants", () => {
|
||||
const sessions = [
|
||||
session({ id: "root" }),
|
||||
session({ id: "child", parentID: "root" }),
|
||||
session({ id: "grand", parentID: "child" }),
|
||||
session({ id: "sibling", parentID: "root" }),
|
||||
session({ id: "other" }),
|
||||
]
|
||||
|
||||
expect(sessionTreeIDs(sessions, "child")).toEqual(["child", "grand"])
|
||||
expect(sessionTreeIDs(sessions, "root")).toEqual(["root", "child", "sibling", "grand"])
|
||||
expect(sessionTreeIDs(sessions)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe("sessionPermissionRequest", () => {
|
||||
test("prefers the current session permission", () => {
|
||||
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
|
||||
@@ -81,7 +97,7 @@ describe("sessionPermissionRequest", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("sessionQuestionForm", () => {
|
||||
describe("sessionFormRequest", () => {
|
||||
test("prefers the current session question", () => {
|
||||
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
|
||||
const questions = {
|
||||
@@ -89,7 +105,7 @@ describe("sessionQuestionForm", () => {
|
||||
child: [question("q-child", "child")],
|
||||
}
|
||||
|
||||
expect(sessionQuestionForm(sessions, questions, "root")?.id).toBe("q-root")
|
||||
expect(sessionFormRequest(sessions, questions, "root")?.id).toBe("q-root")
|
||||
})
|
||||
|
||||
test("returns a nested child question", () => {
|
||||
@@ -102,15 +118,29 @@ describe("sessionQuestionForm", () => {
|
||||
grand: [question("q-grand", "grand")],
|
||||
}
|
||||
|
||||
expect(sessionQuestionForm(sessions, questions, "root")?.id).toBe("q-grand")
|
||||
expect(sessionFormRequest(sessions, questions, "root")?.id).toBe("q-grand")
|
||||
})
|
||||
|
||||
test("skips forms that are not questions", () => {
|
||||
test("skips unsupported forms", () => {
|
||||
const sessions = [session({ id: "root" })]
|
||||
const forms = {
|
||||
root: [{ ...question("form", "root"), metadata: { kind: "integration" } }],
|
||||
}
|
||||
|
||||
expect(sessionQuestionForm(sessions, forms, "root")).toBeUndefined()
|
||||
expect(sessionFormRequest(sessions, forms, "root")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("finds web search consent in a nested child session", () => {
|
||||
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
|
||||
const form = { ...question("search", "child"), metadata: { kind: "websearch.provider" } }
|
||||
expect(sessionFormRequest(sessions, { child: [form] }, "root")).toBe(form)
|
||||
})
|
||||
|
||||
test("preserves request order across questions and web search", () => {
|
||||
const sessions = [session({ id: "root" }), session({ id: "child", parentID: "root" })]
|
||||
const form = { ...question("search", "root"), metadata: { kind: "websearch.provider" } }
|
||||
expect(sessionFormRequest(sessions, { root: [form, question("q", "root")] }, "root")).toBe(form)
|
||||
expect(sessionFormRequest(sessions, { root: [question("q", "root"), form] }, "root")?.id).toBe("q")
|
||||
expect(sessionFormRequest(sessions, { root: [form], child: [question("q", "child")] }, "root")).toBe(form)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,8 +6,16 @@ function sessionTreeRequest<T>(
|
||||
sessionID?: string,
|
||||
include: (item: T) => boolean = () => true,
|
||||
) {
|
||||
if (!sessionID) return
|
||||
const ids = sessionTreeIDs(session, sessionID)
|
||||
if (!ids.length) return
|
||||
const list = (id: string) => (typeof request === "function" ? request(id) : request[id])
|
||||
const id = ids.find((id) => list(id)?.some(include))
|
||||
if (!id) return
|
||||
return list(id)?.find(include)
|
||||
}
|
||||
|
||||
export function sessionTreeIDs(session: SessionInfo[], sessionID?: string) {
|
||||
if (!sessionID) return []
|
||||
const map = session.reduce((acc, item) => {
|
||||
if (!item.parentID) return acc
|
||||
const list = acc.get(item.parentID)
|
||||
@@ -27,11 +35,7 @@ function sessionTreeRequest<T>(
|
||||
ids.push(child)
|
||||
}
|
||||
}
|
||||
|
||||
const list = (id: string) => (typeof request === "function" ? request(id) : request[id])
|
||||
const id = ids.find((id) => list(id)?.some(include))
|
||||
if (!id) return
|
||||
return list(id)?.find(include)
|
||||
return ids
|
||||
}
|
||||
|
||||
export function sessionPermissionRequest(
|
||||
@@ -43,10 +47,15 @@ export function sessionPermissionRequest(
|
||||
return sessionTreeRequest(session, request, sessionID, include)
|
||||
}
|
||||
|
||||
export function sessionQuestionForm(
|
||||
export function sessionFormRequest(
|
||||
session: SessionInfo[],
|
||||
request: Record<string, FormInfo[] | undefined> | ((sessionID: string) => FormInfo[] | undefined),
|
||||
sessionID?: string,
|
||||
) {
|
||||
return sessionTreeRequest(session, request, sessionID, (item) => item.metadata?.kind === "question")
|
||||
return sessionTreeRequest(
|
||||
session,
|
||||
request,
|
||||
sessionID,
|
||||
(item) => item.metadata?.kind === "question" || item.metadata?.kind === "websearch.provider",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
[data-component="session-websearch-dock"] {
|
||||
width: 100%;
|
||||
border: 0.5px solid var(--v2-border-border-base);
|
||||
border-radius: 12px;
|
||||
|
||||
.websearch-body {
|
||||
box-shadow: var(--v2-elevation-raised);
|
||||
}
|
||||
|
||||
.websearch-setting {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.websearch-setting [data-component="settings-row"] {
|
||||
column-gap: 24px;
|
||||
padding-block: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.websearch-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 16px;
|
||||
padding: 24px 16px 12px;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.websearch-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-inline-end: auto;
|
||||
color: var(--v2-text-text-base);
|
||||
font-size: 13px;
|
||||
line-height: var(--line-height-compact);
|
||||
}
|
||||
|
||||
.websearch-status:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.websearch-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="menu-v2-content"][data-slot="select-v2-content"].websearch-provider-menu {
|
||||
width: max-content;
|
||||
min-width: 0;
|
||||
|
||||
[data-component="menu-v2-item"] {
|
||||
gap: 24px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { createMemo, Show } from "solid-js"
|
||||
import { Button } from "@opencode-ai/ui/button"
|
||||
import { DockShell, DockTray } from "@opencode-ai/ui/dock-surface"
|
||||
import { Select } from "@opencode-ai/ui/select"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { SettingsRow } from "@/settings/row"
|
||||
import type { WebSearchRequestModel } from "./websearch"
|
||||
import "./session-websearch-dock.css"
|
||||
|
||||
export function SessionWebSearchDock(props: { model: WebSearchRequestModel; onSubmit: () => void }) {
|
||||
const language = useLanguage()
|
||||
const options = createMemo(() => [
|
||||
...(props.model.specific() ? [] : [{ value: "random", label: language.t("session.websearch.any") }]),
|
||||
...props.model.options(),
|
||||
])
|
||||
const current = createMemo(() => options().find((option) => option.value === props.model.selected()))
|
||||
const busy = () => props.model.sending() || !props.model.connected()
|
||||
const status = () => {
|
||||
if (props.model.loading()) return language.t("common.loading")
|
||||
if (props.model.failed()) return language.t("session.websearch.failed")
|
||||
if (!props.model.options().length) return language.t("session.websearch.empty")
|
||||
}
|
||||
const unavailable = () => props.model.loading() || props.model.loadFailed() || !props.model.options().length
|
||||
const submit = (selection: string | false) => {
|
||||
if (busy()) return
|
||||
props.onSubmit()
|
||||
void props.model.submit(selection)
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
data-component="session-websearch-dock"
|
||||
aria-label={language.t("session.websearch.title")}
|
||||
aria-busy={props.model.sending()}
|
||||
>
|
||||
<DockShell class="websearch-body">
|
||||
<div class="websearch-setting">
|
||||
<SettingsRow
|
||||
title={language.t("session.websearch.title")}
|
||||
description={language.t("session.websearch.description")}
|
||||
>
|
||||
<Select
|
||||
aria-label={language.t("session.websearch.provider")}
|
||||
options={options()}
|
||||
current={current()}
|
||||
value={(option) => option.value}
|
||||
label={(option) => option.label}
|
||||
onSelect={(option) => option && props.model.select(option.value)}
|
||||
disabled={busy() || unavailable()}
|
||||
placeholder={language.t("session.websearch.provider")}
|
||||
contentClass="websearch-provider-menu"
|
||||
/>
|
||||
</SettingsRow>
|
||||
</div>
|
||||
</DockShell>
|
||||
<DockTray attach="top" class="websearch-footer">
|
||||
<div class="websearch-status" aria-live="polite">
|
||||
<Show when={props.model.loadFailed()} fallback={status()}>
|
||||
<span>{language.t("session.websearch.loadFailed")}</span>
|
||||
<Button variant="ghost" size="small" onClick={props.model.retry} disabled={busy()}>
|
||||
{language.t("session.websearch.retry")}
|
||||
</Button>
|
||||
</Show>
|
||||
</div>
|
||||
<div class="websearch-actions">
|
||||
<Show when={!props.model.specific()}>
|
||||
<Button variant="ghost" size="small" onClick={() => submit(false)} disabled={busy()}>
|
||||
{language.t("session.websearch.disable")}
|
||||
</Button>
|
||||
</Show>
|
||||
<Button
|
||||
variant="neutral"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
const selected = props.model.selected()
|
||||
if (selected) submit(selected)
|
||||
}}
|
||||
disabled={busy() || unavailable() || !current()}
|
||||
>
|
||||
{language.t("session.websearch.enable")}
|
||||
</Button>
|
||||
</div>
|
||||
</DockTray>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { FormAnswer, FormCreated, FormReplyInput, OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||
import { replyWebSearch } from "./websearch"
|
||||
|
||||
const consent: FormCreated["data"]["form"] = {
|
||||
id: "frm_consent",
|
||||
sessionID: "ses_child",
|
||||
title: "Web Search",
|
||||
metadata: { kind: "websearch.provider" },
|
||||
fields: [{ key: "choice", type: "string", required: true, custom: false }],
|
||||
}
|
||||
const provider: FormCreated["data"]["form"] = {
|
||||
...consent,
|
||||
id: "frm_provider",
|
||||
fields: [
|
||||
{
|
||||
key: "provider",
|
||||
type: "string",
|
||||
required: true,
|
||||
custom: false,
|
||||
options: [
|
||||
{ value: "exa", label: "Exa" },
|
||||
{ value: "parallel", label: "Parallel" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const listeners = new Set<(event: OpenCodeEvent) => void>()
|
||||
const replies: FormReplyInput[] = []
|
||||
const abort = new AbortController()
|
||||
const emit = (event: OpenCodeEvent) => listeners.forEach((listener) => listener(event))
|
||||
return {
|
||||
form: consent,
|
||||
signal: abort.signal,
|
||||
abort,
|
||||
listeners,
|
||||
replies,
|
||||
events: {
|
||||
listen(listener: (event: OpenCodeEvent) => void) {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
},
|
||||
},
|
||||
reply: async (input: FormReplyInput) => {
|
||||
replies.push(input)
|
||||
},
|
||||
create: (form = provider) => emit({ id: "evt_create", created: 0, type: "form.created", data: { form } }),
|
||||
cancel: (id: string) =>
|
||||
emit({
|
||||
id: "evt_cancel",
|
||||
created: 0,
|
||||
type: "form.cancelled",
|
||||
data: { id, sessionID: consent.sessionID },
|
||||
}),
|
||||
answer: (id: string, answer: FormAnswer) =>
|
||||
emit({
|
||||
id: "evt_reply",
|
||||
created: 0,
|
||||
type: "form.replied",
|
||||
data: { id, sessionID: consent.sessionID, answer },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
describe("web search desktop consent", () => {
|
||||
test.each([
|
||||
["random", "allow"],
|
||||
[false, "disable"],
|
||||
] as const)("submits %s without a second form", async (selection, choice) => {
|
||||
const input = fixture()
|
||||
await replyWebSearch({ ...input, selection })
|
||||
expect(input.replies).toEqual([{ sessionID: consent.sessionID, formID: consent.id, answer: { choice } }])
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("subscribes before the first reply and answers the owning session's provider form", async () => {
|
||||
const input = fixture()
|
||||
await replyWebSearch({
|
||||
...input,
|
||||
selection: "parallel",
|
||||
reply: async (answer) => {
|
||||
input.replies.push(answer)
|
||||
if (answer.answer.choice === "choose") input.create()
|
||||
},
|
||||
})
|
||||
expect(input.replies).toEqual([
|
||||
{ sessionID: consent.sessionID, formID: consent.id, answer: { choice: "choose" } },
|
||||
{ sessionID: consent.sessionID, formID: provider.id, answer: { provider: "parallel" } },
|
||||
])
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("ignores questions, other sessions, and repeated consent forms during handoff", async () => {
|
||||
const input = fixture()
|
||||
const pending = replyWebSearch({ ...input, selection: "exa" })
|
||||
input.create({ ...provider, sessionID: "ses_other" })
|
||||
input.create({ ...provider, metadata: { kind: "question" } })
|
||||
input.create(consent)
|
||||
input.create()
|
||||
await pending
|
||||
expect(input.replies).toHaveLength(2)
|
||||
expect(input.replies[1]?.formID).toBe(provider.id)
|
||||
})
|
||||
|
||||
test("leaves a changed provider list for explicit confirmation", async () => {
|
||||
const input = fixture()
|
||||
const pending = replyWebSearch({ ...input, selection: "removed" })
|
||||
input.create()
|
||||
await pending
|
||||
expect(input.replies).toHaveLength(1)
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("supports direct entry into the provider form", async () => {
|
||||
const input = fixture()
|
||||
await replyWebSearch({ ...input, form: provider, selection: "exa" })
|
||||
expect(input.replies).toEqual([{ sessionID: consent.sessionID, formID: provider.id, answer: { provider: "exa" } }])
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("does not misrepresent cancelling the provider form as disabling search", async () => {
|
||||
const input = fixture()
|
||||
await replyWebSearch({ ...input, form: provider, selection: false })
|
||||
expect(input.replies).toEqual([])
|
||||
})
|
||||
|
||||
test.each(["cancel", "other-client", "abort"])("ends a pending handoff on %s", async (action) => {
|
||||
const input = fixture()
|
||||
const pending = replyWebSearch({ ...input, selection: "exa" })
|
||||
if (action === "cancel") input.cancel(consent.id)
|
||||
if (action === "other-client") input.answer(consent.id, { choice: "disable" })
|
||||
if (action === "abort") input.abort.abort()
|
||||
await pending
|
||||
input.create()
|
||||
expect(input.replies).toHaveLength(1)
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("cleans up after a failed consent submission", async () => {
|
||||
const input = fixture()
|
||||
await expect(
|
||||
replyWebSearch({
|
||||
...input,
|
||||
selection: "exa",
|
||||
reply: async () => {
|
||||
throw new Error("offline")
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("offline")
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("propagates provider submission failures for retry", async () => {
|
||||
const input = fixture()
|
||||
await expect(
|
||||
replyWebSearch({
|
||||
...input,
|
||||
selection: "exa",
|
||||
reply: async (answer) => {
|
||||
if (answer.formID === provider.id) throw new Error("offline")
|
||||
input.create()
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("offline")
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { FormInfo, FormOption, FormReplyInput, FormStringField } from "@opencode-ai/client/promise"
|
||||
import { createEffect, createMemo, createResource, on, onCleanup } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import type { OpenCodeEventStream } from "@/runtime/server/client"
|
||||
|
||||
export function webSearchProviderField(form: FormInfo) {
|
||||
return form.fields.find(
|
||||
(field): field is FormStringField => field.type === "string" && field.key === "provider" && !!field.options,
|
||||
)
|
||||
}
|
||||
|
||||
export function createWebSearchRequest(input: {
|
||||
owner: () => string | undefined
|
||||
connected: () => boolean
|
||||
request: () => FormInfo | undefined
|
||||
providers: (sessionID: string) => Promise<FormOption[]>
|
||||
reply: (input: FormReplyInput) => Promise<unknown>
|
||||
events: Pick<OpenCodeEventStream, "listen">
|
||||
}) {
|
||||
const [store, setStore] = createStore({
|
||||
selected: "random",
|
||||
sending: undefined as { form: FormInfo; abort: AbortController } | undefined,
|
||||
error: false,
|
||||
})
|
||||
const [providers, resource] = createResource(input.request, async (form) => {
|
||||
const field = webSearchProviderField(form)
|
||||
if (field) return field.options ?? []
|
||||
return input.providers(form.sessionID)
|
||||
})
|
||||
const request = createMemo(() => store.sending?.form ?? input.request())
|
||||
const specific = createMemo(() => {
|
||||
const form = request()
|
||||
return !!form && !!webSearchProviderField(form)
|
||||
})
|
||||
const options = createMemo(() => (providers.error ? [] : (providers() ?? [])))
|
||||
const selected = createMemo(() => {
|
||||
if (!specific()) return store.selected
|
||||
return options().some((option) => option.value === store.selected) ? store.selected : options()[0]?.value
|
||||
})
|
||||
|
||||
createEffect(
|
||||
on([input.owner, input.connected], () => {
|
||||
store.sending?.abort.abort()
|
||||
setStore({ sending: undefined, selected: "random", error: false })
|
||||
}),
|
||||
)
|
||||
createEffect(
|
||||
on(
|
||||
() => input.request()?.id,
|
||||
() => {
|
||||
const form = input.request()
|
||||
if (!form || store.sending || webSearchProviderField(form)) return
|
||||
setStore({ selected: "random", error: false })
|
||||
},
|
||||
),
|
||||
)
|
||||
onCleanup(() => store.sending?.abort.abort())
|
||||
|
||||
const submit = async (selection: string | false) => {
|
||||
const form = input.request()
|
||||
if (!form || store.sending || !input.connected()) return
|
||||
if (selection === false && webSearchProviderField(form)) return
|
||||
const sending = { form, abort: new AbortController() }
|
||||
setStore({ sending, error: false })
|
||||
await replyWebSearch({ ...input, form, selection, signal: sending.abort.signal })
|
||||
.catch(() => {
|
||||
if (!sending.abort.signal.aborted) setStore("error", true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (store.sending?.abort === sending.abort) setStore("sending", undefined)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
request,
|
||||
options,
|
||||
selected,
|
||||
specific,
|
||||
loading: () => providers.loading,
|
||||
loadFailed: () => !!providers.error,
|
||||
failed: () => store.error,
|
||||
sending: () => !!store.sending,
|
||||
connected: input.connected,
|
||||
select: (value: string) => setStore({ selected: value, error: false }),
|
||||
retry: () => void resource.refetch(),
|
||||
submit,
|
||||
}
|
||||
}
|
||||
|
||||
export type WebSearchRequestModel = ReturnType<typeof createWebSearchRequest>
|
||||
|
||||
export async function replyWebSearch(input: {
|
||||
form: FormInfo
|
||||
selection: string | false
|
||||
signal: AbortSignal
|
||||
reply: (input: FormReplyInput) => Promise<unknown>
|
||||
events: Pick<OpenCodeEventStream, "listen">
|
||||
}) {
|
||||
if (input.signal.aborted) return
|
||||
if (webSearchProviderField(input.form)) {
|
||||
if (input.selection === false) return
|
||||
return input.reply({
|
||||
sessionID: input.form.sessionID,
|
||||
formID: input.form.id,
|
||||
answer: { provider: input.selection },
|
||||
})
|
||||
}
|
||||
if (input.selection === false || input.selection === "random") {
|
||||
return input.reply({
|
||||
sessionID: input.form.sessionID,
|
||||
formID: input.form.id,
|
||||
answer: { choice: input.selection === false ? "disable" : "allow" },
|
||||
})
|
||||
}
|
||||
|
||||
const next = Promise.withResolvers<FormInfo | undefined>()
|
||||
const stop = input.events.listen((event) => {
|
||||
if (event.type === "form.created") {
|
||||
const form = event.data.form
|
||||
if (
|
||||
form.sessionID !== input.form.sessionID ||
|
||||
form.id === input.form.id ||
|
||||
form.metadata?.kind !== "websearch.provider" ||
|
||||
!webSearchProviderField(form)
|
||||
)
|
||||
return
|
||||
next.resolve(form)
|
||||
}
|
||||
if (event.type === "form.cancelled" && event.data.id === input.form.id) next.resolve(undefined)
|
||||
if (event.type === "form.replied" && event.data.id === input.form.id && event.data.answer.choice !== "choose")
|
||||
next.resolve(undefined)
|
||||
})
|
||||
const cancel = () => next.resolve(undefined)
|
||||
input.signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
return Promise.all([
|
||||
input.reply({ sessionID: input.form.sessionID, formID: input.form.id, answer: { choice: "choose" } }),
|
||||
next.promise,
|
||||
])
|
||||
.then(([, form]) => {
|
||||
if (!form || input.signal.aborted) return
|
||||
const field = webSearchProviderField(form)
|
||||
if (!field?.options?.some((option) => option.value === input.selection)) return
|
||||
return input.reply({
|
||||
sessionID: form.sessionID,
|
||||
formID: form.id,
|
||||
answer: { provider: input.selection },
|
||||
})
|
||||
})
|
||||
.finally(() => {
|
||||
stop()
|
||||
input.signal.removeEventListener("abort", cancel)
|
||||
})
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import { createSessionReview } from "./review/model"
|
||||
import { SessionDesktopReview, SessionMobileReview, SessionMobileViewTabs } from "./review/view"
|
||||
import { SessionContextTab } from "./files/session-context-tab"
|
||||
import { createSessionTimelineInteraction } from "./timeline/interaction"
|
||||
import { createTimelineSearchController } from "./timeline/search-controller"
|
||||
import { TimelineSearchBar } from "./timeline/search-bar"
|
||||
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
|
||||
import { SessionIdentityHeader } from "./session-identity-header"
|
||||
import { SessionReviewToggle } from "./header/session-header-actions"
|
||||
@@ -47,6 +49,12 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
const isDesktop = session.isDesktop
|
||||
const screen = createSessionScreenLayout(session)
|
||||
const timeline = createSessionTimelineInteraction(session)
|
||||
const timelineSearch = createTimelineSearchController({
|
||||
sessionID: session.identity.sessionID,
|
||||
scrollRef: timeline.scroller,
|
||||
revealMessage: timeline.actions.revealMessage,
|
||||
pauseAutoScroll: timeline.view.unpin,
|
||||
})
|
||||
const messagesReady = timeline.ready
|
||||
const [store, setStore] = createStore({
|
||||
deferRender: false,
|
||||
@@ -262,6 +270,7 @@ export function SessionScreen(props: { session: SessionModel }) {
|
||||
anchor={timeline.view.anchor}
|
||||
setRevealMessage={timeline.view.setRevealMessage}
|
||||
setScrollToEnd={timeline.view.setScrollToEnd}
|
||||
search={<TimelineSearchBar controller={timelineSearch} />}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
@@ -2,30 +2,54 @@ import { describe, expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createSessionResolution } from "./session-resolution"
|
||||
|
||||
function store() {
|
||||
const syncs = { session: 0, message: 0, pending: 0 }
|
||||
const sessions = {
|
||||
get: () => undefined,
|
||||
sync: () => {
|
||||
syncs.session++
|
||||
return Promise.resolve()
|
||||
},
|
||||
message: {
|
||||
sync: () => {
|
||||
syncs.message++
|
||||
return Promise.resolve()
|
||||
},
|
||||
},
|
||||
pending: {
|
||||
sync: () => {
|
||||
syncs.pending++
|
||||
return Promise.resolve()
|
||||
},
|
||||
},
|
||||
}
|
||||
return { syncs, sessions }
|
||||
}
|
||||
|
||||
describe("session resolution", () => {
|
||||
test("waits for a route session ID", () => {
|
||||
createRoot((dispose) => {
|
||||
const syncs = { session: 0, message: 0 }
|
||||
const sessions = {
|
||||
get: () => undefined,
|
||||
sync: () => {
|
||||
syncs.session++
|
||||
return Promise.resolve()
|
||||
},
|
||||
message: {
|
||||
sync: () => {
|
||||
syncs.message++
|
||||
return Promise.resolve()
|
||||
},
|
||||
},
|
||||
}
|
||||
const input = store()
|
||||
const session = createSessionResolution(
|
||||
() => undefined,
|
||||
() => sessions,
|
||||
() => input.sessions,
|
||||
)
|
||||
|
||||
expect(session()).toBeUndefined()
|
||||
expect(syncs).toEqual({ session: 0, message: 0 })
|
||||
expect(input.syncs).toEqual({ session: 0, message: 0, pending: 0 })
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
test("starts the transcript and queued input reads with metadata", () => {
|
||||
createRoot((dispose) => {
|
||||
const input = store()
|
||||
createSessionResolution(
|
||||
() => "ses_open",
|
||||
() => input.sessions,
|
||||
{ children: true },
|
||||
)
|
||||
expect(input.syncs).toEqual({ session: 1, message: 1, pending: 1 })
|
||||
dispose()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,9 @@ type SessionStore<T> = {
|
||||
message: {
|
||||
sync: (id: string) => Promise<unknown>
|
||||
}
|
||||
pending: {
|
||||
sync: (id: string) => Promise<unknown>
|
||||
}
|
||||
}
|
||||
|
||||
type Resolution<T> = { id: string; store: SessionStore<T> } & (
|
||||
@@ -52,8 +55,11 @@ export function createSessionResolution<T>(
|
||||
onCleanup(() => {
|
||||
stale = true
|
||||
})
|
||||
// The timeline owns message errors; metadata resolution stays independent.
|
||||
// The timeline owns message errors; metadata resolution stays independent. Queued inputs
|
||||
// ride along so a reconnect refreshes them with the transcript instead of leaving the
|
||||
// pre-disconnect queue on screen.
|
||||
void store.message.sync(id).catch(() => undefined)
|
||||
void store.pending.sync(id).catch(() => undefined)
|
||||
if (cached() && !options?.children && !options?.connected) {
|
||||
setStatus({ id, store, state: "settled" })
|
||||
return
|
||||
|
||||
@@ -138,6 +138,26 @@ export const QuestionRequest = {
|
||||
),
|
||||
}
|
||||
|
||||
export const WebSearchRequest = {
|
||||
render: () => (
|
||||
<SessionPreview
|
||||
title="Search for current documentation"
|
||||
description={description}
|
||||
document={questionPendingDocument}
|
||||
request={{
|
||||
type: "websearch",
|
||||
value: {
|
||||
id: "frm_websearch_preview",
|
||||
sessionID: "ses_websearch_preview",
|
||||
title: "Web Search",
|
||||
metadata: { kind: "websearch.provider" },
|
||||
fields: [{ key: "choice", type: "string", required: true, custom: false }],
|
||||
},
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const RetryAndInterruption = {
|
||||
render: () => (
|
||||
<SessionPreview title="Recover the interrupted run" description={description} document={retryAfterInterruption} />
|
||||
|
||||
@@ -23,6 +23,7 @@ import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ReviewPanelView } from "@/session/review/panel"
|
||||
import { createReviewPanelState } from "@/session/review/panel-state"
|
||||
import { TerminalSurface } from "@/session/terminal/surface"
|
||||
import type { WebSearchRequestModel } from "./requests/websearch"
|
||||
|
||||
const modelReady = Object.assign(() => true, { promise: undefined }) satisfies ModelSelection["ready"]
|
||||
const storyComposerModel = {
|
||||
@@ -82,7 +83,7 @@ export type SessionPreviewProps = {
|
||||
description: string
|
||||
document: SessionDocument
|
||||
draft?: string
|
||||
request?: { type: "permission"; value: PermissionRequest } | { type: "question"; value: FormInfo }
|
||||
request?: { type: "permission"; value: PermissionRequest } | { type: "question" | "websearch"; value: FormInfo }
|
||||
reviewOpened?: boolean
|
||||
child?: { parentID: string }
|
||||
terminal?: { title: string; lines: string[] }
|
||||
@@ -173,10 +174,12 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
|
||||
activity: string
|
||||
reviewOpened: boolean
|
||||
request: SessionPreviewProps["request"]
|
||||
searchProvider: string
|
||||
}>({
|
||||
activity: "Ready",
|
||||
reviewOpened: props.reviewOpened ?? false,
|
||||
request: props.request,
|
||||
searchProvider: "random",
|
||||
})
|
||||
const prompt = createPromptController({
|
||||
initial: props.draft ?? "",
|
||||
@@ -189,6 +192,27 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
|
||||
const region = {
|
||||
state: {
|
||||
questionRequest: () => (state.request?.type === "question" ? state.request.value : undefined),
|
||||
websearch: {
|
||||
request: () => (state.request?.type === "websearch" ? state.request.value : undefined),
|
||||
options: () => [
|
||||
{ value: "exa", label: "Exa" },
|
||||
{ value: "parallel", label: "Parallel" },
|
||||
{ value: "tavily", label: "Tavily" },
|
||||
],
|
||||
selected: () => state.searchProvider,
|
||||
specific: () => false,
|
||||
loading: () => false,
|
||||
loadFailed: () => false,
|
||||
failed: () => false,
|
||||
sending: () => false,
|
||||
connected: () => true,
|
||||
select: (value) => setState("searchProvider", value),
|
||||
retry() {},
|
||||
submit: async (value) => {
|
||||
setState("request", undefined)
|
||||
setState("activity", `Web search selection (local only): ${value}`)
|
||||
},
|
||||
} satisfies WebSearchRequestModel,
|
||||
permissionRequest: () => (state.request?.type === "permission" ? state.request.value : undefined),
|
||||
permissionResponding: () => false,
|
||||
decide: (response) => {
|
||||
|
||||
@@ -24,6 +24,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
pinned: true,
|
||||
},
|
||||
refs: {
|
||||
scroller: undefined as HTMLDivElement | undefined,
|
||||
content: undefined as HTMLDivElement | undefined,
|
||||
dock: undefined as HTMLDivElement | undefined,
|
||||
},
|
||||
@@ -38,7 +39,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
}
|
||||
let scroller: HTMLDivElement | undefined
|
||||
let dockHeight = 0
|
||||
let revealMessage = (_id: string) => {}
|
||||
let revealMessage = (_id: string, _partID?: string) => {}
|
||||
let scrollToEnd = () => {}
|
||||
let scrollMark = 0
|
||||
let messageMark = 0
|
||||
@@ -157,6 +158,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
}
|
||||
const setScrollRef = (element: HTMLDivElement | undefined) => {
|
||||
scroller = element
|
||||
setState("refs", "scroller", element)
|
||||
if (!element) return
|
||||
scheduleScrollState(element)
|
||||
fill()
|
||||
@@ -290,6 +292,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
return {
|
||||
actions: {
|
||||
navigateMessage,
|
||||
revealMessage: (id: string, partID?: string) => revealMessage(id, partID),
|
||||
resume,
|
||||
setActiveMessage,
|
||||
},
|
||||
@@ -297,7 +300,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
resource: timeline.resource,
|
||||
ready: timeline.ready,
|
||||
scroll: state.scroll,
|
||||
scroller: () => scroller,
|
||||
scroller: () => state.refs.scroller,
|
||||
view: {
|
||||
anchor,
|
||||
markUserScroll,
|
||||
@@ -313,7 +316,7 @@ export function createSessionTimelineInteraction(session: SessionModel) {
|
||||
setDockRef: (element: HTMLDivElement | undefined) => {
|
||||
setState("refs", "dock", element)
|
||||
},
|
||||
setRevealMessage: (reveal: (id: string) => void) => {
|
||||
setRevealMessage: (reveal: (id: string, partID?: string) => void) => {
|
||||
revealMessage = reveal
|
||||
},
|
||||
setScrollRef,
|
||||
|
||||
@@ -58,7 +58,6 @@ export function BackgroundMoveHint(props: { keybind?: string[]; onMove?: () => v
|
||||
type="button"
|
||||
variant="ghost-faint"
|
||||
size="small"
|
||||
icon="outline-arrow-to-corner-top-right"
|
||||
class="max-w-full"
|
||||
aria-label={language.t("session.background.moveInline", { keybind: keybind() })}
|
||||
onClick={() => props.onMove?.()}
|
||||
@@ -354,8 +353,9 @@ type MessageTimelineProps = {
|
||||
workspaceMoveEligible: boolean
|
||||
onSummaryOpenChange: (open: boolean) => void
|
||||
anchor: (id: string) => string
|
||||
setRevealMessage?: (fn: (id: string) => void) => void
|
||||
setRevealMessage?: (fn: (id: string, partID?: string) => void) => void
|
||||
setScrollToEnd?: (fn: () => void) => void
|
||||
search?: JSX.Element
|
||||
}
|
||||
|
||||
export function MessageTimeline(props: MessageTimelineProps) {
|
||||
@@ -790,6 +790,7 @@ function MessageTimelineView(
|
||||
<Show when={sessionID()} keyed>
|
||||
{(id) => (
|
||||
<div class="shrink-0 flex items-center gap-2">
|
||||
{props.search}
|
||||
<SessionContextUsage placement="bottom" />
|
||||
<Show when={!parentID() && project()}>
|
||||
{(project) => (
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[data-component="timeline-search-bar"] [data-component="text-input-v2"] {
|
||||
background: var(--v2-background-bg-base);
|
||||
box-shadow: inset 0 0 0 1px var(--v2-border-border-base);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
[data-component="timeline-search-bar"] [data-component="text-input-v2"]:hover {
|
||||
background: var(--v2-background-bg-base);
|
||||
}
|
||||
|
||||
[data-component="timeline-search-bar"] [data-component="text-input-v2"]:focus-within {
|
||||
box-shadow: inset 0 0 0 1px var(--v2-border-border-focus);
|
||||
outline: none;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Icon } from "@opencode-ai/ui/icon"
|
||||
import "@opencode-ai/ui/text-input.css"
|
||||
import { Show } from "solid-js"
|
||||
import type { TimelineSearchController } from "./search-controller"
|
||||
import "./search-bar.css"
|
||||
|
||||
export function TimelineSearchBar(props: { controller: TimelineSearchController }) {
|
||||
const c = props.controller
|
||||
|
||||
return (
|
||||
<Show when={c.visible()}>
|
||||
<div data-component="timeline-search-bar" class="h-7 w-[200px] max-w-[50vw] shrink-0">
|
||||
<div data-component="text-input-v2" data-appearance="base" data-leading-icon class="!h-7 !w-full max-w-full">
|
||||
<div data-slot="text-input-v2-value">
|
||||
<span data-slot="text-input-v2-leading-icon">
|
||||
<Icon name="magnifying-glass" size="small" />
|
||||
</span>
|
||||
<input
|
||||
ref={c.element.setInput}
|
||||
data-slot="text-input-v2-input"
|
||||
type="search"
|
||||
value={c.query.value()}
|
||||
placeholder={c.query.placeholder()}
|
||||
aria-label={c.query.placeholder()}
|
||||
onInput={(event) => c.query.setValue(event.currentTarget.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault()
|
||||
c.query.close()
|
||||
return
|
||||
}
|
||||
if (event.altKey || event.metaKey || event.ctrlKey) return
|
||||
if (event.key === "Enter" && !event.isComposing) {
|
||||
event.preventDefault()
|
||||
c.result.move(event.shiftKey ? -1 : 1)
|
||||
return
|
||||
}
|
||||
if (event.key === "ArrowDown" && !event.isComposing) {
|
||||
event.preventDefault()
|
||||
c.result.move(1)
|
||||
return
|
||||
}
|
||||
if (event.key === "ArrowUp" && !event.isComposing) {
|
||||
event.preventDefault()
|
||||
c.result.move(-1)
|
||||
return
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Show when={c.query.value()}>
|
||||
<span
|
||||
data-slot="timeline-search-count"
|
||||
class="shrink-0 self-center text-[11px] text-v2-text-text-muted [font-weight:440] tabular-nums"
|
||||
>
|
||||
{c.result.count() > 0 ? c.result.activeIndex() + 1 : 0}/{c.result.count()}
|
||||
</span>
|
||||
</Show>
|
||||
<button
|
||||
type="button"
|
||||
class="-me-1 flex size-5 shrink-0 self-center items-center justify-center rounded-[2px] border-0 bg-transparent p-0 text-v2-icon-icon-muted outline outline-1 outline-transparent hover:bg-v2-overlay-simple-overlay-hover active:bg-v2-overlay-simple-overlay-pressed focus-visible:outline-v2-border-border-focus"
|
||||
aria-label={c.query.placeholder()}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => c.query.close()}
|
||||
>
|
||||
<Icon name="xmark-small" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import { useCommand } from "@/shell/commands/command"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { Timeline } from "@opencode-ai/session-ui/timeline/projection"
|
||||
import { createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
|
||||
export type TimelineSearchMatch = {
|
||||
messageID: string
|
||||
role: "user" | "assistant"
|
||||
revealID: string
|
||||
partID: string
|
||||
occurrence: number
|
||||
text: string
|
||||
}
|
||||
|
||||
const HIGHLIGHT_HIT = "timeline-search-hit"
|
||||
const HIGHLIGHT_ACTIVE = "timeline-search-hit-active"
|
||||
const TEXT_SELECTORS = '[data-slot="text-part-body"], [data-slot="user-message-text"]'
|
||||
|
||||
function supportsHighlights() {
|
||||
return typeof CSS !== "undefined" && typeof CSS.highlights === "object" && CSS.highlights !== null
|
||||
}
|
||||
|
||||
function clearHighlights() {
|
||||
if (!supportsHighlights()) return
|
||||
CSS.highlights.delete(HIGHLIGHT_HIT)
|
||||
CSS.highlights.delete(HIGHLIGHT_ACTIVE)
|
||||
}
|
||||
|
||||
function collectRanges(
|
||||
root: HTMLElement,
|
||||
query: string,
|
||||
activePartID: string | undefined,
|
||||
activeOccurrence: number | undefined,
|
||||
) {
|
||||
const hits: Range[] = []
|
||||
const active: Range[] = []
|
||||
const lower = query.toLowerCase()
|
||||
const bodies = root.querySelectorAll<HTMLElement>(TEXT_SELECTORS)
|
||||
for (const body of bodies) {
|
||||
const part = body.closest("[data-timeline-part-id]")
|
||||
const partID = part?.getAttribute("data-timeline-part-id")
|
||||
const isActivePart = activePartID !== undefined && partID === activePartID
|
||||
let occurrenceInPart = 0
|
||||
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT)
|
||||
let node = walker.nextNode() as Text | null
|
||||
while (node) {
|
||||
const value = node.nodeValue ?? ""
|
||||
const lowerValue = value.toLowerCase()
|
||||
let from = 0
|
||||
let at = lowerValue.indexOf(lower, from)
|
||||
while (at !== -1) {
|
||||
const range = document.createRange()
|
||||
range.setStart(node, at)
|
||||
range.setEnd(node, at + query.length)
|
||||
if (isActivePart && activeOccurrence === occurrenceInPart) active.push(range)
|
||||
else hits.push(range)
|
||||
occurrenceInPart += 1
|
||||
from = at + query.length
|
||||
at = lowerValue.indexOf(lower, from)
|
||||
}
|
||||
node = walker.nextNode() as Text | null
|
||||
}
|
||||
}
|
||||
return { hits, active }
|
||||
}
|
||||
|
||||
function applyHighlights(
|
||||
root: HTMLElement,
|
||||
query: string,
|
||||
activePartID: string | undefined,
|
||||
activeOccurrence: number | undefined,
|
||||
) {
|
||||
if (!supportsHighlights()) return
|
||||
const { hits, active } = collectRanges(root, query, activePartID, activeOccurrence)
|
||||
CSS.highlights.set(HIGHLIGHT_HIT, new Highlight(...hits))
|
||||
CSS.highlights.set(HIGHLIGHT_ACTIVE, new Highlight(...active))
|
||||
}
|
||||
|
||||
export function createTimelineSearchController(input: {
|
||||
sessionID: () => string | undefined
|
||||
scrollRef: () => HTMLDivElement | undefined
|
||||
revealMessage: (id: string, partID?: string) => void
|
||||
pauseAutoScroll: () => void
|
||||
}) {
|
||||
const command = useCommand()
|
||||
const language = useLanguage()
|
||||
const data = useData()
|
||||
const [state, setState] = createStore({ value: "", active: 0, visible: false })
|
||||
const [focusTick, setFocusTick] = createSignal(0)
|
||||
let inputEl: HTMLInputElement | undefined
|
||||
|
||||
const query = createMemo(() => state.value.trim().toLowerCase())
|
||||
|
||||
const matches = createMemo<TimelineSearchMatch[]>(() => {
|
||||
const value = query()
|
||||
if (!value) return []
|
||||
const sessionID = input.sessionID()
|
||||
if (!sessionID) return []
|
||||
const messages = data.session.message.list(sessionID)
|
||||
const result: TimelineSearchMatch[] = []
|
||||
let revealID = ""
|
||||
for (const message of messages) {
|
||||
if (message.type === "user" || message.type === "shell") revealID = message.id
|
||||
if (message.type !== "user" && message.type !== "assistant") continue
|
||||
const visibleParts =
|
||||
message.type === "user"
|
||||
? [{ id: `${message.id}:text:0`, content: { type: "text" as const, text: message.text } }]
|
||||
: Timeline.contentEntries(message)
|
||||
for (const textPart of visibleParts) {
|
||||
if (textPart.content.type !== "text") continue
|
||||
const text = textPart.content.text
|
||||
if (!text) continue
|
||||
const lower = text.toLowerCase()
|
||||
let from = 0
|
||||
let occurrence = 0
|
||||
let at = lower.indexOf(value, from)
|
||||
while (at !== -1) {
|
||||
result.push({
|
||||
messageID: message.id,
|
||||
role: message.type,
|
||||
revealID,
|
||||
partID: textPart.id,
|
||||
occurrence,
|
||||
text,
|
||||
})
|
||||
occurrence += 1
|
||||
from = at + value.length
|
||||
at = lower.indexOf(value, from)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
})
|
||||
|
||||
const activeIndex = createMemo(() => {
|
||||
const list = matches()
|
||||
if (list.length === 0) return 0
|
||||
if (state.active >= list.length) return 0
|
||||
if (state.active < 0) return 0
|
||||
return state.active
|
||||
})
|
||||
|
||||
const activePartID = createMemo(() => matches()[activeIndex()]?.partID)
|
||||
const activeOccurrence = createMemo(() => matches()[activeIndex()]?.occurrence)
|
||||
|
||||
createEffect(() => {
|
||||
const root = input.scrollRef()
|
||||
const q = query()
|
||||
if (!root || !state.visible || !q) {
|
||||
clearHighlights()
|
||||
return
|
||||
}
|
||||
applyHighlights(root, q, activePartID(), activeOccurrence())
|
||||
let frame: number | undefined
|
||||
const scheduleApply = () => {
|
||||
if (frame !== undefined) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
if (!state.visible) return
|
||||
applyHighlights(root, query(), activePartID(), activeOccurrence())
|
||||
})
|
||||
}
|
||||
const observer = new MutationObserver(scheduleApply)
|
||||
observer.observe(root, { childList: true, subtree: true, characterData: true })
|
||||
onCleanup(() => {
|
||||
observer.disconnect()
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
clearHighlights()
|
||||
})
|
||||
})
|
||||
|
||||
createEffect(
|
||||
on(focusTick, () => {
|
||||
if (!state.visible) return
|
||||
requestAnimationFrame(() => {
|
||||
inputEl?.focus()
|
||||
inputEl?.select()
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
command.register("session.search", () => [
|
||||
{
|
||||
id: "session.search",
|
||||
title: language.t("session.search.placeholder"),
|
||||
keybind: "mod+f",
|
||||
hidden: true,
|
||||
onSelect: () => open(),
|
||||
},
|
||||
])
|
||||
const onOpenRequest = () => open()
|
||||
document.addEventListener("opencode:timeline-search-open", onOpenRequest)
|
||||
onCleanup(() => document.removeEventListener("opencode:timeline-search-open", onOpenRequest))
|
||||
|
||||
function open() {
|
||||
setState("visible", true)
|
||||
setFocusTick((t) => t + 1)
|
||||
}
|
||||
|
||||
function close() {
|
||||
setState({ value: "", active: 0, visible: false })
|
||||
inputEl?.blur()
|
||||
}
|
||||
|
||||
function setValue(value: string) {
|
||||
setState("value", value)
|
||||
const list = matches()
|
||||
const match = list[0]
|
||||
if (!value.trim() || !match) {
|
||||
setState("active", 0)
|
||||
return
|
||||
}
|
||||
setState("active", 0)
|
||||
input.pauseAutoScroll()
|
||||
input.revealMessage(match.revealID, match.partID)
|
||||
scrollToMatch(match)
|
||||
}
|
||||
|
||||
function scrollToMatch(match: TimelineSearchMatch) {
|
||||
let attempts = 0
|
||||
const seek = () => {
|
||||
if (!state.visible) return
|
||||
const root = input.scrollRef()
|
||||
if (!root) return
|
||||
const { active } = collectRanges(root, query(), match.partID, match.occurrence)
|
||||
if (active.length === 0) {
|
||||
if (attempts++ < 12) requestAnimationFrame(seek)
|
||||
return
|
||||
}
|
||||
const rect = active[0].getBoundingClientRect()
|
||||
const rootRect = root.getBoundingClientRect()
|
||||
const sticky = root.querySelector("[data-session-title]")
|
||||
const inset = sticky instanceof HTMLElement ? sticky.offsetHeight : 0
|
||||
const top = rect.top - rootRect.top + root.scrollTop - inset - (rootRect.height - rect.height) / 2
|
||||
root.scrollTo({ top: Math.max(0, top), behavior: "auto" })
|
||||
}
|
||||
requestAnimationFrame(seek)
|
||||
}
|
||||
|
||||
function move(delta: number) {
|
||||
const list = matches()
|
||||
if (list.length === 0) return
|
||||
const next = (activeIndex() + delta + list.length) % list.length
|
||||
setState("active", next)
|
||||
const match = list[next]
|
||||
if (!match) return
|
||||
input.pauseAutoScroll()
|
||||
input.revealMessage(match.revealID, match.partID)
|
||||
scrollToMatch(match)
|
||||
}
|
||||
|
||||
return {
|
||||
visible: () => state.visible,
|
||||
query: {
|
||||
value: () => state.value,
|
||||
placeholder: () => language.t("session.search.placeholder"),
|
||||
noResults: () => language.t("session.search.noResults"),
|
||||
open,
|
||||
close,
|
||||
setValue,
|
||||
},
|
||||
result: {
|
||||
activeIndex,
|
||||
count: () => matches().length,
|
||||
move,
|
||||
},
|
||||
element: {
|
||||
setInput: (element: HTMLInputElement) => (inputEl = element),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type TimelineSearchController = ReturnType<typeof createTimelineSearchController>
|
||||
@@ -69,7 +69,7 @@ type Input = {
|
||||
row: TimelineRow.TimelineRow,
|
||||
disclosure: Readonly<Record<string, boolean | undefined>>,
|
||||
) => boolean
|
||||
setRevealMessage?: (fn: (id: string) => void) => void
|
||||
setRevealMessage?: (fn: (id: string, partID?: string) => void) => void
|
||||
setScrollToEnd?: (fn: () => void) => void
|
||||
}
|
||||
|
||||
@@ -271,8 +271,13 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
const virtualRowKeys = createMemo(() => virtualizer.getVirtualItems().map((item) => String(item.key)))
|
||||
|
||||
createEffect(() => {
|
||||
input.setRevealMessage?.((id) => {
|
||||
const index = input.projection.messageRowIndex().get(id)
|
||||
input.setRevealMessage?.((id, partID) => {
|
||||
const partIndex = partID
|
||||
? rows().findIndex(
|
||||
(row) => row._tag === "AssistantPart" && row.group.type === "part" && row.group.ref.partID === partID,
|
||||
)
|
||||
: -1
|
||||
const index = partIndex >= 0 ? partIndex : input.projection.messageRowIndex().get(id)
|
||||
if (index === undefined) return
|
||||
virtualizer.scrollToIndex(index, { align: "center" })
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component } from "solid-js"
|
||||
import { Component, Show } from "solid-js"
|
||||
import { Select } from "@opencode-ai/ui/select"
|
||||
import { Switch } from "@opencode-ai/ui/switch"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
@@ -61,6 +61,22 @@ export const SettingsExperimental: Component = () => {
|
||||
</Switch>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
<Show when={import.meta.env.VITE_OPENCODE_CHANNEL !== "prod"}>
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.showProjectIcon.title")}
|
||||
description={language.t("settings.general.row.showProjectIcon.description")}
|
||||
>
|
||||
<div data-action="settings-show-project-icon">
|
||||
<Switch
|
||||
checked={settings.general.showProjectIcon()}
|
||||
onChange={settings.general.setShowProjectIcon}
|
||||
hideLabel
|
||||
>
|
||||
{language.t("settings.general.row.showProjectIcon.title")}
|
||||
</Switch>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
</Show>
|
||||
</SettingsList>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -348,20 +348,6 @@ export const SettingsGeneral: Component<{
|
||||
</div>
|
||||
</SettingsRow>
|
||||
|
||||
<Show when={import.meta.env.VITE_OPENCODE_CHANNEL !== "prod"}>
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.showProjectIcon.title")}
|
||||
description={language.t("settings.general.row.showProjectIcon.description")}
|
||||
>
|
||||
<div data-action="settings-show-project-icon">
|
||||
<Switch
|
||||
checked={settings.general.showProjectIcon()}
|
||||
onChange={(checked) => settings.general.setShowProjectIcon(checked)}
|
||||
/>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
</Show>
|
||||
|
||||
<Show when={mobile() && import.meta.env.VITE_OPENCODE_CHANNEL !== "prod"}>
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.mobileTitlebarBottom.title")}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createMemo, type Accessor } from "solid-js"
|
||||
import { useGlobal, useServerCtx } from "@/runtime/server/runtime"
|
||||
import { sessionPermissionRequest, sessionQuestionForm } from "@/session/requests/session-request-tree"
|
||||
import { sessionPermissionRequest, sessionFormRequest } from "@/session/requests/session-request-tree"
|
||||
import { ServerConnection } from "@/runtime/server/registry"
|
||||
import { useSettings } from "@/settings/model"
|
||||
|
||||
@@ -29,12 +29,12 @@ export function useSessionTabAvatarState(
|
||||
if (!ctx) return false
|
||||
return !!sessionPermissionRequest(sessions(), ctx.data.session.permission.list, sessionId())
|
||||
})
|
||||
const hasQuestions = createMemo(() => {
|
||||
const hasForms = createMemo(() => {
|
||||
const data = serverCtx()?.data
|
||||
if (!data) return false
|
||||
return !!sessionQuestionForm(sessions(), data.session.form.list, sessionId())
|
||||
return !!sessionFormRequest(sessions(), data.session.form.list, sessionId())
|
||||
})
|
||||
const needsAttention = createMemo(() => hasPermissions() || hasQuestions())
|
||||
const needsAttention = createMemo(() => hasPermissions() || hasForms())
|
||||
const unread = createMemo(
|
||||
() => needsAttention() || (serverCtx()?.notification.session.unseenCount(sessionId()) ?? 0) > 0,
|
||||
)
|
||||
|
||||
@@ -21,6 +21,19 @@ describe("serverStatusDotClass", () => {
|
||||
expect(serverStatusDotClass({ ready: true, serverHealth: false, issue: true })).toBe("bg-icon-critical-base")
|
||||
})
|
||||
|
||||
test("pulses the neutral dot while the event stream is reconnecting", () => {
|
||||
expect(serverStatusDotClass({ ready: true, serverHealth: true, issue: false, connecting: true })).toBe(
|
||||
"bg-border-weak-base animate-pulse",
|
||||
)
|
||||
expect(serverStatusDotClass({ ready: false, serverHealth: undefined, issue: false, connecting: true })).toBe(
|
||||
"bg-border-weak-base animate-pulse",
|
||||
)
|
||||
// A server that is known to be down stays critical rather than looking like a routine reconnect.
|
||||
expect(serverStatusDotClass({ ready: true, serverHealth: false, issue: false, connecting: true })).toBe(
|
||||
"bg-icon-critical-base",
|
||||
)
|
||||
})
|
||||
|
||||
test("stays neutral before status is ready", () => {
|
||||
expect(serverStatusDotClass({ ready: false, serverHealth: true, issue: false })).toBe("bg-border-weak-base")
|
||||
expect(serverStatusDotClass({ ready: false, serverHealth: undefined, issue: false })).toBe("bg-border-weak-base")
|
||||
|
||||
@@ -20,8 +20,12 @@ export function serverStatusDotClass(input: {
|
||||
serverHealth: boolean | undefined
|
||||
attention?: boolean
|
||||
issue: boolean
|
||||
connecting?: boolean
|
||||
}) {
|
||||
if (input.serverHealth === false) return "bg-icon-critical-base"
|
||||
// The event stream is (re)connecting: keep the neutral dot but let it breathe so a stale
|
||||
// session is visibly waiting on the server rather than silently frozen.
|
||||
if (input.connecting) return "bg-border-weak-base animate-pulse"
|
||||
if (!input.ready || input.serverHealth === undefined) return "bg-border-weak-base"
|
||||
if (input.attention) return "bg-v2-background-bg-accent"
|
||||
if (input.issue) return "bg-icon-warning-base"
|
||||
|
||||
@@ -20,6 +20,7 @@ export function StatusPopover() {
|
||||
const sdk = useWorkspaceLocation()
|
||||
const settings = useSettings()
|
||||
const desktop = createMediaQuery("(min-width: 768px)")
|
||||
const sidebar = () => desktop() && settings.appearance.tabLayout() === "vertical"
|
||||
const [shown, setShown] = createSignal(false)
|
||||
const serverHealth = () => global.servers.health[server.key]?.healthy
|
||||
const mcp = () => data.location.mcp.server.list({ directory: sdk().directory })
|
||||
@@ -41,8 +42,10 @@ export function StatusPopover() {
|
||||
serverHealth: serverHealth(),
|
||||
attention: attention(),
|
||||
issue: issue(),
|
||||
placement: desktop() && settings.appearance.tabLayout() === "vertical" ? "top-start" : "bottom-end",
|
||||
shift: desktop() && settings.appearance.tabLayout() === "vertical" ? 0 : -168,
|
||||
connecting: server.ctx.sdk.connection.status() !== "connected",
|
||||
sidebar: sidebar(),
|
||||
placement: sidebar() ? "top-start" : "bottom-end",
|
||||
shift: sidebar() ? 0 : -168,
|
||||
label: language.t("status.popover.trigger"),
|
||||
onOpenChange: setShown,
|
||||
body: () => (
|
||||
@@ -61,6 +64,8 @@ type StatusPopoverState = {
|
||||
serverHealth: boolean | undefined
|
||||
attention: boolean
|
||||
issue: boolean
|
||||
connecting: boolean
|
||||
sidebar: boolean
|
||||
placement: "top-start" | "bottom-end"
|
||||
shift: number
|
||||
label: string
|
||||
@@ -93,21 +98,37 @@ function StatusPopoverView(props: { state: StatusPopoverState }) {
|
||||
<Popover
|
||||
open={props.state.shown}
|
||||
onOpenChange={props.state.onOpenChange}
|
||||
triggerAs={IconButton}
|
||||
triggerProps={{
|
||||
variant: "ghost-muted",
|
||||
size: "large",
|
||||
class: "!w-9 shrink-0",
|
||||
state: props.state.shown ? "pressed" : undefined,
|
||||
"aria-label": props.state.label,
|
||||
}}
|
||||
triggerAs={props.state.sidebar ? "button" : IconButton}
|
||||
triggerProps={
|
||||
props.state.sidebar
|
||||
? {
|
||||
type: "button",
|
||||
class:
|
||||
"flex h-7 w-full shrink-0 items-center gap-1.5 rounded-[6px] px-1.5 text-[13px] leading-4 text-v2-text-text-faint hover:bg-v2-background-bg-layer-02 hover:text-v2-text-text-base data-[state=pressed]:bg-v2-background-bg-layer-02 data-[state=pressed]:text-v2-text-text-base focus-visible:outline-none focus-visible:bg-v2-background-bg-layer-02 [app-region:no-drag]",
|
||||
"data-state": props.state.shown ? "pressed" : undefined,
|
||||
"aria-label": props.state.label,
|
||||
}
|
||||
: {
|
||||
variant: "ghost-muted",
|
||||
size: "large",
|
||||
class: "!w-9 shrink-0",
|
||||
state: props.state.shown ? "pressed" : undefined,
|
||||
"aria-label": props.state.label,
|
||||
}
|
||||
}
|
||||
trigger={
|
||||
<div class="relative size-4">
|
||||
<Icon name={props.state.shown ? "status-active" : "status"} />
|
||||
<div
|
||||
class={`absolute -top-1 -right-1 size-2 rounded-full border border-[var(--v2-background-bg-deep)] ${serverStatusDotClass(props.state)}`}
|
||||
/>
|
||||
</div>
|
||||
<>
|
||||
<div class="relative size-4 shrink-0">
|
||||
<Icon name={props.state.shown ? "status-active" : "status"} />
|
||||
<div
|
||||
data-slot="status-indicator"
|
||||
class={`absolute -top-1 -end-1 size-2 rounded-full border border-[var(--v2-background-bg-deep)] ${serverStatusDotClass(props.state)}`}
|
||||
/>
|
||||
</div>
|
||||
<Show when={props.state.sidebar}>
|
||||
<span class="min-w-0 truncate">{props.state.label}</span>
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
{...popoverProps}
|
||||
>
|
||||
|
||||
@@ -38,9 +38,15 @@ export function createTitlebarRightSlot(): TitlebarRightSlot {
|
||||
}
|
||||
}
|
||||
|
||||
export function TitlebarRightMount() {
|
||||
export function TitlebarRightMount(props: { vertical?: boolean }) {
|
||||
const slot = useTitlebarRightSlot()
|
||||
return <div ref={slot.setMount} id="opencode-titlebar-right" class="flex shrink-0 items-center justify-end gap-0" />
|
||||
return (
|
||||
<div
|
||||
ref={slot.setMount}
|
||||
id="opencode-titlebar-right"
|
||||
class={props.vertical ? "flex w-full shrink-0 flex-col" : "flex shrink-0 items-center justify-end gap-0"}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function TitlebarRight(props: ParentProps) {
|
||||
|
||||
@@ -680,20 +680,8 @@ export function Titlebar(props: {
|
||||
onReorder={(keys) => tabsStoreActions.reorder(keys)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
data-action="vertical-tabs-settings"
|
||||
data-state={layout.route().type === "settings" ? "pressed" : undefined}
|
||||
class="mt-2 flex h-7 w-full shrink-0 items-center gap-1.5 rounded-[6px] px-1.5 text-[13px] leading-4 text-v2-text-text-faint hover:bg-v2-background-bg-layer-02 hover:text-v2-text-text-base data-[state=pressed]:bg-v2-background-bg-layer-02 data-[state=pressed]:text-v2-text-text-base focus-visible:outline-none focus-visible:bg-v2-background-bg-layer-02 [app-region:no-drag]"
|
||||
onClick={openSettings}
|
||||
aria-label={language.t("sidebar.settings")}
|
||||
aria-pressed={layout.route().type === "settings"}
|
||||
>
|
||||
<Icon name="settings-gear" />
|
||||
{language.t("sidebar.settings")}
|
||||
</button>
|
||||
<div data-slot="vertical-tabs-footer" class="flex w-full shrink-0 items-center gap-1.5">
|
||||
<TitlebarRightMount />
|
||||
<div data-slot="vertical-tabs-footer" class="mt-2 flex w-full shrink-0 flex-col">
|
||||
<TitlebarRightMount vertical />
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
|
||||
@@ -17,9 +17,11 @@ function createFixture(initial: Record<string, Session> = {}) {
|
||||
const deferred = new Map<string, PromiseWithResolvers<unknown>>()
|
||||
const resolves: string[] = []
|
||||
const messages = { syncs: [] as string[], ...Promise.withResolvers<unknown>() }
|
||||
const pending = { syncs: [] as string[] }
|
||||
return {
|
||||
resolves,
|
||||
messages,
|
||||
pending,
|
||||
sessions: {
|
||||
get: (id: string) => cache()[id],
|
||||
sync: (id: string) => {
|
||||
@@ -34,6 +36,12 @@ function createFixture(initial: Record<string, Session> = {}) {
|
||||
return messages.promise
|
||||
},
|
||||
},
|
||||
pending: {
|
||||
sync: (id: string) => {
|
||||
pending.syncs.push(id)
|
||||
return Promise.resolve()
|
||||
},
|
||||
},
|
||||
},
|
||||
settle(id: string, directory = `/dir/${id}`) {
|
||||
setCache({ ...cache(), [id]: { id, directory } })
|
||||
@@ -86,6 +94,7 @@ test("refreshes the current session on reconnect while keeping cached content vi
|
||||
expect(fixture.resolves).toEqual(["ses_a", "ses_a"])
|
||||
expect(current()).toEqual(sessionOf("ses_a"))
|
||||
expect(fixture.messages.syncs).toEqual(["ses_a", "ses_a"])
|
||||
expect(fixture.pending.syncs).toEqual(["ses_a", "ses_a"])
|
||||
fixture.settle("ses_a", "/worktrees/moved")
|
||||
await flush()
|
||||
expect(current()?.directory).toBe("/worktrees/moved")
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import type { FormCreated, FormReplyInput, OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||
import { createEffect, createRoot } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createWebSearchRequest } from "@/session/requests/websearch"
|
||||
|
||||
const consent: FormCreated["data"]["form"] = {
|
||||
id: "frm_consent",
|
||||
sessionID: "ses_child",
|
||||
title: "Web Search",
|
||||
metadata: { kind: "websearch.provider" },
|
||||
fields: [{ key: "choice", type: "string", required: true, custom: false }],
|
||||
}
|
||||
const options = [
|
||||
{ value: "exa", label: "Exa" },
|
||||
{ value: "parallel", label: "Parallel" },
|
||||
]
|
||||
const provider: FormCreated["data"]["form"] = {
|
||||
...consent,
|
||||
id: "frm_provider",
|
||||
fields: [{ key: "provider", type: "string", options, required: true, custom: false }],
|
||||
}
|
||||
|
||||
const cleanups: VoidFunction[] = []
|
||||
afterEach(() => cleanups.splice(0).forEach((dispose) => dispose()))
|
||||
|
||||
function ready(condition: () => boolean) {
|
||||
return new Promise<void>((resolve) => {
|
||||
createRoot((dispose) => {
|
||||
cleanups.push(dispose)
|
||||
createEffect(() => {
|
||||
if (!condition()) return
|
||||
dispose()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function fixture(form: FormCreated["data"]["form"] | null = consent) {
|
||||
return createRoot((dispose) => {
|
||||
cleanups.push(dispose)
|
||||
const listeners = new Set<(event: OpenCodeEvent) => void>()
|
||||
const replies: FormReplyInput[] = []
|
||||
const loads: string[] = []
|
||||
const [state, setState] = createStore({
|
||||
request: form ?? undefined,
|
||||
owner: "ses_root",
|
||||
connected: true,
|
||||
loadFails: false,
|
||||
replyFails: false,
|
||||
})
|
||||
const model = createWebSearchRequest({
|
||||
owner: () => state.owner,
|
||||
connected: () => state.connected,
|
||||
request: () => state.request,
|
||||
providers: async (sessionID) => {
|
||||
loads.push(sessionID)
|
||||
if (state.loadFails) throw new Error("offline")
|
||||
return options
|
||||
},
|
||||
reply: async (input) => {
|
||||
replies.push(input)
|
||||
if (state.replyFails) throw new Error("offline")
|
||||
setState("request", undefined)
|
||||
},
|
||||
events: {
|
||||
listen(listener) {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
return {
|
||||
model,
|
||||
state,
|
||||
setState,
|
||||
replies,
|
||||
loads,
|
||||
dispose,
|
||||
listeners,
|
||||
create(form = provider) {
|
||||
setState("request", form)
|
||||
listeners.forEach((listener) =>
|
||||
listener({
|
||||
id: "evt_create",
|
||||
created: 0,
|
||||
type: "form.created",
|
||||
data: { form },
|
||||
}),
|
||||
)
|
||||
},
|
||||
cancel(id: string) {
|
||||
setState("request", undefined)
|
||||
listeners.forEach((listener) =>
|
||||
listener({
|
||||
id: "evt_cancel",
|
||||
created: 0,
|
||||
type: "form.cancelled",
|
||||
data: { id, sessionID: consent.sessionID },
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe("web search request state", () => {
|
||||
test("loads providers for the form owner, not the viewed parent, and waits for consent", async () => {
|
||||
const input = fixture()
|
||||
await ready(() => !input.model.loading())
|
||||
expect(input.loads).toEqual(["ses_child"])
|
||||
expect(input.model.selected()).toBe("random")
|
||||
input.model.select("exa")
|
||||
expect(input.replies).toEqual([])
|
||||
await input.model.submit(false)
|
||||
expect(input.replies[0]?.answer).toEqual({ choice: "disable" })
|
||||
expect(input.model.request()).toBeUndefined()
|
||||
expect(input.model.sending()).toBe(false)
|
||||
})
|
||||
|
||||
test("does not load providers when there is no consent request", () => {
|
||||
const input = fixture(null)
|
||||
expect(input.model.request()).toBeUndefined()
|
||||
expect(input.loads).toEqual([])
|
||||
})
|
||||
|
||||
test("holds the card across both forms and prevents duplicate submissions", async () => {
|
||||
const input = fixture()
|
||||
await ready(() => !input.model.loading())
|
||||
input.model.select("parallel")
|
||||
const pending = input.model.submit("parallel")
|
||||
await input.model.submit("parallel")
|
||||
expect(input.state.request).toBeUndefined()
|
||||
expect(input.model.request()?.id).toBe(consent.id)
|
||||
expect(input.model.sending()).toBe(true)
|
||||
input.create()
|
||||
await pending
|
||||
expect(input.replies.map((reply) => reply.answer)).toEqual([{ choice: "choose" }, { provider: "parallel" }])
|
||||
expect(input.model.request()).toBeUndefined()
|
||||
expect(input.model.sending()).toBe(false)
|
||||
expect(input.listeners.size).toBe(0)
|
||||
})
|
||||
|
||||
test("direct provider requests need confirmation and do not load a different provider list", async () => {
|
||||
const input = fixture(provider)
|
||||
await ready(() => !input.model.loading())
|
||||
expect(input.loads).toEqual([])
|
||||
expect(input.model.specific()).toBe(true)
|
||||
expect(input.model.options()).toEqual(options)
|
||||
expect(input.replies).toEqual([])
|
||||
await input.model.submit("exa")
|
||||
expect(input.replies.map((reply) => reply.answer)).toEqual([{ provider: "exa" }])
|
||||
})
|
||||
|
||||
test("keeps the selected provider after failure and retries only the provider form", async () => {
|
||||
const input = fixture()
|
||||
await ready(() => !input.model.loading())
|
||||
input.model.select("parallel")
|
||||
const pending = input.model.submit("parallel")
|
||||
input.setState("replyFails", true)
|
||||
input.create()
|
||||
await pending
|
||||
expect(input.model.failed()).toBe(true)
|
||||
expect(input.model.sending()).toBe(false)
|
||||
expect(input.model.request()?.id).toBe(provider.id)
|
||||
expect(input.model.selected()).toBe("parallel")
|
||||
input.setState("replyFails", false)
|
||||
await input.model.submit("parallel")
|
||||
expect(input.replies.map((reply) => reply.answer)).toEqual([
|
||||
{ choice: "choose" },
|
||||
{ provider: "parallel" },
|
||||
{ provider: "parallel" },
|
||||
])
|
||||
expect(input.model.request()).toBeUndefined()
|
||||
})
|
||||
|
||||
test("can retry loading providers without submitting consent", async () => {
|
||||
const input = fixture()
|
||||
await ready(() => !input.model.loading())
|
||||
input.setState("loadFails", true)
|
||||
input.model.retry()
|
||||
await ready(() => input.model.loadFailed())
|
||||
expect(input.model.options()).toEqual([])
|
||||
input.setState("loadFails", false)
|
||||
input.model.retry()
|
||||
await ready(() => !input.model.loading())
|
||||
expect(input.model.options()).toEqual(options)
|
||||
expect(input.model.loadFailed()).toBe(false)
|
||||
expect(input.replies).toEqual([])
|
||||
})
|
||||
|
||||
test.each(["navigate", "disconnect", "dispose", "cancel"])("stops automatic replies on %s", async (action) => {
|
||||
const input = fixture()
|
||||
await ready(() => !input.model.loading())
|
||||
const pending = input.model.submit("exa")
|
||||
if (action === "navigate") input.setState("owner", "ses_other")
|
||||
if (action === "disconnect") input.setState("connected", false)
|
||||
if (action === "dispose") input.dispose()
|
||||
if (action === "cancel") input.cancel(consent.id)
|
||||
await pending
|
||||
expect(input.model.sending()).toBe(false)
|
||||
expect(input.listeners.size).toBe(0)
|
||||
input.create()
|
||||
expect(input.replies.map((reply) => reply.answer)).toEqual([{ choice: "choose" }])
|
||||
})
|
||||
})
|
||||
@@ -17,8 +17,8 @@ import {
|
||||
} from "./shared"
|
||||
|
||||
const integrationPriority = new Map([
|
||||
["opencode", 0],
|
||||
["opencode-go", 1],
|
||||
["opencode-go", 0],
|
||||
["opencode", 1],
|
||||
["openai", 2],
|
||||
["github-copilot", 3],
|
||||
["google", 4],
|
||||
|
||||
@@ -18,7 +18,9 @@ export const loadIntegrations = Effect.fn("cli.auth.integrations")(function* (cl
|
||||
// The model endpoint is the existing public readiness boundary for the initial plugin generation.
|
||||
yield* request((signal) => client.model.default({ location }, { signal }))
|
||||
return yield* request((signal) => client.integration.list({ location }, { signal })).pipe(
|
||||
Effect.map((response) => response.data),
|
||||
Effect.map((response) =>
|
||||
response.data.toSorted((a, b) => Number(b.id === "opencode-go") - Number(a.id === "opencode-go")),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -68,6 +68,36 @@ describe("auth command", () => {
|
||||
expect(requests.indexOf("/api/model/default")).toBeLessThan(requests.indexOf("/api/integration"))
|
||||
})
|
||||
|
||||
test("lists OpenCode Go before Zen and preserves the remaining integration order", async () => {
|
||||
using server = authServer((request, url) => {
|
||||
if (url.pathname === "/api/integration") {
|
||||
return Response.json(
|
||||
located(
|
||||
[
|
||||
{ id: "opencode", name: "OpenCode Zen" },
|
||||
{ id: "anthropic", name: "Anthropic" },
|
||||
{ id: "opencode-go", name: "OpenCode Go" },
|
||||
].map((integration) => ({
|
||||
...integration,
|
||||
methods: [],
|
||||
connections: [{ type: "env", name: "TEST_API_KEY" }],
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
return new Response("Not found", { status: 404 })
|
||||
})
|
||||
|
||||
const result = await cli(["auth", "list", "--server", server.url.toString()])
|
||||
expect({ exitCode: result.exitCode, stderr: result.stderr }).toEqual({ exitCode: 0, stderr: "" })
|
||||
expect(
|
||||
result.stdout
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => line.split(/\s{2,}/)[0]),
|
||||
).toEqual(["OpenCode Go", "OpenCode Zen", "Anthropic"])
|
||||
})
|
||||
|
||||
test("runs command authentication without interactive input", async () => {
|
||||
const requests: Array<{ method: string; path: string }> = []
|
||||
using server = authServer((request, url) => {
|
||||
|
||||
@@ -9,7 +9,7 @@ export type { ClientOptions, RequestOptions } from "./generated/client.js"
|
||||
|
||||
export function make(options: ClientOptions) {
|
||||
const raw = OpenCode.make(options)
|
||||
const events = SharedEvents.make((signal) => raw.event.subscribe({ signal }))
|
||||
const events = SharedEvents.make((signal, onActivity) => raw.event.subscribe({ signal, onActivity }))
|
||||
return {
|
||||
...raw,
|
||||
rpc: Object.assign(makeRpc(raw, events), raw.rpc),
|
||||
|
||||
@@ -278,6 +278,8 @@ export interface ClientOptions {
|
||||
export interface RequestOptions {
|
||||
readonly signal?: AbortSignal
|
||||
readonly headers?: RequestInit["headers"]
|
||||
/** Reports every chunk a streaming response receives, including keepalive comments that yield no event. */
|
||||
readonly onActivity?: () => void
|
||||
}
|
||||
|
||||
interface RequestDescriptor {
|
||||
@@ -369,6 +371,7 @@ export function make(options: ClientOptions) {
|
||||
} catch (cause) {
|
||||
throw new ClientError("Transport", { cause })
|
||||
}
|
||||
if (!next.done) requestOptions?.onActivity?.()
|
||||
buffer += decoder.decode(next.value, { stream: !next.done })
|
||||
if (buffer.length > maxSseEventBytes) throw new ClientError("SseEventTooLarge")
|
||||
const trailingCarriageReturn = !next.done && buffer.endsWith("\r")
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
export * as SharedEvents from "./shared-events.js"
|
||||
|
||||
export function make<A extends { readonly type: string }>(connect: (signal: AbortSignal) => AsyncIterable<A>) {
|
||||
export type SubscribeOptions = {
|
||||
readonly signal?: AbortSignal
|
||||
/** Reports transport activity on the shared stream, including keepalive frames that carry no event. */
|
||||
readonly onActivity?: () => void
|
||||
}
|
||||
|
||||
export function make<A extends { readonly type: string }>(
|
||||
connect: (signal: AbortSignal, onActivity: () => void) => AsyncIterable<A>,
|
||||
) {
|
||||
type Completion = { readonly error: unknown } | Record<string, never>
|
||||
type Subscriber = {
|
||||
push: (value: A) => void
|
||||
finish: (completion: Completion) => void
|
||||
activity?: () => void
|
||||
}
|
||||
type Connection = {
|
||||
controller: AbortController
|
||||
@@ -26,7 +35,9 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
|
||||
let completion: Completion = {}
|
||||
try {
|
||||
if (connection.controller.signal.aborted) return
|
||||
iterator = connect(connection.controller.signal)[Symbol.asyncIterator]()
|
||||
iterator = connect(connection.controller.signal, () => {
|
||||
connection.subscribers.forEach((subscriber) => subscriber.activity?.())
|
||||
})[Symbol.asyncIterator]()
|
||||
while (!connection.controller.signal.aborted) {
|
||||
const item = await iterator.next()
|
||||
if (item.done || connection.controller.signal.aborted) break
|
||||
@@ -47,7 +58,7 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
|
||||
}
|
||||
|
||||
return {
|
||||
subscribe(options?: { readonly signal?: AbortSignal }): AsyncIterable<A> {
|
||||
subscribe(options?: SubscribeOptions): AsyncIterable<A> {
|
||||
return {
|
||||
[Symbol.asyncIterator]() {
|
||||
const pending: ReturnType<typeof Promise.withResolvers<IteratorResult<A>>>[] = []
|
||||
@@ -72,6 +83,7 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
|
||||
}
|
||||
|
||||
const subscriber: Subscriber = {
|
||||
activity: options?.onActivity,
|
||||
finish(result) {
|
||||
finish(result, false)
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { batch, onCleanup, onMount } from "solid-js"
|
||||
import { batch, onCleanup } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "../promise"
|
||||
|
||||
@@ -18,6 +18,11 @@ export type ClientConnectionOptions = {
|
||||
readonly onEvent: (event: OpenCodeEvent) => void
|
||||
readonly flushInterval?: number
|
||||
readonly pageLifecycle?: boolean
|
||||
/**
|
||||
* Abort and reconnect a stream that receives no bytes for this long. The server writes a keepalive
|
||||
* comment every 15 seconds, so a quiet but healthy stream never trips this.
|
||||
*/
|
||||
readonly idleTimeout?: number
|
||||
readonly log?: {
|
||||
readonly debug?: (message: string, data?: Readonly<Record<string, unknown>>) => void
|
||||
readonly info?: (message: string, data?: Readonly<Record<string, unknown>>) => void
|
||||
@@ -27,10 +32,15 @@ export type ClientConnectionOptions = {
|
||||
const connectTimeout = 2_000
|
||||
const reconnectDelay = 1_000
|
||||
const connectionHistoryLimit = 50
|
||||
export const defaultIdleTimeout = 45_000
|
||||
// Longer than one server keepalive interval: a stream that is silent this long when the page
|
||||
// returns to the foreground is probably half-open after the device slept.
|
||||
export const foregroundIdleThreshold = 20_000
|
||||
|
||||
export function createClientConnection(initialApi: OpenCodeClient, options: ClientConnectionOptions) {
|
||||
const abort = new AbortController()
|
||||
const history: ClientConnectionEvent[] = []
|
||||
const idleTimeout = options.idleTimeout ?? defaultIdleTimeout
|
||||
const [connection, setConnection] = createStore<{
|
||||
status: ClientConnectionStatus
|
||||
attempt: number
|
||||
@@ -40,9 +50,12 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
let pending: OpenCodeEvent[] = []
|
||||
let flushTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let stream: AbortController | undefined
|
||||
let current: AbortController | undefined
|
||||
let run: Promise<void> | undefined
|
||||
let started = false
|
||||
let generation = 0
|
||||
let lastActivity = 0
|
||||
let forced = false
|
||||
|
||||
function record(status: ClientConnectionEvent["data"]["status"], attempt: number, error?: string) {
|
||||
history.push({ type: "client.connection", created: Date.now(), data: { status, attempt, error } })
|
||||
@@ -63,14 +76,25 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
async function connect(signal: AbortSignal, attempt: number) {
|
||||
let connectedAt: number | undefined
|
||||
const request = new AbortController()
|
||||
current = request
|
||||
const cancel = () => request.abort(signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
// Any received bytes, including keepalive comments, push the stall deadline out. A timer whose
|
||||
// deadline passed while the page was suspended fires as soon as the page resumes.
|
||||
let watchdog: ReturnType<typeof setTimeout> | undefined
|
||||
const touch = () => {
|
||||
lastActivity = Date.now()
|
||||
if (connectedAt === undefined) return
|
||||
clearTimeout(watchdog)
|
||||
watchdog = setTimeout(() => request.abort(new Error("Event stream stalled")), idleTimeout)
|
||||
}
|
||||
|
||||
try {
|
||||
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
|
||||
options.log?.info?.("event stream connecting", { attempt })
|
||||
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const iterator = api.event.subscribe({ signal: request.signal, onActivity: touch })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (first.done)
|
||||
@@ -85,6 +109,7 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
clearTimeout(timeout)
|
||||
record("connected", attempt)
|
||||
connectedAt = Date.now()
|
||||
touch()
|
||||
options.log?.info?.("event stream connected")
|
||||
publish(first.value)
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
@@ -92,7 +117,13 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
while (!signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
|
||||
if (event.done)
|
||||
return {
|
||||
error:
|
||||
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected"),
|
||||
connectedAt,
|
||||
}
|
||||
touch()
|
||||
if ("durable" in event.value && event.value.durable)
|
||||
options.log?.debug?.("event", {
|
||||
type: event.value.type,
|
||||
@@ -106,7 +137,9 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
return { error, connectedAt }
|
||||
} finally {
|
||||
request.abort()
|
||||
if (current === request) current = undefined
|
||||
clearTimeout(timeout)
|
||||
clearTimeout(watchdog)
|
||||
signal.removeEventListener("abort", cancel)
|
||||
}
|
||||
}
|
||||
@@ -140,6 +173,11 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
if (attempt === 1) continue
|
||||
}
|
||||
}
|
||||
// A deliberate resync already knows the old socket is gone; reconnect without backing off.
|
||||
if (forced) {
|
||||
forced = false
|
||||
continue
|
||||
}
|
||||
await wait(reconnectDelay, controller.signal)
|
||||
}
|
||||
}
|
||||
@@ -147,6 +185,7 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
function start() {
|
||||
if (started) return run
|
||||
started = true
|
||||
forced = false
|
||||
const active = ++generation
|
||||
const previous = run
|
||||
const current = (async () => {
|
||||
@@ -161,26 +200,45 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
}
|
||||
|
||||
function stop() {
|
||||
if (!started) return
|
||||
started = false
|
||||
generation += 1
|
||||
stream?.abort()
|
||||
// Nothing is listening once stopped, so consumers must treat their data as stale until start() reconnects.
|
||||
setConnection({ status: "connecting", attempt: 0, error: undefined })
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (options.pageLifecycle) {
|
||||
const pagehide = () => stop()
|
||||
const pageshow = (event: PageTransitionEvent) => {
|
||||
if (event.persisted) void start()
|
||||
}
|
||||
window.addEventListener("pagehide", pagehide)
|
||||
window.addEventListener("pageshow", pageshow)
|
||||
onCleanup(() => {
|
||||
window.removeEventListener("pagehide", pagehide)
|
||||
window.removeEventListener("pageshow", pageshow)
|
||||
})
|
||||
// Drop the live request so the reconnect loop replaces it now instead of waiting for the idle watchdog.
|
||||
function resync(reason: string) {
|
||||
if (!started || connection.status !== "connected") return
|
||||
options.log?.info?.("event stream resync", { reason, idle: Date.now() - lastActivity })
|
||||
forced = true
|
||||
current?.abort(new Error(reason))
|
||||
}
|
||||
|
||||
if (options.pageLifecycle) {
|
||||
const pagehide = () => stop()
|
||||
const pageshow = () => void start()
|
||||
// Locking a phone or switching apps hides the document without a pagehide; the socket usually
|
||||
// dies while the page is suspended, and the browser may never report that on the hung read.
|
||||
const visibility = () => {
|
||||
if (document.visibilityState !== "visible") return
|
||||
if (Date.now() - lastActivity < foregroundIdleThreshold) return
|
||||
resync("Page returned to the foreground after the event stream went quiet")
|
||||
}
|
||||
void start()
|
||||
})
|
||||
const online = () => resync("Network connection restored")
|
||||
window.addEventListener("pagehide", pagehide)
|
||||
window.addEventListener("pageshow", pageshow)
|
||||
window.addEventListener("online", online)
|
||||
document.addEventListener("visibilitychange", visibility)
|
||||
onCleanup(() => {
|
||||
window.removeEventListener("pagehide", pagehide)
|
||||
window.removeEventListener("pageshow", pageshow)
|
||||
window.removeEventListener("online", online)
|
||||
document.removeEventListener("visibilitychange", visibility)
|
||||
})
|
||||
}
|
||||
void start()
|
||||
|
||||
onCleanup(() => {
|
||||
stop()
|
||||
@@ -195,6 +253,7 @@ export function createClientConnection(initialApi: OpenCodeClient, options: Clie
|
||||
error: () => connection.error,
|
||||
internal: {
|
||||
history: () => history.slice(),
|
||||
resync,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,8 @@ export type CreateDataInput = {
|
||||
|
||||
const messageIDFromEvent = (eventID: string) => eventID.replace(/^evt_/, "msg_")
|
||||
const messagePageLimit = 20
|
||||
// Trailing window for event bursts that each ask for the same refetch.
|
||||
export const settleMs = 150
|
||||
|
||||
// Global MCP elicitations temporarily use "global" instead of a real session ID, so the
|
||||
// server cannot recover their Location when settling them. Preserve the event Location
|
||||
@@ -141,12 +143,18 @@ function formRequestOptions(sessionID: string, ref?: LocationRef) {
|
||||
}
|
||||
|
||||
function createSync() {
|
||||
type Pending = { promise: Promise<void>; invalidated: boolean }
|
||||
// `started` is false while a reload waits for the load it replaces. Invalidations that land in
|
||||
// that window are already covered, since the reload has not read anything yet.
|
||||
type Pending = { promise: Promise<void>; invalidated: boolean; started: boolean }
|
||||
const state = new Map<string, true | Pending>()
|
||||
const start = (key: string, load: () => Promise<void>, wait?: Promise<void>) => {
|
||||
const entry: Pending = { promise: Promise.resolve(), invalidated: false }
|
||||
const entry: Pending = { promise: Promise.resolve(), invalidated: false, started: !wait }
|
||||
state.set(key, entry)
|
||||
entry.promise = (wait ? wait.catch(() => undefined).then(load) : load())
|
||||
const run = () => {
|
||||
entry.started = true
|
||||
return load()
|
||||
}
|
||||
entry.promise = (wait ? wait.catch(() => undefined).then(run) : run())
|
||||
.then(() => {
|
||||
if (state.get(key) === entry && !entry.invalidated) state.set(key, true)
|
||||
})
|
||||
@@ -178,12 +186,12 @@ function createSync() {
|
||||
if (key) {
|
||||
const active = state.get(key)
|
||||
if (active === true) state.delete(key)
|
||||
if (active !== undefined && active !== true) active.invalidated = true
|
||||
if (active !== undefined && active !== true && active.started) active.invalidated = true
|
||||
return
|
||||
}
|
||||
state.forEach((active, current) => {
|
||||
if (active === true) state.delete(current)
|
||||
if (active !== true) active.invalidated = true
|
||||
if (active !== true && active.started) active.invalidated = true
|
||||
})
|
||||
},
|
||||
}
|
||||
@@ -203,6 +211,20 @@ export function createData(config: CreateDataInput) {
|
||||
})
|
||||
}
|
||||
|
||||
// Runs `load` once a burst of same-key events goes quiet, so N events cost one refetch.
|
||||
const settling = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
onCleanup(() => settling.forEach((timer) => clearTimeout(timer)))
|
||||
function settle(key: string, load: () => Promise<unknown>) {
|
||||
clearTimeout(settling.get(key))
|
||||
settling.set(
|
||||
key,
|
||||
setTimeout(() => {
|
||||
settling.delete(key)
|
||||
refresh(load)
|
||||
}, settleMs),
|
||||
)
|
||||
}
|
||||
|
||||
const [store, setStore] = createStore<Store>({
|
||||
session: {
|
||||
info: {},
|
||||
@@ -1226,10 +1248,11 @@ export function createData(config: CreateDataInput) {
|
||||
refresh(() => result.location.websearch.refresh(location))
|
||||
break
|
||||
// Authenticating an MCP integration reconnects its server, which emits mcp.status.changed,
|
||||
// so the mcp list syncs here rather than off integration.updated.
|
||||
// so the mcp list syncs here rather than off integration.updated. The server emits one event
|
||||
// per MCP server as each settles, so a location booting nine servers emitted nine refetches.
|
||||
case "mcp.status.changed":
|
||||
result.location.mcp.server.invalidate(location)
|
||||
refresh(() => result.location.mcp.server.sync(location))
|
||||
settle(`mcp.status:${locationKey(location)}`, () => result.location.mcp.server.sync(location))
|
||||
break
|
||||
case "mcp.resources.changed":
|
||||
result.location.mcp.resource.invalidate(location)
|
||||
|
||||
@@ -675,6 +675,31 @@ test("event.subscribe ignores server heartbeat comments", async () => {
|
||||
expect(received).toEqual([event])
|
||||
})
|
||||
|
||||
test("event.subscribe reports heartbeat comments as stream activity", async () => {
|
||||
const event = { id: "evt_sentinel", created: 1, type: "server.connected", data: {} }
|
||||
const encoder = new TextEncoder()
|
||||
const client = OpenCode.make({
|
||||
baseUrl: "http://localhost:3000",
|
||||
fetch: async () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode(": heartbeat\n\n"))
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
|
||||
controller.enqueue(encoder.encode(": heartbeat\n\n"))
|
||||
controller.close()
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "text/event-stream" } },
|
||||
),
|
||||
})
|
||||
let activity = 0
|
||||
const received = []
|
||||
for await (const item of client.event.subscribe({ onActivity: () => activity++ })) received.push(item)
|
||||
expect(received).toEqual([event])
|
||||
expect(activity).toBe(3)
|
||||
})
|
||||
|
||||
// Moved from packages/app/e2e/regression/session-timeline-transport.spec.ts
|
||||
test("event transport passes through ordinary health requests", async () => {
|
||||
const requests: string[] = []
|
||||
|
||||
@@ -359,3 +359,24 @@ test("synchronous source creation failures reject subscribers without automatic
|
||||
await expect(shared.subscribe()[Symbol.asyncIterator]().next()).rejects.toBe(failure)
|
||||
expect(attempts).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("source activity fans out to every subscriber that asked for it", async () => {
|
||||
const events = source()
|
||||
let activity: (() => void) | undefined
|
||||
const shared = SharedEvents.make<Event>((signal, onActivity) => {
|
||||
activity = onActivity
|
||||
return events.connect(signal)
|
||||
})
|
||||
const counts = { first: 0, second: 0 }
|
||||
const first = shared.subscribe({ onActivity: () => counts.first++ })[Symbol.asyncIterator]()
|
||||
const second = shared.subscribe()[Symbol.asyncIterator]()
|
||||
const reads = Promise.all([first.next(), second.next()])
|
||||
activity!()
|
||||
activity!()
|
||||
events.connections[0].push({ type: "server.connected" })
|
||||
await reads
|
||||
expect(counts).toEqual({ first: 2, second: 0 })
|
||||
await first.return!()
|
||||
await second.return!()
|
||||
await events.connections[0].closed
|
||||
})
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createClientConnection } from "../src/solid"
|
||||
import { OpenCode, type OpenCodeEvent } from "../src/promise"
|
||||
|
||||
const connected = { id: "evt_connected", created: 1, type: "server.connected", data: {} }
|
||||
|
||||
// One fake server whose event streams stay open until the test writes to them or the client aborts.
|
||||
function server() {
|
||||
const encoder = new TextEncoder()
|
||||
const streams: {
|
||||
write: (text: string) => void
|
||||
close: () => void
|
||||
aborted: boolean
|
||||
}[] = []
|
||||
const api = OpenCode.make({
|
||||
baseUrl: "http://opencode.local",
|
||||
fetch: async (input, init) => {
|
||||
const request = input instanceof Request ? input : new Request(input, init)
|
||||
let controller!: ReadableStreamDefaultController<Uint8Array>
|
||||
const entry = {
|
||||
write: (text: string) => controller.enqueue(encoder.encode(text)),
|
||||
close: () => controller.close(),
|
||||
aborted: false,
|
||||
}
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(value) {
|
||||
controller = value
|
||||
},
|
||||
cancel() {
|
||||
entry.aborted = true
|
||||
},
|
||||
})
|
||||
request.signal.addEventListener("abort", () => {
|
||||
entry.aborted = true
|
||||
controller.error(request.signal.reason)
|
||||
})
|
||||
streams.push(entry)
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } })
|
||||
},
|
||||
})
|
||||
return { api, streams }
|
||||
}
|
||||
|
||||
function setup(input: ReturnType<typeof server>, idleTimeout: number) {
|
||||
const events: OpenCodeEvent[] = []
|
||||
return createRoot((dispose) => ({
|
||||
events,
|
||||
dispose,
|
||||
connection: createClientConnection(input.api, {
|
||||
idleTimeout,
|
||||
flushInterval: 0,
|
||||
onEvent: (event) => events.push(event),
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
async function until(check: () => boolean, timeout = 2_000) {
|
||||
const deadline = Date.now() + timeout
|
||||
while (!check()) {
|
||||
if (Date.now() > deadline) throw new Error("Timed out waiting for condition")
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
}
|
||||
}
|
||||
|
||||
test("a stream that goes silent past the idle timeout is replaced", async () => {
|
||||
const fake = server()
|
||||
const ctx = setup(fake, 60)
|
||||
try {
|
||||
await until(() => fake.streams.length === 1)
|
||||
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected")
|
||||
|
||||
await until(() => fake.streams.length === 2)
|
||||
expect(fake.streams[0].aborted).toBe(true)
|
||||
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
|
||||
status: "disconnected",
|
||||
attempt: 1,
|
||||
error: "Event stream stalled",
|
||||
})
|
||||
|
||||
fake.streams[1].write(`data: ${JSON.stringify({ ...connected, id: "evt_connected_2" })}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected" && ctx.events.length === 2)
|
||||
expect(ctx.connection.error()).toBeUndefined()
|
||||
} finally {
|
||||
ctx.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("keepalive comments hold a quiet stream open", async () => {
|
||||
const fake = server()
|
||||
const ctx = setup(fake, 60)
|
||||
try {
|
||||
await until(() => fake.streams.length === 1)
|
||||
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected")
|
||||
|
||||
const heartbeat = setInterval(() => fake.streams[0].write(": heartbeat\n\n"), 20)
|
||||
await new Promise((resolve) => setTimeout(resolve, 250))
|
||||
clearInterval(heartbeat)
|
||||
|
||||
expect(fake.streams).toHaveLength(1)
|
||||
expect(fake.streams[0].aborted).toBe(false)
|
||||
expect(ctx.connection.status()).toBe("connected")
|
||||
expect(ctx.events).toHaveLength(1)
|
||||
} finally {
|
||||
ctx.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a forced resync replaces the stream immediately and only while connected", async () => {
|
||||
const fake = server()
|
||||
const ctx = setup(fake, 10_000)
|
||||
try {
|
||||
ctx.connection.internal.resync("too early")
|
||||
await until(() => fake.streams.length === 1)
|
||||
expect(fake.streams[0].aborted).toBe(false)
|
||||
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected")
|
||||
|
||||
const started = Date.now()
|
||||
ctx.connection.internal.resync("Network connection restored")
|
||||
await until(() => fake.streams.length === 2)
|
||||
expect(Date.now() - started).toBeLessThan(500)
|
||||
expect(fake.streams[0].aborted).toBe(true)
|
||||
expect(ctx.connection.internal.history().map((item) => item.data)).toContainEqual({
|
||||
status: "disconnected",
|
||||
attempt: 1,
|
||||
error: "Network connection restored",
|
||||
})
|
||||
fake.streams[1].write(`data: ${JSON.stringify(connected)}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected")
|
||||
} finally {
|
||||
ctx.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("a stream the server closes reconnects and reports the disconnect", async () => {
|
||||
const fake = server()
|
||||
const ctx = setup(fake, 10_000)
|
||||
try {
|
||||
await until(() => fake.streams.length === 1)
|
||||
fake.streams[0].write(`data: ${JSON.stringify(connected)}\n\n`)
|
||||
await until(() => ctx.connection.status() === "connected")
|
||||
|
||||
fake.streams[0].close()
|
||||
await until(() => ctx.connection.status() === "reconnecting")
|
||||
expect(ctx.connection.error()).toBe("Event stream disconnected")
|
||||
await until(() => fake.streams.length === 2)
|
||||
} finally {
|
||||
ctx.dispose()
|
||||
}
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createData, type CreateDataInput } from "../src/solid"
|
||||
import { createData, settleMs, type CreateDataInput } from "../src/solid"
|
||||
import { OpenCode, type OpenCodeEvent, type SessionInfo } from "../src/promise"
|
||||
|
||||
test("config reads and update refreshes are opt-in", async () => {
|
||||
@@ -165,3 +165,86 @@ test.each(["reconnecting", "disposed"] as const)("background reads respect %s ow
|
||||
expect(state.requests).toBe(1)
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
|
||||
test("a burst of mcp.status.changed events refetches the server list once it settles", async () => {
|
||||
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
|
||||
const requests: string[] = []
|
||||
const location = { directory: "/project" }
|
||||
const api = OpenCode.make({
|
||||
baseUrl: "http://opencode.local",
|
||||
fetch: async (input, init) => {
|
||||
const request = input instanceof Request ? input : new Request(input, init)
|
||||
requests.push(new URL(request.url).pathname)
|
||||
return Response.json({ location, data: [] })
|
||||
},
|
||||
})
|
||||
const setup = createRoot((dispose) => ({
|
||||
data: createData({
|
||||
api: () => api,
|
||||
directory: location.directory,
|
||||
event: {
|
||||
on: () => () => {},
|
||||
listen(handler) {
|
||||
listeners.add(handler)
|
||||
return () => listeners.delete(handler)
|
||||
},
|
||||
},
|
||||
}),
|
||||
dispose,
|
||||
}))
|
||||
try {
|
||||
await setup.data.location.mcp.server.sync()
|
||||
expect(requests.filter((path) => path === "/api/mcp")).toHaveLength(1)
|
||||
for (const server of ["a", "b", "c", "d", "e"]) {
|
||||
const event: OpenCodeEvent = { id: `evt_${server}`, created: 1, type: "mcp.status.changed", location, data: { server } }
|
||||
listeners.forEach((listener) => listener({ name: event.type, details: event }))
|
||||
}
|
||||
expect(requests.filter((path) => path === "/api/mcp")).toHaveLength(1)
|
||||
await new Promise((resolve) => setTimeout(resolve, settleMs * 2))
|
||||
expect(requests.filter((path) => path === "/api/mcp")).toHaveLength(2)
|
||||
} finally {
|
||||
setup.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("invalidations that land before a queued reload starts are absorbed by it", async () => {
|
||||
const pending: Array<PromiseWithResolvers<Response>> = []
|
||||
const location = { directory: "/project" }
|
||||
const api = OpenCode.make({
|
||||
baseUrl: "http://opencode.local",
|
||||
fetch: () => {
|
||||
const deferred = Promise.withResolvers<Response>()
|
||||
pending.push(deferred)
|
||||
return deferred.promise
|
||||
},
|
||||
})
|
||||
const setup = createRoot((dispose) => ({
|
||||
data: createData({
|
||||
api: () => api,
|
||||
directory: location.directory,
|
||||
event: { on: () => () => {}, listen: () => () => {} },
|
||||
}),
|
||||
dispose,
|
||||
}))
|
||||
try {
|
||||
const first = setup.data.location.agent.sync()
|
||||
expect(pending).toHaveLength(1)
|
||||
setup.data.location.agent.invalidate()
|
||||
const second = setup.data.location.agent.sync()
|
||||
setup.data.location.agent.invalidate()
|
||||
const third = setup.data.location.agent.sync()
|
||||
setup.data.location.agent.invalidate()
|
||||
expect(pending).toHaveLength(1)
|
||||
pending[0].resolve(Response.json({ location, data: [] }))
|
||||
await first
|
||||
await Promise.resolve()
|
||||
expect(pending).toHaveLength(2)
|
||||
pending[1].resolve(Response.json({ location, data: [{ name: "reviewer" }] }))
|
||||
await Promise.all([second, third])
|
||||
expect(pending).toHaveLength(2)
|
||||
await setup.data.location.agent.sync()
|
||||
expect(pending).toHaveLength(2)
|
||||
} finally {
|
||||
setup.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ FROM ${REGISTRY}/build/base:24.04
|
||||
SHELL ["/bin/bash", "-lc"]
|
||||
|
||||
ARG NODE_VERSION=24.4.0
|
||||
ARG BUN_VERSION=1.4.1
|
||||
ARG BUN_VERSION=1.4.2
|
||||
|
||||
ENV BUN_INSTALL=/opt/bun
|
||||
ENV PATH=/opt/bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
|
||||
@@ -100,7 +100,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/alibaba": "1.0.17",
|
||||
"@ai-sdk/amazon-bedrock": "4.0.112",
|
||||
"@ai-sdk/anthropic": "3.0.82",
|
||||
"@ai-sdk/azure": "3.0.88",
|
||||
"@ai-sdk/cohere": "3.0.27",
|
||||
@@ -112,7 +111,6 @@
|
||||
"@ai-sdk/provider": "3.0.8",
|
||||
"@ai-sdk/provider-utils": "4.0.23",
|
||||
"@ai-sdk/vercel": "2.0.39",
|
||||
"@aws-sdk/credential-providers": "3.1057.0",
|
||||
"@lydell/node-pty": "catalog:",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@ff-labs/fff-bun": "0.10.5",
|
||||
|
||||
@@ -195,7 +195,9 @@ function mapBedrockSettings(
|
||||
? { baseURL: settings.endpoint }
|
||||
: {}),
|
||||
...(apiKey === undefined ? {} : { apiKey }),
|
||||
...(settings.auth === "bearer" || settings.auth === "sigv4" ? { auth: settings.auth } : {}),
|
||||
...(credentials === undefined ? {} : { credentials }),
|
||||
...(typeof settings.profile === "string" ? { profile: settings.profile } : {}),
|
||||
...(typeof settings.region === "string" ? { region: settings.region } : {}),
|
||||
...(typeof settings.topP === "number" ? { topP: settings.topP } : {}),
|
||||
}
|
||||
|
||||
@@ -245,7 +245,8 @@ export const connect = Effect.fnUntraced(function* (
|
||||
|
||||
return yield* open(url).pipe(
|
||||
Effect.catch((error) => {
|
||||
if (!addedCodemode || !(error instanceof StreamableHTTPError) || error.code !== 404) return Effect.fail(error)
|
||||
if (!addedCodemode || !(error instanceof StreamableHTTPError) || (error.code !== 400 && error.code !== 404))
|
||||
return Effect.fail(error)
|
||||
// Some servers reject unknown query params. Retry once with the user's original URL.
|
||||
return open(new URL(config.url))
|
||||
}),
|
||||
|
||||
@@ -87,7 +87,7 @@ import { ProviderPlugins } from "./provider.js"
|
||||
import { WebSearchPlugins } from "./websearch/index.js"
|
||||
import { SkillPlugin } from "./skill.js"
|
||||
import { VcsHgPlugin } from "./vcs/hg.js"
|
||||
import { SystemPromptPlugin } from "./system-prompt.js"
|
||||
import { OptimizePlugin } from "./optimize.js"
|
||||
import { VariantPlugin } from "./variant.js"
|
||||
import { VcsGitPlugin } from "./vcs/git.js"
|
||||
import { WarmingPlugin } from "./warming.js"
|
||||
@@ -201,11 +201,12 @@ const pre = [
|
||||
CommandPlugin.Plugin,
|
||||
SkillPlugin.Plugin,
|
||||
VcsHgPlugin.Plugin,
|
||||
...SystemPromptPlugin.Plugins,
|
||||
ModelsDevPlugin,
|
||||
...ProviderPlugins,
|
||||
...WebSearchPlugins,
|
||||
PatchTool.Plugin,
|
||||
// Render model prompts after the patch plugin selects the available editing tools.
|
||||
...OptimizePlugin.Plugins,
|
||||
EditTool.Plugin,
|
||||
GlobTool.Plugin,
|
||||
GrepTool.Plugin,
|
||||
|
||||
@@ -2,14 +2,60 @@ export * as PluginModule from "./module.js"
|
||||
|
||||
import type { Plugin } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Host } from "@opencode-ai/plugin/host"
|
||||
import { createPluginSources } from "@opencode-ai/plugin/source"
|
||||
import { Npm } from "@opencode-ai/util/npm"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Deferred, Effect, FiberSet, PubSub, Schema, Stream } from "effect"
|
||||
import path from "path"
|
||||
import { stat } from "node:fs/promises"
|
||||
import { fileURLToPath, pathToFileURL } from "url"
|
||||
import type { ConfigPluginSource } from "../config/plugin/source.js"
|
||||
import type { Generation } from "../plugin.js"
|
||||
import { PluginPromise } from "./promise.js"
|
||||
import { Watcher } from "../filesystem/watcher.js"
|
||||
|
||||
export const make = Effect.fn("PluginModule.make")(function* () {
|
||||
const watcher = yield* Watcher.Service
|
||||
const scope = yield* Effect.scope
|
||||
const runPromise = yield* FiberSet.makeRuntimePromise()
|
||||
const changes = yield* PubSub.unbounded<void>()
|
||||
const watched = new Set<string>()
|
||||
const watch = Effect.fn("PluginModule.watch")(function* (file: string) {
|
||||
if (watched.has(file)) return
|
||||
watched.add(file)
|
||||
const ready = yield* Deferred.make<void>()
|
||||
const target = yield* Effect.promise(() => watchTarget(file))
|
||||
const updates = yield* watcher.subscribe(target, Deferred.succeed(ready, undefined))
|
||||
yield* updates.pipe(
|
||||
Stream.runForEach(() => PubSub.publish(changes, undefined)),
|
||||
Effect.ensuring(Deferred.succeed(ready, undefined)),
|
||||
Effect.forkIn(scope, { startImmediately: true }),
|
||||
)
|
||||
yield* Deferred.await(ready)
|
||||
})
|
||||
const sources = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => createPluginSources((file) => runPromise(watch(file)))),
|
||||
(sources) => Effect.sync(() => sources.dispose()),
|
||||
)
|
||||
return {
|
||||
load: (
|
||||
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
|
||||
options?: { readonly install?: boolean },
|
||||
) => load(operation, sources, options),
|
||||
changes: () => Stream.fromPubSub(changes),
|
||||
}
|
||||
})
|
||||
|
||||
// A missing dependency may have missing parents too. Watch the nearest existing
|
||||
// ancestor recursively so creating the rest of the path can trigger recovery.
|
||||
function watchTarget(file: string): Promise<Watcher.WatchInput> {
|
||||
return stat(file).then(
|
||||
(info) => ({ path: file, type: info.isDirectory() ? "directory" : "file" }),
|
||||
(cause) => {
|
||||
if (path.dirname(file) === file) throw cause
|
||||
return watchTarget(path.dirname(file))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const Module = Schema.Struct({
|
||||
default: Schema.Union([
|
||||
@@ -31,8 +77,9 @@ export class LoadError extends Schema.TaggedError<LoadError>()("PluginModule.Loa
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
|
||||
export const load = Effect.fn("PluginModule.load")(function* (
|
||||
const load = Effect.fn("PluginModule.load")(function* (
|
||||
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
|
||||
sources: ReturnType<typeof createPluginSources>,
|
||||
options?: { readonly install?: boolean },
|
||||
) {
|
||||
const local = path.isAbsolute(operation.target)
|
||||
@@ -51,12 +98,13 @@ export const load = Effect.fn("PluginModule.load")(function* (
|
||||
const entrypoint = entrypoints.server
|
||||
if (!local && options?.install === false && !entrypoint) return { pending: true as const }
|
||||
if (!entrypoint) return yield* new LoadError({ message: `Plugin entrypoint not found: ${operation.target}` })
|
||||
// Bun currently ignores query parameters when caching file:// imports.
|
||||
const target = typeof Bun !== "undefined" ? fileURLToPath(entrypoint).replaceAll("\\", "/") : entrypoint
|
||||
const source = operation.mtime === undefined ? entrypoint : `${target}?mtime=${operation.mtime}`
|
||||
yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint: source })
|
||||
const mod = yield* Effect.promise(() => Host.load(source))
|
||||
const value = (yield* Schema.decodeUnknownEffect(Module)(mod).pipe(
|
||||
yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint })
|
||||
const loaded = yield* Effect.promise(() =>
|
||||
local
|
||||
? sources.read(entrypoint)
|
||||
: Host.load(entrypoint).then((module) => ({ module, version: installed?.revision })),
|
||||
)
|
||||
const value = (yield* Schema.decodeUnknownEffect(Module)(loaded.module).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new LoadError({
|
||||
@@ -72,7 +120,7 @@ export const load = Effect.fn("PluginModule.load")(function* (
|
||||
...(entrypoints.tui ? { tui: true as const } : {}),
|
||||
...(entrypoints.rpc ? { rpc: true as const } : {}),
|
||||
},
|
||||
revision: JSON.stringify([operation, installed?.revision]),
|
||||
revision: JSON.stringify([operation, loaded.version]),
|
||||
source: path.isAbsolute(operation.target)
|
||||
? { type: "local" as const, path: fileURLToPath(entrypoint) }
|
||||
: {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
export * as OptimizePlugin from "./optimize.js"
|
||||
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
|
||||
import { Model } from "@opencode-ai/schema/model"
|
||||
import { Effect } from "effect"
|
||||
import { SessionSystemPrompt } from "../session/system-prompt.js"
|
||||
|
||||
import PROMPT_GPT from "./system-prompt/gpt.txt"
|
||||
import PROMPT_ASTRA from "./system-prompt/gpt-astra.txt"
|
||||
import PROMPT_KIMI from "./system-prompt/kimi.txt"
|
||||
import PROMPT_META from "./system-prompt/meta.txt"
|
||||
import PROMPT_TRINITY from "./system-prompt/trinity.txt"
|
||||
|
||||
export const OpenAIPlugin = make("opencode.prompt.openai", (model) => {
|
||||
const id = model.id.toLowerCase()
|
||||
if (!id.includes("gpt")) return undefined
|
||||
return id.includes("gpt-6") ? PROMPT_ASTRA : PROMPT_GPT
|
||||
})
|
||||
|
||||
export const OpenAIToolsPlugin = make("opencode.optimize.openai.tools", (model, tools) => {
|
||||
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
|
||||
if (!ids.includes("gpt")) return undefined
|
||||
delete tools.grep
|
||||
delete tools.glob
|
||||
return undefined
|
||||
})
|
||||
|
||||
export const AnthropicToolsPlugin = make("opencode.optimize.anthropic.tools", (model, tools) => {
|
||||
const ids = [model.id, model.modelID, model.family].join(" ").toLowerCase()
|
||||
if (!ids.includes("claude")) return undefined
|
||||
delete tools.grep
|
||||
delete tools.glob
|
||||
return undefined
|
||||
})
|
||||
|
||||
export const KimiPlugin = make("opencode.prompt.kimi", (model) =>
|
||||
model.id.toLowerCase().includes("kimi") ? PROMPT_KIMI : undefined,
|
||||
)
|
||||
export const ArceePlugin = make("opencode.prompt.arcee", (model) =>
|
||||
model.id.toLowerCase().includes("trinity") ? PROMPT_TRINITY : undefined,
|
||||
)
|
||||
export const MetaPlugin = make("opencode.prompt.meta", (model) => {
|
||||
if (!model.id.toLowerCase().includes("muse")) return undefined
|
||||
return PROMPT_META.replaceAll("{{MODEL_NAME}}", model.name)
|
||||
})
|
||||
|
||||
export const Plugins = [OpenAIPlugin, KimiPlugin, ArceePlugin, MetaPlugin] as const
|
||||
|
||||
function make(
|
||||
id: string,
|
||||
optimize: (model: Model.Info, tools: SessionHooks["context"]["tools"]) => string | undefined,
|
||||
) {
|
||||
return define({
|
||||
id,
|
||||
effect: Effect.fn(`OptimizePlugin.${id}`)(function* (ctx) {
|
||||
yield* ctx.session.hook("context", (event) =>
|
||||
Effect.gen(function* () {
|
||||
const model =
|
||||
(yield* ctx.catalog.model.list()).data.find(
|
||||
(model) => model.providerID === event.model.providerID && model.id === event.model.id,
|
||||
) ?? Model.Info.default(event.model.providerID, event.model.id)
|
||||
// Curate tools before rendering their guidance, including for agents with a custom system prompt.
|
||||
const template = optimize(model, event.tools)
|
||||
if (!template) return
|
||||
if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return
|
||||
const system = event.system[0]
|
||||
if (!system) return
|
||||
event.system[0] = { ...system, text: SessionSystemPrompt.render(template, Object.keys(event.tools)) }
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -1,123 +1,59 @@
|
||||
import { Effect } from "effect"
|
||||
import type { LanguageModelV3 } from "@ai-sdk/provider"
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Provider } from "../../provider.js"
|
||||
|
||||
type MantleSDK = {
|
||||
chat: (modelID: string) => LanguageModelV3
|
||||
responses: (modelID: string) => LanguageModelV3
|
||||
}
|
||||
// Ambient inputs the AWS default credential chain can turn into credentials
|
||||
// without any key stored in opencode. Mirrors the presence checks the AWS CLI
|
||||
// and SDK use before consulting shared config.
|
||||
const CHAIN_ENV = [
|
||||
"AWS_PROFILE",
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_WEB_IDENTITY_TOKEN_FILE",
|
||||
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
|
||||
"AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
]
|
||||
|
||||
// Bedrock cross-region inference profiles require regional prefixes only for
|
||||
// specific model/region combinations. Keep the mapping narrow and avoid
|
||||
// double-prefixing model IDs that models.dev already marks as global/us/eu/etc.
|
||||
function resolveModelID(modelID: string, region: string | undefined) {
|
||||
const crossRegionPrefixes = ["global.", "us.", "eu.", "jp.", "apac.", "au."]
|
||||
if (crossRegionPrefixes.some((prefix) => modelID.startsWith(prefix))) return modelID
|
||||
|
||||
const resolvedRegion = region ?? "us-east-1"
|
||||
const regionPrefix = resolvedRegion.split("-")[0]
|
||||
if (regionPrefix === "us") {
|
||||
const requiresPrefix = ["nova-micro", "nova-lite", "nova-pro", "nova-premier", "nova-2", "claude", "deepseek"].some(
|
||||
(item) => modelID.includes(item),
|
||||
)
|
||||
if (requiresPrefix && !resolvedRegion.startsWith("us-gov")) return `${regionPrefix}.${modelID}`
|
||||
return modelID
|
||||
}
|
||||
if (regionPrefix === "eu") {
|
||||
const regionRequiresPrefix = [
|
||||
"eu-west-1",
|
||||
"eu-west-2",
|
||||
"eu-west-3",
|
||||
"eu-north-1",
|
||||
"eu-central-1",
|
||||
"eu-south-1",
|
||||
"eu-south-2",
|
||||
].some((item) => resolvedRegion.includes(item))
|
||||
const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((item) =>
|
||||
modelID.includes(item),
|
||||
)
|
||||
return regionRequiresPrefix && modelRequiresPrefix ? `${regionPrefix}.${modelID}` : modelID
|
||||
}
|
||||
if (regionPrefix !== "ap") return modelID
|
||||
|
||||
const australia = ["ap-southeast-2", "ap-southeast-4"].includes(resolvedRegion)
|
||||
if (australia && ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((item) => modelID.includes(item))) {
|
||||
return `au.${modelID}`
|
||||
}
|
||||
|
||||
const prefix = resolvedRegion === "ap-northeast-1" ? "jp" : "apac"
|
||||
return ["claude", "nova-lite", "nova-micro", "nova-pro"].some((item) => modelID.includes(item))
|
||||
? `${prefix}.${modelID}`
|
||||
: modelID
|
||||
}
|
||||
|
||||
function selectMantleModel(sdk: MantleSDK, modelID: string) {
|
||||
if (modelID === "openai.gpt-oss-safeguard-20b" || modelID === "openai.gpt-oss-safeguard-120b")
|
||||
return sdk.chat(modelID)
|
||||
return sdk.responses(modelID)
|
||||
const isBedrock = (item: { readonly package: string }) => {
|
||||
const name = Provider.packageName(item.package)
|
||||
return name.startsWith("@ai-sdk/amazon-bedrock") || name.startsWith("@opencode-ai/ai/providers/amazon-bedrock")
|
||||
}
|
||||
|
||||
export const AmazonBedrockPlugin = define({
|
||||
id: "opencode.provider.amazon.bedrock",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
yield* ctx.integration.transform((editor) => {
|
||||
// models.dev advertises AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and
|
||||
// AWS_REGION alongside the bearer token. Only the bearer token is a key;
|
||||
// the rest feed the SigV4 credential chain and must not become one.
|
||||
editor.method.update({
|
||||
integrationID: Provider.ID.amazonBedrock,
|
||||
method: { type: "env", names: ["AWS_BEARER_TOKEN_BEDROCK"] },
|
||||
})
|
||||
})
|
||||
yield* ctx.catalog.transform((evt) => {
|
||||
for (const item of evt.provider.list()) {
|
||||
if (!Provider.isAISDK(item.provider.package)) continue
|
||||
if (Provider.packageName(item.provider.package) !== "@ai-sdk/amazon-bedrock") continue
|
||||
if (!isBedrock(item.provider)) continue
|
||||
evt.provider.update(item.provider.id, (provider) => {
|
||||
if (typeof provider.settings?.endpoint !== "string") return
|
||||
// The AI SDK expects a base URL, but users configure Bedrock private/VPC
|
||||
// endpoints as `endpoint`; move it into the catalog endpoint URL once.
|
||||
provider.settings.baseURL = provider.settings.endpoint
|
||||
const settings = provider.settings ?? {}
|
||||
const chain = typeof settings.profile === "string" || CHAIN_ENV.some((name) => process.env[name])
|
||||
// SigV4 authenticates through the AWS default chain rather than a key
|
||||
// credential, so ambient AWS configuration is what makes Bedrock usable.
|
||||
if (chain && provider.activation === "auto") provider.activation = "enabled"
|
||||
// Same default the native package uses, made explicit here so catalog
|
||||
// `${AWS_REGION}` URLs resolve without any region configured.
|
||||
const region = process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? "us-east-1"
|
||||
provider.settings = {
|
||||
...settings,
|
||||
...(typeof settings.region !== "string" ? { region } : {}),
|
||||
// Users configure Bedrock private/VPC endpoints as `endpoint`; move it
|
||||
// into the catalog base URL once.
|
||||
...(typeof settings.baseURL !== "string" && typeof settings.endpoint === "string"
|
||||
? { baseURL: settings.endpoint }
|
||||
: {}),
|
||||
}
|
||||
delete provider.settings.endpoint
|
||||
})
|
||||
}
|
||||
})
|
||||
yield* ctx.aisdk.hook(
|
||||
"sdk",
|
||||
Effect.fn(function* (evt) {
|
||||
if (!["@ai-sdk/amazon-bedrock", "@ai-sdk/amazon-bedrock/mantle"].includes(evt.package)) return
|
||||
const options = { ...evt.options }
|
||||
const profile = typeof options.profile === "string" ? options.profile : process.env.AWS_PROFILE
|
||||
const region = typeof options.region === "string" ? options.region : (process.env.AWS_REGION ?? "us-east-1")
|
||||
const bearerToken =
|
||||
process.env.AWS_BEARER_TOKEN_BEDROCK ??
|
||||
(typeof options.bearerToken === "string" ? options.bearerToken : undefined)
|
||||
if (bearerToken && !process.env.AWS_BEARER_TOKEN_BEDROCK) process.env.AWS_BEARER_TOKEN_BEDROCK = bearerToken
|
||||
options.region = region
|
||||
if (typeof options.endpoint === "string") options.baseURL = options.endpoint
|
||||
if (!bearerToken && options.credentialProvider === undefined) {
|
||||
// Do not gate SDK creation on explicit AWS env vars. The default chain
|
||||
// also handles ~/.aws/credentials, SSO, process creds, and instance roles.
|
||||
const { fromNodeProviderChain } = yield* Effect.promise(() => import("@aws-sdk/credential-providers"))
|
||||
options.credentialProvider = fromNodeProviderChain(profile ? { profile } : {})
|
||||
}
|
||||
|
||||
if (evt.package === "@ai-sdk/amazon-bedrock/mantle") {
|
||||
const mod = yield* Effect.promise(() => import("@ai-sdk/amazon-bedrock/mantle"))
|
||||
evt.sdk = mod.createBedrockMantle(options)
|
||||
return
|
||||
}
|
||||
|
||||
const mod = yield* Effect.promise(() => import("@ai-sdk/amazon-bedrock"))
|
||||
evt.sdk = mod.createAmazonBedrock(options)
|
||||
}),
|
||||
)
|
||||
yield* ctx.aisdk.hook(
|
||||
"language",
|
||||
Effect.fn(function* (evt) {
|
||||
if (evt.model.providerID !== Provider.ID.amazonBedrock) return
|
||||
if (
|
||||
Provider.isAISDK(evt.model.package) &&
|
||||
Provider.packageName(evt.model.package) === "@ai-sdk/amazon-bedrock/mantle"
|
||||
) {
|
||||
evt.language = selectMantleModel(evt.sdk, evt.model.modelID ?? evt.model.id)
|
||||
return
|
||||
}
|
||||
const region = typeof evt.options.region === "string" ? evt.options.region : process.env.AWS_REGION
|
||||
evt.language = evt.sdk.languageModel(resolveModelID(evt.model.modelID ?? evt.model.id, region))
|
||||
}),
|
||||
)
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -261,6 +261,7 @@ export const GithubCopilotPlugin = define({
|
||||
.pipe(Effect.orElseSucceed(() => undefined))
|
||||
const interaction = interactionType(evt.kind, session?.parentID !== undefined)
|
||||
evt.headers["X-Interaction-Type"] = interaction
|
||||
evt.headers["X-Interaction-Id"] = evt.sessionID
|
||||
if (interaction !== "conversation-agent") evt.headers["x-initiator"] = "agent"
|
||||
}),
|
||||
{ providerID: Provider.ID.githubCopilot },
|
||||
|
||||
@@ -13,8 +13,10 @@ import { PluginInternal } from "./internal.js"
|
||||
import { PluginModule } from "./module.js"
|
||||
import { SdkPlugins } from "./sdk.js"
|
||||
import { PluginUpdate } from "./update.js"
|
||||
import { Watcher } from "../filesystem/watcher.js"
|
||||
|
||||
const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
|
||||
modules: Effect.Success<ReturnType<typeof PluginModule.make>>,
|
||||
pre: readonly Plugin.Generation[],
|
||||
post: readonly Plugin.Generation[],
|
||||
operations: readonly ConfigPluginSource.Operation[],
|
||||
@@ -53,7 +55,7 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
|
||||
continue
|
||||
}
|
||||
|
||||
const plugin = yield* PluginModule.load(operation, { install }).pipe(
|
||||
const plugin = yield* modules.load(operation, { install }).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
const ref = `err_${crypto.randomUUID().slice(0, 8)}`
|
||||
const error = Cause.squash(cause)
|
||||
@@ -117,6 +119,7 @@ export const layer = Layer.effectDiscard(
|
||||
const sdk = yield* SdkPlugins.Service
|
||||
const instance = yield* InstancePlugins.Service
|
||||
const sources = yield* ConfigPluginSource.Service
|
||||
const modules = yield* PluginModule.make()
|
||||
const bus = yield* Bus.Service
|
||||
const updates = yield* PluginUpdate.Service
|
||||
const internal = yield* PluginInternal.list()
|
||||
@@ -149,7 +152,7 @@ export const layer = Layer.effectDiscard(
|
||||
}))
|
||||
const operations = yield* sources.operations()
|
||||
// Activate everything available locally before waiting on missing package installs.
|
||||
const immediate = yield* resolve(pre, post, operations, false, running)
|
||||
const immediate = yield* resolve(modules, pre, post, operations, false, running)
|
||||
const source = (source: Plugin.Source) =>
|
||||
source.type === "package"
|
||||
? {
|
||||
@@ -164,7 +167,9 @@ export const layer = Layer.effectDiscard(
|
||||
resolved.failures.map((failure) => ({ ...failure, source: source(failure.source) })),
|
||||
)
|
||||
yield* apply(immediate)
|
||||
const resolved = immediate.pending.length ? yield* resolve(pre, post, operations, true, running) : immediate
|
||||
const resolved = immediate.pending.length
|
||||
? yield* resolve(modules, pre, post, operations, true, running)
|
||||
: immediate
|
||||
if (resolved !== immediate) yield* apply(resolved)
|
||||
running = resolved.packages
|
||||
const targets = new Set(
|
||||
@@ -203,6 +208,7 @@ export const layer = Layer.effectDiscard(
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
yield* watch(sources.changes())
|
||||
yield* watch(modules.changes())
|
||||
yield* watch(Stream.fromEffectRepeat(Effect.sleep("24 hours")))
|
||||
yield* watch(bus.subscribe([Event.Updated, SdkPlugins.Updated]))
|
||||
yield* watch(
|
||||
@@ -240,6 +246,7 @@ const nodeDeps = [
|
||||
PluginUpdate.node,
|
||||
Bus.node,
|
||||
Npm.node,
|
||||
Watcher.node,
|
||||
PluginInternal.requirements,
|
||||
] as const
|
||||
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
export * as SystemPromptPlugin from "./system-prompt.js"
|
||||
|
||||
import { SystemPart } from "@opencode-ai/ai"
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Effect } from "effect"
|
||||
|
||||
import PROMPT_ANTHROPIC from "./system-prompt/anthropic.txt"
|
||||
import PROMPT_GPT from "./system-prompt/gpt-extension.txt"
|
||||
import PROMPT_KIMI from "./system-prompt/kimi.txt"
|
||||
import PROMPT_META from "./system-prompt/meta.txt"
|
||||
import PROMPT_TRINITY from "./system-prompt/trinity.txt"
|
||||
|
||||
export const OpenAIPlugin = make("openai", (id) => (id.includes("gpt") ? PROMPT_GPT : undefined), {
|
||||
operation: "append",
|
||||
})
|
||||
|
||||
export const AnthropicPlugin = make("anthropic", (id) => (id.includes("claude") ? PROMPT_ANTHROPIC : undefined), {
|
||||
operation: "replace",
|
||||
})
|
||||
export const KimiPlugin = make("kimi", (id) => (id.includes("kimi") ? PROMPT_KIMI : undefined), {
|
||||
operation: "replace",
|
||||
})
|
||||
export const ArceePlugin = make("arcee", (id) => (id.includes("trinity") ? PROMPT_TRINITY : undefined), {
|
||||
operation: "replace",
|
||||
})
|
||||
export const MetaPlugin = make(
|
||||
"meta",
|
||||
(id) => {
|
||||
if (!id.includes("muse")) return
|
||||
const name = id.includes("muse-glimmer") ? "Muse Glimmer" : "Muse Spark"
|
||||
return PROMPT_META.replaceAll("{{MODEL_NAME}}", name)
|
||||
},
|
||||
{ operation: "replace" },
|
||||
)
|
||||
|
||||
export const Plugins = [OpenAIPlugin, AnthropicPlugin, KimiPlugin, ArceePlugin, MetaPlugin] as const
|
||||
|
||||
function make(
|
||||
id: string,
|
||||
getPrompt: (modelID: string) => string | undefined,
|
||||
options: { operation: "replace" | "append" },
|
||||
) {
|
||||
return define({
|
||||
id: `opencode.prompt.${id}`,
|
||||
effect: Effect.fn(`SystemPromptPlugin.${id}`)(function* (ctx) {
|
||||
yield* ctx.session.hook("context", (event) =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* ctx.agent.get({ agentID: event.agent })).data.system) return
|
||||
const system = event.system[0]
|
||||
if (!system) return
|
||||
const model = (yield* ctx.catalog.model.list()).data.find(
|
||||
(model) => model.providerID === event.model.providerID && model.id === event.model.id,
|
||||
)
|
||||
const prompt = getPrompt(`${model?.modelID ?? event.model.id} ${model?.family ?? ""}`.toLowerCase())
|
||||
if (!prompt) return
|
||||
if (options.operation === "append") {
|
||||
event.system.splice(1, 0, SystemPart.make(prompt))
|
||||
return
|
||||
}
|
||||
event.system[0] = { ...system, text: prompt }
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
You are OpenCode, the best coding agent on the planet.
|
||||
|
||||
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
||||
|
||||
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
||||
|
||||
If the user asks for help or wants to give feedback inform them of the following:
|
||||
- ctrl+p to list available actions
|
||||
- To give feedback, users should report the issue at
|
||||
https://github.com/anomalyco/opencode
|
||||
|
||||
When the user directly asks about OpenCode (eg. "can OpenCode do...", "does OpenCode have..."), or asks in second person (eg. "are you able...", "can you do..."), or asks how to use a specific OpenCode feature (eg. implement a hook, write a slash command, or install an MCP server), use the webfetch tool to gather information to answer the question from OpenCode docs. The list of available docs is available at https://opencode.ai/v2/docs/
|
||||
|
||||
# Tone and style
|
||||
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
||||
- Your output will be displayed on a command line interface. Your responses should be short and concise. You can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
||||
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like the shell tool or code comments as means to communicate with the user during the session.
|
||||
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
|
||||
|
||||
# Professional objectivity
|
||||
Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if OpenCode honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs.
|
||||
|
||||
# Doing tasks
|
||||
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
||||
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
|
||||
|
||||
|
||||
# Tool usage policy
|
||||
- When doing file search, prefer to use the subagent tool in order to reduce context usage.
|
||||
- You should proactively use the subagent tool with specialized agents when the task at hand matches the agent's description.
|
||||
|
||||
- When webfetch returns a message about a redirect to a different host, you should immediately make a new webfetch request with the redirect URL provided in the response.
|
||||
- You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
|
||||
- If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple subagent tool calls.
|
||||
- Use specialized tools instead of shell commands when possible, as this provides a better user experience. For file operations, use dedicated tools: read for reading files instead of cat/head/tail, edit for editing instead of sed/awk, and write for creating files instead of cat with heredoc or echo redirection. Reserve the shell tool exclusively for actual system commands and terminal operations that require shell execution. NEVER use shell echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
|
||||
- VERY IMPORTANT: When exploring the codebase to gather context or to answer a question that is not a needle query for a specific file/class/function, it is CRITICAL that you use the subagent tool instead of running search commands directly.
|
||||
<example>
|
||||
user: Where are errors from the client handled?
|
||||
assistant: [Uses the subagent tool to find the files that handle client errors instead of using glob or grep directly]
|
||||
</example>
|
||||
<example>
|
||||
user: What is the codebase structure?
|
||||
assistant: [Uses the subagent tool]
|
||||
</example>
|
||||
|
||||
# Code References
|
||||
|
||||
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
|
||||
|
||||
<example>
|
||||
user: Where are errors from the client handled?
|
||||
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
|
||||
</example>
|
||||
@@ -0,0 +1,45 @@
|
||||
You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.
|
||||
|
||||
# Harness
|
||||
- Responses are rendered as GitHub-flavored Markdown.
|
||||
- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.
|
||||
- Prefer parallelizing independent tool calls.
|
||||
- Do not use a skill based solely on keywords, superficial relevance, or its availability. Avoid re-reading skills already available in the conversation unless needed.
|
||||
${OPENCODE_TOOL_GUIDANCE}
|
||||
|
||||
# Communication
|
||||
|
||||
State the main point clearly and early. Keep responses clear and concise, and avoid unnecessary technical jargon. Use only as much structure as needed, and include technical detail only when it helps the conversation. Use clear file paths when referring to files.
|
||||
|
||||
When describing your work, avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not introduce unprompted alternatives through framing such as "X, not Y" or "This isn't about X. It's about Y."
|
||||
|
||||
## Autonomy
|
||||
|
||||
Infer the user's intent and your task scope from their instructions and the prior conversation context. You should bias towards action and carry out the user's intended task until it is completed. If the intent is unclear, progress towards the goal using the available information and ask for clarification while continuing independent work when possible.
|
||||
|
||||
When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution to save time, effort, or tokens. Continue until the user's intended goal is fulfilled, even when it requires sustained work.
|
||||
|
||||
## Intermediate Commentary
|
||||
|
||||
As you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.
|
||||
|
||||
By default, treat new messages received during ongoing work as steering the active task rather than replacing it. Incorporate corrections and constraints, and answer questions briefly in commentary before continuing. Replace the task only when the user clearly cancels it or requests an incompatible objective.
|
||||
|
||||
Do not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.
|
||||
|
||||
## Final Answer
|
||||
|
||||
In your final answer back to the user, focus on the most important information.
|
||||
|
||||
# Working in codebases
|
||||
|
||||
- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.
|
||||
- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.
|
||||
- Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
|
||||
- Do not write tests for reversible, low-impact changes or that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
|
||||
- Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
|
||||
|
||||
|
||||
# Delegation
|
||||
|
||||
Do not spawn subagents unless the user or applicable AGENTS.md/skill instructions explicitly ask for subagents, delegation, or parallel agent work.
|
||||
+22
-2
@@ -1,10 +1,30 @@
|
||||
# Response channels
|
||||
You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.
|
||||
|
||||
# Harness
|
||||
- Responses are rendered as GitHub-flavored Markdown.
|
||||
- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.
|
||||
- Prefer parallelizing independent tool calls.
|
||||
${OPENCODE_TOOL_GUIDANCE}
|
||||
|
||||
# Communication
|
||||
|
||||
Use clear file paths when referring to files. Keep responses clear and concise, and avoid unnecessary technical jargon.
|
||||
|
||||
## Intermediate Commentary
|
||||
|
||||
As you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.
|
||||
|
||||
By default, treat new messages received during ongoing work as steering the active task rather than replacing it. Incorporate corrections and constraints, and answer questions briefly in commentary before continuing. Replace the task only when the user clearly cancels it or requests an incompatible objective.
|
||||
|
||||
Do not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.
|
||||
|
||||
In the final answer, lead with the outcome, not the steps you took to reach it. Cover the most important information, use only as much structure as the answer needs, and skip explanation the user did not ask for. Include technical detail only where it helps.
|
||||
## Final Answer
|
||||
|
||||
In the final answer, lead with the outcome, not the steps you took to reach it. Cover the most important information, use only as much structure as the answer needs, and avoid long-winded explanations unless necessary. Include technical detail only where it helps.
|
||||
|
||||
# Working in codebases
|
||||
- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.
|
||||
- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.
|
||||
|
||||
# Delegation
|
||||
|
||||
@@ -3,10 +3,15 @@ export * as SessionSystemPrompt from "./system-prompt.js"
|
||||
import PROMPT from "./runner/prompt/system.txt"
|
||||
|
||||
export function make(tools: string[]) {
|
||||
return render(PROMPT, tools)
|
||||
}
|
||||
|
||||
export function render(prompt: string, tools: string[]) {
|
||||
const instructions: string[] = []
|
||||
if (tools.includes("shell")) {
|
||||
instructions.push(
|
||||
"- Prefer dedicated tools over shell commands; fall back to the shell when a tool cannot do what you need.",
|
||||
"- Do not chain shell commands with separators like `echo \"====\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.",
|
||||
)
|
||||
}
|
||||
if (tools.includes("write")) {
|
||||
@@ -19,5 +24,5 @@ export function make(tools: string[]) {
|
||||
"- Use the edit tool for targeted changes to existing text files. It replaces the exact text in `oldString` with `newString`, and the values must differ. By default, `oldString` must occur exactly once. If it occurs multiple times, include more surrounding context to make it unique or set `replaceAll` to true to replace every occurrence.",
|
||||
)
|
||||
}
|
||||
return PROMPT.replace("${OPENCODE_TOOL_GUIDANCE}", instructions.join("\n"))
|
||||
return prompt.replace("${OPENCODE_TOOL_GUIDANCE}", instructions.join("\n"))
|
||||
}
|
||||
|
||||
@@ -311,7 +311,6 @@ describe("AISDKNative", () => {
|
||||
region: "eu-west-1",
|
||||
},
|
||||
baseURL: "https://bedrock-mantle.${AWS_REGION}.api.aws/v1",
|
||||
profile: "ignored",
|
||||
credentialProvider: "ignored",
|
||||
fetch: "ignored",
|
||||
store: false,
|
||||
@@ -333,6 +332,19 @@ describe("AISDKNative", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("forwards Bedrock profile and auth mode for the default credential chain", () => {
|
||||
expect(
|
||||
map("@ai-sdk/amazon-bedrock", { profile: "work", auth: "sigv4", region: "eu-west-1" }, "anthropic.claude"),
|
||||
).toEqual({
|
||||
package: "@opencode-ai/ai/providers/amazon-bedrock",
|
||||
settings: { profile: "work", auth: "sigv4", region: "eu-west-1" },
|
||||
})
|
||||
expect(map("@ai-sdk/amazon-bedrock", { auth: "bogus" }, "anthropic.claude")).toEqual({
|
||||
package: "@opencode-ai/ai/providers/amazon-bedrock",
|
||||
settings: {},
|
||||
})
|
||||
})
|
||||
|
||||
test("maps the legacy Bedrock endpoint override", () => {
|
||||
expect(
|
||||
map(
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
"headers": {
|
||||
"content-type": "application/json"
|
||||
},
|
||||
"body": "{\"model\":\"gpt-4o-mini\",\"messages\":[{\"role\":\"system\",\"content\":\"You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.\\n\\n# Harness\\n- Responses are rendered as GitHub-flavored Markdown.\\n- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.\\n- Prefer parallelizing independent tool calls.\\n\\n\\n# Communication\\n- Use clear file paths when referring to files.\\n- Keep responses clear and concise, and avoid unnecessary technical jargon.\\n\\n# Working in codebases\\n- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.\\n- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.\\n\\n# Response channels\\n\\nAs you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.\\n\\nDo not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.\\n\\nIn the final answer, lead with the outcome, not the steps you took to reach it. Cover the most important information, use only as much structure as the answer needs, and skip explanation the user did not ask for. Include technical detail only where it helps.\\n\\n# Delegation\\n\\nDo not spawn subagents unless the user or applicable AGENTS.md/skill instructions explicitly ask for subagents, delegation, or parallel agent work.\\n\\n# Destructive actions\\n\\nDo not revert, reset, or discard changes you did not make. Never run destructive commands such as `git reset --hard`, `git checkout --`, or recursive deletes on broad paths unless the user clearly asked for that operation; if the target or scope is unclear, ask first. Prefer non-interactive git commands.\\n\\n# Autonomy\\n\\nDo not infer authorization for work beyond the user's request. Assumptions that help you make progress are fine as long as they stay within the user's intent and the scope of the task.\\n\"},{\"role\":\"user\",\"content\":\"Say hello in one short sentence.\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"store\":false,\"prompt_cache_key\":\"ses_runner_recorded\",\"max_completion_tokens\":20,\"temperature\":0}"
|
||||
"body": "{\"model\":\"gpt-4o-mini\",\"messages\":[{\"role\":\"system\",\"content\":\"You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.\\n\\n# Harness\\n- Responses are rendered as GitHub-flavored Markdown.\\n- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.\\n- Prefer parallelizing independent tool calls.\\n\\n\\n# Communication\\n\\nUse clear file paths when referring to files. Keep responses clear and concise, and avoid unnecessary technical jargon.\\n\\n## Intermediate Commentary\\n\\nAs you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.\\n\\nBy default, treat new messages received during ongoing work as steering the active task rather than replacing it. Incorporate corrections and constraints, and answer questions briefly in commentary before continuing. Replace the task only when the user clearly cancels it or requests an incompatible objective.\\n\\nDo not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.\\n\\n## Final Answer\\n\\nIn the final answer, lead with the outcome, not the steps you took to reach it. Cover the most important information, use only as much structure as the answer needs, and avoid long-winded explanations unless necessary. Include technical detail only where it helps.\\n\\n# Working in codebases\\n- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.\\n- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.\\n\\n# Delegation\\n\\nDo not spawn subagents unless the user or applicable AGENTS.md/skill instructions explicitly ask for subagents, delegation, or parallel agent work.\\n\\n# Destructive actions\\n\\nDo not revert, reset, or discard changes you did not make. Never run destructive commands such as `git reset --hard`, `git checkout --`, or recursive deletes on broad paths unless the user clearly asked for that operation; if the target or scope is unclear, ask first. Prefer non-interactive git commands.\\n\\n# Autonomy\\n\\nDo not infer authorization for work beyond the user's request. Assumptions that help you make progress are fine as long as they stay within the user's intent and the scope of the task.\\n\"},{\"role\":\"user\",\"content\":\"Say hello in one short sentence.\"}],\"stream\":true,\"stream_options\":{\"include_usage\":true},\"store\":false,\"prompt_cache_key\":\"ses_runner_recorded\",\"max_completion_tokens\":20,\"temperature\":0}"
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user