diff --git a/.env.example b/.env.example index c80886a8bf..067aad9cc6 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ -# Optional: T3 Cloud source builds -# Leave these unset to disable optional T3 Cloud features in local source builds. +# Optional: T3 Connect source builds +# Leave these unset to disable optional T3 Connect features in local source builds. # Release builds inject their public values at build time. Do not add server-side # secrets to this file. diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index 1f777ed291..94d4af17e4 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -1,4 +1,4 @@ -name: Deploy T3 Cloud relay +name: Deploy T3 Connect relay on: push: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f130bad5d..25109b01d2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -167,7 +167,7 @@ jobs: --github-output relay_public_config: - name: Resolve T3 Cloud public config + name: Resolve T3 Connect public config needs: preflight if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }} runs-on: blacksmith-8vcpu-ubuntu-2404 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e61587f653..339f796370 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.26", + "version": "0.0.27", "private": true, "type": "module", "main": "dist-electron/main.cjs", diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.ts index cffe157241..50706923fb 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.ts @@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd input.readMagicDnsName ?? readTailscaleStatus.pipe( Effect.map((status) => status.magicDnsName), - Effect.catch(() => Effect.succeed(null)), + Effect.orElseSucceed(() => null), ); const dnsName = input.statusJson === undefined diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 66b809b2ac..005c86e086 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -44,6 +44,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM continue; } + // Header items are decorative section labels for the web fallback only — + // Electron's native menu has no equivalent affordance, so we skip them. + if (sourceItem.header === true) { + continue; + } + const normalizedItem: ContextMenuItem = { id: sourceItem.id, label: sourceItem.label, diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index d73c6ecce8..f62f2d7d48 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -163,7 +163,7 @@ describe("DesktopWindow", () => { assert.isTrue( DesktopWindow.isSameOriginRendererNavigation({ applicationUrl: "http://127.0.0.1:3773/", - navigationUrl: "http://127.0.0.1:3773/settings/cloud", + navigationUrl: "http://127.0.0.1:3773/settings/connections", }), ); assert.isFalse( diff --git a/apps/marketing/src/components/TuxIcon.astro b/apps/marketing/src/components/TuxIcon.astro deleted file mode 100644 index a6f1b4902c..0000000000 --- a/apps/marketing/src/components/TuxIcon.astro +++ /dev/null @@ -1,53 +0,0 @@ ---- -interface Props { - class?: string; - idPrefix: string; -} - -const { class: className, idPrefix } = Astro.props; ---- - - diff --git a/apps/marketing/src/pages/download.astro b/apps/marketing/src/pages/download.astro index b9e0e0181e..76977ad4ce 100644 --- a/apps/marketing/src/pages/download.astro +++ b/apps/marketing/src/pages/download.astro @@ -47,7 +47,7 @@ import { RELEASES_URL } from "../lib/releases";
- +

Linux

diff --git a/apps/marketing/src/pages/index.astro b/apps/marketing/src/pages/index.astro index dd2ba30a71..0b76f35089 100644 --- a/apps/marketing/src/pages/index.astro +++ b/apps/marketing/src/pages/index.astro @@ -1,6 +1,5 @@ --- import Layout from "../layouts/Layout.astro"; -import TuxIcon from "../components/TuxIcon.astro"; import { tweets } from "../lib/tweets"; const desktopEndorsementRows = [ @@ -53,7 +52,7 @@ const mobileEndorsementRows = [ > - + Download for macOS @@ -360,7 +359,8 @@ const mobileEndorsementRows = [ - + + Download for macOS Windows · Linux · other @@ -548,7 +548,7 @@ const mobileEndorsementRows = [ :global([data-platform="mac"]) .dl-icon--apple { display: block; } :global([data-platform="win"]) .dl-icon--windows { display: block; } :global([data-platform="linux"]) .dl-icon--linux { display: block; } - :global(:not([data-platform])) .dl-icon--apple { display: block; } + :global(html:not([data-platform])) .dl-icon--apple { display: block; } /* Floating harness marks */ .hero-float { diff --git a/apps/mobile/README.md b/apps/mobile/README.md index f5be27c6c3..ad0242c271 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -16,7 +16,7 @@ This app has three variants: Run commands from `apps/mobile`. -T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the +T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See [`../../.env.example`](../../.env.example). diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx index b25de62686..85d2699c76 100644 --- a/apps/mobile/src/app/settings/index.tsx +++ b/apps/mobile/src/app/settings/index.tsx @@ -1,4 +1,4 @@ -import { useAuth, useUser, useUserProfileModal } from "@clerk/expo"; +import { useAuth, useUser } from "@clerk/expo"; import * as Notifications from "expo-notifications"; import { Link, Stack, useRouter } from "expo-router"; import { SymbolView } from "expo-symbols"; @@ -68,7 +68,6 @@ function ConfiguredSettingsRouteScreen() { const { push } = useRouter(); const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { user } = useUser(); - const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal(); const { savedConnectionsById } = useRemoteEnvironmentState(); const [notificationStatus, setNotificationStatus] = useState("checking"); const [liveActivityStatus, setLiveActivityStatus] = useState("checking"); @@ -266,15 +265,11 @@ function ConfiguredSettingsRouteScreen() { push("/settings/waitlist"); return; } - if (isUserProfileModalAvailable) { - void presentUserProfile(); - return; - } Alert.alert( "T3 Cloud unavailable", "Native T3 Cloud account management is not available in this build.", ); - }, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]); + }, [isLoaded, isSignedIn, push]); return ( diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index 16a7a74539..36544cf46c 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -572,7 +572,7 @@ describe("mobile cloud link environment client", () => { if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } - if (String(url).endsWith("/api/cloud/link-proof")) { + if (String(url).endsWith("/api/connect/link-proof")) { return Promise.resolve(Response.json(validLinkProof())); } return Promise.resolve(Response.json(validLinkResponse("env-other"))); @@ -631,7 +631,7 @@ describe("mobile cloud link environment client", () => { if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } - if (String(url).endsWith("/api/cloud/link-proof")) { + if (String(url).endsWith("/api/connect/link-proof")) { return Promise.resolve(Response.json(validLinkProof())); } return Promise.resolve( @@ -669,7 +669,7 @@ describe("mobile cloud link environment client", () => { if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } - if (String(url).endsWith("/api/cloud/link-proof")) { + if (String(url).endsWith("/api/connect/link-proof")) { return Promise.resolve(Response.json(validLinkProof())); } return Promise.resolve( @@ -713,7 +713,7 @@ describe("mobile cloud link environment client", () => { if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } - if (String(url).endsWith("/api/cloud/link-proof")) { + if (String(url).endsWith("/api/connect/link-proof")) { return Promise.resolve(Response.json(validLinkProof())); } if (String(url).endsWith("/v1/client/environment-links")) { diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index f72b35d175..bca1ac21bc 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -301,7 +301,7 @@ export function linkEnvironmentToCloud(input: { ), ); const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl); - const proof = yield* environmentClient.cloud + const proof = yield* environmentClient.connect .linkProof({ headers: { authorization: `Bearer ${localBearerToken}` }, payload: { @@ -336,7 +336,7 @@ export function linkEnvironmentToCloud(input: { link, }); - yield* environmentClient.cloud + yield* environmentClient.connect .relayConfig({ headers: { authorization: `Bearer ${localBearerToken}` }, payload: { diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index e267ae9a07..aa7d033236 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -10,7 +10,7 @@ import type { import { detectComposerTrigger, replaceTextRange, - serializeComposerMentionPath, + serializeComposerFileLink, type ComposerTrigger, } from "@t3tools/shared/composerTrigger"; import { TextInputWrapper } from "expo-paste-input"; @@ -419,7 +419,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer let replacement = ""; if (item.type === "path") { - replacement = `@${serializeComposerMentionPath(item.path)} `; + replacement = `${serializeComposerFileLink(item.path)} `; } else if (item.type === "skill") { replacement = `$${item.skill.name} `; } else if (item.type === "slash-command") { diff --git a/apps/server/package.json b/apps/server/package.json index 2043a74595..8ef9784ba7 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.26", + "version": "0.0.27", "license": "MIT", "repository": { "type": "git", @@ -22,7 +22,7 @@ "test": "vp test run" }, "dependencies": { - "@anthropic-ai/claude-agent-sdk": "^0.3.154", + "@anthropic-ai/claude-agent-sdk": "^0.3.170", "@effect/platform-bun": "catalog:", "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 1a38e489fb..2b5da74eef 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -22,6 +22,7 @@ const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1"; const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1"; const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT; +const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0"); const permissionOptionIds = { allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once", allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always", @@ -364,6 +365,10 @@ const program = Effect.gen(function* () { Effect.gen(function* () { const requestedSessionId = String(request.sessionId ?? sessionId); + if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) { + yield* Effect.sleep(`${promptDelayMs} millis`); + } + if (emitInterleavedAssistantToolCalls) { const toolCallId = "tool-call-1"; diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.ts index 5911bfd987..27a1d55e90 100644 --- a/apps/server/src/bin.test.ts +++ b/apps/server/src/bin.test.ts @@ -38,11 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts"; const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {} -const cloudCli = makeCli({ cloudEnabled: true }); -const noCloudCli = makeCli({ cloudEnabled: false }); +const connectCli = makeCli({ cloudEnabled: true }); +const noConnectCli = makeCli({ cloudEnabled: false }); const runCli = (args: ReadonlyArray, command = cli) => Command.runWith(command, { version: "0.0.0" })(args); -const runCloudCli = (args: ReadonlyArray) => runCli(args, cloudCli); +const runConnectCli = (args: ReadonlyArray) => runCli(args, connectCli); const runCliWithRuntime = (args: ReadonlyArray) => runCli(args).pipe(Effect.provide(CliRuntimeLayer)); @@ -179,9 +179,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { }), ); - it.effect("rejects cloud commands when public cloud configuration is missing", () => + it.effect("rejects connect commands when public configuration is missing", () => Effect.gen(function* () { - const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip); + const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip); if (!CliError.isCliError(error)) { assert.fail(`Expected CliError, got ${String(error)}`); @@ -189,20 +189,20 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { if (error._tag !== "ShowHelp") { assert.fail(`Expected ShowHelp, got ${error._tag}`); } - assert.deepEqual(error.commandPath, ["t3", "cloud"]); - assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration"); + assert.deepEqual(error.commandPath, ["t3", "connect"]); + assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration"); const output = (yield* TestConsole.errorLines).join("\n"); assert.include(output, "ERROR"); - assert.include(output, "missing T3 Cloud public configuration"); + assert.include(output, "missing T3 Connect public configuration"); }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))), ); - it.effect("reports fresh headless cloud state without requiring local configuration", () => + it.effect("reports fresh headless connect state without requiring local configuration", () => Effect.gen(function* () { const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-")); const { output } = yield* captureStdout( - runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]), + runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]), ); // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO. const status = JSON.parse(output) as { @@ -221,21 +221,21 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { }), ); - it.effect("reports actionable human-readable headless cloud state", () => + it.effect("reports actionable human-readable headless connect state", () => Effect.gen(function* () { const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-")); const { output } = yield* captureStdout( - runCloudCli(["cloud", "status", "--base-dir", baseDir]), + runConnectCli(["connect", "status", "--base-dir", baseDir]), ); - assert.include(output, "T3 Cloud\n Exposure: disabled"); + assert.include(output, "T3 Connect\n Exposure: disabled"); assert.include(output, " Authorization: missing"); assert.include(output, " Environment link: not provisioned"); - assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure."); + assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect."); }), ); - it.effect("logs in to headless cloud without enabling exposure", () => + it.effect("logs in to headless connect without enabling access", () => Effect.gen(function* () { const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-")); const { secretsDir } = yield* deriveServerPaths(baseDir, undefined); @@ -250,9 +250,11 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { }), ); - const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir])); + const login = yield* captureStdout( + runConnectCli(["connect", "login", "--base-dir", baseDir]), + ); const status = yield* captureStdout( - runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]), + runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]), ); // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO. const decoded = JSON.parse(status.output) as { @@ -260,24 +262,24 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { readonly authenticated: boolean; }; - assert.equal(login.output, "Signed in to T3 Cloud."); + assert.equal(login.output, "Signed in to T3 Connect."); assert.isFalse(decoded.desired); assert.isTrue(decoded.authenticated); }), ); - it.effect("disables headless cloud exposure without a running server", () => + it.effect("disables headless connect without a running server", () => Effect.gen(function* () { const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-")); const { output } = yield* captureStdout( - runCloudCli(["cloud", "unlink", "--base-dir", baseDir]), + runConnectCli(["connect", "unlink", "--base-dir", baseDir]), ); - assert.equal(output, "T3 Cloud exposure is disabled locally."); + assert.equal(output, "T3 Connect is disabled locally."); }), ); - it.effect("logs out of headless cloud and removes the stored CLI authorization", () => + it.effect("logs out of headless connect and removes the stored CLI authorization", () => Effect.gen(function* () { const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-")); const { secretsDir } = yield* deriveServerPaths(baseDir, undefined); @@ -286,10 +288,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => { writeFileSync(tokenPath, "invalid persisted token"); const { output } = yield* captureStdout( - runCloudCli(["cloud", "logout", "--base-dir", baseDir]), + runConnectCli(["connect", "logout", "--base-dir", baseDir]), ); - assert.equal(output, "Signed out of T3 Cloud locally."); + assert.equal(output, "Signed out of T3 Connect locally."); assert.isFalse(existsSync(tokenPath)); }), ); diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 04d5bdfada..ddfbf5e3ec 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -8,7 +8,7 @@ import * as CliError from "effect/unstable/cli/CliError"; import * as NetService from "@t3tools/shared/Net"; import packageJson from "../package.json" with { type: "json" }; import { authCommand } from "./cli/auth.ts"; -import { cloudCommand } from "./cli/cloud.ts"; +import { connectCommand } from "./cli/connect.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import { sharedServerCommandFlags } from "./cli/config.ts"; import { projectCommand } from "./cli/project.ts"; @@ -16,23 +16,23 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts"; const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); -const cloudPublicConfigMissingMessage = - "T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration."; +const connectPublicConfigMissingMessage = + "T3 Connect commands are unavailable: this build is missing T3 Connect public configuration."; -class CloudPublicConfigMissingError extends CliError.UserError { +class ConnectPublicConfigMissingError extends CliError.UserError { override get message() { - return cloudPublicConfigMissingMessage; + return connectPublicConfigMissingMessage; } } -const cloudUnavailableCommand = Command.make("cloud").pipe( - Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."), +const connectUnavailableCommand = Command.make("connect").pipe( + Command.withDescription("T3 Connect is unavailable in builds without public configuration."), Command.withHidden, Command.withHandler(() => Effect.fail( new CliError.ShowHelp({ - commandPath: ["t3", "cloud"], - errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })], + commandPath: ["t3", "connect"], + errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })], }), ), ), @@ -47,7 +47,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => serveCommand, authCommand, projectCommand, - cloudEnabled ? cloudCommand : cloudUnavailableCommand, + cloudEnabled ? connectCommand : connectUnavailableCommand, ]), ); diff --git a/apps/server/src/cli/cloud.test.ts b/apps/server/src/cli/connect.test.ts similarity index 98% rename from apps/server/src/cli/cloud.test.ts rename to apps/server/src/cli/connect.test.ts index 4dda50c0ce..5fce3bc1cd 100644 --- a/apps/server/src/cli/cloud.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -3,7 +3,7 @@ import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; -import { acquireRelayClientForLink } from "./cloud.ts"; +import { acquireRelayClientForLink } from "./connect.ts"; const managedExecutable = { status: "available", diff --git a/apps/server/src/cli/cloud.ts b/apps/server/src/cli/connect.ts similarity index 87% rename from apps/server/src/cli/cloud.ts rename to apps/server/src/cli/connect.ts index 78027d1e80..167fb75a37 100644 --- a/apps/server/src/cli/cloud.ts +++ b/apps/server/src/cli/connect.ts @@ -89,15 +89,15 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b ? "pending server startup" : "not provisioned"; const nextStep = !status.authenticated - ? "Run `t3 cloud link` to authorize and enable cloud exposure." + ? "Run `t3 connect link` to authorize and enable T3 Connect." : !status.desired - ? "Run `t3 cloud link` to enable cloud exposure." + ? "Run `t3 connect link` to enable T3 Connect." : !status.linked ? "Start T3 to provision the environment link and launch its managed tunnel." : undefined; return [ - "T3 Cloud", + "T3 Connect", ` Exposure: ${status.desired ? "enabled" : "disabled"}`, ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`, ` Environment link: ${provisioned}`, @@ -112,7 +112,7 @@ const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5); const confirmRelayClientInstall = (version: string) => Prompt.run( Prompt.confirm({ - message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`, + message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`, initial: false, }), ); @@ -169,7 +169,7 @@ const withCloudCliSessionToken = ( environmentAuth.issueSession({ scopes: [AuthRelayWriteScope], subject: "cloud-cli", - label: "t3 cloud cli", + label: "t3 connect cli", }), (issued) => run(issued.token), (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })), @@ -194,7 +194,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () { baseUrl: runtimeState.value.origin, }).pipe( Effect.flatMap((client) => - client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }), + client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }), ), Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT), ), @@ -249,24 +249,24 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: { if (liveResult.status === "failed") { yield* Console.warn( - `T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`, + `T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`, ); } else { - yield* Console.log("T3 Cloud exposure is disabled locally."); + yield* Console.log("T3 Connect is disabled locally."); } if (Exit.isFailure(relayResult)) { yield* Console.warn( options.clearAuthorization ? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.` - : `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`, + : `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`, ); } else if (relayResult.value.status === "revoked") { yield* Console.log("Revoked the relay-side environment record."); } if (options.clearAuthorization) { - yield* Console.log("Signed out of T3 Cloud locally."); + yield* Console.log("Signed out of T3 Connect locally."); } }); @@ -307,26 +307,26 @@ const runCloudCommand = ( return yield* run.pipe(Effect.provide(runtimeLayer)); }); -const cloudLoginCommand = Command.make("login", { +const connectLoginCommand = Command.make("login", { ...projectLocationFlags, }).pipe( - Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."), + Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."), Command.withHandler((flags) => runCloudCommand( flags, Effect.gen(function* () { const tokens = yield* CliTokenManager.CloudCliTokenManager; yield* tokens.get; - yield* Console.log("Signed in to T3 Cloud."); + yield* Console.log("Signed in to T3 Connect."); }), ), ), ); -const cloudLinkCommand = Command.make("link", { +const connectLinkCommand = Command.make("link", { ...projectLocationFlags, }).pipe( - Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."), + Command.withDescription("Authorize this environment for T3 Connect on next start."), Command.withHandler((flags) => runCloudCommand( flags, @@ -338,7 +338,7 @@ const cloudLinkCommand = Command.make("link", { reportRelayClientInstallProgress, ); if (Option.isNone(installed)) { - yield* Console.log("T3 Cloud link cancelled. The relay client was not installed."); + yield* Console.log("T3 Connect setup cancelled. The relay client was not installed."); return; } yield* Console.log( @@ -349,18 +349,18 @@ const cloudLinkCommand = Command.make("link", { yield* tokens.get; yield* CliState.setCliDesiredCloudLink(true); yield* Console.log( - "This T3 environment will be available over T3 Cloud the next time T3 starts.", + "This T3 environment will be available through T3 Connect the next time T3 starts.", ); }), ), ), ); -const cloudStatusCommand = Command.make("status", { +const connectStatusCommand = Command.make("status", { ...projectLocationFlags, json: jsonFlag, }).pipe( - Command.withDescription("Show persisted T3 Cloud and relay client state."), + Command.withDescription("Show persisted T3 Connect and relay client state."), Command.withHandler((flags) => runCloudCommand( flags, @@ -395,31 +395,31 @@ const cloudStatusCommand = Command.make("status", { ), ); -const cloudUnlinkCommand = Command.make("unlink", { +const connectUnlinkCommand = Command.make("unlink", { ...projectLocationFlags, }).pipe( - Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."), + Command.withDescription("Disable T3 Connect while retaining the stored authorization."), Command.withHandler((flags) => runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })), ), ); -const cloudLogoutCommand = Command.make("logout", { +const connectLogoutCommand = Command.make("logout", { ...projectLocationFlags, }).pipe( - Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."), + Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."), Command.withHandler((flags) => runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })), ), ); -export const cloudCommand = Command.make("cloud").pipe( - Command.withDescription("Manage headless T3 Cloud exposure."), +export const connectCommand = Command.make("connect").pipe( + Command.withDescription("Manage headless T3 Connect access."), Command.withSubcommands([ - cloudLoginCommand, - cloudLinkCommand, - cloudStatusCommand, - cloudUnlinkCommand, - cloudLogoutCommand, + connectLoginCommand, + connectLinkCommand, + connectStatusCommand, + connectUnlinkCommand, + connectLogoutCommand, ]), ); diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index c10b892293..765ef05833 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -96,7 +96,7 @@ const make = Effect.gen(function* () { const clear = secrets .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET) - .pipe(wrapError("Could not remove the stored T3 Cloud CLI credential.")); + .pipe(wrapError("Could not remove the stored T3 Connect CLI credential.")); const read = Effect.fn("cloud.cli_token.read")(function* () { const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET); @@ -146,7 +146,7 @@ const make = Effect.gen(function* () { const url = new URL(request.originalUrl, metadata.redirectUri); const code = url.searchParams.get("code"); if (url.searchParams.get("state") !== state || !code) { - return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", { + return HttpServerResponse.text("Invalid T3 Connect authorization callback.", { status: 400, }); } @@ -154,7 +154,7 @@ const make = Effect.gen(function* () { return yield* HttpServerResponse.html` -

T3 Cloud authorization complete

+

T3 Connect authorization complete

You can close this window and return to your terminal.

@@ -182,13 +182,13 @@ const make = Effect.gen(function* () { authorizationUrl.searchParams.set("state", state); authorizationUrl.searchParams.set("code_challenge", challenge); authorizationUrl.searchParams.set("code_challenge_method", "S256"); - yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`); + yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`); const code = yield* Deferred.await(callback).pipe( Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT), Effect.catchTag("TimeoutError", () => Effect.fail( new CloudCliTokenManagerError({ - message: "Timed out waiting for T3 Cloud authorization.", + message: "Timed out waiting for T3 Connect authorization.", }), ), ), @@ -213,12 +213,12 @@ const make = Effect.gen(function* () { }); const getExisting = semaphore.withPermits(1)( - getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")), + getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")), ); const hasCredential = semaphore.withPermits(1)( read().pipe( Effect.map(Option.isSome), - wrapError("Could not read the stored T3 Cloud CLI credential."), + wrapError("Could not read the stored T3 Connect CLI credential."), ), ); const get = semaphore.withPermits(1)( @@ -227,7 +227,7 @@ const make = Effect.gen(function* () { return Option.isSome(token) ? token.value : yield* Effect.scoped(login()).pipe(Effect.flatMap(persist)); - }).pipe(wrapError("Could not authorize the T3 Cloud CLI.")), + }).pipe(wrapError("Could not authorize the T3 Connect CLI.")), ); return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear }); diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 2b7e7d249e..799ab609f4 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -76,7 +76,7 @@ describe("reconcileDesiredCloudLink", () => { expect(error).toMatchObject({ _tag: "EnvironmentHttpUnauthorizedError", - message: "Run `t3 cloud link` to authorize this environment.", + message: "Run `t3 connect link` to authorize this environment.", }); }).pipe( Effect.provideService( diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 38203dae37..896990849b 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -509,7 +509,7 @@ const relayClientRequest = ( Effect.mapError( (cause) => new EnvironmentHttpInternalServerError({ - message: `T3 Cloud relay request failed: ${String(cause)}`, + message: `T3 Connect relay request failed: ${String(cause)}`, }), ), ); @@ -535,7 +535,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi onNone: () => Effect.fail( new EnvironmentHttpUnauthorizedError({ - message: "Run `t3 cloud link` to authorize this environment.", + message: "Run `t3 connect link` to authorize this environment.", }), ), onSome: Effect.succeed, @@ -595,7 +595,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi CloudCliTokenManagerError: (error) => failEnvironmentCloudInternalError(error.message)(error.cause), SecretStoreError: failEnvironmentCloudInternalError( - "Could not persist desired T3 Cloud link state.", + "Could not persist desired T3 Connect link state.", ), }), ); @@ -874,7 +874,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential") scopes: AuthStandardClientScopes, subject: "cloud-connect", ttl: Duration.minutes(2), - label: "T3 Cloud connect", + label: "T3 Connect connect", proofKeyThumbprint: proof.clientProofKeyThumbprint, }); const responsePayload = { @@ -924,9 +924,9 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential") }), ); -export const cloudHttpApiLayer = HttpApiBuilder.group( +export const connectHttpApiLayer = HttpApiBuilder.group( EnvironmentHttpApi, - "cloud", + "connect", Effect.fnUntraced(function* (handlers) { const dependencies = yield* cloudHttpDependencies; return handlers diff --git a/apps/server/src/codexModelOptions.test.ts b/apps/server/src/codexModelOptions.test.ts new file mode 100644 index 0000000000..d035a60a46 --- /dev/null +++ b/apps/server/src/codexModelOptions.test.ts @@ -0,0 +1,22 @@ +import { assert, it } from "@effect/vitest"; + +import { ProviderInstanceId } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; + +import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts"; + +it("returns the selected Codex service tier id", () => { + const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [ + { id: "serviceTier", value: "flex" }, + ]); + + assert.equal(getCodexServiceTierOptionValue(selection), "flex"); +}); + +it("keeps legacy persisted fast mode selections working", () => { + const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "fastMode", value: true }, + ]); + + assert.equal(getCodexServiceTierOptionValue(selection), "fast"); +}); diff --git a/apps/server/src/codexModelOptions.ts b/apps/server/src/codexModelOptions.ts new file mode 100644 index 0000000000..43b8a3c184 --- /dev/null +++ b/apps/server/src/codexModelOptions.ts @@ -0,0 +1,14 @@ +import type { ModelSelection } from "@t3tools/contracts"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, +} from "@t3tools/shared/model"; + +export function getCodexServiceTierOptionValue( + modelSelection: ModelSelection | null | undefined, +): string | undefined { + return ( + getModelSelectionStringOptionValue(modelSelection, "serviceTier") ?? + (getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined) + ); +} diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 5423f4f147..92ee9007b3 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { ); const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) { const details = yield* gitCore - .statusDetails(cwd) + .statusDetailsRemote(cwd) .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null))); if (details === null || !details.isRepo) { return null; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 369eea0f7a..5a997de366 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { }), ); + it.effect("keeps the turn running across interim assistant messages until the session ends", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-turn-lifecycle"); + const turnId = TurnId.make("turn-lifecycle-1"); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.make("evt-tl1"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-tl1"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-tl1"), + metadata: {}, + payload: { + threadId, + projectId: ProjectId.make("project-turn-lifecycle"), + title: "Turn lifecycle", + modelSelection: { + instanceId: ProviderInstanceId.make("claude"), + model: "claude-opus", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + yield* eventStore.append({ + type: "thread.session-set", + eventId: EventId.make("evt-tl2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: "2026-01-01T00:00:01.000Z", + commandId: CommandId.make("cmd-tl2"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-tl2"), + metadata: {}, + payload: { + threadId, + session: { + threadId, + status: "running", + providerName: "claude", + runtimeMode: "full-access", + activeTurnId: turnId, + lastError: null, + updatedAt: "2026-01-01T00:00:01.000Z", + }, + }, + }); + + // Interim assistant message completes mid-turn (commentary between + // tool calls) — the turn must stay running and unsettled. + yield* eventStore.append({ + type: "thread.message-sent", + eventId: EventId.make("evt-tl3"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: "2026-01-01T00:00:05.000Z", + commandId: CommandId.make("cmd-tl3"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-tl3"), + metadata: {}, + payload: { + threadId, + messageId: MessageId.make("message-tl-interim"), + role: "assistant", + text: "interim commentary", + turnId, + streaming: false, + createdAt: "2026-01-01T00:00:05.000Z", + updatedAt: "2026-01-01T00:00:05.000Z", + }, + }); + + yield* projectionPipeline.bootstrap; + + const runningRows = yield* sql<{ + readonly state: string; + readonly completedAt: string | null; + }>` + SELECT state, completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} AND turn_id = ${turnId} + `; + assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]); + + // The session leaving "running" is the turn-end signal. + yield* eventStore.append({ + type: "thread.session-set", + eventId: EventId.make("evt-tl4"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: "2026-01-01T00:01:00.000Z", + commandId: CommandId.make("cmd-tl4"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-tl4"), + metadata: {}, + payload: { + threadId, + session: { + threadId, + status: "ready", + providerName: "claude", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: "2026-01-01T00:01:00.000Z", + }, + }, + }); + + yield* projectionPipeline.bootstrap; + + const settledRows = yield* sql<{ + readonly state: string; + readonly completedAt: string | null; + }>` + SELECT state, completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} AND turn_id = ${turnId} + `; + assert.deepEqual(settledRows, [ + { state: "completed", completedAt: "2026-01-01T00:01:00.000Z" }, + ]); + }), + ); + + it.effect("settles a superseded running turn when a new turn becomes active", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = "2026-01-01T00:00:00.000Z"; + const threadId = ThreadId.make("thread-turn-supersede"); + const oldTurnId = TurnId.make("turn-superseded"); + const newTurnId = TurnId.make("turn-steer"); + + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.make("evt-ts1"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-ts1"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-ts1"), + metadata: {}, + payload: { + threadId, + projectId: ProjectId.make("project-turn-supersede"), + title: "Turn supersede", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "big-pickle", + }, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }); + + const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) => + eventStore.append({ + type: "thread.session-set", + eventId: EventId.make(eventId), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: updatedAt, + commandId: CommandId.make(`cmd-${eventId}`), + causationEventId: null, + correlationId: CorrelationId.make(`cmd-${eventId}`), + metadata: {}, + payload: { + threadId, + session: { + threadId, + status: "running", + providerName: "opencode", + runtimeMode: "full-access", + activeTurnId: turnId, + lastError: null, + updatedAt, + }, + }, + }); + + yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z"); + // A steer: a new turn becomes active without the provider ever + // completing the previous one. + yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z"); + + yield* projectionPipeline.bootstrap; + + const rows = yield* sql<{ + readonly turnId: string; + readonly state: string; + readonly completedAt: string | null; + }>` + SELECT turn_id AS "turnId", state, completed_at AS "completedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + ORDER BY requested_at + `; + assert.deepEqual(rows, [ + { turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" }, + { turnId: newTurnId, state: "running", completedAt: null }, + ]); + }), + ); + it.effect("keeps accumulated assistant text when completion payload text is empty", () => Effect.gen(function* () { const projectionPipeline = yield* OrchestrationProjectionPipeline; @@ -1656,6 +1877,142 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { }), ); + it.effect("clears stale pending user input from projected shell summaries", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const appendAndProject = (event: Parameters[0]) => + eventStore + .append(event) + .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); + + yield* appendAndProject({ + type: "project.created", + eventId: EventId.make("evt-stale-user-input-1"), + aggregateKind: "project", + aggregateId: ProjectId.make("project-stale-user-input"), + occurredAt: "2026-02-26T12:35:00.000Z", + commandId: CommandId.make("cmd-stale-user-input-1"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-stale-user-input-1"), + metadata: {}, + payload: { + projectId: ProjectId.make("project-stale-user-input"), + title: "Project Stale User Input", + workspaceRoot: "/tmp/project-stale-user-input", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-02-26T12:35:00.000Z", + updatedAt: "2026-02-26T12:35:00.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.created", + eventId: EventId.make("evt-stale-user-input-2"), + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-stale-user-input"), + occurredAt: "2026-02-26T12:35:01.000Z", + commandId: CommandId.make("cmd-stale-user-input-2"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-stale-user-input-2"), + metadata: {}, + payload: { + threadId: ThreadId.make("thread-stale-user-input"), + projectId: ProjectId.make("project-stale-user-input"), + title: "Thread Stale User Input", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-02-26T12:35:01.000Z", + updatedAt: "2026-02-26T12:35:01.000Z", + }, + }); + + yield* appendAndProject({ + type: "thread.activity-appended", + eventId: EventId.make("evt-stale-user-input-3"), + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-stale-user-input"), + occurredAt: "2026-02-26T12:35:02.000Z", + commandId: CommandId.make("cmd-stale-user-input-3"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-stale-user-input-3"), + metadata: {}, + payload: { + threadId: ThreadId.make("thread-stale-user-input"), + activity: { + id: EventId.make("activity-stale-user-input-requested"), + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + requestId: "user-input-request-stale-1", + questions: [ + { + id: "sandbox_mode", + header: "Sandbox", + question: "Which mode should be used?", + options: [ + { + label: "workspace-write", + description: "Allow workspace writes only", + }, + ], + }, + ], + }, + turnId: null, + createdAt: "2026-02-26T12:35:02.000Z", + }, + }, + }); + + yield* appendAndProject({ + type: "thread.activity-appended", + eventId: EventId.make("evt-stale-user-input-4"), + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-stale-user-input"), + occurredAt: "2026-02-26T12:35:03.000Z", + commandId: CommandId.make("cmd-stale-user-input-4"), + causationEventId: null, + correlationId: CorrelationId.make("cmd-stale-user-input-4"), + metadata: {}, + payload: { + threadId: ThreadId.make("thread-stale-user-input"), + activity: { + id: EventId.make("activity-stale-user-input-failed"), + tone: "error", + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + payload: { + requestId: "user-input-request-stale-1", + detail: + "Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1", + }, + turnId: null, + createdAt: "2026-02-26T12:35:03.000Z", + }, + }, + }); + + const threadRows = yield* sql<{ + readonly pendingUserInputCount: number; + }>` + SELECT pending_user_input_count AS "pendingUserInputCount" + FROM projection_threads + WHERE thread_id = 'thread-stale-user-input' + `; + assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]); + }), + ); + it.effect("ignores non-stale provider approval response failures", () => Effect.gen(function* () { const projectionPipeline = yield* OrchestrationProjectionPipeline; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 4a48de19d3..f12df85094 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -2,6 +2,7 @@ import { ApprovalRequestId, type ChatAttachment, type OrchestrationEvent, + type OrchestrationSessionStatus, ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = { type ProjectorName = (typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES]; +/** + * Turn state to settle still-running turns with when their session leaves the + * "running" status, or null while the session is (re)starting or running and + * turns must stay unsettled. + */ +function settledTurnStateForSessionStatus( + status: OrchestrationSessionStatus, +): "completed" | "interrupted" | "error" | null { + switch (status) { + case "idle": + case "ready": + return "completed"; + case "error": + return "error"; + case "interrupted": + case "stopped": + return "interrupted"; + case "starting": + case "running": + return null; + } +} + interface ProjectorDefinition { readonly name: ProjectorName; readonly apply: ( @@ -141,7 +165,9 @@ function derivePendingUserInputCountFromActivities( activity.kind === "provider.user-input.respond.failed" && detail !== null && (detail.includes("stale pending user-input request") || - detail.includes("unknown pending user-input request")) + detail.includes("unknown pending user-input request") || + detail.includes("unknown pending user input request") || + detail.includes("unknown pending codex user input request")) ) { openRequestIds.delete(requestId); } @@ -999,9 +1025,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.session-set": { const turnId = event.payload.session.activeTurnId; if (turnId === null || event.payload.session.status !== "running") { + // Leaving the "running" session status is the turn-end signal: + // settle still-running turns so their duration reflects the whole + // turn rather than the last assistant message. + const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status); + if (settledTurnState === null) { + return; + } + const existingTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach( + existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"), + (turn) => + turn.turnId === null + ? Effect.void + : projectionTurnRepository.upsertByTurnId({ + ...turn, + turnId: turn.turnId, + state: settledTurnState, + // A running turn's completedAt can only hold a mid-turn + // placeholder checkpoint timestamp — the session leaving + // "running" is the authoritative turn end. + completedAt: event.payload.session.updatedAt, + }), + { concurrency: 1 }, + ); return; } + // A new active turn supersedes any still-running turn on the same + // thread — steering can open a new turn without the provider ever + // completing the previous one. + const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + yield* Effect.forEach( + otherRunningTurns.filter( + (turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running", + ), + (turn) => + turn.turnId === null + ? Effect.void + : projectionTurnRepository.upsertByTurnId({ + ...turn, + turnId: turn.turnId, + state: "completed", + completedAt: event.payload.session.updatedAt, + }), + { concurrency: 1 }, + ); + const existingTurn = yield* projectionTurnRepository.getByTurnId({ threadId: event.payload.threadId, turnId, @@ -1080,6 +1154,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti if (event.payload.turnId === null || event.payload.role !== "assistant") { return; } + // A completed assistant message only settles the turn once the + // session is no longer running it — providers may emit several + // assistant messages per turn (commentary between tool calls), and + // the turn must stay unsettled until the provider reports turn end + // (projected as thread.session-set leaving the "running" status). + const session = yield* projectionThreadSessionRepository.getByThreadId({ + threadId: event.payload.threadId, + }); + const turnStillRunning = + Option.isSome(session) && + session.value.status === "running" && + session.value.activeTurnId === event.payload.turnId; + const settlesTurn = !event.payload.streaming && !turnStillRunning; const existingTurn = yield* projectionTurnRepository.getByTurnId({ threadId: event.payload.threadId, turnId: event.payload.turnId, @@ -1088,16 +1175,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionTurnRepository.upsertByTurnId({ ...existingTurn.value, assistantMessageId: event.payload.messageId, - state: event.payload.streaming - ? existingTurn.value.state - : existingTurn.value.state === "interrupted" + state: settlesTurn + ? existingTurn.value.state === "interrupted" ? "interrupted" : existingTurn.value.state === "error" ? "error" - : "completed", - completedAt: event.payload.streaming - ? existingTurn.value.completedAt - : (existingTurn.value.completedAt ?? event.payload.updatedAt), + : "completed" + : existingTurn.value.state, + completedAt: settlesTurn + ? (existingTurn.value.completedAt ?? event.payload.updatedAt) + : existingTurn.value.completedAt, startedAt: existingTurn.value.startedAt ?? event.payload.createdAt, requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt, }); @@ -1110,10 +1197,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti sourceProposedPlanThreadId: null, sourceProposedPlanId: null, assistantMessageId: event.payload.messageId, - state: event.payload.streaming ? "running" : "completed", + state: settlesTurn ? "completed" : "running", requestedAt: event.payload.createdAt, startedAt: event.payload.createdAt, - completedAt: event.payload.streaming ? null : event.payload.updatedAt, + completedAt: settlesTurn ? event.payload.updatedAt : null, checkpointTurnCount: null, checkpointRef: null, checkpointStatus: null, @@ -1160,6 +1247,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti } case "thread.turn-diff-completed": { + // Mid-turn diff updates produce placeholder checkpoints; record the + // checkpoint, but don't settle a turn its session is still running. + const session = yield* projectionThreadSessionRepository.getByThreadId({ + threadId: event.payload.threadId, + }); + const turnStillRunning = + Option.isSome(session) && + session.value.status === "running" && + session.value.activeTurnId === event.payload.turnId; const existingTurn = yield* projectionTurnRepository.getByTurnId({ threadId: event.payload.threadId, turnId: event.payload.turnId, @@ -1175,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionTurnRepository.upsertByTurnId({ ...existingTurn.value, assistantMessageId: event.payload.assistantMessageId, - state: nextState, + state: turnStillRunning ? existingTurn.value.state : nextState, checkpointTurnCount: event.payload.checkpointTurnCount, checkpointRef: event.payload.checkpointRef, checkpointStatus: event.payload.status, @@ -1193,7 +1289,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti sourceProposedPlanThreadId: null, sourceProposedPlanId: null, assistantMessageId: event.payload.assistantMessageId, - state: nextState, + state: turnStillRunning ? "running" : nextState, requestedAt: event.payload.completedAt, startedAt: event.payload.completedAt, completedAt: event.payload.completedAt, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 0d5cfe2feb..77f9a2ed90 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1943,7 +1943,7 @@ describe("ProviderCommandReactor", () => { expect(resolvedActivity).toBeUndefined(); }); - it("surfaces stale provider user-input failures without faking user-input resolution", async () => { + it("surfaces non-resumable provider user-input callbacks as stale failures", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; harness.respondToUserInput.mockImplementation(() => @@ -1951,7 +1951,7 @@ describe("ProviderCommandReactor", () => { new ProviderAdapterRequestError({ provider: ProviderDriverKind.make("claudeAgent"), method: "item/tool/respondToUserInput", - detail: "Unknown pending user-input request: user-input-request-1", + detail: "Unknown pending Codex user input request: user-input-request-1", }), ), ); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index e0db0fc320..9c7a7c94bb 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -141,9 +141,19 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause): boolean { const error = findProviderAdapterRequestError(cause); if (error) { - return error.detail.toLowerCase().includes("unknown pending user-input request"); + const detail = error.detail.toLowerCase(); + return ( + detail.includes("unknown pending user-input request") || + detail.includes("unknown pending user input request") || + detail.includes("unknown pending codex user input request") + ); } - return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request"); + const message = Cause.pretty(cause).toLowerCase(); + return ( + message.includes("unknown pending user-input request") || + message.includes("unknown pending user input request") || + message.includes("unknown pending codex user input request") + ); } function stalePendingRequestDetail( diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index dceb594486..6495559023 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => { const createdAt = "2026-01-01T00:00:00.000Z"; await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-source-guarded"), - threadId: sourceThreadId, - projectId: asProjectId("project-1"), - title: "Plan Source", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "plan", - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-source-guarded"), - threadId: sourceThreadId, - session: { + Effect.andThen( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-thread-create-plan-source-guarded"), threadId: sourceThreadId, - status: "ready", - providerName: "codex", + projectId: asProjectId("project-1"), + title: "Plan Source", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + interactionMode: "plan", runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), + branch: null, + worktreePath: null, + createdAt, + }), + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-set-plan-source-guarded"), + threadId: sourceThreadId, + session: { + threadId: sourceThreadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ), ); harness.setProviderSession({ provider: ProviderDriverKind.make("codex"), @@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => { expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId); }); + it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => { + // Steering a running turn: the server requests a new turn while the old + // one is still active, and providers like opencode open the new turn + // without ever completing the superseded one. The new turn.started must + // replace the active turn instead of being rejected as stale. + const harness = await createHarness(); + const threadId = asThreadId("thread-1"); + const oldTurnId = asTurnId("turn-steered-over"); + const newTurnId = asTurnId("turn-from-steer"); + const createdAt = "2026-01-01T00:00:00.000Z"; + + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "running", + runtimeMode: "approval-required", + threadId, + createdAt, + updatedAt: createdAt, + activeTurnId: oldTurnId, + }); + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-steered-over"), + provider: ProviderDriverKind.make("codex"), + createdAt, + threadId, + turnId: oldTurnId, + }); + await waitForThread( + harness.readModel, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId, + 2_000, + threadId, + ); + + // The steer: a user-requested turn start while the old turn still runs. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-steer"), + threadId, + message: { + messageId: asMessageId("msg-steer"), + role: "user", + text: "actually, do 15 instead", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt, + }), + ); + + // The provider session tracks the new turn before emitting turn.started + // (sendTurn updates the session first). + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "running", + runtimeMode: "approval-required", + threadId, + createdAt, + updatedAt: createdAt, + activeTurnId: newTurnId, + }); + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-from-steer"), + provider: ProviderDriverKind.make("codex"), + createdAt, + threadId, + turnId: newTurnId, + }); + + const threadAfterSteer = await waitForThread( + harness.readModel, + (thread) => + thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId, + 2_000, + threadId, + ); + expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId); + expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId); + expect(threadAfterSteer.latestTurn?.state).toBe("running"); + }); + it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => { const harness = await createHarness(); const sourceThreadId = asThreadId("thread-plan"); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index c5c155fd24..3e5978f484 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () { activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; + // A turn.started that conflicts with the active turn is legitimate when + // the server itself has a turn start pending for this thread AND the + // provider session already tracks the event's turn as its active turn: + // steering a running turn makes some providers (e.g. opencode) open a + // new turn without ever completing the superseded one. A stale + // turn.started for some other turn id still gets rejected. + const conflictingTurnStartIsPendingTurnStart = + event.type === "turn.started" && conflictsWithActiveTurn + ? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) && + Option.isSome( + yield* projectionTurnRepository.getPendingTurnStartByThreadId({ + threadId: thread.id, + }), + ) + : false; + const shouldApplyThreadLifecycle = (() => { if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { return true; @@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () { case "thread.started": return true; case "turn.started": - return !conflictsWithActiveTurn; + return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart; case "turn.completed": if (conflictsWithActiveTurn || missingTurnForActiveTurn) { return false; diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index 804c1e8a6f..fadd507802 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -267,37 +267,76 @@ describe("orchestration projector", () => { ), ); - const afterRunning = await Effect.runPromise( - projectEvent( - afterCreate, - makeEvent({ - sequence: 2, - type: "thread.session-set", - aggregateKind: "thread", - aggregateId: "thread-1", - occurredAt: startedAt, - commandId: "cmd-running", - payload: { - threadId: "thread-1", - session: { + const settledAt = "2026-02-23T08:01:00.000Z"; + const [afterRunning, afterReady] = await Effect.runPromise( + Effect.flatMap( + projectEvent( + afterCreate, + makeEvent({ + sequence: 2, + type: "thread.session-set", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: startedAt, + commandId: "cmd-running", + payload: { threadId: "thread-1", - status: "running", - providerName: "codex", - providerSessionId: "session-1", - providerThreadId: "provider-thread-1", - runtimeMode: "approval-required", - activeTurnId: "turn-1", - lastError: null, - updatedAt: startedAt, + session: { + threadId: "thread-1", + status: "running", + providerName: "codex", + providerSessionId: "session-1", + providerThreadId: "provider-thread-1", + runtimeMode: "approval-required", + activeTurnId: "turn-1", + lastError: null, + updatedAt: startedAt, + }, }, - }, - }), + }), + ), + (running) => + Effect.map( + projectEvent( + running, + makeEvent({ + sequence: 3, + type: "thread.session-set", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: settledAt, + commandId: "cmd-ready", + payload: { + threadId: "thread-1", + session: { + threadId: "thread-1", + status: "ready", + providerName: "codex", + providerSessionId: "session-1", + providerThreadId: "provider-thread-1", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: settledAt, + }, + }, + }), + ), + (ready) => [running, ready] as const, + ), ), ); const thread = afterRunning.threads[0]; expect(thread?.latestTurn?.turnId).toBe("turn-1"); expect(thread?.session?.status).toBe("running"); + + // Leaving the "running" session status settles the running turn with the + // session timestamp as the turn end. + const settledThread = afterReady.threads[0]; + expect(settledThread?.latestTurn?.turnId).toBe("turn-1"); + expect(settledThread?.latestTurn?.state).toBe("completed"); + expect(settledThread?.latestTurn?.completedAt).toBe(settledAt); }); it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => { diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 0c92f96543..fc6ab8f6fc 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error" return "completed" as const; } +/** + * Turn state to settle a still-running latest turn with when its session + * leaves the "running" status, or null while the session is (re)starting or + * running and the turn must stay unsettled. + */ +function settledTurnStateForSessionStatus( + status: OrchestrationSession["status"], +): "completed" | "interrupted" | "error" | null { + switch (status) { + case "idle": + case "ready": + return "completed"; + case "error": + return "error"; + case "interrupted": + case "stopped": + return "interrupted"; + case "starting": + case "running": + return null; + } +} + function updateThread( threads: ReadonlyArray, threadId: ThreadId, @@ -438,6 +461,9 @@ export function projectEvent( "session", ); + // Leaving the "running" session status is the turn-end signal: settle + // a still-running latest turn so its duration reflects the whole turn. + const settledTurnState = settledTurnStateForSessionStatus(session.status); return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { @@ -461,7 +487,18 @@ export function projectEvent( ? thread.latestTurn.assistantMessageId : null, } - : thread.latestTurn, + : thread.latestTurn !== null && + thread.latestTurn.state === "running" && + settledTurnState !== null + ? { + ...thread.latestTurn, + state: settledTurnState, + // A running turn's completedAt can only hold a mid-turn + // placeholder checkpoint timestamp — the session leaving + // "running" is the authoritative turn end. + completedAt: session.updatedAt, + } + : thread.latestTurn, updatedAt: event.occurredAt, }), }; @@ -544,24 +581,31 @@ export function projectEvent( .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount) .slice(-MAX_THREAD_CHECKPOINTS); + // Mid-turn diff updates produce placeholder checkpoints; record the + // checkpoint, but don't settle a turn its session is still running. + const turnStillRunning = + thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId; + return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { checkpoints, - latestTurn: { - turnId: payload.turnId, - state: checkpointStatusToLatestTurnState(payload.status), - requestedAt: - thread.latestTurn?.turnId === payload.turnId - ? thread.latestTurn.requestedAt - : payload.completedAt, - startedAt: - thread.latestTurn?.turnId === payload.turnId - ? (thread.latestTurn.startedAt ?? payload.completedAt) - : payload.completedAt, - completedAt: payload.completedAt, - assistantMessageId: payload.assistantMessageId, - }, + latestTurn: turnStillRunning + ? thread.latestTurn + : { + turnId: payload.turnId, + state: checkpointStatusToLatestTurnState(payload.status), + requestedAt: + thread.latestTurn?.turnId === payload.turnId + ? thread.latestTurn.requestedAt + : payload.completedAt, + startedAt: + thread.latestTurn?.turnId === payload.turnId + ? (thread.latestTurn.startedAt ?? payload.completedAt) + : payload.completedAt, + completedAt: payload.completedAt, + assistantMessageId: payload.assistantMessageId, + }, updatedAt: event.occurredAt, }), }; diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index dfaff75b8c..916c9d077d 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -890,6 +890,73 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const runtimeEventsFiber = yield* Stream.takeUntil( + adapter.streamEvents, + (event) => event.type === "turn.completed", + ).pipe(Stream.runCollect, Effect.forkChild); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: ProviderDriverKind.make("claudeAgent"), + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "run 5 commands", + attachments: [], + }); + + // Steer: a second sendTurn while the turn is still running continues + // the same turn — the message is queued into the live agent loop. + const steeredTurn = yield* adapter.sendTurn({ + threadId: session.threadId, + input: "actually run 15", + attachments: [], + }); + assert.equal(String(steeredTurn.turnId), String(turn.turnId)); + + harness.query.emit({ + type: "assistant", + session_id: "sdk-session-steer", + uuid: "assistant-steer-1", + parent_tool_use_id: null, + message: { + id: "assistant-message-steer-1", + content: [{ type: "text", text: "Adjusting to 15." }], + }, + } as unknown as SDKMessage); + + harness.query.emit({ + type: "result", + subtype: "success", + is_error: false, + errors: [], + session_id: "sdk-session-steer", + uuid: "result-steer-1", + } as unknown as SDKMessage); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started"); + const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed"); + + // One turn boundary for the whole run: the steer produced no + // turn.completed/turn.started pair. + assert.equal(turnStartedEvents.length, 1); + assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId)); + assert.equal(turnCompletedEvents.length, 1); + assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId)); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 78365eb8a1..38b77c6926 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -14,6 +14,7 @@ import { type PermissionResult, type PermissionUpdate, type SDKMessage, + type SDKControlGetContextUsageResponse, type SDKResultMessage, type SettingSource, type SDKUserMessage, @@ -29,6 +30,7 @@ import { type ProviderApprovalDecision, ProviderDriverKind, ProviderInstanceId, + type ModelSelection, ProviderItemId, type ProviderRuntimeEvent, type ProviderRuntimeTurnStatus, @@ -120,6 +122,13 @@ interface ClaudeResumeState { interface ClaudeTurnState { readonly turnId: TurnId; readonly startedAt: string; + /** + * True for turns auto-started by assistant output arriving without an + * active turn (background agent/subagent responses between user prompts). + * Synthetic turns are auto-closed by the next sendTurn; real turns are + * steered instead (the queued message continues the same turn). + */ + readonly synthetic?: boolean; readonly items: Array; readonly assistantTextBlocks: Map; readonly assistantTextBlockOrder: Array; @@ -159,6 +168,13 @@ interface ToolInFlight { readonly lastEmittedInputFingerprint?: string; } +interface ClaudeTaskState { + readonly id: string; + subject: string; + status: PlanStep["status"]; + readonly blockedBy: Set; +} + interface ClaudeSessionContext { session: ProviderSession; readonly promptQueue: Queue.Queue; @@ -175,9 +191,11 @@ interface ClaudeSessionContext { items: Array; }>; readonly inFlightTools: Map; + readonly claudeTasks: Map; turnState: ClaudeTurnState | undefined; lastKnownContextWindow: number | undefined; lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined; + lastKnownTotalProcessedTokens: number | undefined; lastAssistantUuid: string | undefined; lastThreadStartedId: string | undefined; stopped: boolean; @@ -188,6 +206,7 @@ interface ClaudeQueryRuntime extends AsyncIterable { readonly setModel: (model?: string) => Promise; readonly setPermissionMode: (mode: PermissionMode) => Promise; readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise; + readonly getContextUsage?: () => Promise; readonly close: () => void; } @@ -337,60 +356,220 @@ function maxClaudeContextWindowFromModelUsage( return maxContextWindow; } -function normalizeClaudeTokenUsage( +function selectedClaudeContextWindow( + modelSelection: ModelSelection | undefined, +): number | undefined { + switch (modelSelection?.model) { + case "claude-opus-4-8": + case "claude-opus-4-7": + return 1_000_000; + } + + const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow"); + if (optionValue === "1m") { + return 1_000_000; + } + if (optionValue === "200k") { + return 200_000; + } + const caps = getClaudeModelCapabilities(modelSelection?.model); + const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some( + (descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow", + ); + if (hasContextWindowOption) { + return 200_000; + } + return undefined; +} + +function finiteNonNegativeInteger(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) && value >= 0 + ? Math.round(value) + : undefined; +} + +function finitePositiveInteger(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) && value > 0 + ? Math.round(value) + : undefined; +} + +function claudeUsageInputTokens(usage: Record): number { + return ( + (finiteNonNegativeInteger(usage.input_tokens) ?? 0) + + (finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) + + (finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0) + ); +} + +function claudeUsageOutputTokens(usage: Record): number { + return finiteNonNegativeInteger(usage.output_tokens) ?? 0; +} + +function lastClaudeUsageIteration( + value: Record, +): Record | undefined { + const iterations = Array.isArray(value.iterations) ? value.iterations : []; + return iterations.findLast( + (iteration): iteration is Record => + iteration !== null && typeof iteration === "object" && !Array.isArray(iteration), + ); +} + +function claudeTotalProcessedTokens(value: unknown): number | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return undefined; + } + + const usage = value as Record; + const explicitTotal = finiteNonNegativeInteger(usage.total_tokens); + if (explicitTotal !== undefined && explicitTotal > 0) { + return explicitTotal; + } + + const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage); + return total > 0 ? total : undefined; +} + +function makeClaudeTokenUsageSnapshot(input: { + readonly activeTokens: number; + readonly inputTokens?: number; + readonly outputTokens?: number; + readonly contextWindow?: number; + readonly totalProcessedTokens?: number; + readonly lastUsedTokens?: number; + readonly compactsAutomatically?: boolean; +}): ThreadTokenUsageSnapshot | undefined { + const activeTokens = finiteNonNegativeInteger(input.activeTokens); + if (activeTokens === undefined || activeTokens <= 0) { + return undefined; + } + + const maxTokens = finitePositiveInteger(input.contextWindow); + const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens; + const lastUsedTokens = + finiteNonNegativeInteger(input.lastUsedTokens) ?? + (maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens); + const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens); + const inputTokens = finiteNonNegativeInteger(input.inputTokens); + const outputTokens = finiteNonNegativeInteger(input.outputTokens); + + return { + usedTokens, + lastUsedTokens, + ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens + ? { totalProcessedTokens } + : {}), + ...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}), + ...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}), + ...(maxTokens !== undefined ? { maxTokens } : {}), + ...(input.compactsAutomatically !== undefined + ? { compactsAutomatically: input.compactsAutomatically } + : {}), + }; +} + +function normalizeClaudeActiveTokenUsage( value: unknown, contextWindow?: number, + totalProcessedTokens?: number, ): ThreadTokenUsageSnapshot | undefined { if (!value || typeof value !== "object") { return undefined; } const usage = value as Record; - const inputTokens = - (typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens) - ? usage.input_tokens - : 0) + - (typeof usage.cache_creation_input_tokens === "number" && - Number.isFinite(usage.cache_creation_input_tokens) - ? usage.cache_creation_input_tokens - : 0) + - (typeof usage.cache_read_input_tokens === "number" && - Number.isFinite(usage.cache_read_input_tokens) - ? usage.cache_read_input_tokens - : 0); - const outputTokens = - typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens) - ? usage.output_tokens - : 0; - const derivedTotalProcessedTokens = inputTokens + outputTokens; - const totalProcessedTokens = - (typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens) - ? usage.total_tokens - : undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined); - if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) { + const activeUsage = lastClaudeUsageIteration(usage) ?? usage; + const inputTokens = claudeUsageInputTokens(activeUsage); + const outputTokens = claudeUsageOutputTokens(activeUsage); + const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens; + if (activeTokens <= 0) { return undefined; } - const maxTokens = - typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0 - ? contextWindow - : undefined; - const usedTokens = - maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens; + return makeClaudeTokenUsageSnapshot({ + activeTokens, + inputTokens, + outputTokens, + ...(contextWindow !== undefined ? { contextWindow } : {}), + ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}), + }); +} +function normalizeClaudeContextUsageApiSnapshot( + value: SDKControlGetContextUsageResponse, + totalProcessedTokens?: number, +): ThreadTokenUsageSnapshot | undefined { + return makeClaudeTokenUsageSnapshot({ + activeTokens: value.totalTokens, + contextWindow: value.maxTokens, + ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}), + compactsAutomatically: value.isAutoCompactEnabled, + }); +} + +function compactBoundaryTokenUsageSnapshot( + message: Record, + contextWindow?: number, + totalProcessedTokens?: number, +): ThreadTokenUsageSnapshot | undefined { + const metadata = message.compact_metadata; + if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) { + return undefined; + } + + const compactMetadata = metadata as Record; + const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens); + if (postTokens === undefined || postTokens <= 0) { + return undefined; + } + + const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens); + return makeClaudeTokenUsageSnapshot({ + activeTokens: postTokens, + ...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}), + ...(contextWindow !== undefined ? { contextWindow } : {}), + ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}), + }); +} + +function normalizeClaudeTaskProgressTokenUsage( + value: unknown, + context: ClaudeSessionContext, +): ThreadTokenUsageSnapshot | undefined { + const totalTokens = claudeTotalProcessedTokens(value); + if (totalTokens === undefined || totalTokens <= 0) { + return undefined; + } + + const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens; + const activeTokens = + lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens; + if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) { + return undefined; + } + + const usage = value as Record; + const snapshot = makeClaudeTokenUsageSnapshot({ + activeTokens, + ...(context.lastKnownContextWindow !== undefined + ? { contextWindow: context.lastKnownContextWindow } + : {}), + totalProcessedTokens: Math.max( + totalTokens, + context.lastKnownTotalProcessedTokens ?? totalTokens, + ), + }); + if (!snapshot) { + return undefined; + } + + const toolUses = finiteNonNegativeInteger(usage.tool_uses); + const durationMs = finiteNonNegativeInteger(usage.duration_ms); return { - usedTokens, - lastUsedTokens: usedTokens, - ...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}), - ...(inputTokens > 0 ? { inputTokens } : {}), - ...(outputTokens > 0 ? { outputTokens } : {}), - ...(maxTokens !== undefined ? { maxTokens } : {}), - ...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses) - ? { toolUses: usage.tool_uses } - : {}), - ...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms) - ? { durationMs: usage.duration_ms } - : {}), + ...snapshot, + ...(toolUses !== undefined ? { toolUses } : {}), + ...(durationMs !== undefined ? { durationMs } : {}), }; } @@ -539,6 +718,140 @@ function extractPlanStepsFromTodoInput(input: Record): PlanStep })); } +function isClaudeTaskTool(toolName: string): boolean { + return toolName === "TaskCreate" || toolName === "TaskUpdate" || toolName === "TaskList"; +} + +function normalizeClaudeTaskStatus(value: unknown): PlanStep["status"] { + return value === "completed" ? "completed" : value === "in_progress" ? "inProgress" : "pending"; +} + +function readString(value: unknown): string | undefined { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; +} + +function readStringArray(value: unknown): Array { + return Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0) + : []; +} + +function readClaudeToolUseResult(message: SDKMessage): Record | undefined { + if (message.type !== "user") { + return undefined; + } + const result = (message as { readonly tool_use_result?: unknown }).tool_use_result; + return result !== null && typeof result === "object" && !Array.isArray(result) + ? (result as Record) + : undefined; +} + +function readClaudeTaskFromResult( + result: Record | undefined, +): Record | undefined { + const task = result?.task; + return task !== null && typeof task === "object" && !Array.isArray(task) + ? (task as Record) + : undefined; +} + +function applyClaudeTaskToolResult( + tasks: Map, + tool: ToolInFlight, + result: Record | undefined, +): boolean { + if (!isClaudeTaskTool(tool.toolName)) { + return false; + } + + let changed = false; + if (tool.toolName === "TaskList") { + const resultTasks = result?.tasks; + if (!Array.isArray(resultTasks)) { + return false; + } + tasks.clear(); + for (const entry of resultTasks) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) { + continue; + } + const task = entry as Record; + const id = readString(task.id); + const subject = readString(task.subject); + if (!id || !subject) { + continue; + } + tasks.set(id, { + id, + subject, + status: normalizeClaudeTaskStatus(task.status), + blockedBy: new Set(readStringArray(task.blockedBy)), + }); + } + return tasks.size > 0; + } + + if (tool.toolName === "TaskCreate") { + const resultTask = readClaudeTaskFromResult(result); + const id = readString(resultTask?.id); + const subject = readString(resultTask?.subject) ?? readString(tool.input.subject); + if (!id || !subject) { + return false; + } + tasks.set(id, { + id, + subject, + status: normalizeClaudeTaskStatus(tool.input.status), + blockedBy: new Set(readStringArray(tool.input.blockedBy)), + }); + return true; + } + + const taskId = readString(tool.input.taskId) ?? readString(result?.taskId); + if (!taskId) { + return false; + } + const task = tasks.get(taskId); + if (!task) { + return false; + } + const subject = readString(tool.input.subject); + if (subject && task.subject !== subject) { + task.subject = subject; + changed = true; + } + if (typeof tool.input.status === "string") { + const status = normalizeClaudeTaskStatus(tool.input.status); + if (task.status !== status) { + task.status = status; + changed = true; + } + } + for (const dependency of readStringArray(tool.input.addBlockedBy)) { + if (!task.blockedBy.has(dependency)) { + task.blockedBy.add(dependency); + changed = true; + } + } + for (const dependency of readStringArray(tool.input.removeBlockedBy)) { + if (task.blockedBy.delete(dependency)) { + changed = true; + } + } + return changed; +} + +function planStepsFromClaudeTasks(tasks: Map): PlanStep[] { + return Array.from(tasks.values()).map((task) => { + const blockedBy = Array.from(task.blockedBy); + const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(", #")})` : ""; + return { + step: `${task.subject}${blockedSuffix}`, + status: task.status, + }; + }); +} + function summarizeToolRequest(toolName: string, input: Record): string { const commandValue = input.command ?? input.cmd; const command = typeof commandValue === "string" ? commandValue : undefined; @@ -1438,6 +1751,70 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); }); + const emitThreadTokenUsage = Effect.fn("emitThreadTokenUsage")(function* ( + context: ClaudeSessionContext, + usage: ThreadTokenUsageSnapshot | undefined, + options?: { + readonly rawMethod?: string; + readonly rawPayload?: unknown; + }, + ) { + if (!usage) { + return; + } + + context.lastKnownTokenUsage = usage; + context.lastKnownTotalProcessedTokens = + usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens; + + const turnState = context.turnState; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.token-usage.updated", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(turnState ? { turnId: turnState.turnId } : {}), + payload: { + usage, + }, + providerRefs: nativeProviderRefs(context), + ...(options?.rawMethod || options?.rawPayload + ? { + raw: { + source: "claude.sdk.message" as const, + ...(options.rawMethod ? { method: options.rawMethod } : {}), + payload: options.rawPayload, + }, + } + : {}), + }); + }); + + const queryCurrentContextUsage = Effect.fn("queryCurrentContextUsage")(function* ( + context: ClaudeSessionContext, + totalProcessedTokens?: number, + ) { + if (!context.query.getContextUsage) { + return undefined; + } + + const usage = yield* Effect.promise(async () => { + try { + return await context.query.getContextUsage?.(); + } catch { + return undefined; + } + }); + if (!usage) { + return undefined; + } + + context.lastKnownContextWindow = usage.maxTokens; + return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens); + }); + const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* ( context: ClaudeSessionContext, input: { @@ -1485,6 +1862,42 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); }); + const emitClaudeTaskPlanUpdated = Effect.fn("emitClaudeTaskPlanUpdated")(function* ( + context: ClaudeSessionContext, + input: { + readonly toolUseId: string; + readonly rawMethod: string; + readonly rawPayload: unknown; + }, + ) { + const plan = planStepsFromClaudeTasks(context.claudeTasks); + if (plan.length === 0) { + return; + } + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.plan.updated", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + payload: { + explanation: "Claude Tasks", + plan, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: input.toolUseId, + }), + raw: { + source: "claude.sdk.message", + method: input.rawMethod, + payload: input.rawPayload, + }, + }); + }); + const completeTurn = Effect.fn("completeTurn")(function* ( context: ClaudeSessionContext, status: ProviderRuntimeTurnStatus, @@ -1496,51 +1909,77 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( context.lastKnownContextWindow = resultContextWindow; } - // The SDK result.usage contains *accumulated* totals across all API calls - // (input_tokens, cache_read_input_tokens, etc. summed over every request). - // This does NOT represent the current context window size. - // Instead, use the last known context-window-accurate usage from task_progress - // events and treat the accumulated total as totalProcessedTokens. - const accumulatedSnapshot = normalizeClaudeTokenUsage( - result?.usage, - resultContextWindow ?? context.lastKnownContextWindow, - ); - const accumulatedTotalProcessedTokens = - accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens; - const lastGoodUsage = context.lastKnownTokenUsage; const maxTokens = resultContextWindow ?? context.lastKnownContextWindow; - const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage - ? { - ...lastGoodUsage, - ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 - ? { maxTokens } - : {}), - ...(typeof accumulatedTotalProcessedTokens === "number" && - Number.isFinite(accumulatedTotalProcessedTokens) && - accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens - ? { - totalProcessedTokens: accumulatedTotalProcessedTokens, - } - : {}), - } - : accumulatedSnapshot; + const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage); + if (accumulatedTotalProcessedTokens !== undefined) { + context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens; + } + + const contextUsageSnapshot = yield* queryCurrentContextUsage( + context, + accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens, + ); + const resultUsageRecord = + result?.usage && typeof result.usage === "object" && !Array.isArray(result.usage) + ? (result.usage as Record) + : undefined; + const hasResultUsageIteration = + resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined; + const resultHasActiveUsage = + resultUsageRecord !== undefined && + (hasResultUsageIteration || + claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0); + const resultTotalOnly = + resultUsageRecord !== undefined && + !resultHasActiveUsage && + claudeTotalProcessedTokens(resultUsageRecord) !== undefined; + const resultIterationSnapshot = resultUsageRecord + ? normalizeClaudeActiveTokenUsage( + resultUsageRecord, + maxTokens, + accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens, + ) + : undefined; + const lastGoodUsage = context.lastKnownTokenUsage; + const usageSnapshot: ThreadTokenUsageSnapshot | undefined = + contextUsageSnapshot ?? + (resultTotalOnly && lastGoodUsage + ? { + ...lastGoodUsage, + ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 + ? { maxTokens } + : {}), + ...(typeof accumulatedTotalProcessedTokens === "number" && + Number.isFinite(accumulatedTotalProcessedTokens) && + accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens + ? { + totalProcessedTokens: accumulatedTotalProcessedTokens, + } + : {}), + } + : resultIterationSnapshot) ?? + (lastGoodUsage + ? { + ...lastGoodUsage, + ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 + ? { maxTokens } + : {}), + ...(typeof accumulatedTotalProcessedTokens === "number" && + Number.isFinite(accumulatedTotalProcessedTokens) && + accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens + ? { + totalProcessedTokens: accumulatedTotalProcessedTokens, + } + : {}), + } + : undefined); const turnState = context.turnState; if (!turnState) { - if (usageSnapshot) { - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "thread.token-usage.updated", - eventId: usageStamp.eventId, - provider: PROVIDER, - createdAt: usageStamp.createdAt, - threadId: context.session.threadId, - payload: { - usage: usageSnapshot, - }, - providerRefs: {}, - }); - } + yield* emitThreadTokenUsage(context, usageSnapshot, { + rawMethod: "claude/result", + rawPayload: result ?? { status }, + }); const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ @@ -1611,21 +2050,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( items: [...turnState.items], }); - if (usageSnapshot) { - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "thread.token-usage.updated", - eventId: usageStamp.eventId, - provider: PROVIDER, - createdAt: usageStamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, - payload: { - usage: usageSnapshot, - }, - providerRefs: nativeProviderRefs(context), - }); - } + yield* emitThreadTokenUsage(context, usageSnapshot, { + rawMethod: "claude/result", + rawPayload: result ?? { status }, + }); const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ @@ -1670,6 +2098,23 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const { event } = message; + if (event.type === "message_delta") { + if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) { + return; + } + + const snapshot = normalizeClaudeActiveTokenUsage( + event.usage, + context.lastKnownContextWindow, + context.lastKnownTotalProcessedTokens, + ); + yield* emitThreadTokenUsage(context, snapshot, { + rawMethod: "claude/stream_event/message_delta", + rawPayload: message, + }); + return; + } + if (event.type === "content_block_delta") { if ( (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") && @@ -1932,6 +2377,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const [index, tool] = toolEntry; const itemStatus = toolResult.isError ? "failed" : "completed"; + const toolUseResult = readClaudeToolUseResult(message); const toolData = { toolName: tool.toolName, input: tool.input, @@ -2016,6 +2462,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }, }); + if ( + !toolResult.isError && + applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult) + ) { + yield* emitClaudeTaskPlanUpdated(context, { + toolUseId: tool.itemId, + rawMethod: "claude/user", + rawPayload: message, + }); + } + context.inFlightTools.delete(index); } }); @@ -2036,6 +2493,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( context.turnState = { turnId, startedAt, + synthetic: true, items: [], assistantTextBlocks: new Map(), assistantTextBlockOrder: [], @@ -2171,6 +2629,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); return; case "compact_boundary": + yield* emitThreadTokenUsage( + context, + compactBoundaryTokenUsageSnapshot( + message as unknown as Record, + context.lastKnownContextWindow, + context.lastKnownTotalProcessedTokens, + ), + { + rawMethod: "claude/system/compact_boundary", + rawPayload: message, + }, + ); yield* offerRuntimeEvent({ ...base, type: "thread.state.changed", @@ -2229,25 +2699,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); return; case "task_progress": - if (message.usage) { - const normalizedUsage = normalizeClaudeTokenUsage( - message.usage, - context.lastKnownContextWindow, - ); - if (normalizedUsage) { - context.lastKnownTokenUsage = normalizedUsage; - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - ...base, - eventId: usageStamp.eventId, - createdAt: usageStamp.createdAt, - type: "thread.token-usage.updated", - payload: { - usage: normalizedUsage, - }, - }); - } - } + yield* emitThreadTokenUsage( + context, + normalizeClaudeTaskProgressTokenUsage(message.usage, context), + { + rawMethod: "claude/system/task_progress", + rawPayload: message, + }, + ); yield* offerRuntimeEvent({ ...base, type: "task.progress", @@ -2261,25 +2720,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); return; case "task_notification": - if (message.usage) { - const normalizedUsage = normalizeClaudeTokenUsage( - message.usage, - context.lastKnownContextWindow, - ); - if (normalizedUsage) { - context.lastKnownTokenUsage = normalizedUsage; - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - ...base, - eventId: usageStamp.eventId, - createdAt: usageStamp.createdAt, - type: "thread.token-usage.updated", - payload: { - usage: normalizedUsage, - }, - }); - } - } + yield* emitThreadTokenUsage( + context, + normalizeClaudeTaskProgressTokenUsage(message.usage, context), + { + rawMethod: "claude/system/task_notification", + rawPayload: message, + }, + ); yield* offerRuntimeEvent({ ...base, type: "task.completed", @@ -2669,6 +3117,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const pendingApprovals = new Map(); const pendingUserInputs = new Map(); const inFlightTools = new Map(); + const claudeTasks = new Map(); const contextRef = yield* Ref.make(undefined); @@ -2969,6 +3418,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const caps = getClaudeModelCapabilities(modelSelection?.model); const descriptors = getProviderOptionDescriptors({ caps }); const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined; + const initialContextWindow = selectedClaudeContextWindow(modelSelection); const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort"); const effort = resolveClaudeEffort(caps, rawEffort) ?? null; const fastModeSupported = descriptors.some( @@ -3094,9 +3544,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( pendingUserInputs, turns: [], inFlightTools, + claudeTasks, turnState: undefined, - lastKnownContextWindow: undefined, + lastKnownContextWindow: initialContextWindow, lastKnownTokenUsage: undefined, + lastKnownTotalProcessedTokens: undefined, lastAssistantUuid: resumeState?.resumeSessionAt, lastThreadStartedId: undefined, stopped: false, @@ -3185,9 +3637,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ? input.modelSelection : undefined; - if (context.turnState) { - // Auto-close a stale synthetic turn (from background agent responses - // between user prompts) to prevent blocking the user's next turn. + // A sendTurn while a real turn is running is a steer: the message is + // queued into the live SDK agent loop and the work continues as the same + // turn — no synthetic turn boundary. Stale synthetic turns (from + // background agent responses between user prompts) are auto-closed + // instead, so they don't block the user's next turn. + const steeringTurnState = + context.turnState && context.turnState.synthetic !== true ? context.turnState : null; + if (context.turnState && steeringTurnState === null) { yield* completeTurn(context, "completed"); } @@ -3222,37 +3679,39 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( }); } - const turnId = TurnId.make(yield* randomUUIDv4); - const turnState: ClaudeTurnState = { - turnId, - startedAt: yield* nowIso, - items: [], - assistantTextBlocks: new Map(), - assistantTextBlockOrder: [], - capturedProposedPlanKeys: new Set(), - nextSyntheticAssistantBlockIndex: -1, - }; + const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4); + if (steeringTurnState === null) { + const turnState: ClaudeTurnState = { + turnId, + startedAt: yield* nowIso, + items: [], + assistantTextBlocks: new Map(), + assistantTextBlockOrder: [], + capturedProposedPlanKeys: new Set(), + nextSyntheticAssistantBlockIndex: -1, + }; - const updatedAt = yield* nowIso; - context.turnState = turnState; - context.session = { - ...context.session, - status: "running", - activeTurnId: turnId, - updatedAt, - }; + const updatedAt = yield* nowIso; + context.turnState = turnState; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt, + }; - const turnStartedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.started", - eventId: turnStartedStamp.eventId, - provider: PROVIDER, - createdAt: turnStartedStamp.createdAt, - threadId: context.session.threadId, - turnId, - payload: modelSelection?.model ? { model: modelSelection.model } : {}, - providerRefs: {}, - }); + const turnStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.started", + eventId: turnStartedStamp.eventId, + provider: PROVIDER, + createdAt: turnStartedStamp.createdAt, + threadId: context.session.threadId, + turnId, + payload: modelSelection?.model ? { model: modelSelection.model } : {}, + providerRefs: {}, + }); + } const message = yield* buildUserMessageEffect(input, { fileSystem, diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 3b3eb99c84..d5bbc8f657 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -108,14 +108,6 @@ const BUILT_IN_MODELS: ReadonlyArray = [ id: "fastMode", label: "Fast Mode", }), - buildSelectOptionDescriptor({ - id: "contextWindow", - label: "Context Window", - options: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - }), ], }), }, @@ -142,14 +134,6 @@ const BUILT_IN_MODELS: ReadonlyArray = [ id: "fastMode", label: "Fast Mode", }), - buildSelectOptionDescriptor({ - id: "contextWindow", - label: "Context Window", - options: [ - { value: "200k", label: "200k", isDefault: true }, - { value: "1m", label: "1M" }, - ], - }), ], }), }, diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 3ae98ec248..04ef44d54e 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => { provider: ProviderDriverKind.make("codex"), threadId: asThreadId("thread-1"), modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ - { id: "fastMode", value: true }, + { id: "serviceTier", value: "priority" }, ]), runtimeMode: "full-access", }); @@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => { cwd: process.cwd(), model: "gpt-5.3-codex", providerInstanceId: ProviderInstanceId.make("codex"), - serviceTier: "fast", + serviceTier: "priority", threadId: asThreadId("thread-1"), runtimeMode: "full-access", }); @@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { input: "hello", modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: true }, + { id: "serviceTier", value: "priority" }, ]), attachments: [], }), @@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { input: "hello", model: "gpt-5.3-codex", effort: "high", - serviceTier: "fast", + serviceTier: "priority", }); }), ); @@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { "gpt-5.3-codex", [ { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: true }, + { id: "serviceTier", value: "flex" }, ], ), attachments: [], @@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => { input: "hello", model: "gpt-5.3-codex", effort: "high", - serviceTier: "fast", + serviceTier: "flex", }); }).pipe(Effect.provide(customLayer)); }); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 9893cf6c14..8c9969e2bc 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import * as CodexErrors from "effect-codex-app-server/errors"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; -import { - getModelSelectionBooleanOptionValue, - getModelSelectionStringOptionValue, -} from "@t3tools/shared/model"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts"; import { ProviderAdapterRequestError, @@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( yield* Effect.suspend(() => stopSessionInternal(existing)); } + const serviceTier = + input.modelSelection?.instanceId === boundInstanceId + ? getCodexServiceTierOptionValue(input.modelSelection) + : undefined; const runtimeInput: CodexSessionRuntimeOptions = { threadId: input.threadId, providerInstanceId: boundInstanceId, @@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ...(input.modelSelection?.instanceId === boundInstanceId ? { model: input.modelSelection.model } : {}), - ...(input.modelSelection?.instanceId === boundInstanceId && - getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true - ? { serviceTier: "fast" } - : {}), + ...(serviceTier ? { serviceTier } : {}), }; const sessionScope = yield* Scope.make("sequential"); let sessionScopeTransferred = false; @@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( input.modelSelection?.instanceId === boundInstanceId ? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") : undefined; - const fastMode = + const serviceTier = input.modelSelection?.instanceId === boundInstanceId - ? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") + ? getCodexServiceTierOptionValue(input.modelSelection) : undefined; return yield* session.runtime .sendTurn({ @@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort, } : {}), - ...(fastMode === true ? { serviceTier: "fast" } : {}), + ...(serviceTier ? { serviceTier } : {}), ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}), ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), }) diff --git a/apps/server/src/provider/Layers/CodexProvider.test.ts b/apps/server/src/provider/Layers/CodexProvider.test.ts new file mode 100644 index 0000000000..0e21b76306 --- /dev/null +++ b/apps/server/src/provider/Layers/CodexProvider.test.ts @@ -0,0 +1,104 @@ +import { assert, it } from "@effect/vitest"; + +import { mapCodexModelCapabilities } from "./CodexProvider.ts"; + +it("maps current Codex model capability fields", () => { + const capabilities = mapCodexModelCapabilities({ + additionalSpeedTiers: [], + defaultReasoningEffort: "super-high", + description: "Test model", + displayName: "GPT Test", + hidden: false, + id: "gpt-test", + isDefault: true, + model: "gpt-test", + defaultServiceTier: "flex", + serviceTiers: [ + { + id: "priority", + name: "Fast", + description: "Lower latency responses.", + }, + { + id: "flex", + name: "Flex", + description: "Lower-cost asynchronous routing.", + }, + ], + supportedReasoningEfforts: [ + { + description: "Maximum reasoning", + reasoningEffort: "super-high", + }, + ], + }); + + assert.deepStrictEqual(capabilities.optionDescriptors, [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: [{ id: "super-high", label: "super-high", isDefault: true }], + currentValue: "super-high", + }, + { + id: "serviceTier", + label: "Service Tier", + type: "select", + options: [ + { id: "default", label: "Standard" }, + { + id: "priority", + label: "Fast", + description: "Lower latency responses.", + }, + { + id: "flex", + label: "Flex", + description: "Lower-cost asynchronous routing.", + isDefault: true, + }, + ], + currentValue: "flex", + }, + ]); +}); + +it("uses standard routing when the catalog has no default service tier", () => { + const capabilities = mapCodexModelCapabilities({ + additionalSpeedTiers: ["fast"], + defaultReasoningEffort: "medium", + defaultServiceTier: null, + description: "Test model", + displayName: "GPT Test", + hidden: false, + id: "gpt-test", + isDefault: true, + model: "gpt-test", + serviceTiers: [ + { + id: "priority", + name: "Fast", + description: "1.5x speed, increased usage", + }, + ], + supportedReasoningEfforts: [], + }); + + assert.deepStrictEqual(capabilities.optionDescriptors, [ + { + id: "serviceTier", + label: "Service Tier", + type: "select", + options: [ + { id: "default", label: "Standard", isDefault: true }, + { + id: "priority", + label: "Fast", + description: "1.5x speed, increased usage", + }, + ], + currentValue: "default", + }, + ]); +}); diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 4d793194c1..89d7421b23 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -17,6 +17,7 @@ import type { ServerProvider, ServerProviderState, ModelCapabilities, + ProviderOptionDescriptor, ServerProviderModel, ServerProviderSkill, } from "@t3tools/contracts"; @@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot { readonly skills: ReadonlyArray; } -const REASONING_EFFORT_LABELS: Record = { +const REASONING_EFFORT_LABELS: Readonly> = { none: "None", minimal: "Minimal", low: "Low", @@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record reasoningEffort === model.defaultReasoningEffort ? { id: reasoningEffort, - label: REASONING_EFFORT_LABELS[reasoningEffort], + label: reasoningEffortLabel(reasoningEffort), isDefault: true, } : { id: reasoningEffort, - label: REASONING_EFFORT_LABELS[reasoningEffort], + label: reasoningEffortLabel(reasoningEffort), }, ); const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id; - const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast"); + const serviceTiers = + model.serviceTiers && model.serviceTiers.length > 0 + ? model.serviceTiers + : (model.additionalSpeedTiers ?? []).map((id) => ({ + id, + name: id === "fast" ? "Fast" : id, + description: "", + })); + const catalogDefaultServiceTier = serviceTiers.some( + (tier) => tier.id === model.defaultServiceTier, + ) + ? model.defaultServiceTier + : null; + const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID; + const optionDescriptors: ProviderOptionDescriptor[] = []; + + if (reasoningOptions.length > 0) { + optionDescriptors.push({ + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: reasoningOptions, + ...(defaultReasoning ? { currentValue: defaultReasoning } : {}), + }); + } + if (serviceTiers.length > 0) { + optionDescriptors.push({ + id: "serviceTier", + label: "Service Tier", + type: "select", + options: [ + { + id: DEFAULT_SERVICE_TIER_ID, + label: "Standard", + ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}), + }, + ...serviceTiers.map((tier) => ({ + id: tier.id, + label: tier.name, + ...(tier.description ? { description: tier.description } : {}), + ...(defaultServiceTier === tier.id ? { isDefault: true } : {}), + })), + ], + currentValue: defaultServiceTier, + }); + } + return createModelCapabilities({ - optionDescriptors: [ - ...(reasoningOptions.length > 0 - ? [ - { - id: "reasoningEffort", - label: "Reasoning", - type: "select" as const, - options: reasoningOptions, - ...(defaultReasoning ? { currentValue: defaultReasoning } : {}), - }, - ] - : []), - ...(supportsFastMode - ? [ - { - id: "fastMode", - label: "Fast Mode", - type: "boolean" as const, - }, - ] - : []), - ], + optionDescriptors, }); } diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts index b1e54948ba..c71c696445 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -13,6 +13,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { createModelSelection } from "@t3tools/shared/model"; import { @@ -232,6 +233,82 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { }), ); + it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => + Effect.gen(function* () { + const adapter = yield* CursorAdapter; + const settings = yield* ServerSettingsService; + const threadId = ThreadId.make("cursor-steer-thread"); + + // Keep the first prompt in flight long enough for the steer to land. + const wrapperPath = yield* Effect.promise(() => + makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }), + ); + yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } }); + + const runtimeEventsFiber = yield* adapter.streamEvents.pipe( + Stream.filter((event) => event.threadId === threadId), + Stream.takeUntil((event) => event.type === "turn.completed"), + Stream.runCollect, + Effect.forkChild, + ); + + yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("cursor"), + cwd: process.cwd(), + runtimeMode: "full-access", + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, + }); + + const firstTurnFiber = yield* adapter + .sendTurn({ + threadId, + input: "run 5 commands", + attachments: [], + }) + .pipe(Effect.forkChild); + + // Poll until the first prompt is in flight — sendTurn binds the active + // turn id before prompting. The mock agent runs on the real clock, so + // each TestClock.adjust just provides the scheduler hops for its stdio + // responses to land. + yield* Effect.gen(function* () { + for (let attempt = 0; attempt < 200; attempt += 1) { + const sessions = yield* adapter.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + if (session?.activeTurnId !== undefined) { + return; + } + yield* TestClock.adjust("10 millis"); + } + throw new Error("Timed out waiting for the first prompt to be in flight."); + }); + + // Steer: a second sendTurn while the first prompt is still in flight + // continues the same turn. + const steeredTurn = yield* adapter.sendTurn({ + threadId, + input: "actually run 15", + attachments: [], + }); + const firstTurn = yield* Fiber.join(firstTurnFiber); + assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId)); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started"); + const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed"); + + // One turn boundary for the whole run: the superseded first prompt + // resolving must not settle the merged turn. + assert.equal(turnStartedEvents.length, 1); + assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId)); + assert.equal(turnCompletedEvents.length, 1); + assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId)); + + yield* adapter.stopSession(threadId); + }), + ); + it.effect("closes the ACP child process when a session stops", () => Effect.gen(function* () { const adapter = yield* CursorAdapter; diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts index 016feeb79a..cdb3c224b9 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -132,6 +132,10 @@ interface CursorSessionContext { readonly turns: Array<{ id: TurnId; items: Array }>; lastPlanFingerprint: string | undefined; activeTurnId: TurnId | undefined; + /** Number of sendTurn prompts currently in flight or being prepared. + * >0 means a turn is actively running, so a new sendTurn is a steer that + * continues it, and only the last remaining prompt settles the turn. */ + promptsInFlight: number; stopped: boolean; } @@ -754,6 +758,7 @@ export function makeCursorAdapter( turns: [], lastPlanFingerprint: undefined, activeTurnId: undefined, + promptsInFlight: 0, stopped: false, }; @@ -882,121 +887,152 @@ export function makeCursorAdapter( const sendTurn: CursorAdapterShape["sendTurn"] = (input) => Effect.gen(function* () { const ctx = yield* requireSession(input.threadId); - const turnId = TurnId.make(yield* randomUUIDv4); - const turnModelSelection = - input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; - const model = turnModelSelection?.model ?? ctx.session.model; - const resolvedModel = resolveCursorAcpBaseModelId(model); - yield* applyRequestedSessionConfiguration({ - runtime: ctx.acp, - runtimeMode: ctx.session.runtimeMode, - interactionMode: input.interactionMode, - modelSelection: - model === undefined - ? undefined - : { - model, - options: turnModelSelection?.options, - }, - mapError: ({ cause, method }) => - mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), - }); - ctx.activeTurnId = turnId; - ctx.lastPlanFingerprint = undefined; - ctx.session = { - ...ctx.session, - activeTurnId: turnId, - updatedAt: yield* nowIso, - }; + // A sendTurn while a prompt is in flight is a steer: the agent folds + // the new prompt into the ongoing work, so the active turn id is + // reused instead of opening a new turn. + const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined; + const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4); + // Count this prompt immediately so a superseded in-flight prompt + // resolving from here on does not settle the turn; the matching + // decrement is the `ensuring` below. + ctx.promptsInFlight += 1; - yield* offerRuntimeEvent({ - type: "turn.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { model: resolvedModel }, - }); + return yield* Effect.gen(function* () { + const turnModelSelection = + input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; + const model = turnModelSelection?.model ?? ctx.session.model; + const resolvedModel = resolveCursorAcpBaseModelId(model); + yield* applyRequestedSessionConfiguration({ + runtime: ctx.acp, + runtimeMode: ctx.session.runtimeMode, + interactionMode: input.interactionMode, + modelSelection: + model === undefined + ? undefined + : { + model, + options: turnModelSelection?.options, + }, + mapError: ({ cause, method }) => + mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), + }); + ctx.activeTurnId = turnId; + if (steeringTurnId === undefined) { + ctx.lastPlanFingerprint = undefined; + } + ctx.session = { + ...ctx.session, + activeTurnId: turnId, + updatedAt: yield* nowIso, + }; - const promptParts: Array = []; - if (input.input?.trim()) { - promptParts.push({ type: "text", text: input.input.trim() }); - } - if (input.attachments && input.attachments.length > 0) { - for (const attachment of input.attachments) { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!attachmentPath) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: `Invalid attachment id '${attachment.id}'.`, - }); - } - const bytes = yield* fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: cause.message, - cause, - }), - ), - ); - promptParts.push({ - type: "image", - data: Buffer.from(bytes).toString("base64"), - mimeType: attachment.mimeType, + if (steeringTurnId === undefined) { + yield* offerRuntimeEvent({ + type: "turn.started", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId, + payload: { model: resolvedModel }, }); } - } - if (promptParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "Turn requires non-empty text or attachments.", - }); - } + const promptParts: Array = []; + if (input.input?.trim()) { + promptParts.push({ type: "text", text: input.input.trim() }); + } + if (input.attachments && input.attachments.length > 0) { + for (const attachment of input.attachments) { + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }); + if (!attachmentPath) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session/prompt", + detail: `Invalid attachment id '${attachment.id}'.`, + }); + } + const bytes = yield* fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session/prompt", + detail: cause.message, + cause, + }), + ), + ); + promptParts.push({ + type: "image", + data: Buffer.from(bytes).toString("base64"), + mimeType: attachment.mimeType, + }); + } + } - const result = yield* ctx.acp - .prompt({ - prompt: promptParts, - }) - .pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), - ), - ); + if (promptParts.length === 0) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: "Turn requires non-empty text or attachments.", + }); + } - ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); - ctx.session = { - ...ctx.session, - activeTurnId: turnId, - updatedAt: yield* nowIso, - model: resolvedModel, - }; + const result = yield* ctx.acp + .prompt({ + prompt: promptParts, + }) + .pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), + ), + ); - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: { - state: result.stopReason === "cancelled" ? "cancelled" : "completed", - stopReason: result.stopReason ?? null, - }, - }); + const turnRecord = ctx.turns.find((turn) => turn.id === turnId); + if (turnRecord) { + turnRecord.items.push({ prompt: promptParts, result }); + } else { + ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] }); + } + ctx.session = { + ...ctx.session, + activeTurnId: turnId, + updatedAt: yield* nowIso, + model: resolvedModel, + }; - return { - threadId: input.threadId, - turnId, - resumeCursor: ctx.session.resumeCursor, - }; + // Only the last remaining prompt settles the turn — a steer- + // superseded prompt resolving (usually cancelled) while another is + // in flight or pending must leave the merged turn running. + if (ctx.promptsInFlight === 1) { + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId, + payload: { + state: result.stopReason === "cancelled" ? "cancelled" : "completed", + stopReason: result.stopReason ?? null, + }, + }); + } + + return { + threadId: input.threadId, + turnId, + resumeCursor: ctx.session.resumeCursor, + }; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1); + }), + ), + ); }); const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) => diff --git a/apps/server/src/provider/Layers/GrokAdapter.ts b/apps/server/src/provider/Layers/GrokAdapter.ts index ed4097ecda..0f1007f261 100644 --- a/apps/server/src/provider/Layers/GrokAdapter.ts +++ b/apps/server/src/provider/Layers/GrokAdapter.ts @@ -107,6 +107,10 @@ interface GrokSessionContext { turns: Array<{ id: TurnId; items: Array }>; lastPlanFingerprint: string | undefined; activeTurnId: TurnId | undefined; + /** Number of sendTurn prompts currently in flight or being prepared. + * >0 means a turn is actively running, so a new sendTurn is a steer that + * continues it, and only the last remaining prompt settles the turn. */ + promptsInFlight: number; currentModelId: string | undefined; stopped: boolean; } @@ -555,6 +559,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte turns: [], lastPlanFingerprint: undefined, activeTurnId: undefined, + promptsInFlight: 0, currentModelId: boundModelId, stopped: false, }; @@ -664,150 +669,199 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte input.threadId, Effect.gen(function* () { const ctx = yield* requireSession(input.threadId); - const turnId = TurnId.make(yield* randomUUIDv4); - const turnModelSelection = - input.modelSelection?.instanceId === boundInstanceId - ? input.modelSelection - : undefined; - const requestedTurnModelId = turnModelSelection?.model - ? resolveGrokAcpBaseModelId(turnModelSelection.model) - : undefined; - const currentModelId = yield* applyGrokAcpModelSelection({ - runtime: ctx.acp, - currentModelId: ctx.currentModelId, - requestedModelId: requestedTurnModelId, - mapError: (cause) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause), - }); + // A sendTurn while a prompt is in flight is a steer: the agent + // folds the new prompt into the ongoing work, so the active turn + // id is reused instead of opening a new turn. + const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined; + const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4); + // Count this prompt immediately so a superseded in-flight prompt + // resolving from here on does not settle the turn; decremented on + // preparation failure here, and after the prompt below otherwise. + ctx.promptsInFlight += 1; - const text = input.input?.trim(); - const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) => - Effect.gen(function* () { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!attachmentPath) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: `Invalid attachment id '${attachment.id}'.`, - }); - } - const bytes = yield* fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ + return yield* Effect.gen(function* () { + const turnModelSelection = + input.modelSelection?.instanceId === boundInstanceId + ? input.modelSelection + : undefined; + const requestedTurnModelId = turnModelSelection?.model + ? resolveGrokAcpBaseModelId(turnModelSelection.model) + : undefined; + const currentModelId = yield* applyGrokAcpModelSelection({ + runtime: ctx.acp, + currentModelId: ctx.currentModelId, + requestedModelId: requestedTurnModelId, + mapError: (cause) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause), + }); + + const text = input.input?.trim(); + const imagePromptParts = yield* Effect.forEach( + input.attachments ?? [], + (attachment) => + Effect.gen(function* () { + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }); + if (!attachmentPath) { + return yield* new ProviderAdapterRequestError({ provider: PROVIDER, method: "session/prompt", - detail: cause.message, - cause, - }), - ), - ); - return { - type: "image", - data: Buffer.from(bytes).toString("base64"), - mimeType: attachment.mimeType, - } satisfies EffectAcpSchema.ContentBlock; - }), + detail: `Invalid attachment id '${attachment.id}'.`, + }); + } + const bytes = yield* fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session/prompt", + detail: cause.message, + cause, + }), + ), + ); + return { + type: "image", + data: Buffer.from(bytes).toString("base64"), + mimeType: attachment.mimeType, + } satisfies EffectAcpSchema.ContentBlock; + }), + ); + const promptParts: Array = [ + ...(text ? [{ type: "text" as const, text }] : []), + ...imagePromptParts, + ]; + + if (promptParts.length === 0) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: "Turn requires non-empty text or attachments.", + }); + } + + ctx.currentModelId = currentModelId; + const displayModel = currentModelId + ? resolveGrokAcpBaseModelId(currentModelId) + : undefined; + ctx.activeTurnId = turnId; + if (steeringTurnId === undefined) { + ctx.lastPlanFingerprint = undefined; + } + ctx.session = { + ...ctx.session, + activeTurnId: turnId, + updatedAt: yield* nowIso, + ...(displayModel ? { model: displayModel } : {}), + }; + + if (steeringTurnId === undefined) { + yield* offerRuntimeEvent({ + type: "turn.started", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId, + payload: displayModel ? { model: displayModel } : {}, + }); + } + + return { + acp: ctx.acp, + acpSessionId: ctx.acpSessionId, + displayModel, + promptParts, + turnId, + }; + }).pipe( + Effect.tapCause(() => + Effect.sync(() => { + ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1); + }), + ), ); - const promptParts: Array = [ - ...(text ? [{ type: "text" as const, text }] : []), - ...imagePromptParts, - ]; - - if (promptParts.length === 0) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "sendTurn", - issue: "Turn requires non-empty text or attachments.", - }); - } - - ctx.currentModelId = currentModelId; - const displayModel = currentModelId - ? resolveGrokAcpBaseModelId(currentModelId) - : undefined; - ctx.activeTurnId = turnId; - ctx.lastPlanFingerprint = undefined; - ctx.session = { - ...ctx.session, - activeTurnId: turnId, - updatedAt: yield* nowIso, - ...(displayModel ? { model: displayModel } : {}), - }; - - yield* offerRuntimeEvent({ - type: "turn.started", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId, - payload: displayModel ? { model: displayModel } : {}, - }); - - return { - acp: ctx.acp, - acpSessionId: ctx.acpSessionId, - displayModel, - promptParts, - turnId, - }; }), ); - const result = yield* prepared.acp - .prompt({ - prompt: prepared.promptParts, - }) - .pipe( - Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), - ), + return yield* Effect.gen(function* () { + const result = yield* prepared.acp + .prompt({ + prompt: prepared.promptParts, + }) + .pipe( + Effect.mapError((error) => + mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), + ), + ); + + return yield* withThreadLock( + input.threadId, + Effect.gen(function* () { + const ctx = yield* requireSession(input.threadId); + if (ctx.acpSessionId !== prepared.acpSessionId) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session/prompt", + detail: "Grok session changed before the turn completed.", + }); + } + + const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId); + ctx.turns = existingTurnRecord + ? ctx.turns.map((turn) => + turn.id === prepared.turnId + ? { + ...turn, + items: [...turn.items, { prompt: prepared.promptParts, result }], + } + : turn, + ) + : [ + ...ctx.turns, + { id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] }, + ]; + ctx.session = { + ...ctx.session, + activeTurnId: prepared.turnId, + updatedAt: yield* nowIso, + ...(prepared.displayModel ? { model: prepared.displayModel } : {}), + }; + + // Only the last remaining prompt settles the turn — a steer- + // superseded prompt resolving (usually cancelled) while another + // is in flight or pending must leave the merged turn running. + if (ctx.promptsInFlight === 1) { + yield* offerRuntimeEvent({ + type: "turn.completed", + ...(yield* makeEventStamp()), + provider: PROVIDER, + threadId: input.threadId, + turnId: prepared.turnId, + payload: { + state: result.stopReason === "cancelled" ? "cancelled" : "completed", + stopReason: result.stopReason ?? null, + }, + }); + } + + return { + threadId: input.threadId, + turnId: prepared.turnId, + resumeCursor: ctx.session.resumeCursor, + }; + }), ); - - return yield* withThreadLock( - input.threadId, - Effect.gen(function* () { - const ctx = yield* requireSession(input.threadId); - if (ctx.acpSessionId !== prepared.acpSessionId) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "session/prompt", - detail: "Grok session changed before the turn completed.", - }); - } - - ctx.turns = [ - ...ctx.turns, - { id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] }, - ]; - ctx.session = { - ...ctx.session, - activeTurnId: prepared.turnId, - updatedAt: yield* nowIso, - ...(prepared.displayModel ? { model: prepared.displayModel } : {}), - }; - - yield* offerRuntimeEvent({ - type: "turn.completed", - ...(yield* makeEventStamp()), - provider: PROVIDER, - threadId: input.threadId, - turnId: prepared.turnId, - payload: { - state: result.stopReason === "cancelled" ? "cancelled" : "completed", - stopReason: result.stopReason ?? null, - }, - }); - - return { - threadId: input.threadId, - turnId: prepared.turnId, - resumeCursor: ctx.session.resumeCursor, - }; - }), + }).pipe( + Effect.ensuring( + Effect.sync(() => { + const liveCtx = sessions.get(input.threadId); + if (liveCtx) { + liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1); + } + }), + ), ); }); diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts index 5c0badc2de..3f483d8fd7 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts @@ -395,6 +395,85 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => { }), ); + it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => + Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + const threadId = asThreadId("thread-steer"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId, + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId, + input: "run 5 commands", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "openai/gpt-5", + }, + }); + + // Steer: OpenCode queues the prompt into the busy session, so the + // active turn id is reused instead of opening a new turn. + const steeredTurn = yield* adapter.sendTurn({ + threadId, + input: "actually run 15", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "openai/gpt-5", + }, + }); + assert.equal(String(steeredTurn.turnId), String(turn.turnId)); + + const sessions = yield* adapter.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + assert.equal(session?.status, "running"); + assert.equal(String(session?.activeTurnId), String(turn.turnId)); + assert.equal(runtimeMock.state.promptCalls.length, 2); + }), + ); + + it.effect("keeps the running turn when a steer prompt fails", () => + Effect.gen(function* () { + const adapter = yield* OpenCodeAdapter; + const threadId = asThreadId("thread-steer-failure"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("opencode"), + threadId, + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId, + input: "run 5 commands", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "openai/gpt-5", + }, + }); + + runtimeMock.state.promptAsyncError = new Error("steer failed"); + const error = yield* adapter + .sendTurn({ + threadId, + input: "actually run 15", + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model: "openai/gpt-5", + }, + }) + .pipe(Effect.flip); + + // The original turn keeps running — only the steer prompt failed. + assert.equal(error._tag, "ProviderAdapterRequestError"); + const sessions = yield* adapter.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + assert.equal(session?.status, "running"); + assert.equal(String(session?.activeTurnId), String(turn.turnId)); + }), + ); + it.effect("passes agent and variant options for the adapter's bound custom instance id", () => { const instanceId = ProviderInstanceId.make("opencode_zen"); const adapterLayer = Layer.effect( diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index 34a6719912..54444ce586 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -1151,7 +1151,11 @@ export function makeOpenCodeAdapter( const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { const context = ensureSessionContext(sessions, input.threadId); - const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`); + // A sendTurn while a turn is active is a steer: OpenCode queues the + // prompt into the busy session and the work continues as one turn, so + // the active turn id is reused instead of opening a new turn. + const steeringTurnId = context.activeTurnId; + const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`); const modelSelection = input.modelSelection ?? (context.session.model @@ -1206,14 +1210,16 @@ export function makeOpenCodeAdapter( { clearLastError: true }, ); - yield* emit({ - ...(yield* buildEventBase({ threadId: input.threadId, turnId })), - type: "turn.started", - payload: { - model: modelSelection?.model ?? context.session.model, - ...(variant ? { effort: variant } : {}), - }, - }); + if (steeringTurnId === undefined) { + yield* emit({ + ...(yield* buildEventBase({ threadId: input.threadId, turnId })), + type: "turn.started", + payload: { + model: modelSelection?.model ?? context.session.model, + ...(variant ? { effort: variant } : {}), + }, + }); + } yield* runOpenCodeSdk("session.promptAsync", () => context.client.session.promptAsync({ @@ -1225,35 +1231,38 @@ export function makeOpenCodeAdapter( }), ).pipe( Effect.mapError(toRequestError), - // On failure: clear active-turn state, flip the session back to ready - // with lastError set, emit turn.aborted, then let the typed error - // propagate. We don't need to rebuild the error here — `toRequestError` - // already produced the right shape. + // On failure of a fresh turn: clear active-turn state, flip the + // session back to ready with lastError set, emit turn.aborted, then + // let the typed error propagate. We don't need to rebuild the error + // here — `toRequestError` already produced the right shape. A failed + // steer leaves the still-running original turn untouched. Effect.tapError((requestError) => - Effect.gen(function* () { - context.activeTurnId = undefined; - context.activeAgent = undefined; - context.activeVariant = undefined; - yield* updateProviderSession( - context, - { - status: "ready", - model: modelSelection?.model ?? context.session.model, - lastError: requestError.detail, - }, - { clearActiveTurnId: true }, - ); - yield* emit({ - ...(yield* buildEventBase({ - threadId: input.threadId, - turnId, - })), - type: "turn.aborted", - payload: { - reason: requestError.detail, - }, - }); - }), + steeringTurnId !== undefined + ? Effect.void + : Effect.gen(function* () { + context.activeTurnId = undefined; + context.activeAgent = undefined; + context.activeVariant = undefined; + yield* updateProviderSession( + context, + { + status: "ready", + model: modelSelection?.model ?? context.session.model, + lastError: requestError.detail, + }, + { clearActiveTurnId: true }, + ); + yield* emit({ + ...(yield* buildEventBase({ + threadId: input.threadId, + turnId, + })), + type: "turn.aborted", + payload: { + reason: requestError.detail, + }, + }); + }), ), ); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 273cf22f31..56b80f6c4a 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T ]); }); + it.effect("does not run provider probes during layer construction", () => + Effect.gen(function* () { + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const initialProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "warning", + enabled: true, + installed: false, + auth: { status: "unknown" }, + checkedAt: "2026-06-10T00:00:00.000Z", + version: null, + message: "Checking Codex provider status.", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshCalls = yield* Ref.make(0); + const instance = { + instanceId: codexInstanceId, + driverKind: codexDriver, + continuationIdentity: { + driverKind: codexDriver, + continuationKey: "codex:instance:codex", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: codexDriver, + packageName: null, + }), + getSnapshot: Effect.succeed(initialProvider), + refresh: Ref.update(refreshCalls, (count) => count + 1).pipe( + Effect.andThen(Effect.never), + ), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-background-refresh-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]); + assert.strictEqual(yield* Ref.get(refreshCalls), 0); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it("persists merged provider snapshots for the providers that were refreshed", () => { const previousProviders = [ { @@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T yield* Effect.gen(function* () { const registry = yield* ProviderRegistry; - const providers = yield* registry.getProviders; + let providers = yield* registry.getProviders; + for ( + let attempts = 0; + attempts < 50 && + providers.find((provider) => provider.instanceId === "codex_personal")?.status !== + "error"; + attempts += 1 + ) { + yield* Effect.yieldNow; + providers = yield* registry.getProviders; + } const codexPersonal = providers.find( (provider) => provider.instanceId === "codex_personal", ); @@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // instance and rebuild it so a fresh probe runs with the new binary. // This test drives the real settings stream → registry reconcile → // aggregator sync pipeline and asserts that `getProviders` reflects - // the new probe's outcome. If `syncLiveSources` stops awaiting the - // rebuilt instance's refresh (previous bug mode), the aggregator - // keeps the old snapshot and this test fails. + // the new background probe's outcome. // it.effect("re-probes when settings change the codex binaryPath", () => Effect.gen(function* () { @@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // the two probe runs is `checkedAt` — each probe stamps a // fresh DateTime, so we capture it and assert it advances // after the settings mutation. - const initialProviders = yield* registry.getProviders; + let initialProviders = yield* registry.getProviders; + for ( + let attempts = 0; + attempts < 50 && + initialProviders.find((provider) => provider.instanceId === "codex")?.status !== + "error"; + attempts += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + initialProviders = yield* registry.getProviders; + } const initialCodex = initialProviders.find( (provider) => provider.instanceId === "codex", ); @@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // envelope changed because `binaryPath` differs → `entryEqual` // is false). The registry's `Stream.runForEach( // instanceRegistry.streamChanges, () => syncLiveSources)` - // fires `syncLiveSources`, which subscribes + awaits a fresh - // refresh on the rebuilt instance. + // fires `syncLiveSources`, which subscribes and launches a fresh + // background refresh on the rebuilt instance. yield* serverSettings.updateSettings({ providers: { codex: { enabled: true, binaryPath: secondMissing }, @@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T for (let attempts = 0; attempts < 60; attempts += 1) { const providers = yield* registry.getProviders; const codex = providers.find((provider) => provider.instanceId === "codex"); - if (codex !== undefined && codex.checkedAt !== initialCheckedAt) { + if ( + codex !== undefined && + codex.status === "error" && + codex.checkedAt !== initialCheckedAt + ) { return providers; } yield* TestClock.adjust("50 millis"); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index 22a120f0a5..2df63e5383 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect( * - subscribe to each newly-added or rebuilt instance's * `streamChanges` (so periodic + enrichment refreshes land in * `providersRef`); - * - force-refresh each newly-added/rebuilt instance and feed the - * result directly into `providersRef`, bypassing the PubSub - * attachment race that otherwise drops the initial probe; + * - read each newly-added/rebuilt instance's current snapshot after + * subscribing, closing the race with its independently-running + * background startup probe; * - prune `providersRef` of instances that no longer exist. * - * Initial refreshes are awaited in parallel rather than forked, so - * callers (layer build; `streamChanges` watcher) see fully-probed - * state on return. This matters for layer build in particular: - * consumers reading `getProviders` immediately after layer build - * expect the probe to have already landed. + * Provider refreshes are owned by each managed provider and never run + * on this layer's construction path. Consumers see cached or pending + * snapshots immediately, then receive live probe results through the + * already-attached change stream. * * Per-instance subscription fibers are not tracked explicitly. When * a rebuilt instance's old child scope closes, its PubSub shuts @@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect( } // Fork long-lived subscriptions to each new/rebuilt instance's - // change stream BEFORE kicking off refreshes — if the driver's - // own initial probe (line 140 in `makeManagedServerProvider`) - // wins the refreshSemaphore race, its PubSub publish must land - // in an active subscriber or the result is dropped. + // change stream before reading its current snapshot. If the + // driver's own initial probe finishes during this sync, either + // the current read or the active subscriber observes the result. for (const [, instance] of newlyAdded) { const source = buildSnapshotSource(instance); yield* Stream.runForEach(source.streamChanges, (provider) => correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)), ).pipe(Effect.forkScoped); } + yield* Effect.yieldNow; - // Force-refresh every new/rebuilt instance in parallel and wait - // for them all to complete. The refresh's result is piped - // directly into `syncProvider`, so `providersRef` is populated - // deterministically by the time this block returns — regardless - // of PubSub subscription timing. Failures are logged and - // swallowed so one bad driver can't wedge the whole registry. + // Snapshot current state without starting a probe. Managed providers + // launch their startup refresh independently, so this closes the + // subscription race without putting external work on the registry + // or HTTP server construction path. yield* Effect.forEach( newlyAdded, ([, instance]) => - refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })), + Effect.gen(function* () { + const source = buildSnapshotSource(instance); + const provider = yield* source.getSnapshot; + yield* correlateSnapshotWithSource(source, provider).pipe( + Effect.flatMap(syncProvider), + ); + }).pipe(Effect.ignoreCause({ log: true })), { concurrency: "unbounded", discard: true }, ); yield* upsertProviders(unavailableProviders, { @@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect( // was dropped, which made any settings change that replaced an // instance never propagate to the aggregator's `providersRef`.) const instanceChanges = yield* instanceRegistry.subscribeChanges; - // Initial sync: subscribe + kick off refreshes for every instance - // present at boot. Run synchronously so consumers pulling immediately - // after the layer build see the correct aggregator state. + // Initial sync attaches subscriptions and snapshots current state for + // every instance present at boot. Provider probes are already running in + // their managed background fibers and never block this layer. yield* syncLiveSources; // React to registry mutations — instance added / removed / rebuilt. // `Stream.fromSubscription` builds a stream over the pre-acquired diff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.ts index 1f3ebeab08..ba1f01fe2b 100644 --- a/apps/server/src/provider/makeManagedServerProvider.test.ts +++ b/apps/server/src/provider/makeManagedServerProvider.test.ts @@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => { Effect.forkChild, ); yield* Effect.yieldNow; + assert.strictEqual(yield* Ref.get(checkCalls), 1); yield* Deferred.succeed(releaseCheck, undefined); diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index 2f07c5d508..88547fb3af 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( return { maintenanceCapabilities: input.maintenanceCapabilities, - getSnapshot: input.getSettings.pipe( - Effect.flatMap(applySnapshot), - Effect.tapError(Effect.logError), - Effect.orDie, - ), + getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie), get streamChanges() { return Stream.fromPubSub(changesPubSub); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 6266a39b79..960f27e752 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -303,7 +303,7 @@ const make = Effect.gen(function* () { } const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); if (!relayConfig) { - yield* Effect.logDebug("agent activity publish skipped; T3 Cloud config missing", { + yield* Effect.logDebug("agent activity publish skipped; T3 Connect config missing", { threadId, }); return; @@ -421,7 +421,7 @@ const make = Effect.gen(function* () { } const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); if (!relayConfig) { - yield* Effect.logDebug("agent activity snapshot skipped; T3 Cloud config missing"); + yield* Effect.logDebug("agent activity snapshot skipped; T3 Connect config missing"); return false; } const environmentId = yield* serverEnvironment.getEnvironmentId; @@ -459,7 +459,7 @@ const make = Effect.gen(function* () { function* () { const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); if (!relayConfig) { - yield* Effect.logInfo("agent activity publishing standby; T3 Cloud config missing"); + yield* Effect.logInfo("agent activity publishing standby; T3 Connect config missing"); } else { yield* Effect.logInfo("agent activity publishing enabled", { relayUrl: relayConfig.url, diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 18fe41723f..3190bb273f 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -782,7 +782,7 @@ const buildAppUnderTest = (options?: { ), Layer.provide( Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({ - get: Effect.die(new Error("Unexpected T3 Cloud CLI authorization request.")), + get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")), getExisting: Effect.succeed(Option.none()), hasCredential: Effect.succeed(false), clear: Effect.void, @@ -1713,7 +1713,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const linkProofResponse = yield* fetchEffect(linkProofUrl, { method: "POST", headers: { @@ -1750,7 +1750,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const serverPort = Number(new URL(linkProofUrl).port); const linkProofResponse = yield* fetchEffect(linkProofUrl, { method: "POST", @@ -1762,10 +1762,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => { challenge: "relay-link-challenge", relayIssuer: "https://relay.example.test", endpoint: { - httpBaseUrl: linkProofUrl.replace("/api/cloud/link-proof", ""), + httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""), wsBaseUrl: linkProofUrl .replace("http://", "ws://") - .replace("/api/cloud/link-proof", "/ws"), + .replace("/api/connect/link-proof", "/ws"), providerKind: "manual", }, origin: { @@ -1789,9 +1789,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { headers: { cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", @@ -1833,9 +1833,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { headers: { cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", @@ -1875,9 +1875,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", { + const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { headers: { cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", @@ -1918,7 +1918,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const serverPort = Number(new URL(linkProofUrl).port); const linkProofResponse = yield* fetchEffect(linkProofUrl, { method: "POST", @@ -1962,7 +1962,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }); const credential = (yield* credentialResponse.json) as { readonly credential: string }; const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); - const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); + const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); const response = yield* fetchEffect(linkStateUrl, { headers: { cookie: pairedCookie }, }); @@ -2028,7 +2028,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const preferencesUrl = yield* getHttpServerUrl("/api/cloud/preferences"); + const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences"); const ownerResponse = yield* fetchEffect(preferencesUrl, { method: "POST", headers: { @@ -2072,7 +2072,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* buildAppUnderTest(); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2107,7 +2107,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const postRelayConfig = (body: { readonly relayUrl: string; readonly relayIssuer?: string; @@ -2184,7 +2184,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const postRelayConfig = (cloudUserId: string, environmentCredential: string) => fetchEffect(relayConfigUrl, { method: "POST", @@ -2227,8 +2227,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const initialResponse = yield* fetchEffect(linkStateUrl, { headers: { @@ -2284,7 +2284,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { Effect.gen(function* () { yield* buildAppUnderTest(); - const reconcileUrl = yield* getHttpServerUrl("/api/cloud/reconcile"); + const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile"); const response = yield* fetchEffect(reconcileUrl, { method: "POST", }); @@ -2321,9 +2321,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); - const unlinkUrl = yield* getHttpServerUrl("/api/cloud/unlink"); - const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); + const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink"); + const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", @@ -2398,7 +2398,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2424,7 +2424,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { issuedAt: DateTime.formatIso(now), expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), }); - const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); const postMint = () => fetchEffect(mintUrl, { method: "POST", @@ -2448,7 +2448,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("serves the documented T3 Cloud mint credential endpoint", () => + it.effect("serves the documented T3 Connect mint credential endpoint", () => Effect.gen(function* () { yield* buildAppUnderTest(); @@ -2457,7 +2457,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2484,7 +2484,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { issuedAt: DateTime.formatIso(now), expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), }); - const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); const response = yield* fetchEffect(mintUrl, { method: "POST", headers: { @@ -2507,7 +2507,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("serves signed T3 Cloud environment health checks", () => + it.effect("serves signed T3 Connect environment health checks", () => Effect.gen(function* () { yield* buildAppUnderTest(); @@ -2516,7 +2516,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2542,7 +2542,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { issuedAt: DateTime.formatIso(now), expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), }); - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const response = yield* fetchEffect(healthUrl, { method: "POST", headers: { @@ -2576,7 +2576,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2602,7 +2602,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { issuedAt: DateTime.formatIso(now), expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), }); - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const postHealth = () => fetchEffect(healthUrl, { method: "POST", @@ -2637,7 +2637,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2656,7 +2656,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); const postMint = (request: ReturnType) => fetchEffect(mintUrl, { method: "POST", @@ -2717,7 +2717,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2756,7 +2756,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { issuedAt: DateTime.formatIso(now), expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), }); - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const healthResponse = yield* fetchEffect(healthUrl, { method: "POST", headers: { @@ -2786,7 +2786,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2804,7 +2804,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); const postMint = (request: ReturnType) => fetchEffect(mintUrl, { method: "POST", @@ -2853,7 +2853,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2871,7 +2871,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); const response = yield* fetchEffect(mintUrl, { method: "POST", headers: { @@ -2904,7 +2904,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2922,7 +2922,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential"); + const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); const response = yield* fetchEffect(mintUrl, { method: "POST", headers: { @@ -2955,7 +2955,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -2973,7 +2973,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const postHealth = (request: ReturnType) => fetchEffect(healthUrl, { method: "POST", @@ -3020,7 +3020,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -3038,7 +3038,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const response = yield* fetchEffect(healthUrl, { method: "POST", headers: { @@ -3070,7 +3070,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { publicKeyEncoding: { format: "pem", type: "spki" }, }); const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config"); + const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { method: "POST", headers: { @@ -3088,7 +3088,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(relayConfigResponse.status, 200); const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health"); + const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); const response = yield* fetchEffect(healthUrl, { method: "POST", headers: { @@ -3280,7 +3280,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { config: { devUrl: new URL(crossOriginClientOrigin) }, }); - const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); const response = yield* fetchEffect(linkProofUrl, { method: "OPTIONS", headers: { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 98bef90bb2..b7331f95e6 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -69,7 +69,7 @@ import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import { cloudHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts"; +import { connectHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts"; import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts"; import * as CloudCliState from "./cloud/CliState.ts"; @@ -87,6 +87,12 @@ import * as NetService from "@t3tools/shared/Net"; import * as RelayClient from "@t3tools/shared/relayClient"; import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale"; +// Effect's default preemptive shutdown waits 20s before finalizing request scopes. +// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer +// already closes the websocket gracefully. Do not add an artificial drain before +// those finalizers get a chance to run. +const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0; + const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { if (typeof Bun !== "undefined") { @@ -116,6 +122,7 @@ const HttpServerLive = Layer.unwrap( return BunHttpServer.layer({ port: config.port, ...(config.host ? { hostname: config.host } : {}), + gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS, }); } else { const [NodeHttpServer, NodeHttp] = yield* Effect.all([ @@ -125,6 +132,7 @@ const HttpServerLive = Layer.unwrap( return NodeHttpServer.layer(NodeHttp.createServer, { host: config.host, port: config.port, + gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS, }); } }), @@ -321,7 +329,7 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( export const makeRoutesLayer = Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), - Layer.provide(cloudHttpApiLayer), + Layer.provide(connectHttpApiLayer), Layer.provide(orchestrationHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), @@ -429,9 +437,9 @@ export const makeServerLayer = Layer.unwrap( Effect.sleep("250 millis").pipe( Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)), Effect.retry({ times: 4 }), - Effect.tap(() => Effect.logInfo("T3 Cloud desired link reconciled on startup")), + Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")), Effect.catch((cause) => - Effect.logWarning("Failed to reconcile T3 Cloud desired link on startup", { + Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", { cause, }), ), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index f72b8100bb..cf0ad7d578 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -32,7 +32,7 @@ function makeFakeCodexBinary( exitCode?: number; stderr?: string; requireImage?: boolean; - requireFastServiceTier?: boolean; + requireServiceTier?: string; requireReasoningEffort?: string; forbidReasoningEffort?: boolean; stdinMustContain?: string; @@ -52,7 +52,7 @@ function makeFakeCodexBinary( "#!/bin/sh", 'output_path=""', 'seen_image="0"', - 'seen_fast_service_tier="0"', + 'seen_service_tier=""', 'seen_reasoning_effort=""', "while [ $# -gt 0 ]; do", ' if [ "$1" = "--image" ]; then', @@ -65,9 +65,11 @@ function makeFakeCodexBinary( " fi", ' if [ "$1" = "--config" ]; then', " shift", - ' if [ "$1" = "service_tier=\\"fast\\"" ]; then', - ' seen_fast_service_tier="1"', - " fi", + ' case "$1" in', + " service_tier=*)", + ' seen_service_tier="$1"', + " ;;", + " esac", ' case "$1" in', " model_reasoning_effort=*)", ' seen_reasoning_effort="$1"', @@ -93,10 +95,10 @@ function makeFakeCodexBinary( "fi", ] : []), - ...(input.requireFastServiceTier + ...(input.requireServiceTier ? [ - 'if [ "$seen_fast_service_tier" != "1" ]; then', - ' printf "%s\\n" "missing fast service tier config" >&2', + `if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`, + ' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2', ` exit 5`, "fi", ] @@ -161,7 +163,7 @@ function withFakeCodexEnv( exitCode?: number; stderr?: string; requireImage?: boolean; - requireFastServiceTier?: boolean; + requireServiceTier?: string; requireReasoningEffort?: string; forbidReasoningEffort?: boolean; stdinMustContain?: string; @@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => { ); it.effect( - "forwards codex fast mode and non-default reasoning effort into codex exec config", + "forwards codex service tier and non-default reasoning effort into codex exec config", () => withFakeCodexEnv( { @@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => { subject: "Add important change", body: "", }), - requireFastServiceTier: true, + requireServiceTier: "priority", requireReasoningEffort: "xhigh", stdinMustNotContain: "branch must be a short semantic git branch fragment", }, @@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => { stagedPatch: "diff --git a/README.md b/README.md", modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "xhigh" }, - { id: "fastMode", value: true }, + { id: "serviceTier", value: "priority" }, ]), }), ), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index d42fb07aa0..bebd0acf80 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -32,10 +32,8 @@ import { sanitizeThreadTitle, toJsonSchemaObject, } from "./TextGenerationUtils.ts"; -import { - getModelSelectionBooleanOptionValue, - getModelSelectionStringOptionValue, -} from "@t3tools/shared/model"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; @@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func const reasoningEffort = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; + const serviceTier = getCodexServiceTierOptionValue(modelSelection); const command = ChildProcess.make( codexConfig.binaryPath || "codex", [ @@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func modelSelection.model, "--config", `model_reasoning_effort="${reasoningEffort}"`, - ...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true - ? ["--config", `service_tier="fast"`] - : []), + ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []), "--output-schema", schemaPath, "--output-last-message", diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 465cd21f32..adf991556d 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -68,6 +68,17 @@ export interface GitStatusDetails { aheadOfDefaultCount: number; } +export interface GitRemoteStatusDetails { + isRepo: boolean; + isDefaultBranch: boolean; + branch: string | null; + upstreamRef: string | null; + hasUpstream: boolean; + aheadCount: number; + behindCount: number; + aheadOfDefaultCount: number; +} + export interface GitPreparedCommitContext { stagedSummary: string; stagedPatch: string; @@ -162,6 +173,9 @@ export interface GitVcsDriverShape { readonly status: (input: VcsStatusInput) => Effect.Effect; readonly statusDetails: (cwd: string) => Effect.Effect; readonly statusDetailsLocal: (cwd: string) => Effect.Effect; + readonly statusDetailsRemote: ( + cwd: string, + ) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 1909b3b503..c0e0f1876c 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -155,6 +155,67 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports remote divergence without reading working-tree details", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + yield* git(cwd, ["checkout", "-b", "feature/remote-status"]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature commit"]); + yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]); + yield* writeTextFile(cwd, "untracked.txt", "local-only\n"); + + const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + + assert.equal(status.isRepo, true); + assert.equal(status.branch, "feature/remote-status"); + assert.equal(status.hasUpstream, true); + assert.equal(status.aheadCount, 0); + assert.equal(status.behindCount, 0); + assert.equal(status.aheadOfDefaultCount, 1); + assert.notProperty(status, "workingTree"); + assert.notProperty(status, "hasWorkingTreeChanges"); + }), + ); + + it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-vcs-driver-origin-"); + const upstream = yield* makeTmpDir("git-vcs-driver-upstream-"); + yield* initRepoWithCommit(cwd); + yield* git(origin, ["init", "--bare"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* git(cwd, ["push", "origin", "main"]); + yield* git(cwd, ["push", "upstream", "main"]); + yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]); + yield* git(cwd, ["checkout", "-b", "release"]); + yield* writeTextFile(cwd, "release.txt", "release\n"); + yield* git(cwd, ["add", "release.txt"]); + yield* git(cwd, ["commit", "-m", "release commit"]); + yield* git(cwd, ["push", "-u", "upstream", "release"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/upstream/HEAD", + "refs/remotes/upstream/release", + ]); + + const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + + assert.equal(status.branch, "release"); + assert.equal(status.upstreamRef, "upstream/release"); + assert.equal(status.isDefaultBranch, false); + }), + ); + it.effect("disables SSH askpass for background upstream status fetches", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 240c20336c..33d009b9dc 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -71,6 +71,16 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze({ + isRepo: false, + isDefaultBranch: false, + branch: null, + upstreamRef: null, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + aheadOfDefaultCount: 0, +}); type TraceTailState = { processedChars: number; @@ -1154,6 +1164,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; }); + const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) { + const branchResult = yield* executeGit( + "GitVcsDriver.statusDetailsRemote.branch", + cwd, + ["rev-parse", "--abbrev-ref", "HEAD"], + { allowNonZeroExit: true }, + ).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null))); + + if (branchResult === null) { + return NON_REPOSITORY_REMOTE_STATUS_DETAILS; + } + if (branchResult.exitCode !== 0) { + const stderr = branchResult.stderr.trim(); + return yield* createGitCommandError( + "GitVcsDriver.statusDetailsRemote.branch", + cwd, + ["rev-parse", "--abbrev-ref", "HEAD"], + stderr || "git branch lookup failed", + ); + } + + const branchValue = branchResult.stdout.trim(); + const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null; + const upstream = yield* resolveCurrentUpstream(cwd); + const upstreamRef = upstream?.upstreamRef ?? null; + let aheadCount = 0; + let behindCount = 0; + + if (upstreamRef) { + const divergence = yield* executeGit( + "GitVcsDriver.statusDetailsRemote.divergence", + cwd, + ["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`], + { allowNonZeroExit: true }, + ); + if (divergence.exitCode === 0) { + const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/); + const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10); + const parsedBehind = Number.parseInt(behindRaw ?? "0", 10); + aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0; + behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0; + } + } else if (branch) { + aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( + Effect.orElseSucceed(() => 0), + ); + } + + const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin"); + const isDefaultBranch = + branch !== null && + (branch === defaultBranch || + (defaultBranch === null && (branch === "main" || branch === "master"))); + const aheadOfDefaultCount = + branch && !isDefaultBranch + ? upstreamRef === null + ? aheadCount + : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) + : 0; + + return { + isRepo: true, + isDefaultBranch, + branch, + upstreamRef, + hasUpstream: upstreamRef !== null, + aheadCount, + behindCount, + aheadOfDefaultCount, + }; + }); + const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) { const branchRecency = yield* executeGit( "GitVcsDriver.readBranchRecency", @@ -1356,6 +1438,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }, ); + const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn( + "statusDetailsRemote", + )(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe( + Effect.catchIf(isMissingGitCwdError, () => Effect.void), + Effect.ignoreCause({ log: true }), + ); + return yield* readStatusDetailsRemote(cwd); + }); + const status: GitVcsDriver.GitVcsDriverShape["status"] = (input) => statusDetails(input.cwd).pipe( Effect.map((details) => ({ @@ -1402,7 +1494,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stagedPatch = yield* runGitStdoutWithOptions( "GitVcsDriver.prepareCommitContext.stagedPatch", cwd, - ["diff", "--cached", "--patch", "--minimal"], + ["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"], { maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, appendTruncationMarker: true, @@ -1639,7 +1731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* runGitStdoutWithOptions( "GitVcsDriver.readRangeContext.diffPatch", cwd, - ["diff", "--patch", "--minimal", range], + ["diff", "--no-ext-diff", "--patch", "--minimal", range], { maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, appendTruncationMarker: true, @@ -2302,6 +2394,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* status, statusDetails, statusDetailsLocal, + statusDetailsRemote, prepareCommitContext, commit, pushCurrentBranch, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index d47dda29bf..e92ab374f4 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -10,6 +10,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import type { VcsStatusLocalResult, VcsStatusRemoteResult, @@ -310,6 +311,48 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(makeTestLayer(state))); }); + it.effect("delays automatic refresh when a cached remote snapshot is available", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const scope = yield* Scope.make(); + const snapshotDeferred = yield* Deferred.make(); + yield* Stream.runForEach( + broadcaster.streamStatus( + { cwd: "/repo" }, + { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) }, + ), + (event) => + event._tag === "snapshot" + ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore) + : Effect.void, + ).pipe(Effect.forkIn(scope)); + + yield* Deferred.await(snapshotDeferred); + assert.equal(state.remoteStatusCalls, 1); + assert.equal(state.remoteInvalidationCalls, 0); + + yield* TestClock.adjust(Duration.seconds(59)); + assert.equal(state.remoteStatusCalls, 1); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* Effect.yieldNow; + assert.equal(state.remoteStatusCalls, 2); + assert.equal(state.remoteInvalidationCalls, 1); + + yield* Scope.close(scope, Exit.void); + }).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer()))); + }); + it("backs off remote refresh failures exponentially and honors larger configured intervals", () => { assert.equal( Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))), diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 40cdcf2c80..9cd5a6c337 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -257,6 +257,7 @@ export const layer = Layer.effect( const makeRemoteRefreshLoop = ( cwd: string, automaticRemoteRefreshInterval: Effect.Effect, + refreshImmediately: boolean, ) => { return Effect.gen(function* () { const consecutiveFailuresRef = yield* Ref.make(0); @@ -289,6 +290,15 @@ export const layer = Layer.effect( return nextDelay; }); + if (!refreshImmediately) { + const configuredInterval = yield* automaticRemoteRefreshInterval; + yield* Effect.sleep( + Duration.isZero(configuredInterval) + ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL + : configuredInterval, + ); + } + return yield* refreshRemoteStatusIfEnabled.pipe( Effect.repeat( Schedule.identity().pipe( @@ -303,6 +313,7 @@ export const layer = Layer.effect( const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* ( cwd: string, automaticRemoteRefreshInterval: Effect.Effect, + refreshImmediately: boolean, ) { yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => { const existing = activePollers.get(cwd); @@ -315,7 +326,7 @@ export const layer = Layer.effect( return Effect.succeed([undefined, nextPollers] as const); } - return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe( + return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe( Effect.forkIn(broadcasterScope), Effect.map((fiber) => { const nextPollers = new Map(activePollers); @@ -363,11 +374,13 @@ export const layer = Layer.effect( const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); const subscription = yield* PubSub.subscribe(changesPubSub); const initialLocal = yield* getOrLoadLocalStatus(cwd); - const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null; + const cachedStatus = yield* getCachedStatus(cwd); + const initialRemote = cachedStatus?.remote?.value ?? null; yield* retainRemotePoller( cwd, options?.automaticRemoteRefreshInterval ?? Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL), + cachedStatus?.remote === null || cachedStatus?.remote === undefined, ); const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid); diff --git a/apps/web/components.json b/apps/web/components.json index 6d93c116a2..5977a2b065 100644 --- a/apps/web/components.json +++ b/apps/web/components.json @@ -22,6 +22,7 @@ "hooks": "~/hooks" }, "registries": { - "@coss": "https://coss.com/ui/r/{name}.json" + "@coss": "https://coss.com/ui/r/{name}.json", + "@spell": "https://spell.sh/r/{name}.json" } } diff --git a/apps/web/index.html b/apps/web/index.html index 88e1c8b4f2..dadef17d3b 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -48,6 +48,7 @@ background: #ffffff; color: #262626; font-family: + "DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, @@ -83,12 +84,6 @@ object-fit: contain; } - - - T3 Code (Alpha) diff --git a/apps/web/package.json b/apps/web/package.json index c336dd7735..cbf554a667 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.26", + "version": "0.0.27", "private": true, "type": "module", "scripts": { @@ -21,6 +21,8 @@ "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", "@effect/atom-react": "catalog:", + "@fontsource-variable/dm-sans": "^5.2.8", + "@fontsource/jetbrains-mono": "^5.2.8", "@formkit/auto-animate": "^0.9.0", "@legendapp/list": "3.0.0-beta.44", "@lexical/react": "^0.41.0", @@ -41,6 +43,9 @@ "react": "19.2.6", "react-dom": "19.2.6", "react-markdown": "^10.1.0", + "rehype-raw": "^7.0.0", + "rehype-sanitize": "^6.0.0", + "remark-breaks": "^4.0.0", "remark-gfm": "^4.0.1", "tailwind-merge": "^3.4.0", "zustand": "^5.0.11" diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts index 9baae20a68..dc09a7fa04 100644 --- a/apps/web/src/cloud/linkEnvironment.test.ts +++ b/apps/web/src/cloud/linkEnvironment.test.ts @@ -514,7 +514,7 @@ describe("web cloud link environment client", () => { expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include"); expect(String(fetchMock.mock.calls[1]?.[0])).toBe( - "http://127.0.0.1:3000/api/cloud/link-proof", + "http://127.0.0.1:3000/api/connect/link-proof", ); expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ method: "POST", @@ -553,7 +553,7 @@ describe("web cloud link environment client", () => { }); expect(String(fetchMock.mock.calls[3]?.[0])).toBe( - "http://127.0.0.1:3000/api/cloud/relay-config", + "http://127.0.0.1:3000/api/connect/relay-config", ); expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({ method: "POST", @@ -615,7 +615,7 @@ describe("web cloud link environment client", () => { publishAgentActivity: false, }); expect(String(fetchMock.mock.calls[0]?.[0])).toBe( - "http://127.0.0.1:3000/api/cloud/link-state", + "http://127.0.0.1:3000/api/connect/link-state", ); expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ method: "GET", @@ -654,7 +654,7 @@ describe("web cloud link environment client", () => { }), ); - expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink"); + expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink"); expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ method: "POST", credentials: "include", @@ -698,7 +698,7 @@ describe("web cloud link environment client", () => { ); expect(fetchMock).toHaveBeenCalledTimes(2); - expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink"); + expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink"); expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ method: "POST", credentials: "include", diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index f68849e276..b13b324a41 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -451,7 +451,7 @@ export function readPrimaryCloudLinkState(): Effect.Effect< return null; } const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/")); - return yield* client.cloud + return yield* client.connect .linkState({ headers: {} }) .pipe( withPrimaryEnvironmentRequestInit, @@ -465,7 +465,7 @@ export function updatePrimaryCloudPreferences(input: { }): Effect.Effect { return Effect.gen(function* () { const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/")); - return yield* client.cloud + return yield* client.connect .preferences({ headers: {}, payload: input, @@ -488,7 +488,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: { }); } const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/")); - yield* client.cloud + yield* client.connect .unlink({ headers: {} }) .pipe( withPrimaryEnvironmentRequestInit, @@ -568,7 +568,7 @@ export function linkEnvironmentToCloud(input: { ), ), ); - const proof = yield* environmentClient.cloud + const proof = yield* environmentClient.connect .linkProof({ headers, payload: { @@ -604,7 +604,7 @@ export function linkEnvironmentToCloud(input: { link, }); - yield* environmentClient.cloud + yield* environmentClient.connect .relayConfig({ headers, payload: { @@ -656,7 +656,7 @@ export function linkPrimaryEnvironmentToCloud(input: { ), ), ); - const proof = yield* environmentClient.cloud + const proof = yield* environmentClient.connect .linkProof({ headers: {}, payload: { @@ -695,7 +695,7 @@ export function linkPrimaryEnvironmentToCloud(input: { link, }); - yield* environmentClient.cloud + yield* environmentClient.connect .relayConfig({ headers: {}, payload: { diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.ts index ecc2297595..095ca84228 100644 --- a/apps/web/src/cloud/primaryCloudLinkState.ts +++ b/apps/web/src/cloud/primaryCloudLinkState.ts @@ -55,7 +55,7 @@ export function usePrimaryCloudLinkState() { let error: string | null = null; if (result._tag === "Failure") { const cause = Cause.squash(result.cause); - error = cause instanceof Error ? cause.message : "Could not read T3 Cloud link state."; + error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state."; } return { diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 152df1bf3e..72391f714f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -1,11 +1,12 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; -import { ChevronDownIcon } from "lucide-react"; +import { ChevronDownIcon, GitBranchIcon, SearchIcon } from "lucide-react"; import { useCallback, useDeferredValue, useEffect, + useLayoutEffect, useMemo, useOptimistic, useRef, @@ -37,7 +38,6 @@ import { ComboboxEmpty, ComboboxInput, ComboboxItem, - ComboboxList, ComboboxListVirtualized, ComboboxPopup, ComboboxStatus, @@ -281,7 +281,6 @@ export function BranchToolbarBranchSelector({ (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch, ); const [isBranchActionPending, startBranchActionTransition] = useTransition(); - const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40; const totalBranchCount = branchRefState.data?.totalCount ?? 0; const branchStatusText = isInitialBranchesLoadPending ? "Loading refs..." @@ -421,7 +420,9 @@ export function BranchToolbarBranchSelector({ [branchRefTarget], ); - const branchListScrollElementRef = useRef(null); + const branchListScrollElementRef = useRef(null); + const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false); + const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false); const fetchNextBranchPage = useCallback(() => { if (!hasNextPage || isFetchingNextPage) { return; @@ -451,44 +452,61 @@ export function BranchToolbarBranchSelector({ fetchNextBranchPage(); }, [fetchNextBranchPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]); + const branchListRef = useRef(null); - const setBranchListRef = useCallback((element: HTMLDivElement | null) => { - branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null; + const updateBranchListScrollFades = useCallback(() => { + const scrollElement = branchListRef.current?.getScrollableNode?.(); + if (!(scrollElement instanceof HTMLElement)) { + return; + } + branchListScrollElementRef.current = scrollElement; + const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight); + setShowTopBranchScrollFade(scrollElement.scrollTop > 1); + setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); }, []); + useEffect(() => { + if (isBranchMenuOpen) { + return; + } + setShowTopBranchScrollFade(false); + setShowBottomBranchScrollFade(false); + }, [isBranchMenuOpen]); + + useLayoutEffect(() => { + if (!isBranchMenuOpen) { + return; + } + + setShowTopBranchScrollFade(false); + setShowBottomBranchScrollFade(filteredBranchPickerItems.length > 8); + let nestedFrame = 0; + const frame = requestAnimationFrame(() => { + updateBranchListScrollFades(); + nestedFrame = requestAnimationFrame(updateBranchListScrollFades); + }); + return () => { + cancelAnimationFrame(frame); + cancelAnimationFrame(nestedFrame); + }; + }, [ + deferredTrimmedBranchQuery, + filteredBranchPickerItems.length, + isBranchMenuOpen, + updateBranchListScrollFades, + ]); + useEffect(() => { if (!isBranchMenuOpen) { return; } - if (shouldVirtualizeBranchList) { - branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false }); - } else { - branchListScrollElementRef.current?.scrollTo({ top: 0 }); - } - }, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]); + branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false }); + }, [deferredTrimmedBranchQuery, isBranchMenuOpen]); useEffect(() => { - const scrollElement = branchListScrollElementRef.current; - if (!scrollElement || !isBranchMenuOpen) { - return; - } - - const handleScroll = () => { - maybeFetchNextBranchPage(); - }; - - scrollElement.addEventListener("scroll", handleScroll, { passive: true }); - handleScroll(); - return () => { - scrollElement.removeEventListener("scroll", handleScroll); - }; - }, [isBranchMenuOpen, maybeFetchNextBranchPage]); - - useEffect(() => { - if (shouldVirtualizeBranchList) return; maybeFetchNextBranchPage(); - }, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]); + }, [refs.length, maybeFetchNextBranchPage]); const triggerLabel = getBranchTriggerLabel({ activeWorktreePath, @@ -504,6 +522,7 @@ export function BranchToolbarBranchSelector({ key={itemValue} index={index} value={itemValue} + className="pe-2" onClick={() => { if (!prReference || !onCheckoutPullRequestRequest) { return; @@ -533,6 +552,7 @@ export function BranchToolbarBranchSelector({ key={itemValue} index={index} value={itemValue} + className="pe-1.5" onClick={() => createRef(trimmedBranchQuery)} > Create new ref "{trimmedBranchQuery}" @@ -560,10 +580,11 @@ export function BranchToolbarBranchSelector({ key={itemValue} index={index} value={itemValue} + className="pe-1.5" onClick={() => selectBranch(refName)} > -
- {itemValue} +
+ {itemValue} {badge && {badge}}
@@ -575,7 +596,7 @@ export function BranchToolbarBranchSelector({ items={branchPickerItems} filteredItems={filteredBranchPickerItems} autoHighlight - virtualized={shouldVirtualizeBranchList} + virtualized onItemHighlighted={(_value, eventDetails) => { if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") { return; @@ -594,48 +615,64 @@ export function BranchToolbarBranchSelector({ className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)} disabled={isInitialBranchesLoadPending || isBranchActionPending} > + {triggerLabel} - + - -
- setBranchQuery(event.target.value)} - /> -
- No refs found. - - {shouldVirtualizeBranchList ? ( - - - ref={branchListRef} - data={filteredBranchPickerItems} - keyExtractor={(item) => item} - renderItem={({ item, index }) => renderPickerItem(item, index)} - estimatedItemSize={28} - drawDistance={336} - onEndReached={() => { - if (hasNextPage && !isFetchingNextPage) { - fetchNextBranchPage(); - } - }} - style={{ maxHeight: "14rem" }} + +
+
+
+
+
+ No refs found. +
+ + + ref={branchListRef} + data={filteredBranchPickerItems} + keyExtractor={(item) => item} + renderItem={({ item, index }) => renderPickerItem(item, index)} + estimatedItemSize={28} + drawDistance={336} + onEndReached={() => { + if (hasNextPage && !isFetchingNextPage) { + fetchNextBranchPage(); + } + }} + onLayout={() => { + updateBranchListScrollFades(); + maybeFetchNextBranchPage(); + }} + onScroll={() => { + updateBranchListScrollFades(); + maybeFetchNextBranchPage(); + }} + className={cn( + "scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 pt-2 pb-1 [--fade-size:1.5rem]", + showTopBranchScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]", + showBottomBranchScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]", + )} + style={{ maxHeight: "14rem" }} + /> + +
+ {branchStatusText ? {branchStatusText} : null} +
); diff --git a/apps/web/src/components/ChatMarkdown.browser.tsx b/apps/web/src/components/ChatMarkdown.browser.tsx index b2b2989e92..e047392c12 100644 --- a/apps/web/src/components/ChatMarkdown.browser.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.tsx @@ -24,6 +24,7 @@ vi.mock("../localApi", () => ({ })); import ChatMarkdown from "./ChatMarkdown"; +import { serializeTableElementToCsv, serializeTableElementToMarkdown } from "../markdown-clipboard"; describe("ChatMarkdown", () => { afterEach(() => { @@ -134,8 +135,550 @@ describe("ChatMarkdown", () => { await expect.element(link).toBeInTheDocument(); await expect.element(link).toHaveAttribute("href", "https://openai.com/docs"); await expect.element(link).toHaveAttribute("target", "_blank"); + const favicon = link.element().querySelector(".chat-markdown-link-favicon"); + const leading = link.element().querySelector(".chat-markdown-link-leading"); + expect(favicon).not.toBeNull(); + expect(leading).not.toBeNull(); + expect(leading?.contains(favicon)).toBe(true); + expect(getComputedStyle(leading!).display).toBe("inline"); + expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap"); + expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline"); + expect(leading?.textContent).toBe("O"); + expect(link.element().textContent).toBe("OpenAI"); + expect(getComputedStyle(link.element()).textDecorationLine).toBe("none"); + expect(link.element().querySelector("img, svg")?.getBoundingClientRect().width).toBe(14); + await link.hover(); + expect(getComputedStyle(link.element()).backgroundImage).not.toBe("none"); + await expect.element(page.getByText("https://openai.com/docs")).toBeVisible(); } finally { await screen.unmount(); } }); + + it("keeps a favicon with the leading segment of a wrapping URL", async () => { + const url = "https://github.com/pingdotgg/t3code/pull/3017/changes"; + const screen = await render( +
+ +
, + ); + + try { + const link = page.getByRole("link", { name: url }); + const leading = link.element().querySelector(".chat-markdown-link-leading"); + const favicon = link.element().querySelector(".chat-markdown-link-favicon"); + expect(leading).not.toBeNull(); + expect(favicon).not.toBeNull(); + expect(leading?.contains(favicon)).toBe(true); + expect(leading?.textContent).toBe("https://"); + expect(getComputedStyle(leading!).display).toBe("inline"); + expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap"); + expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline"); + expect(link.element().textContent).toBe(url); + expect(link.element().querySelectorAll("wbr").length).toBeGreaterThan(0); + const markdownRoot = link.element().closest(".chat-markdown"); + expect(markdownRoot).not.toBeNull(); + expect(markdownRoot!.scrollWidth).toBeLessThanOrEqual(markdownRoot!.clientWidth); + } finally { + await screen.unmount(); + } + }); + + it("renders file links with the shared file tag chip treatment", async () => { + const screen = await render( + , + ); + + try { + const link = page.getByRole("link", { name: "package.json" }); + await expect.element(link).toHaveClass(/chat-markdown-file-link/); + const element = document.querySelector(".chat-markdown-file-link"); + expect(element?.querySelector("img, svg")).not.toBeNull(); + expect(getComputedStyle(element!).display).toBe("inline-flex"); + expect(getComputedStyle(element!).textDecorationLine).toBe("none"); + expect(getComputedStyle(element!).borderStyle).toBe("solid"); + expect(getComputedStyle(element!).userSelect).not.toBe("none"); + } finally { + await screen.unmount(); + } + }); + + it("renders sanitized details with the design-system collapsible", async () => { + const source = [ + "
", + "Expandable details section", + "", + "This content includes **formatted text**.", + "", + 'Safe inline HTML', + "", + "
", + ].join("\n"); + const screen = await render(); + + try { + const details = document.querySelector("[data-markdown-details]"); + const trigger = page.getByRole("button", { name: "Expandable details section" }); + expect(details).not.toBeNull(); + expect(details?.tagName).toBe("DIV"); + await expect.element(trigger).toHaveAttribute("aria-expanded", "true"); + expect(details?.querySelector("strong")?.textContent).toBe("formatted text"); + expect(details?.querySelector("script")).toBeNull(); + expect(details?.querySelector("[title]")).toBeNull(); + + await trigger.click(); + await expect.element(trigger).toHaveAttribute("aria-expanded", "false"); + await trigger.click(); + await expect.element(trigger).toHaveAttribute("aria-expanded", "true"); + } finally { + await screen.unmount(); + } + }); + + it("renders footnotes as same-document references", async () => { + const source = [ + "A claim with supporting context.[^context]", + "", + "[^context]: Supporting **footnote text**.", + ].join("\n"); + const screen = await render(); + + try { + const reference = document.querySelector( + '.chat-markdown a[data-footnote-ref=""]', + ); + const footnotes = document.querySelector( + ".chat-markdown section[data-footnotes]", + ); + expect(reference).not.toBeNull(); + expect(reference?.getAttribute("href")).toMatch(/^#user-content-fn-/); + expect(reference?.hasAttribute("target")).toBe(false); + expect(footnotes).not.toBeNull(); + expect(footnotes?.querySelector("strong")?.textContent).toBe("footnote text"); + expect(footnotes?.querySelector("a[data-footnote-backref]")?.target).toBe( + "", + ); + } finally { + await screen.unmount(); + } + }); + + it("navigates hash links within the clicked markdown message", async () => { + const source = [ + "A claim with supporting context.[^context]", + "", + "[^context]: Supporting footnote text.", + ].join("\n"); + const originalUrl = window.location.href; + const scrollIntoView = vi + .spyOn(HTMLElement.prototype, "scrollIntoView") + .mockImplementation(() => undefined); + const screen = await render( +
+ + +
, + ); + + try { + const markdownRoots = document.querySelectorAll(".chat-markdown"); + const secondRoot = markdownRoots[1]; + const secondReference = + secondRoot?.querySelector('a[data-footnote-ref=""]'); + const secondFootnote = secondRoot?.querySelector( + "section[data-footnotes] li[id]", + ); + expect(secondReference).not.toBeNull(); + expect(secondFootnote).not.toBeNull(); + + secondReference?.click(); + + expect(scrollIntoView).toHaveBeenCalledTimes(1); + expect(scrollIntoView.mock.instances[0]).toBe(secondFootnote); + expect(window.location.hash).toBe(secondReference?.hash); + + const secondBackref = secondRoot?.querySelector( + "a[data-footnote-backref]", + ); + expect(secondBackref).not.toBeNull(); + secondBackref?.click(); + + const secondReferenceTarget = secondReference?.closest("[id]"); + expect(scrollIntoView).toHaveBeenCalledTimes(2); + expect(scrollIntoView.mock.instances[1]).toBe(secondReferenceTarget); + } finally { + scrollIntoView.mockRestore(); + window.history.replaceState(window.history.state, "", originalUrl); + await screen.unmount(); + } + }); + + describe("code block chrome", () => { + it("shows icon-only language titles, text fallbacks, and filename overrides", async () => { + const source = [ + "```ts", + "const a = 1;", + "```", + "", + '```ts title="src/main.ts"', + "const b = 2;", + "```", + "", + "```text", + "plain", + "```", + ].join("\n"); + const screen = await render(); + + try { + const titles = [...document.querySelectorAll(".chat-markdown-codeblock-title")]; + expect(titles).toHaveLength(3); + + // Language with a known icon: icon XOR text — never the redundant pair. + const languageOnly = titles[0]!; + const hasIcon = languageOnly.querySelector("img") != null; + const hasText = (languageOnly.textContent ?? "").includes("ts"); + expect(hasIcon || hasText).toBe(true); + expect(hasIcon && hasText).toBe(false); + if (hasIcon) { + const languageTrigger = page.getByLabelText("Language: ts").first(); + await languageTrigger.hover(); + await vi.waitFor(() => { + const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); + expect(tooltip?.textContent).toContain("ts"); + }); + } + + // Explicit filename: text always shown. + expect(titles[1]!.textContent).toBe("src/main.ts"); + + // Unknown language: no icon attempt, text label. + expect(titles[2]!.querySelector("img")).toBeNull(); + expect(titles[2]!.textContent).toBe("text"); + } finally { + await screen.unmount(); + } + }); + + it("toggles line wrapping per block", async () => { + const screen = await render( + , + ); + + try { + const block = document.querySelector(".chat-markdown-codeblock"); + expect(block?.getAttribute("data-wrap")).toBe("false"); + + const toggle = page.getByRole("button", { name: "Wrap lines" }); + await expect.element(toggle).not.toHaveAttribute("title"); + await toggle.hover(); + await vi.waitFor(() => { + const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); + expect(tooltip?.textContent).toContain("Wrap lines"); + }); + await toggle.click(); + expect(block?.getAttribute("data-wrap")).toBe("true"); + + await page.getByRole("button", { name: "Disable line wrap" }).click(); + expect(block?.getAttribute("data-wrap")).toBe("false"); + } finally { + await screen.unmount(); + } + }); + }); + + it("scrolls wide tables horizontally instead of letter-wrapping cells", async () => { + const header = `| ${Array.from({ length: 8 }, (_, i) => `ColumnHeading${i}`).join(" | ")} |`; + const separator = `| ${Array.from({ length: 8 }, () => "---").join(" | ")} |`; + const row = `| ${Array.from({ length: 8 }, () => "averylongunbrokencellvalue@example-domain.com").join(" | ")} |`; + const screen = await render( + , + ); + + try { + const viewport = document.querySelector( + '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', + ); + expect(viewport).not.toBeNull(); + expect(viewport!.querySelector("table")).not.toBeNull(); + // Content exceeds the container — the scroll-fade viewport scrolls + // horizontally rather than squishing columns. + expect(viewport!.scrollWidth).toBeGreaterThan(viewport!.clientWidth); + // And cells keep their longest word intact instead of breaking mid-word. + const cell = viewport!.querySelector("td"); + expect(cell!.getBoundingClientRect().width).toBeGreaterThan(100); + } finally { + await screen.unmount(); + } + }); + + describe("table chrome", () => { + const longCell = + "This service has been experiencing intermittent latency spikes during peak traffic hours and the on-call team is investigating."; + + it("truncates cells by default and expands them from the footer toggle", async () => { + const source = ["| Name | Notes |", "| --- | --- |", `| api | ${longCell} |`].join("\n"); + const screen = await render(); + + try { + const container = document.querySelector(".chat-markdown-table-container"); + expect(container?.getAttribute("data-expanded")).toBe("false"); + + const noteCell = [...document.querySelectorAll(".chat-markdown td")].at(-1)!; + expect(getComputedStyle(noteCell).whiteSpace).toBe("nowrap"); + expect(noteCell.scrollWidth).toBeGreaterThan(noteCell.clientWidth); + + const expandButton = page.getByRole("button", { name: "Expand table cells" }); + await expect.element(expandButton).not.toHaveAttribute("title"); + await expandButton.hover(); + await vi.waitFor(() => { + const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); + expect(tooltip?.textContent).toContain("Expand table cells"); + }); + await expandButton.click(); + expect(container?.getAttribute("data-expanded")).toBe("true"); + expect(getComputedStyle(noteCell).whiteSpace).not.toBe("nowrap"); + + await page.getByRole("button", { name: "Collapse table cells" }).click(); + expect(container?.getAttribute("data-expanded")).toBe("false"); + + const copyButton = page.getByRole("button", { name: "Copy table" }); + await expect.element(copyButton).not.toHaveAttribute("title"); + await copyButton.hover(); + await vi.waitFor(() => { + const tooltip = document.querySelector('[data-slot="tooltip-popup"]'); + expect(tooltip?.textContent).toContain("Copy table"); + }); + expect(document.querySelector(".chat-markdown [title]")).toBeNull(); + } finally { + await screen.unmount(); + } + }); + + it("retains column widths when cells expand", async () => { + const source = [ + "| ID | Owner | Status | Priority | Region | Summary | Long Description | Metrics | Payload | Notes |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |", + '| 1001 | Ada Lovelace | Active | High | us-west-2 | Payment workflow migration | This cell has enough text to wrap across several lines when expanded without shrinking its column. | Requests: 128,440; Error rate: 0.04%; P95: 212ms | `{ "feature": "billing", "version": 3 }` | Needs post-release monitoring for 24 hours. |', + ].join("\n"); + const screen = await render(); + + try { + const viewport = document.querySelector( + '.chat-markdown-table-container [data-slot="scroll-area-viewport"]', + )!; + const table = viewport.querySelector("table")!; + const collapsedWidths = [...table.querySelectorAll("thead th")].map( + (cell) => cell.getBoundingClientRect().width, + ); + expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth); + + await page.getByRole("button", { name: "Expand table cells" }).click(); + + const expandedWidths = [...table.querySelectorAll("thead th")].map( + (cell) => cell.getBoundingClientRect().width, + ); + expect(expandedWidths).toHaveLength(collapsedWidths.length); + expandedWidths.forEach((width, index) => { + expect(width).toBeGreaterThanOrEqual(collapsedWidths[index]! - 1); + }); + expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth); + } finally { + await screen.unmount(); + } + }); + + it("exports tables as markdown and csv", async () => { + const source = [ + "| Name | Count |", + "| --- | ---: |", + '| widget, "deluxe" | 2 |', + "| plain | 1 |", + ].join("\n"); + const screen = await render(); + + try { + const table = document.querySelector(".chat-markdown table")!; + expect(serializeTableElementToMarkdown(table)).toBe( + ["| Name | Count |", "| --- | ---: |", '| widget, "deluxe" | 2 |', "| plain | 1 |"].join( + "\n", + ), + ); + expect(serializeTableElementToCsv(table)).toBe( + ["Name,Count", '"widget, ""deluxe""",2', "plain,1"].join("\n"), + ); + } finally { + await screen.unmount(); + } + }); + }); + + describe("copying rendered markdown", () => { + function copySelectedMarkdown(): { text: string; html: string } { + const root = document.querySelector(".chat-markdown"); + if (!root) throw new Error("chat-markdown root not rendered"); + const selection = window.getSelection(); + if (!selection) throw new Error("selection unavailable"); + selection.removeAllRanges(); + const range = document.createRange(); + range.selectNodeContents(root); + selection.addRange(range); + + const clipboardData = new DataTransfer(); + root.dispatchEvent( + new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true }), + ); + selection.removeAllRanges(); + return { + text: clipboardData.getData("text/plain"), + html: clipboardData.getData("text/html"), + }; + } + + it("round-trips links, emphasis, and inline code", async () => { + const screen = await render( + , + ); + + try { + const { text, html } = copySelectedMarkdown(); + expect(text).toBe( + "Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`.", + ); + expect(html).toContain('href="https://anthropic.com"'); + } finally { + await screen.unmount(); + } + }); + + it("round-trips block structure: headings, lists, quotes, and fences", async () => { + const source = [ + "## Heading", + "", + "- first", + "- second", + " - nested", + "", + "1. one", + "2. two", + "", + "- [x] done", + "- [ ] todo", + "", + "> quoted", + "", + "```ts", + "const x = 1;", + "", + "const y = 2;", + "```", + ].join("\n"); + const screen = await render(); + + try { + const { text } = copySelectedMarkdown(); + expect(text).toBe(source); + } finally { + await screen.unmount(); + } + }); + + it("round-trips tables with alignment", async () => { + const source = ["| Name | Count |", "| --- | ---: |", "| a | 1 |", "| b | 2 |"].join("\n"); + const screen = await render(); + + try { + const { text } = copySelectedMarkdown(); + expect(text).toBe(source); + } finally { + await screen.unmount(); + } + }); + + it("round-trips details rendered through the collapsible", async () => { + const source = [ + "
", + "Expandable details section", + "", + "This content includes **formatted text**.", + "
", + ].join("\n"); + const screen = await render(); + + try { + const { text } = copySelectedMarkdown(); + expect(text).toBe(source); + } finally { + await screen.unmount(); + } + }); + + it("excludes the code block header chrome from copied markdown", async () => { + const source = ["```ts", "const x = 1;", "```"].join("\n"); + const screen = await render(); + + try { + const { text } = copySelectedMarkdown(); + expect(text).toBe(source); + } finally { + await screen.unmount(); + } + }); + + it("copies file links as markdown and skips UI affordances", async () => { + const filePath = "/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts"; + const screen = await render( + , + ); + + try { + const { text, html } = copySelectedMarkdown(); + expect(text).toBe( + `See [PermissionRule.ts](/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts) for details.`, + ); + expect(html).toContain("PermissionRule.ts"); + expect(html).not.toContain(" { + const source = + "Use $agent-browser with [package.json](path/to/package.json) before continuing."; + const screen = await render( + , + ); + + try { + const root = document.querySelector(".chat-markdown")!; + const selection = window.getSelection()!; + selection.removeAllRanges(); + const range = document.createRange(); + range.selectNodeContents(root); + selection.addRange(range); + expect(selection.toString()).toContain("Agent Browser"); + expect(selection.toString()).toContain("package.json"); + selection.removeAllRanges(); + + const { text, html } = copySelectedMarkdown(); + expect(text).toBe(source); + expect(html).toContain("Agent Browser"); + expect(html).toContain("package.json"); + expect(html).not.toContain(">; + className?: string; + /** Treat single newlines as hard breaks — chat-style user input. */ + lineBreaks?: boolean; } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray> = []; @@ -74,6 +104,18 @@ const highlightedCodeCache = new LRUCache( MAX_HIGHLIGHT_CACHE_MEMORY_BYTES, ); const highlighterPromiseCache = new Map>(); +const CHAT_MARKDOWN_SANITIZE_SCHEMA = { + ...defaultSchema, + attributes: { + ...defaultSchema.attributes, + "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), + code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta"], + }, + protocols: { + ...defaultSchema.protocols, + href: [...(defaultSchema.protocols?.href ?? []), "file"], + }, +} satisfies Parameters[0]; function extractFenceLanguage(className: string | undefined): string { const match = className?.match(CODE_FENCE_LANGUAGE_REGEX); @@ -82,6 +124,64 @@ function extractFenceLanguage(className: string | undefined): string { return raw === "gitignore" ? "ini" : raw; } +const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i; +const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/; + +/** Pulls a filename out of fence meta: ```ts title="x.ts" / ```ts src/main.ts */ +function extractFenceTitle(meta: string | undefined): string | null { + if (!meta) return null; + const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta); + const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3]; + if (attrTitle) return attrTitle; + return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null; +} + +function extractPreCodeMeta(node: unknown): string | undefined { + const children = ( + node as + | { + children?: Array<{ + type?: string; + tagName?: string; + data?: { meta?: unknown }; + properties?: { dataCodeMeta?: unknown }; + }>; + } + | undefined + )?.children; + const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code"); + const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta; + return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; +} + +type MarkdownAstNode = { + type?: string; + meta?: unknown; + data?: { + hProperties?: Record; + }; + children?: MarkdownAstNode[]; +}; + +function remarkPreserveCodeMeta() { + return (tree: MarkdownAstNode) => { + const visit = (node: MarkdownAstNode) => { + if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) { + node.data = { + ...node.data, + hProperties: { + ...node.data?.hProperties, + dataCodeMeta: node.meta.trim(), + }, + }; + } + node.children?.forEach(visit); + }; + + visit(tree); + }; +} + function nodeToPlainText(node: ReactNode): string { if (typeof node === "string" || typeof node === "number") { return String(node); @@ -146,9 +246,254 @@ function getHighlighterPromise(language: string): Promise { return promise; } -function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) { +function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) { + const containerRef = useRef(null); + const tableRef = useRef(null); + const [expanded, setExpanded] = useState(false); const [copied, setCopied] = useState(false); const copiedTimerRef = useRef | null>(null); + const expandLabel = expanded ? "Collapse table cells" : "Expand table cells"; + const copyLabel = copied ? "Copied" : "Copy table"; + + function toggleExpanded() { + const table = tableRef.current; + if (!table) return; + + if (!expanded) { + const rows = [...table.rows]; + const columnWidths = rows.reduce((widths, row) => { + [...row.cells].forEach((cell, columnIndex) => { + widths[columnIndex] = Math.max( + widths[columnIndex] ?? 0, + cell.getBoundingClientRect().width, + ); + }); + return widths; + }, []); + + [...(table.tHead?.rows[0]?.cells ?? [])].forEach((cell, columnIndex) => { + cell.style.minWidth = `${columnWidths[columnIndex] ?? cell.getBoundingClientRect().width}px`; + }); + } + + setExpanded((value) => !value); + } + + const handleCopy = useCallback((format: "markdown" | "csv") => { + const table = containerRef.current?.querySelector("table"); + if (!table || typeof navigator === "undefined" || navigator.clipboard == null) { + return; + } + const text = + format === "markdown" + ? serializeTableElementToMarkdown(table) + : serializeTableElementToCsv(table); + void navigator.clipboard + .writeText(text) + .then(() => { + if (copiedTimerRef.current != null) { + clearTimeout(copiedTimerRef.current); + } + setCopied(true); + copiedTimerRef.current = setTimeout(() => { + setCopied(false); + copiedTimerRef.current = null; + }, 1200); + }) + .catch(() => undefined); + }, []); + + useEffect( + () => () => { + if (copiedTimerRef.current != null) { + clearTimeout(copiedTimerRef.current); + copiedTimerRef.current = null; + } + }, + [], + ); + + return ( +
+ + + {children} +
+
+
+ + + } + > + {expanded ? : } + + {expandLabel} + + + + + } + /> + } + > + {copied ? : } + + {copyLabel} + + + handleCopy("markdown")}>Copy as Markdown + handleCopy("csv")}>Copy as CSV + + +
+
+ ); +} + +function MarkdownDetails({ + children, + open = false, +}: Pick, "children" | "open">) { + const [isOpen, setIsOpen] = useState(open); + const childNodes = Children.toArray(children); + const summaryIndex = childNodes.findIndex( + (child) => isValidElement(child) && child.type === "summary", + ); + const summaryNode = summaryIndex >= 0 ? childNodes[summaryIndex] : null; + const summary = + isValidElement<{ children?: ReactNode }>(summaryNode) && summaryNode.props.children + ? summaryNode.props.children + : "Details"; + const content = childNodes.filter((_, index) => index !== summaryIndex); + + return ( + + + + {summary} + + +
+ {content} +
+
+
+ ); +} + +/** + * Filename titles render icon + text; language-only titles render just the + * icon (redundant next to its own name) and fall back to the language text + * when no specific icon exists or it fails to load. + */ +function MarkdownCodeBlockTitleContent({ + fenceTitle, + language, + theme, +}: { + fenceTitle: string | null; + language: string; + theme: "light" | "dark"; +}) { + const [failedIconUrl, setFailedIconUrl] = useState(null); + + if (fenceTitle) { + return ( + <> + + {fenceTitle} + + ); + } + + const fileName = syntheticFileNameForLanguageId(language); + const iconUrl = hasSpecificVscodeIconForFileName(fileName, theme) + ? getVscodeIconUrlForEntry(fileName, "file", theme) + : null; + if (!iconUrl || failedIconUrl === iconUrl) { + return {language}; + } + return ( + + + } + > + setFailedIconUrl(iconUrl)} + /> + + {language} + + ); +} + +function MarkdownCodeBlock({ + code, + language, + fenceTitle, + theme, + children, +}: { + code: string; + language: string; + fenceTitle: string | null; + theme: "light" | "dark"; + children: ReactNode; +}) { + const [copied, setCopied] = useState(false); + const [wrapped, setWrapped] = useState(false); + const copiedTimerRef = useRef | null>(null); + const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines"; + const copyLabel = copied ? "Copied" : "Copy code"; const handleCopy = useCallback(() => { if (typeof navigator === "undefined" || navigator.clipboard == null) { return; @@ -179,16 +524,57 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo ); return ( -
- +
+
+ + + + + + setWrapped((value) => !value)} + aria-label={wrapLabel} + /> + } + > + + + {wrapLabel} + + + + } + > + {copied ? : } + + {copyLabel} + + +
{children}
); @@ -279,18 +665,17 @@ function UncachedShikiCodeBlock({ interface MarkdownFileLinkProps { href: string; targetPath: string; + iconPath: string; displayPath: string; - filePath: string; label: string; + copyMarkdown: string; theme: "light" | "dark"; className?: string | undefined; } const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g; const MARKDOWN_FILE_LINK_CLASS_NAME = - "chat-markdown-file-link relative top-[2px] max-w-full no-underline"; -const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0"; -const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate"; + "chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70"; function pathParentSegments(path: string): string[] { const normalized = path.replaceAll("\\", "/"); @@ -367,12 +752,197 @@ function normalizeMarkdownLinkHrefKey(href: string): string { return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref; } +const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none"; + +/** Hosts whose favicon request already failed this session — skip straight to the globe. */ +const failedFaviconHosts = new Set(); + +function resolveExternalLinkHost(href: string | undefined): string | null { + if (!href) return null; + try { + const url = new URL(href); + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + return url.hostname || null; + } catch { + return null; + } +} + +const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) { + const [failedHost, setFailedHost] = useState(null); + return ( + + {failedHost === host || failedFaviconHosts.has(host) ? ( + + ) : ( + { + failedFaviconHosts.add(host); + setFailedHost(host); + }} + /> + )} + + ); +}); + +function leadingExternalLinkTextLength(text: string): number { + const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0]; + if (protocol) return protocol.length; + return Math.min(text.length, 1); +} + +function breakableExternalLinkText(text: string): ReactNode[] { + return Array.from(text, (character, index) => ( + + {character} + + + )); +} + +function plainHastText(node: unknown): string | null { + if (!node || typeof node !== "object" || !("children" in node) || !Array.isArray(node.children)) { + return null; + } + const parts = node.children.map((child) => { + if ( + child && + typeof child === "object" && + "type" in child && + child.type === "text" && + "value" in child && + typeof child.value === "string" + ) { + return child.value; + } + return null; + }); + return parts.every((part) => part !== null) ? parts.join("") : null; +} + +const SANITIZED_FRAGMENT_PREFIX = "user-content-"; + +function decodeMarkdownFragmentId(href: string): string { + const encodedId = href.slice(1); + try { + return decodeURIComponent(encodedId); + } catch { + return encodedId; + } +} + +function normalizeSanitizedFragmentId(id: string): string { + let normalizedId = id; + while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) { + normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length); + } + return normalizedId; +} + +function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null { + const decodedId = decodeMarkdownFragmentId(href); + const normalizedId = normalizeSanitizedFragmentId(decodedId); + const matchesFragment = (element: HTMLElement) => + element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId; + const markdownRoot = anchor.closest(".chat-markdown"); + if (markdownRoot) { + const localTargets = Array.from(markdownRoot.querySelectorAll("[id]")); + const localTarget = localTargets.find(matchesFragment); + if (localTarget) return localTarget; + } + + return ( + document.getElementById(decodedId) ?? + Array.from(document.querySelectorAll("[id]")).find(matchesFragment) ?? + null + ); +} + +function handleMarkdownFragmentClick(event: ReactMouseEvent, href: string) { + if ( + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + + const target = findMarkdownFragmentTarget(event.currentTarget, href); + if (!target) return; + + event.preventDefault(); + const nextUrl = new URL(window.location.href); + nextUrl.hash = href.slice(1); + window.history.pushState(window.history.state, "", nextUrl); + target.scrollIntoView({ block: "nearest" }); +} + +function MarkdownExternalLinkContent({ + host, + plainText, + children, +}: { + host: string; + plainText: string | null; + children: ReactNode; +}) { + if (plainText) { + const leadingLength = leadingExternalLinkTextLength(plainText); + return ( + <> + + + {plainText.slice(0, leadingLength)} + + {breakableExternalLinkText(plainText.slice(leadingLength))} + + ); + } + + const childNodes = Children.toArray(children); + const firstChild = childNodes[0]; + + if (typeof firstChild === "string" && firstChild.length > 0) { + const leadingLength = leadingExternalLinkTextLength(firstChild); + return ( + <> + + + {firstChild.slice(0, leadingLength)} + + {breakableExternalLinkText(firstChild.slice(leadingLength))} + {childNodes.slice(1)} + + ); + } + + return ( + <> + + + {firstChild} + + {childNodes.slice(1)} + + ); +} + const MarkdownFileLink = memo(function MarkdownFileLink({ href, targetPath, + iconPath, displayPath, - filePath, label, + copyMarkdown, theme, className, }: MarkdownFileLinkProps) { @@ -467,7 +1037,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ render={
{ event.preventDefault(); event.stopPropagation(); @@ -475,13 +1046,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({ }} onContextMenu={handleContextMenu} > - - {label} + } /> @@ -504,9 +1069,10 @@ function areMarkdownFileLinkPropsEqual( return ( previous.href === next.href && previous.targetPath === next.targetPath && + previous.iconPath === next.iconPath && previous.displayPath === next.displayPath && - previous.filePath === next.filePath && previous.label === next.label && + previous.copyMarkdown === next.copyMarkdown && previous.theme === next.theme && previous.className === next.className ); @@ -517,6 +1083,8 @@ function ChatMarkdown({ cwd, isStreaming = false, skills = EMPTY_MARKDOWN_SKILLS, + className, + lineBreaks = false, }: ChatMarkdownProps) { const { resolvedTheme } = useTheme(); const diffThemeName = resolveDiffThemeName(resolvedTheme); @@ -542,6 +1110,17 @@ function ChatMarkdown({ const markdownUrlTransform = useCallback((href: string) => { return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); }, []); + // Re-emit highlighted content as markdown so copying out of the rendered + // view keeps links, emphasis, lists, and code fences intact. + const handleCopy = useCallback((event: ReactClipboardEvent) => { + const selection = window.getSelection(); + if (!selection || selection.isCollapsed || !event.clipboardData) return; + const payload = chatMarkdownClipboardPayload(selection); + if (!payload) return; + event.preventDefault(); + event.clipboardData.setData("text/plain", payload.text); + event.clipboardData.setData("text/html", payload.html); + }, []); const markdownComponents = useMemo( () => ({ p({ node: _node, children, ...props }) { @@ -550,11 +1129,49 @@ function ChatMarkdown({ li({ node: _node, children, ...props }) { return
  • {renderSkillInlineMarkdownChildren(children, skills)}
  • ; }, - a({ node: _node, href, ...props }) { + a({ node, href, children, ...props }) { const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null; if (!fileLinkMeta) { - return ; + const faviconHost = resolveExternalLinkHost(href); + const isSameDocumentLink = href?.startsWith("#") ?? false; + const onClick = props.onClick; + const link = ( + { + onClick?.(event); + if (isSameDocumentLink && href) { + handleMarkdownFragmentClick(event, href); + } + }} + > + {faviconHost ? ( + + {children} + + ) : ( + children + )} + + ); + if (!faviconHost || !href) { + return link; + } + return ( + + + + {href} + + + ); } const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath); @@ -572,22 +1189,36 @@ function ChatMarkdown({ ); }, - pre({ node: _node, children, ...props }) { + table({ node: _node, ...props }) { + return ; + }, + details({ node: _node, children, open: detailsOpen }) { + return {children}; + }, + pre({ node, children, ...props }) { const codeBlock = extractCodeBlock(children); if (!codeBlock) { return
    {children}
    ; } + const language = extractFenceLanguage(codeBlock.className); + const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); return ( - + {children}}> {children}}> +
    diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 69e0e51406..5a92a244c5 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -1416,13 +1416,15 @@ async function waitForButtonByText(text: string): Promise { return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); } -function findButtonContainingText(text: string): HTMLButtonElement | null { - return (Array.from(document.querySelectorAll("button")).find((button) => - button.textContent?.includes(text), - ) ?? null) as HTMLButtonElement | null; +function findButtonContainingText(text: string): HTMLElement | null { + return ( + Array.from(document.querySelectorAll('button, [role="button"]')).find((button) => + button.textContent?.includes(text), + ) ?? null + ); } -async function waitForButtonContainingText(text: string): Promise { +async function waitForButtonContainingText(text: string): Promise { return waitForElement( () => findButtonContainingText(text), `Unable to find button containing "${text}".`, @@ -2341,7 +2343,7 @@ describe("ChatView timeline estimator parity (full app)", () => { const runButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( - (button) => button.title === "Run Lint", + (button) => button.getAttribute("aria-label") === "Run Lint", ) as HTMLButtonElement | null, "Unable to find Run Lint button.", ); @@ -2420,7 +2422,7 @@ describe("ChatView timeline estimator parity (full app)", () => { const runButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( - (button) => button.title === "Run Test", + (button) => button.getAttribute("aria-label") === "Run Test", ) as HTMLButtonElement | null, "Unable to find Run Test button.", ); @@ -3160,7 +3162,8 @@ describe("ChatView timeline estimator parity (full app)", () => { try { const initialModeButton = await waitForInteractionModeButton("Build"); - expect(initialModeButton.title).toContain("enter plan mode"); + expect(initialModeButton.getAttribute("aria-label")).toContain("enter plan mode"); + expect(initialModeButton.hasAttribute("title")).toBe(false); window.dispatchEvent( new KeyboardEvent("keydown", { @@ -3172,7 +3175,9 @@ describe("ChatView timeline estimator parity (full app)", () => { ); await waitForLayout(); - expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode"); + expect((await waitForInteractionModeButton("Build")).getAttribute("aria-label")).toContain( + "enter plan mode", + ); const composerEditor = await waitForComposerEditor(); composerEditor.focus(); @@ -3187,7 +3192,7 @@ describe("ChatView timeline estimator parity (full app)", () => { await vi.waitFor( async () => { - expect((await waitForInteractionModeButton("Plan")).title).toContain( + expect((await waitForInteractionModeButton("Plan")).getAttribute("aria-label")).toContain( "return to normal build mode", ); }, @@ -3205,7 +3210,9 @@ describe("ChatView timeline estimator parity (full app)", () => { await vi.waitFor( async () => { - expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode"); + expect( + (await waitForInteractionModeButton("Build")).getAttribute("aria-label"), + ).toContain("enter plan mode"); }, { timeout: 8_000, interval: 16 }, ); @@ -3214,6 +3221,89 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("focuses the composer and inserts printable text typed from the page background", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-target-type-to-focus" as MessageId, + targetText: "type-to-focus target", + }), + }); + + const backgroundTarget = document.createElement("div"); + backgroundTarget.tabIndex = -1; + document.body.append(backgroundTarget); + + try { + const composerEditor = await waitForComposerEditor(); + backgroundTarget.focus(); + expect(document.activeElement).not.toBe(composerEditor); + + const event = new KeyboardEvent("keydown", { + key: "h", + bubbles: true, + cancelable: true, + }); + backgroundTarget.dispatchEvent(event); + + await waitForComposerText("h"); + expect(event.defaultPrevented).toBe(true); + expect(document.activeElement).toBe(composerEditor); + + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "i", + bubbles: true, + cancelable: true, + }), + ); + + await waitForComposerText("hi"); + } finally { + backgroundTarget.remove(); + await mounted.cleanup(); + } + }); + + it("does not steal printable keys from editable targets or shortcut modifiers", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-target-type-to-focus-guards" as MessageId, + targetText: "type-to-focus guards target", + }), + }); + const input = document.createElement("input"); + document.body.append(input); + + try { + input.focus(); + input.dispatchEvent( + new KeyboardEvent("keydown", { + key: "x", + bubbles: true, + cancelable: true, + }), + ); + await waitForLayout(); + expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(""); + + window.dispatchEvent( + new KeyboardEvent("keydown", { + key: "k", + metaKey: true, + bubbles: true, + cancelable: true, + }), + ); + await waitForLayout(); + expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(""); + } finally { + input.remove(); + await mounted.cleanup(); + } + }); + it("uses the active draft route session when changing the base branch", async () => { const staleDraftId = draftIdFromPath("/draft/draft-stale-branch-session"); const activeDraftId = draftIdFromPath("/draft/draft-active-branch-session"); @@ -3587,13 +3677,13 @@ describe("ChatView timeline estimator parity (full app)", () => { }, { timeout: 8_000, interval: 16 }, ); - await waitForComposerText("hi @package.json there"); + await waitForComposerText("hi [package.json](package.json) there"); await setComposerSelectionByTextOffsets({ start: "hi package.json ".length, end: "hi package.json there".length, }); await pressComposerKey("("); - await waitForComposerText("hi @package.json (there)"); + await waitForComposerText("hi [package.json](package.json) (there)"); } finally { await mounted.cleanup(); } @@ -3625,6 +3715,47 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("stores selected file tags as markdown links while keeping the composer chip", async () => { + useComposerDraftStore.getState().setPrompt(THREAD_REF, "@pack"); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-file-tag-encoding" as MessageId, + targetText: "file tag encoding", + }), + resolveRpc: (body) => { + if (body._tag !== WS_METHODS.projectsSearchEntries) { + return undefined; + } + return { + entries: [ + { + path: "path/to/package.json", + kind: "file", + parentPath: "path/to", + }, + ], + truncated: false, + }; + }, + }); + + try { + const item = await waitForComposerMenuItem("path:file:path/to/package.json"); + item.click(); + + await waitForComposerText("[package.json](path/to/package.json) "); + const chip = await waitForElement( + () => document.querySelector('[data-composer-mention-chip="true"]'), + "Unable to find rendered composer file chip.", + ); + expect(chip.textContent).toContain("package.json"); + } finally { + await mounted.cleanup(); + } + }); + it("shows runtime mode descriptions in the desktop composer access select", async () => { setDraftThreadWithoutWorktree(); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index df5d5e4a2f..75fc0ad323 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -50,7 +50,6 @@ import { parseStandaloneComposerSlashCommand, } from "../composer-logic"; import { - deriveCompletionDividerBeforeEntryId, derivePendingApprovals, derivePendingUserInputs, derivePhase, @@ -61,9 +60,7 @@ import { findLatestProposedPlan, deriveWorkLogEntries, hasActionableProposedPlan, - hasToolActivityForTurn, isLatestTurnSettled, - formatElapsed, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; import { @@ -203,6 +200,35 @@ const EMPTY_PROPOSED_PLANS: Thread["proposedPlans"] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; +const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [ + "input", + "textarea", + "select", + '[contenteditable="true"]', + '[contenteditable="plaintext-only"]', + '[role="textbox"]', +].join(","); +const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ + "button", + "a[href]", + "summary", + '[role="button"]', + '[role="checkbox"]', + '[role="menuitem"]', + '[role="option"]', + '[role="radio"]', + '[role="switch"]', + '[role="tab"]', +].join(","); +const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [ + '[data-slot="dialog"]', + '[data-slot="menu-popup"]', + '[data-slot="select-popup"]', + '[data-slot="popover-popup"]', + '[data-slot="combobox-popup"]', + '[data-slot="autocomplete-popup"]', +].join(","); + type EnvironmentUnavailableState = { readonly environmentId: EnvironmentId; readonly label: string; @@ -211,6 +237,25 @@ type EnvironmentUnavailableState = { type ThreadPlanCatalogEntry = Pick; +function eventTargetElement(target: EventTarget | null): Element | null { + if (target instanceof Element) return target; + if (target instanceof Node) return target.parentElement; + return null; +} + +function shouldTypeToFocusComposer(event: KeyboardEvent): boolean { + if (event.defaultPrevented || event.isComposing) return false; + if (event.metaKey || event.ctrlKey || event.altKey) return false; + if (event.key.length !== 1) return false; + + const target = eventTargetElement(event.target); + if (target?.closest(TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false; + if (target?.closest(TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false; + if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false; + + return true; +} + function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] { return useStore( useMemo(() => { @@ -1469,14 +1514,7 @@ export default function ChatView(props: ChatViewProps) { const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; - const workLogEntries = useMemo( - () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined), - [activeLatestTurn?.turnId, threadActivities], - ); - const latestTurnHasToolActivity = useMemo( - () => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId), - [activeLatestTurn?.turnId, threadActivities], - ); + const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); const pendingApprovals = useMemo( () => derivePendingApprovals(threadActivities), [threadActivities], @@ -1811,25 +1849,6 @@ export default function ChatView(props: ChatViewProps) { return byUserMessageId; }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); - const completionSummary = useMemo(() => { - if (!latestTurnSettled) return null; - if (!activeLatestTurn?.startedAt) return null; - if (!activeLatestTurn.completedAt) return null; - if (!latestTurnHasToolActivity) return null; - - const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt); - return elapsed ? `Worked for ${elapsed}` : null; - }, [ - activeLatestTurn?.completedAt, - activeLatestTurn?.startedAt, - latestTurnHasToolActivity, - latestTurnSettled, - ]); - const completionDividerBeforeEntryId = useMemo(() => { - if (!latestTurnSettled) return null; - if (!completionSummary) return null; - return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn); - }, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]); const gitCwd = activeProject ? projectScriptCwd({ project: { cwd: activeProject.cwd }, @@ -1843,7 +1862,11 @@ export default function ChatView(props: ChatViewProps) { // `codex_personal`) surfaces its own status/message in the banner rather // than the default Codex's. Falls back to first-match-by-kind when no // saved instance id is available or the instance no longer exists. + const selectedProviderInstanceId = + providerStatuses.find((status) => status.instanceId === selectedProviderByThreadId) + ?.instanceId ?? null; const activeProviderInstanceId = + selectedProviderInstanceId ?? activeThread?.session?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? @@ -2698,6 +2721,18 @@ export default function ChatView(props: ChatViewProps) { modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, }; + if ( + !shortcutContext.terminalFocus && + !shortcutContext.modelPickerOpen && + shouldTypeToFocusComposer(event) + ) { + if (composerRef.current?.insertTextAtEnd(event.key)) { + event.preventDefault(); + event.stopPropagation(); + return; + } + } + const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext, }); @@ -3597,6 +3632,23 @@ export default function ChatView(props: ChatViewProps) { composerRef, ]); + const getModelDisabledReason = useCallback( + (instanceId: ProviderInstanceId, model: string): string | null => { + if (!activeThread) { + return null; + } + const reason = getStartedThreadModelChangeBlockReason({ + providers: providerStatuses, + hasStartedSession: activeThread.session !== null, + currentModelSelection: activeThread.modelSelection, + currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null, + nextModelSelection: { instanceId, model }, + }); + return reason ? `${reason.description} Start a new thread to use this model.` : null; + }, + [activeThread, providerStatuses], + ); + const onProviderModelSelect = useCallback( (instanceId: ProviderInstanceId, model: string) => { if (!activeThread) return; @@ -3804,12 +3856,10 @@ export default function ChatView(props: ChatViewProps) { key={activeThread.id} isWorking={isWorking} activeTurnInProgress={isWorking || !latestTurnSettled} - activeTurnId={activeLatestTurn?.turnId ?? null} activeTurnStartedAt={activeWorkStartedAt} listRef={legendListRef} timelineEntries={timelineEntries} - completionDividerBeforeEntryId={completionDividerBeforeEntryId} - completionSummary={completionSummary} + latestTurn={activeLatestTurn} turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId} activeThreadEnvironmentId={activeThread.environmentId} routeThreadKey={routeThreadKey} @@ -3915,6 +3965,7 @@ export default function ChatView(props: ChatViewProps) { onChangeActivePendingUserInputCustomAnswer } onProviderModelSelect={onProviderModelSelect} + getModelDisabledReason={getModelDisabledReason} toggleInteractionMode={toggleInteractionMode} handleRuntimeModeChange={handleRuntimeModeChange} handleInteractionModeChange={handleInteractionModeChange} diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 4484232c2b..982950be5e 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -95,6 +95,7 @@ export function buildProjectActionItems(input: { valuePrefix: string; icon: (project: Project) => ReactNode; runProject: (project: Project) => Promise; + shortcutCommand?: KeybindingCommand; }): CommandPaletteActionItem[] { return input.projects.map((project) => ({ kind: "action", @@ -103,6 +104,7 @@ export function buildProjectActionItems(input: { title: project.name, description: project.cwd, icon: input.icon(project), + ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}), run: async () => { await input.runProject(project); }, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 3e41a4f94d..8000f33412 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -676,6 +676,7 @@ function OpenCommandPaletteDialog() { buildProjectActionItems({ projects, valuePrefix: "new-thread-in", + shortcutCommand: "chat.new", icon: (project) => ( {addProjectCloneFlow?.step === "repository" ? ( - + + { + event.preventDefault(); + }} + onClick={() => { + void submitAddProjectCloneFlow(); + }} + /> + } + > + {isRemoteProjectPending ? "Working" : remoteProjectButtonLabel} + + Enter + + + + {remoteProjectButtonLabel ?? "Continue"} (Enter) + + ) : isBrowsing ? ( - + > + + {isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel} + + + {hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"} + + + + {submitActionLabel} ({addShortcutLabel}) + + ) : null}
    diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx index ab8e597ea6..2fcbd929e1 100644 --- a/apps/web/src/components/ComposerPromptEditor.tsx +++ b/apps/web/src/components/ComposerPromptEditor.tsx @@ -6,7 +6,7 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin"; import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin"; import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin"; import { type ServerProviderSkill } from "@t3tools/contracts"; -import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger"; +import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { $applyNodeReplacement, $createRangeSelection, @@ -64,14 +64,14 @@ import { type TerminalContextDraft, } from "~/lib/terminalContext"; import { cn } from "~/lib/utils"; -import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons"; +import { basenameOfPath } from "~/vscode-icons"; import { - COMPOSER_INLINE_CHIP_CLASS_NAME, COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME, SKILL_CHIP_ICON_SVG, } from "./composerInlineChip"; +import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { formatProviderSkillDisplayName } from "~/providerSkillPresentation"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; @@ -132,19 +132,12 @@ function ComposerMentionDecorator(props: { path: string }) { const theme = resolvedThemeFromDocument(); const chip = ( - - {basenameOfPath(props.path)} + ); @@ -175,8 +168,7 @@ class ComposerMentionNode extends DecoratorNode { constructor(path: string, key?: NodeKey) { super(key); - const normalizedPath = path.startsWith("@") ? path.slice(1) : path; - this.__path = normalizedPath; + this.__path = path; } override exportJSON(): SerializedComposerMentionNode { @@ -199,7 +191,7 @@ class ComposerMentionNode extends DecoratorNode { } override getTextContent(): string { - return `@${serializeComposerMentionPath(this.__path)}`; + return serializeComposerFileLink(this.__path); } override isInline(): true { @@ -918,6 +910,12 @@ function ComposerCommandKeyPlugin(props: { if (!props.onCommandKeyDown || !event) { return false; } + + if (key === "Enter" && (event.isComposing || event.keyCode === 229)) { + event.stopPropagation(); + return true; + } + const handled = props.onCommandKeyDown(key, event); if (handled) { event.preventDefault(); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index dfc25cad9c..c6d00d4bec 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -42,6 +42,7 @@ import { useSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; type DiffRenderMode = "stacked" | "split"; type DiffThemeType = "light" | "dark"; @@ -52,6 +53,8 @@ const DIFF_PANEL_UNSAFE_CSS = ` [data-file], [data-error-wrapper], [data-virtualizer-buffer] { + --diffs-header-font-family: var(--font-sans) !important; + --diffs-font-family: var(--font-mono) !important; --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; @@ -92,6 +95,37 @@ const DIFF_PANEL_UNSAFE_CSS = ` z-index: 4; background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important; border-bottom: 1px solid var(--border) !important; + align-items: center !important; + font-family: var(--font-sans) !important; + font-size: 12px !important; + line-height: 1 !important; + min-height: 32px !important; + padding-block: 6px !important; +} + +[data-diffs-header] [data-header-content] { + align-items: center !important; + line-height: 1 !important; +} + +[data-diffs-header] [data-metadata] { + align-items: center !important; + line-height: 1 !important; + font-variant-numeric: tabular-nums; +} + +[data-diffs-header] [data-additions-count], +[data-diffs-header] [data-deletions-count] { + font-family: var(--font-mono) !important; + font-size: 11px !important; + font-variant-numeric: tabular-nums; + line-height: 1 !important; +} + +[data-diffs-header] [data-change-icon], +[data-diffs-header] [data-rename-icon] { + display: block; + flex-shrink: 0; } [data-title] { @@ -102,6 +136,7 @@ const DIFF_PANEL_UNSAFE_CSS = ` text-decoration: underline; text-decoration-color: transparent; text-underline-offset: 2px; + font-family: var(--font-sans) !important; } [data-title]:hover { @@ -460,35 +495,41 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
    {orderedTurnDiffSummaries.map((summary) => ( - + + {summary.turnId} + ))}
    @@ -512,30 +553,50 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { - { - setDiffWordWrap(Boolean(pressed)); - }} - > - - - { - setDiffIgnoreWhitespace(Boolean(pressed)); - }} - > - - + + { + setDiffWordWrap(Boolean(pressed)); + }} + /> + } + > + + + + {diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"} + + + + { + setDiffIgnoreWhitespace(Boolean(pressed)); + }} + /> + } + > + + + + {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"} + + ); @@ -609,26 +670,36 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { ( - + + { + event.stopPropagation(); + toggleDiffFileCollapsed(fileKey); + }} + /> + } + > + {collapsed ? ( + + ) : ( + + )} + + + {collapsed ? "Expand diff" : "Collapse diff"} + + )} options={{ collapsed, diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index ef28523fe5..6a8dc53fbc 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -19,6 +19,7 @@ import { ChevronDownIcon, CloudUploadIcon, ExternalLinkIcon, + GitBranchPlusIcon, GitCommitIcon, InfoIcon, LockIcon, @@ -1611,7 +1612,10 @@ export default function GitActionsControl({ void initAction.run(); }} > - {initAction.isPending ? "Initializing..." : "Initialize Git"} + + + {initAction.isPending ? "Initializing..." : "Initialize Git"} + ) : ( diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx index cd1f76ed2c..a2a801a3b4 100644 --- a/apps/web/src/components/NoActiveThreadState.tsx +++ b/apps/web/src/components/NoActiveThreadState.tsx @@ -30,7 +30,7 @@ export function NoActiveThreadState() { -
    +
    Pick a thread to continue diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsx index afd4bb2e0b..62bd1ba89d 100644 --- a/apps/web/src/components/PlanSidebar.tsx +++ b/apps/web/src/components/PlanSidebar.tsx @@ -32,14 +32,14 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; function stepStatusIcon(status: string): React.ReactNode { if (status === "completed") { return ( - + ); } if (status === "inProgress") { return ( - + ); @@ -139,13 +139,14 @@ const PlanSidebar = memo(function PlanSidebar({
    {label} {activePlan ? ( - + {formatTimestamp(activePlan.createdAt, timestampFormat)} ) : null} @@ -211,12 +212,12 @@ const PlanSidebar = memo(function PlanSidebar({
    -
    {stepStatusIcon(step.status)}
    + {stepStatusIcon(step.status)}

    = [ { id: "play", label: "Play" }, @@ -219,17 +220,24 @@ export default function ProjectScriptsControl({ <> {primaryScript ? ( - + + onRunScript(primaryScript)} + /> + } + > + + + {primaryScript.name} + + + Run {primaryScript.name} +

    ) : ( - + + + } + > + + + Add action + + + Add action + )} = repository_path: "Group by repository path", separate: "Keep separate", }; +const SIDEBAR_ICON_ACTION_BUTTON_CLASS = + "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"; function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount { return Math.min( @@ -623,14 +625,20 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
    {terminalStatus && ( - - - + + + } + > + + + {terminalStatus.label} + )}
    @@ -652,13 +660,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) : !isThreadRunning ? ( appSettingsConfirmThreadArchive ? ( -
    +
    + +
    +
    +
    + +
    +
    + ); +}); + export const ChangedFilesTree = memo(function ChangedFilesTree(props: { turnId: TurnId; files: ReadonlyArray; @@ -22,6 +93,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: { () => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes], ); + const hasDirectoryNodes = directoryPathsKey.length > 0; const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`; const [directoryExpansionState, setDirectoryExpansionState] = useState<{ key: string; @@ -60,7 +132,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: { + + + } + > + + {props.planSidebarLabel} + + {planSidebarTooltip} + ) : null} @@ -283,6 +318,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: { compact: boolean; activeContextWindow: ReturnType; + activeThreadProviderDisplayName: string | null; isPreparingWorktree: boolean; pendingAction: { questionIndex: number; @@ -305,7 +341,12 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( }) { return ( <> - {props.activeContextWindow ? : null} + {props.activeContextWindow ? ( + + ) : null} {props.isPreparingWorktree ? ( Preparing worktree... ) : null} @@ -336,6 +377,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( export interface ChatComposerHandle { focusAtEnd: () => void; focusAt: (cursor: number) => void; + insertTextAtEnd: (text: string) => boolean; openModelPicker: () => void; toggleModelPicker: () => void; isModelPickerOpen: () => boolean; @@ -470,6 +512,7 @@ export interface ChatComposerProps { ) => void; onProviderModelSelect: (instanceId: ProviderInstanceId, model: string) => void; + getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null; toggleInteractionMode: () => void; handleRuntimeModeChange: (mode: RuntimeMode) => void; handleInteractionModeChange: (mode: ProviderInteractionMode) => void; @@ -544,6 +587,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPreviousActivePendingUserInputQuestion, onChangeActivePendingUserInputCustomAnswer, onProviderModelSelect, + getModelDisabledReason, toggleInteractionMode, handleRuntimeModeChange, handleInteractionModeChange, @@ -778,6 +822,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) () => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []), [activeThreadActivities], ); + const activeThreadProviderDisplayName = useMemo(() => { + if (!activeThreadModelSelection) return null; + const entry = providerStatuses.find( + (p) => p.instanceId === activeThreadModelSelection.instanceId, + ); + if (entry) { + return getProviderDisplayName(providerStatuses, entry.driver); + } + return formatProviderDisplayName(activeThreadModelSelection.instanceId); + }, [providerStatuses, activeThreadModelSelection]); // ------------------------------------------------------------------ // Composer-local state @@ -1472,7 +1526,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { snapshot, trigger } = resolveActiveComposerTrigger(); if (!trigger) return; if (item.type === "path") { - const replacement = `@${serializeComposerMentionPath(item.path)} `; + const replacement = `${serializeComposerFileLink(item.path)} `; const replacementRangeEnd = extendReplacementRangeForTrailingSpace( snapshot.value, trigger.rangeEnd, @@ -1835,6 +1889,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) focusAt: (cursor: number) => { composerEditorRef.current?.focusAt(cursor); }, + insertTextAtEnd: (text: string) => { + if ( + text.length === 0 || + isConnecting || + isComposerApprovalState || + pendingUserInputs.length > 0 || + (environmentUnavailable !== null && activePendingProgress === null) + ) { + return false; + } + const rangeEnd = promptRef.current.length; + return applyPromptReplacement(rangeEnd, rangeEnd, text); + }, openModelPicker: () => { setIsComposerModelPickerOpen(true); }, @@ -1919,6 +1986,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, composerImagesRef, composerTerminalContextsRef, + isConnecting, + isComposerApprovalState, + pendingUserInputs.length, + environmentUnavailable, + activePendingProgress, + applyPromptReplacement, isComposerModelPickerOpen, readComposerSnapshot, selectedModel, @@ -2132,7 +2205,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} > {composerMenuOpen && !isComposerApprovalState && ( -
    +
    0 && "pt-2", isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0", showMobilePendingAnswerActions && "hidden sm:flex", )} @@ -2328,6 +2402,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onOpenChange={(open) => { setIsComposerModelPickerOpen(open); }} + getModelDisabledReason={getModelDisabledReason} onInstanceModelChange={onProviderModelSelect} /> @@ -2378,6 +2453,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    -

    - {activeThreadTitle} -

    - {activeProjectName && ( - - {activeProjectName} - - )} - {activeProjectName && !isGitRepo && ( - - No Git - - )} + + + {activeThreadTitle} + + } + /> + {activeThreadTitle} +
    {activeProjectScripts && ( @@ -146,7 +139,7 @@ export const ChatHeader = memo(function ChatHeader({ pressed={terminalOpen} onPressedChange={onToggleTerminal} aria-label="Toggle terminal drawer" - variant="outline" + variant="ghost" size="xs" disabled={!terminalAvailable} > @@ -170,7 +163,7 @@ export const ChatHeader = memo(function ChatHeader({ pressed={diffOpen} onPressedChange={onToggleDiff} aria-label="Toggle diff panel" - variant="outline" + variant="ghost" size="xs" disabled={!isGitRepo && !diffOpen} > diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index f687ec7ba2..7f2b180ed0 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -141,34 +141,35 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { >
    - - {groups.map((group, groupIndex) => ( -
    - {groupIndex > 0 ? : null} - - {group.label ? ( - - {group.label} - - ) : null} - {group.items.map((item) => ( - - ))} - -
    - ))} -
    - {props.items.length === 0 ? ( -
    + {props.items.length > 0 ? ( + + {groups.map((group, groupIndex) => ( +
    + {groupIndex > 0 ? : null} + + {group.label ? ( + + {group.label} + + ) : null} + {group.items.map((item) => ( + + ))} + +
    + ))} +
    + ) : ( +
    {props.triggerKind === "skill" ? ( @@ -192,7 +193,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {

    )}
    - ) : null} + )}
    ); diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 3b4093e380..bf869d25c6 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -1,5 +1,5 @@ import { type ApprovalRequestId } from "@t3tools/contracts"; -import { memo, useEffect, useEffectEvent, useRef } from "react"; +import { memo, useEffect, useEffectEvent, useRef, useState } from "react"; import { type PendingUserInput } from "../../session-logic"; import { derivePendingUserInputProgress, @@ -61,11 +61,36 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( const activeQuestion = progress.activeQuestion; const autoAdvanceTimerRef = useRef(null); const onAdvanceRef = useRef(onAdvance); + const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{ + questionId: string; + optionLabel: string; + } | null>(null); useEffect(() => { onAdvanceRef.current = onAdvance; }, [onAdvance]); + useEffect(() => { + if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) { + return; + } + if (optimisticSingleSelect.questionId !== activeQuestion.id) { + setOptimisticSingleSelect(null); + return; + } + if ( + progress.customAnswer.trim().length === 0 && + progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel) + ) { + setOptimisticSingleSelect(null); + } + }, [ + activeQuestion, + optimisticSingleSelect, + progress.customAnswer, + progress.selectedOptionLabels, + ]); + // Clear auto-advance timer on unmount useEffect(() => { return () => { @@ -76,10 +101,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( }, []); const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => { - onToggleOption(questionId, optionLabel); if (activeQuestion?.multiSelect) { + onToggleOption(questionId, optionLabel); return; } + setOptimisticSingleSelect({ questionId, optionLabel }); + onToggleOption(questionId, optionLabel); if (autoAdvanceTimerRef.current !== null) { window.clearTimeout(autoAdvanceTimerRef.current); } @@ -123,64 +150,77 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( return null; } + const customAnswerActive = progress.customAnswer.trim().length > 0; + return (
    -
    -
    - {prompt.questions.length > 1 ? ( - - {questionIndex + 1}/{prompt.questions.length} - - ) : null} - - {activeQuestion.header} +
    + + {activeQuestion.header} + + {prompt.questions.length > 1 ? ( + + {questionIndex + 1}/{prompt.questions.length} -
    + ) : null}
    -

    {activeQuestion.question}

    +

    {activeQuestion.question}

    {activeQuestion.multiSelect ? (

    Select one or more options.

    ) : null} -
    +
    {activeQuestion.options.map((option, index) => { - const isSelected = progress.selectedOptionLabels.includes(option.label); + const isOptimisticallySelected = + optimisticSingleSelect?.questionId === activeQuestion.id && + optimisticSingleSelect.optionLabel === option.label; + const isSelected = + isOptimisticallySelected || + (!customAnswerActive && progress.selectedOptionLabels.includes(option.label)); const shortcutKey = index < 9 ? index + 1 : null; - return ( - + + ); + return ( +
    { + if (isResponding) return; + handleOptionSelection(activeQuestion.id, option.label); + }} + className={className} + > + {content} +
    ); })}
    diff --git a/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx b/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx index 49b03f7724..ea193edfef 100644 --- a/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx +++ b/apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx @@ -1,4 +1,5 @@ import { memo } from "react"; +import { Badge } from "../ui/badge"; export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBanner({ planTitle, @@ -8,7 +9,13 @@ export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBann return (
    - Plan ready + + Plan Ready + {planTitle ? ( {planTitle} ) : null} diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index fbeb9de30b..8999e43084 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -3,6 +3,7 @@ import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; +import { Spinner } from "../ui/spinner"; interface PendingActionState { questionIndex: number; @@ -126,7 +127,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ return ( } /> - -
    -
    - Context window + +
    +
    +
    Context Window
    + {usage.maxTokens !== null && usedPercentage ? ( +
    + {usedPercentage} + · + + {formatContextWindowTokens(usage.usedTokens)}/ + {formatContextWindowTokens(usage.maxTokens ?? null)} + +
    + ) : ( +
    + {formatContextWindowTokens(usage.usedTokens)} +
    + )}
    - {usage.maxTokens !== null && usedPercentage ? ( -
    - {usedPercentage} - ⋅ - {formatContextWindowTokens(usage.usedTokens)} - / - {formatContextWindowTokens(usage.maxTokens ?? null)} context used + {usage.maxTokens !== null ? ( +
    +
    - ) : ( -
    - {formatContextWindowTokens(usage.usedTokens)} tokens used so far -
    - )} - {(usage.totalProcessedTokens ?? null) !== null && - (usage.totalProcessedTokens ?? 0) > usage.usedTokens ? ( -
    - Total processed: {formatContextWindowTokens(usage.totalProcessedTokens ?? null)}{" "} - tokens + ) : null} + {showTotalProcessed ? ( +
    + Total processed + + {formatContextWindowTokens(totalProcessedTokens)} +
    ) : null} {usage.compactsAutomatically ? ( -
    - Automatically compacts its context when needed. +
    + {providerDisplayName ?? "It"} automatically compacts its context when needed.
    ) : null}
    diff --git a/apps/web/src/components/chat/DiffStatLabel.tsx b/apps/web/src/components/chat/DiffStatLabel.tsx index 2dda06fd9d..8fd7e90e38 100644 --- a/apps/web/src/components/chat/DiffStatLabel.tsx +++ b/apps/web/src/components/chat/DiffStatLabel.tsx @@ -1,21 +1,46 @@ import { memo } from "react"; +import { cn } from "~/lib/utils"; export function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean { return stat.additions > 0 || stat.deletions > 0; } +function formatCompactDiffCount(value: number): string { + if (value < 1000) return String(value); + if (value < 1_000_000) { + const k = value / 1000; + return `${k < 10 ? k.toFixed(1).replace(/\.0$/, "") : Math.round(k)}k`; + } + if (value < 1_000_000_000) { + const m = value / 1_000_000; + return `${m < 10 ? m.toFixed(1).replace(/\.0$/, "") : Math.round(m)}m`; + } + const b = value / 1_000_000_000; + return `${b < 10 ? b.toFixed(1).replace(/\.0$/, "") : Math.round(b)}b`; +} + export const DiffStatLabel = memo(function DiffStatLabel(props: { additions: number; deletions: number; + className?: string; showParentheses?: boolean; + layout?: "aligned" | "inline"; }) { - const { additions, deletions, showParentheses = false } = props; + const { additions, deletions, className, showParentheses = false, layout = "aligned" } = props; return ( <> {showParentheses && (} - +{additions} - / - -{deletions} + + +{formatCompactDiffCount(additions)} + -{formatCompactDiffCount(deletions)} + {showParentheses && )} ); diff --git a/apps/web/src/components/chat/FileTagChip.tsx b/apps/web/src/components/chat/FileTagChip.tsx new file mode 100644 index 0000000000..81f8021b92 --- /dev/null +++ b/apps/web/src/components/chat/FileTagChip.tsx @@ -0,0 +1,39 @@ +import { inferEntryKindFromPath } from "../../vscode-icons"; +import { + CHAT_INLINE_CHIP_CLASS_NAME, + CHAT_INLINE_CHIP_LABEL_CLASS_NAME, + COMPOSER_INLINE_CHIP_CLASS_NAME, + COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, + COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, +} from "../composerInlineChip"; +import { VscodeEntryIcon } from "./VscodeEntryIcon"; + +export const FILE_TAG_CHIP_CLASS_NAME = COMPOSER_INLINE_CHIP_CLASS_NAME; +export const CHAT_FILE_TAG_CHIP_CLASS_NAME = CHAT_INLINE_CHIP_CLASS_NAME; + +export function FileTagChipContent(props: { + path: string; + label: string; + theme: "light" | "dark"; + selectable?: boolean; +}) { + return ( + <> + + + {props.label} + + + ); +} diff --git a/apps/web/src/components/chat/MessageCopyButton.tsx b/apps/web/src/components/chat/MessageCopyButton.tsx index ad5d56dd5a..e6a6a491bb 100644 --- a/apps/web/src/components/chat/MessageCopyButton.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.tsx @@ -68,11 +68,11 @@ export const MessageCopyButton = memo(function MessageCopyButton({ type="button" size={size} variant={variant} - className={cn(className)} + className={cn("text-muted-foreground hover:text-foreground", className)} /> } > - {isCopied ? : } + {isCopied ? : }

    Copy to clipboard

    diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.tsx index c7aa3ef1f1..1d633f51d8 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.tsx @@ -7,6 +7,8 @@ import { page } from "vite-plus/test/browser"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { render } from "vitest-browser-react"; +import { getVscodeIconUrlForEntry } from "../../vscode-icons"; + const scrollToEndSpy = vi.fn(); const getStateSpy = vi.fn(() => ({ isAtEnd: true })); @@ -52,11 +54,9 @@ function buildProps() { return { isWorking: false, activeTurnInProgress: false, - activeTurnId: null, activeTurnStartedAt: null, listRef: createRef(), - completionDividerBeforeEntryId: null, - completionSummary: null, + latestTurn: null, turnDiffSummaryByAssistantMessageId: new Map(), routeThreadKey: "environment-local:thread-1", onOpenTurnDiff: vi.fn(), @@ -94,6 +94,21 @@ function buildUserTimelineEntry(text: string) { }; } +function buildAssistantTimelineEntry(text: string) { + return { + id: "entry-assistant-1", + kind: "message" as const, + createdAt: MESSAGE_CREATED_AT, + message: { + id: "message-assistant-1" as never, + role: "assistant" as const, + text, + createdAt: MESSAGE_CREATED_AT, + streaming: false, + }, + }; +} + describe("MessagesTimeline", () => { afterEach(() => { scrollToEndSpy.mockReset(); @@ -114,9 +129,9 @@ describe("MessagesTimeline", () => { entry: { id: "work-1", createdAt: "2026-04-13T12:00:00.000Z", - label: "thinking", + label: "read files", detail: "Inspecting repository state", - tone: "thinking", + tone: "tool", }, }, ]} @@ -127,7 +142,51 @@ describe("MessagesTimeline", () => { await expect .element(page.getByText("Send a message to start the conversation.")) .not.toBeInTheDocument(); - await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible(); + await expect.element(page.getByText("Inspecting repository state")).toBeVisible(); + expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull(); + } finally { + await screen.unmount(); + } + }); + + it("uses accessible expansion instead of native titles or preview tooltips for work entry details", async () => { + const screen = await render( + , + ); + + try { + expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull(); + + const commandTrigger = page.getByLabelText( + "Command - git diff -- apps/web/src/components/ChatMarkdown.tsx", + ); + await commandTrigger.hover(); + expect(document.querySelector('[data-slot="tooltip-popup"]')).toBeNull(); + + await commandTrigger.click(); + await expect + .element(page.getByText("git diff -- apps/web/src/components/ChatMarkdown.tsx --stat")) + .toBeVisible(); } finally { await screen.unmount(); } @@ -161,16 +220,16 @@ describe("MessagesTimeline", () => { entry: { id: "work-1", createdAt: "2026-04-13T12:00:00.000Z", - label: "thinking", + label: "read files", detail: "Inspecting repository state", - tone: "thinking", + tone: "tool", }, }, ]} />, ); - await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible(); + await expect.element(page.getByText("Inspecting repository state")).toBeVisible(); expect(props.onIsAtEndChange).toHaveBeenCalledWith(true); expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false }); expect(requestAnimationFrameSpy).toHaveBeenCalled(); @@ -261,4 +320,162 @@ describe("MessagesTimeline", () => { await screen.unmount(); } }); + + it("renders user messages as markdown with chat-style line breaks", async () => { + const screen = await render( + , + ); + + try { + await expect.element(page.getByRole("heading", { level: 2, name: "Plan" })).toBeVisible(); + await expect + .element(page.getByRole("link", { name: "a link" })) + .toHaveAttribute("href", "https://example.com"); + + const messageBody = document.querySelector("[data-user-message-body='true']"); + expect(messageBody?.querySelector("strong")?.textContent).toBe("bold"); + // remark-breaks: the single newline between the inline runs is a
    . + expect(messageBody?.querySelectorAll("p br").length).toBe(1); + } finally { + await screen.unmount(); + } + }); + + it("renders markdown file tags in user and assistant messages", async () => { + const fileLink = "[package.json](path/to/package.json)"; + const screen = await render( + , + ); + + try { + const userFileLink = document.querySelector( + '[data-message-role="user"] .chat-markdown-file-link', + ); + const assistantFileLink = document.querySelector( + '[data-message-role="assistant"] .chat-markdown-file-link', + ); + + expect(userFileLink?.textContent).toContain("package.json"); + expect(userFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json"); + expect(assistantFileLink?.textContent).toContain("package.json"); + expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json"); + } finally { + await screen.unmount(); + } + }); + + it("uses the file path without line suffix for markdown file tag icons", async () => { + const fileLink = "[package.json](path/to/package.json:25)"; + const screen = await render( + , + ); + + try { + const assistantFileLink = document.querySelector( + '[data-message-role="assistant"] .chat-markdown-file-link', + ); + const icon = assistantFileLink?.querySelector("img"); + + expect(assistantFileLink?.textContent).toContain("package.json"); + expect(assistantFileLink?.textContent).toContain("L25"); + expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json:25"); + expect(icon?.getAttribute("src")).toBe( + getVscodeIconUrlForEntry("/repo/project/path/to/package.json", "file", "dark"), + ); + } finally { + await screen.unmount(); + } + }); + + it("folds settled-turn work behind a Worked-for row and expands it on click", async () => { + const screen = await render( + , + ); + + try { + const foldButton = page.getByRole("button", { name: "Worked for 30s" }); + await expect.element(foldButton).toBeVisible(); + await expect.element(foldButton).toHaveAttribute("aria-expanded", "false"); + + expect(document.body.textContent).toContain("All done."); + expect(document.body.textContent).not.toContain("Let me look around first."); + expect(document.body.textContent).not.toContain("Inspecting repository state"); + + await foldButton.click(); + + await expect.element(foldButton).toHaveAttribute("aria-expanded", "true"); + expect(document.body.textContent).toContain("Let me look around first."); + expect(document.body.textContent).toContain("Inspecting repository state"); + + await foldButton.click(); + + await expect.element(foldButton).toHaveAttribute("aria-expanded", "false"); + expect(document.body.textContent).not.toContain("Inspecting repository state"); + } finally { + await screen.unmount(); + } + }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 5b643263fe..032f863569 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -250,7 +250,7 @@ describe("deriveMessagesTimelineRows", () => { }, }, ], - completionDividerBeforeEntryId: "assistant-final-entry", + expandedTurnIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -265,7 +265,6 @@ describe("deriveMessagesTimelineRows", () => { expect(assistantRows).toHaveLength(2); expect(assistantRows[0]?.showAssistantCopyButton).toBe(false); expect(assistantRows[1]?.showAssistantCopyButton).toBe(true); - expect(assistantRows[1]?.showCompletionDivider).toBe(true); }); it("marks only the active assistant turn as streaming for copy controls", () => { @@ -300,11 +299,13 @@ describe("deriveMessagesTimelineRows", () => { }, }, ], - completionDividerBeforeEntryId: "assistant-two-entry", - completionSummary: "done", + latestTurn: { + turnId: "turn-2" as never, + state: "running", + startedAt: "2026-01-01T00:00:19Z", + completedAt: null, + }, isWorking: false, - activeTurnInProgress: true, - activeTurnId: "turn-2" as never, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), revertTurnCountByUserMessageId: new Map(), @@ -316,9 +317,7 @@ describe("deriveMessagesTimelineRows", () => { ); expect(assistantRows[0]?.assistantCopyStreaming).toBe(false); - expect(assistantRows[0]?.completionSummary).toBeNull(); expect(assistantRows[1]?.assistantCopyStreaming).toBe(true); - expect(assistantRows[1]?.completionSummary).toBe("done"); }); it("projects assistant diff summaries and user revert counts onto the affected rows", () => { @@ -360,7 +359,6 @@ describe("deriveMessagesTimelineRows", () => { }, }, ], - completionDividerBeforeEntryId: null, isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map([ @@ -381,6 +379,441 @@ describe("deriveMessagesTimelineRows", () => { expect(userRow?.revertTurnCount).toBe(1); expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary); }); + + it("folds settled-turn commentary and work behind a Worked-for row", () => { + const timelineEntries = [ + { + id: "user-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:00Z", + message: { + id: "user-1" as never, + role: "user" as const, + text: "Build it", + turnId: null, + createdAt: "2026-01-01T00:00:00Z", + streaming: false, + }, + }, + { + id: "assistant-thought-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant-thought" as never, + role: "assistant" as const, + text: "Looking around first.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + completedAt: "2026-01-01T00:00:06Z", + streaming: false, + }, + }, + { + id: "work-entry-1", + kind: "work" as const, + createdAt: "2026-01-01T00:00:08Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:08Z", + turnId: "turn-1" as never, + label: "Ran command", + tone: "tool" as const, + }, + }, + { + id: "assistant-final-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:20Z", + message: { + id: "assistant-final" as never, + role: "assistant" as const, + text: "Done", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:20Z", + completedAt: "2026-01-01T00:00:22Z", + streaming: false, + }, + }, + ]; + + const collapsedRows = deriveMessagesTimelineRows({ + timelineEntries, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + const foldRow = collapsedRows.find( + (row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> => + row.kind === "turn-fold", + ); + expect(foldRow?.turnId).toBe("turn-1"); + expect(foldRow?.expanded).toBe(false); + // User message boundary (00:00:00) → terminal message completedAt (00:00:22). + expect(foldRow?.label).toBe("Worked for 22s"); + expect(collapsedRows.map((row) => row.id)).toEqual([ + "user-entry", + "turn-fold:turn-1", + "assistant-final-entry", + ]); + + const expandedRows = deriveMessagesTimelineRows({ + timelineEntries, + expandedTurnIds: new Set(["turn-1" as never]), + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(expandedRows.map((row) => row.id)).toEqual([ + "user-entry", + "turn-fold:turn-1", + "assistant-thought-entry", + "work-entry-1", + "assistant-final-entry", + ]); + expect( + expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true), + ).toBeDefined(); + }); + + it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => { + // A steer ends the previous turn early: its only message completes the + // instant it is created, and trailing work entries land after it. The + // fold duration must span from the user message that started the turn to + // the last entry, not message createdAt → message completedAt (~0ms). + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "user-entry", + kind: "message", + createdAt: "2026-01-01T00:00:00Z", + message: { + id: "user-1" as never, + role: "user" as const, + text: "do it once more", + turnId: null, + createdAt: "2026-01-01T00:00:00Z", + streaming: false, + }, + }, + { + id: "assistant-commentary-entry", + kind: "message", + createdAt: "2026-01-01T00:00:09Z", + message: { + id: "assistant-commentary" as never, + role: "assistant" as const, + text: "Kicking off call 1.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:09Z", + completedAt: "2026-01-01T00:00:09Z", + streaming: false, + }, + }, + { + id: "work-entry-1", + kind: "work", + createdAt: "2026-01-01T00:00:12Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:12Z", + turnId: "turn-1" as never, + label: "Ran command", + tone: "tool" as const, + }, + }, + { + id: "steer-user-entry", + kind: "message", + createdAt: "2026-01-01T00:00:14Z", + message: { + id: "user-2" as never, + role: "user" as const, + text: "actually do 15", + turnId: null, + createdAt: "2026-01-01T00:00:14Z", + streaming: false, + }, + }, + { + id: "assistant-next-turn-entry", + kind: "message", + createdAt: "2026-01-01T00:00:17Z", + message: { + id: "assistant-next" as never, + role: "assistant" as const, + text: "One down — adjusting.", + turnId: "turn-2" as never, + createdAt: "2026-01-01T00:00:17Z", + streaming: true, + }, + }, + ], + latestTurn: { + turnId: "turn-2" as never, + state: "running", + startedAt: "2026-01-01T00:00:14Z", + completedAt: null, + }, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:14Z", + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + const foldRow = rows.find( + (row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> => + row.kind === "turn-fold", + ); + // User message (00:00:00) → trailing work entry (00:00:12). + expect(foldRow?.turnId).toBe("turn-1"); + expect(foldRow?.label).toBe("Worked for 12s"); + }); + + it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "work-entry-1", + kind: "work", + createdAt: "2026-01-01T00:00:05Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:05Z", + turnId: "turn-1" as never, + label: "Ran command", + tone: "tool" as const, + }, + }, + ], + latestTurn: { + turnId: "turn-1" as never, + state: "interrupted", + startedAt: "2026-01-01T00:00:00Z", + completedAt: "2026-01-01T00:00:47Z", + }, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(rows).toEqual([ + expect.objectContaining({ + kind: "turn-fold", + turnId: "turn-1", + label: "You stopped after 47s", + expanded: false, + }), + ]); + }); + + it("keeps the previous turn folded while a newly sent message awaits its turn", () => { + // Right after send, isWorking is true but latestTurn still points at the + // previous, settled turn — it must stay folded through that window. + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "work-entry-1", + kind: "work", + createdAt: "2026-01-01T00:00:05Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:05Z", + turnId: "turn-1" as never, + label: "Ran command", + tone: "tool" as const, + }, + }, + { + id: "assistant-final-entry", + kind: "message", + createdAt: "2026-01-01T00:00:20Z", + message: { + id: "assistant-final" as never, + role: "assistant", + text: "Done", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:20Z", + completedAt: "2026-01-01T00:00:22Z", + streaming: false, + }, + }, + { + id: "user-followup-entry", + kind: "message", + createdAt: "2026-01-01T00:01:00Z", + message: { + id: "user-followup" as never, + role: "user", + text: "yooo", + turnId: null, + createdAt: "2026-01-01T00:01:00Z", + streaming: false, + }, + }, + ], + latestTurn: { + turnId: "turn-1" as never, + state: "completed", + startedAt: "2026-01-01T00:00:00Z", + completedAt: "2026-01-01T00:00:22Z", + }, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:01:00Z", + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(rows.map((row) => row.id)).toEqual([ + "turn-fold:turn-1", + "assistant-final-entry", + "user-followup-entry", + "working-indicator-row", + ]); + const finalRow = rows.find((row) => row.id === "assistant-final-entry"); + expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true); + }); + + it("does not fold the active in-progress turn", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "assistant-thought-entry", + kind: "message", + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant-thought" as never, + role: "assistant", + text: "Working on it.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + completedAt: "2026-01-01T00:00:06Z", + streaming: false, + }, + }, + { + id: "work-entry-1", + kind: "work", + createdAt: "2026-01-01T00:00:08Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:08Z", + turnId: "turn-1" as never, + label: "Ran command", + tone: "tool" as const, + }, + }, + ], + latestTurn: { + turnId: "turn-1" as never, + state: "running", + startedAt: "2026-01-01T00:00:00Z", + completedAt: null, + }, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(rows.some((row) => row.kind === "turn-fold")).toBe(false); + expect(rows.map((row) => row.id)).toEqual([ + "assistant-thought-entry", + "work-entry-1", + "working-indicator-row", + ]); + }); + + it("only shows assistant metadata on the terminal assistant message", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "assistant-thought-entry", + kind: "message", + createdAt: "2026-01-01T00:00:10Z", + message: { + id: "assistant-thought" as never, + role: "assistant", + text: "Checking first.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:10Z", + completedAt: "2026-01-01T00:00:11Z", + streaming: false, + }, + }, + { + id: "assistant-final-entry", + kind: "message", + createdAt: "2026-01-01T00:00:20Z", + message: { + id: "assistant-final" as never, + role: "assistant", + text: "Done.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:20Z", + completedAt: "2026-01-01T00:00:30Z", + streaming: false, + }, + }, + ], + expandedTurnIds: new Set(["turn-1" as never]), + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + const assistantRows = rows.filter( + (row): row is Extract<(typeof rows)[number], { kind: "message" }> => + row.kind === "message" && row.message.role === "assistant", + ); + + expect(assistantRows.map((row) => row.showAssistantMeta)).toEqual([false, true]); + }); + + it("withholds assistant metadata while the active turn is still in progress", () => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "assistant-thought-entry", + kind: "message", + createdAt: "2026-01-01T00:00:10Z", + message: { + id: "assistant-thought" as never, + role: "assistant", + text: "Working on it.", + turnId: "turn-1" as never, + createdAt: "2026-01-01T00:00:10Z", + completedAt: "2026-01-01T00:00:11Z", + streaming: false, + }, + }, + ], + latestTurn: { + turnId: "turn-1" as never, + state: "running", + startedAt: "2026-01-01T00:00:00Z", + completedAt: null, + }, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + const assistantRow = rows.find( + (row): row is Extract<(typeof rows)[number], { kind: "message" }> => + row.kind === "message" && row.message.role === "assistant", + ); + + expect(assistantRow?.showAssistantMeta).toBe(false); + expect(assistantRow?.showAssistantCopyButton).toBe(false); + }); }); describe("computeStableMessagesTimelineRows", () => { @@ -417,7 +850,6 @@ describe("computeStableMessagesTimelineRows", () => { message: secondUserMessage, }, ], - completionDividerBeforeEntryId: null, isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -467,7 +899,6 @@ describe("computeStableMessagesTimelineRows", () => { entry: secondWorkEntry, }, ], - completionDividerBeforeEntryId: null, isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -522,7 +953,6 @@ describe("computeStableMessagesTimelineRows", () => { message: secondUserMessage, }, ], - completionDividerBeforeEntryId: null, isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index ad54dd8bde..416b37e4f5 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,9 +1,26 @@ import * as Equal from "effect/Equal"; -import { type TimelineEntry, type WorkLogEntry } from "../../session-logic"; +import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic"; import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; -import { type MessageId, type TurnId } from "@t3tools/contracts"; +import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts"; -export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; +export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; + +function computeElapsedMs(startIso: string, endIso: string): number | null { + const start = Date.parse(startIso); + const end = Date.parse(endIso); + if (!Number.isFinite(start) || !Number.isFinite(end)) return null; + return Math.max(0, end - start); +} + +function maxIsoTimestamp(a: string | null, b: string | null): string | null { + if (a === null) return b; + if (b === null) return a; + const aMs = Date.parse(a); + const bMs = Date.parse(b); + if (!Number.isFinite(aMs)) return b; + if (!Number.isFinite(bMs)) return a; + return bMs > aMs ? b : a; +} export interface TimelineDurationMessage { id: string; @@ -12,6 +29,11 @@ export interface TimelineDurationMessage { completedAt?: string | undefined; } +export type TimelineLatestTurn = Pick< + OrchestrationLatestTurn, + "turnId" | "state" | "startedAt" | "completedAt" +>; + export type MessagesTimelineRow = | { kind: "work"; @@ -19,14 +41,21 @@ export type MessagesTimelineRow = createdAt: string; groupedEntries: WorkLogEntry[]; } + | { + kind: "turn-fold"; + id: string; + createdAt: string; + turnId: TurnId; + label: string; + expanded: boolean; + } | { kind: "message"; id: string; createdAt: string; message: ChatMessage; durationStart: string; - showCompletionDivider: boolean; - completionSummary: string | null; + showAssistantMeta: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; assistantTurnDiffSummary?: TurnDiffSummary | undefined; @@ -110,13 +139,161 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray; + label: string; +} + +/** + * The latest turn counts as unsettled while it is still running (or has not + * recorded a completion). This is deliberately keyed on the turn's own + * lifecycle rather than transient working state: right after the user sends + * a message, the previous turn is still the "active" one until the server + * creates the new turn, and folding must not flicker through that window. + */ +function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null { + if (!latestTurn) { + return null; + } + const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running"; + return isSettled ? null : latestTurn.turnId; +} + +/** + * Settled turns fold their commentary and tool activity behind a + * "Worked for ..." row anchored at the turn's first foldable entry; the + * terminal assistant message stays visible below the fold. + */ +function deriveTurnFolds(input: { + timelineEntries: ReadonlyArray; + terminalAssistantMessageIds: ReadonlySet; + latestTurn: TimelineLatestTurn | null; + unsettledTurnId: TurnId | null; +}): ReadonlyMap { + interface TurnGroup { + entries: Array; + terminalEntry: Extract | null; + hasStreamingMessage: boolean; + /** + * The user message that kicked the turn off. Entry timestamps alone + * undercount the duration (the first entry appears only once the + * provider starts producing output), and a turn cut short by a steer may + * hold a single instantaneous commentary message. + */ + startBoundary: string | null; + } + const groupsByTurnId = new Map(); + + let pendingUserBoundary: string | null = null; + for (const entry of input.timelineEntries) { + if (entry.kind === "message" && entry.message.role === "user") { + pendingUserBoundary = entry.message.createdAt; + continue; + } + const turnId = + entry.kind === "message" && entry.message.role === "assistant" + ? (entry.message.turnId ?? null) + : entry.kind === "work" + ? (entry.entry.turnId ?? null) + : null; + if (!turnId) { + continue; + } + let group = groupsByTurnId.get(turnId); + if (!group) { + group = { + entries: [], + terminalEntry: null, + hasStreamingMessage: false, + // Each user boundary starts at most one turn; a second turn after the + // same user message (e.g. a steer-superseded continuation) falls back + // to its own first entry. + startBoundary: pendingUserBoundary, + }; + pendingUserBoundary = null; + groupsByTurnId.set(turnId, group); + } + group.entries.push(entry); + if (entry.kind === "message") { + if (input.terminalAssistantMessageIds.has(entry.message.id)) { + group.terminalEntry = entry; + } + if (entry.message.streaming) { + group.hasStreamingMessage = true; + } + } + } + + const foldsByAnchorEntryId = new Map(); + for (const [turnId, group] of groupsByTurnId) { + if (turnId === input.unsettledTurnId) { + continue; + } + if (group.hasStreamingMessage) { + continue; + } + const hiddenEntryIds = new Set(); + for (const entry of group.entries) { + if (entry.id !== group.terminalEntry?.id) { + hiddenEntryIds.add(entry.id); + } + } + if (hiddenEntryIds.size === 0) { + continue; + } + + const firstEntry = group.entries[0]; + const lastEntry = group.entries.at(-1); + if (!firstEntry || !lastEntry) { + continue; + } + + const isLatestInterruptedTurn = + input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted"; + // A turn cut short by a steer leaves trailing work entries behind its + // terminal message — take whichever ended last. + const lastEntryEnd = + lastEntry.kind === "message" + ? (lastEntry.message.completedAt ?? lastEntry.createdAt) + : lastEntry.createdAt; + const elapsedMs = + input.latestTurn?.turnId === turnId && + input.latestTurn.startedAt && + input.latestTurn.completedAt + ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt) + : computeElapsedMs( + group.startBoundary ?? firstEntry.createdAt, + maxIsoTimestamp(group.terminalEntry?.message.completedAt ?? null, lastEntryEnd) ?? + lastEntryEnd, + ); + const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null; + const label = isLatestInterruptedTurn + ? duration + ? `You stopped after ${duration}` + : "You stopped this response" + : duration + ? `Worked for ${duration}` + : "Worked"; + + foldsByAnchorEntryId.set(firstEntry.id, { + turnId, + anchorEntryId: firstEntry.id, + createdAt: firstEntry.createdAt, + hiddenEntryIds, + label, + }); + } + return foldsByAnchorEntryId; +} + export function deriveMessagesTimelineRows(input: { timelineEntries: ReadonlyArray; - completionDividerBeforeEntryId: string | null; - completionSummary?: string | null; + latestTurn?: TimelineLatestTurn | null; + expandedTurnIds?: ReadonlySet; isWorking: boolean; - activeTurnInProgress?: boolean; - activeTurnId?: TurnId | null; activeTurnStartedAt: string | null; turnDiffSummaryByAssistantMessageId: ReadonlyMap; revertTurnCountByUserMessageId: ReadonlyMap; @@ -126,6 +303,21 @@ export function deriveMessagesTimelineRows(input: { input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), ); const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries); + const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null); + const foldsByAnchorEntryId = deriveTurnFolds({ + timelineEntries: input.timelineEntries, + terminalAssistantMessageIds, + latestTurn: input.latestTurn ?? null, + unsettledTurnId, + }); + const collapsedEntryIds = new Set(); + for (const fold of foldsByAnchorEntryId.values()) { + if (!input.expandedTurnIds?.has(fold.turnId)) { + for (const entryId of fold.hiddenEntryIds) { + collapsedEntryIds.add(entryId); + } + } + } for (let index = 0; index < input.timelineEntries.length; index += 1) { const timelineEntry = input.timelineEntries[index]; @@ -133,12 +325,35 @@ export function deriveMessagesTimelineRows(input: { continue; } + const turnFold = foldsByAnchorEntryId.get(timelineEntry.id); + if (turnFold) { + nextRows.push({ + kind: "turn-fold", + id: `turn-fold:${turnFold.turnId}`, + createdAt: turnFold.createdAt, + turnId: turnFold.turnId, + label: turnFold.label, + expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false, + }); + } + + if (collapsedEntryIds.has(timelineEntry.id)) { + continue; + } + if (timelineEntry.kind === "work") { const groupedEntries = [timelineEntry.entry]; let cursor = index + 1; while (cursor < input.timelineEntries.length) { const nextEntry = input.timelineEntries[cursor]; - if (!nextEntry || nextEntry.kind !== "work") break; + if ( + !nextEntry || + nextEntry.kind !== "work" || + collapsedEntryIds.has(nextEntry.id) || + foldsByAnchorEntryId.has(nextEntry.id) + ) { + break; + } groupedEntries.push(nextEntry.entry); cursor += 1; } @@ -164,26 +379,28 @@ export function deriveMessagesTimelineRows(input: { const assistantTurnStillInProgress = timelineEntry.message.role === "assistant" && - input.activeTurnInProgress === true && - input.activeTurnId != null && - timelineEntry.message.turnId === input.activeTurnId; + unsettledTurnId !== null && + timelineEntry.message.turnId === unsettledTurnId; - const showCompletionDivider = + const durationStart = + durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt; + + // While the turn is still running, the latest assistant message is only + // provisionally terminal — withhold the metadata row until the turn + // settles so commentary doesn't flash timestamps mid-work. + const showAssistantMeta = timelineEntry.message.role === "assistant" && - input.completionDividerBeforeEntryId === timelineEntry.id; + terminalAssistantMessageIds.has(timelineEntry.message.id) && + !assistantTurnStillInProgress; nextRows.push({ kind: "message", id: timelineEntry.id, createdAt: timelineEntry.createdAt, message: timelineEntry.message, - durationStart: - durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt, - showCompletionDivider, - completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null, - showAssistantCopyButton: - timelineEntry.message.role === "assistant" && - terminalAssistantMessageIds.has(timelineEntry.message.id), + durationStart, + showAssistantMeta, + showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress, assistantTurnDiffSummary: timelineEntry.message.role === "assistant" @@ -235,6 +452,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "working": return a.createdAt === (b as typeof a).createdAt; + case "turn-fold": { + const bf = b as typeof a; + return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded; + } + case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; @@ -246,8 +468,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean return ( a.message === bm.message && a.durationStart === bm.durationStart && - a.showCompletionDivider === bm.showCompletionDivider && - a.completionSummary === bm.completionSummary && + a.showAssistantMeta === bm.showAssistantMeta && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index f5d483aa4c..743de5aa6c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -94,11 +94,9 @@ function buildProps() { return { isWorking: false, activeTurnInProgress: false, - activeTurnId: null, activeTurnStartedAt: null, listRef: createRef(), - completionDividerBeforeEntryId: null, - completionSummary: null, + latestTurn: null, turnDiffSummaryByAssistantMessageId: new Map(), routeThreadKey: "environment-local:thread-1", onOpenTurnDiff: () => {}, @@ -188,7 +186,8 @@ describe("MessagesTimeline", () => { expect(markup).toContain("Terminal 1 lines 1-5"); expect(markup).toContain("lucide-terminal"); - expect(markup).toContain("yoo what's "); + expect(markup).toContain("yoo what's

    "); + expect(markup).toContain(''); expect(markup).toContain("Show full message"); }, 20_000); @@ -228,7 +227,7 @@ describe("MessagesTimeline", () => { ); expect(markup).toContain("Context compacted"); - expect(markup).toContain("Work log"); + expect(markup).toContain("work log"); }); it("formats changed file paths from the workspace root", async () => { @@ -296,4 +295,31 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain("<review_comment"); expect(markup).not.toContain("</review_comment>"); }); + + it("renders a failure marker for failed tool lifecycle entries", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("lucide-x"); + expect(markup).toContain('aria-label="Tool call failed"'); + }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c2fb44c80a..627213ef4f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -6,18 +6,27 @@ import { } from "@t3tools/contracts"; import { createContext, + Fragment, memo, use, useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, + type KeyboardEvent, type ReactNode, } from "react"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { FileDiff } from "@pierre/diffs/react"; -import { deriveTimelineEntries, formatElapsed } from "../../session-logic"; +import { + deriveTimelineEntries, + workEntryIndicatesToolFailure, + workEntryIndicatesToolNeutralStatus, + workEntryIndicatesToolSuccess, + workLogEntryIsToolLike, +} from "../../session-logic"; import { type TurnDiffSummary } from "../../types"; import { summarizeTurnDiffStats } from "../../lib/turnDiffTree"; import { @@ -29,15 +38,20 @@ import ChatMarkdown from "../ChatMarkdown"; import { BotIcon, CheckIcon, + ChevronDownIcon, + ChevronRightIcon, + ChevronUpIcon, CircleAlertIcon, EyeIcon, GlobeIcon, HammerIcon, - type LucideIcon, + MessageCircleIcon, + MinusIcon, SquarePenIcon, TerminalIcon, Undo2Icon, WrenchIcon, + XIcon, ZapIcon, } from "lucide-react"; import { Button } from "../ui/button"; @@ -54,6 +68,7 @@ import { resolveAssistantMessageCopyState, type StableMessagesTimelineRowsState, type MessagesTimelineRow, + type TimelineLatestTurn, } from "./MessagesTimeline.logic"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -64,7 +79,7 @@ import { import { cn } from "~/lib/utils"; import { useUiStateStore } from "~/uiStateStore"; import { type TimestampFormat } from "@t3tools/contracts/settings"; -import { formatTimestamp } from "../../timestampFormat"; +import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat"; import { buildInlineTerminalContextText, @@ -97,11 +112,13 @@ interface TimelineRowSharedState { onRevertUserMessage: (messageId: MessageId) => void; onImageExpand: (preview: ExpandedImagePreview) => void; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onToggleTurnFold: (turnId: TurnId) => void; } interface TimelineRowActivityState { isWorking: boolean; isRevertingCheckpoint: boolean; + activeTurnInProgress: boolean; } const TimelineRowCtx = createContext(null!); @@ -117,12 +134,10 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray; timelineEntries: ReturnType; - completionDividerBeforeEntryId: string | null; - completionSummary: string | null; + latestTurn: TimelineLatestTurn | null; turnDiffSummaryByAssistantMessageId: Map; routeThreadKey: string; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; @@ -146,12 +161,10 @@ interface MessagesTimelineProps { export const MessagesTimeline = memo(function MessagesTimeline({ isWorking, activeTurnInProgress, - activeTurnId, activeTurnStartedAt, listRef, timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + latestTurn, turnDiffSummaryByAssistantMessageId, routeThreadKey, onOpenTurnDiff, @@ -167,26 +180,90 @@ export const MessagesTimeline = memo(function MessagesTimeline({ skills = EMPTY_TIMELINE_SKILLS, onIsAtEndChange, }: MessagesTimelineProps) { + const [expandedTurnIds, setExpandedTurnIds] = useState>(new Set()); + + // Toggling a fold inserts/removes rows between the fold row and the final + // message — everything above the trigger is unchanged, so the trigger stays + // put as long as the list doesn't re-anchor. maintainScrollAtEnd would do + // exactly that (pin the bottom content when row data changes while scrolled + // to the end), yanking the trigger out of view. Suppress it for the frames + // in which the toggle's data change and item measurements settle. + const [foldToggleSettling, setFoldToggleSettling] = useState(false); + const onToggleTurnFold = useCallback((turnId: TurnId) => { + setFoldToggleSettling(true); + setExpandedTurnIds((existing) => { + const next = new Set(existing); + if (next.has(turnId)) { + next.delete(turnId); + } else { + next.add(turnId); + } + return next; + }); + }, []); + useEffect(() => { + if (!foldToggleSettling) { + return; + } + let secondFrameId: number | null = null; + const firstFrameId = window.requestAnimationFrame(() => { + secondFrameId = window.requestAnimationFrame(() => { + setFoldToggleSettling(false); + }); + }); + return () => { + window.cancelAnimationFrame(firstFrameId); + if (secondFrameId !== null) { + window.cancelAnimationFrame(secondFrameId); + } + }; + }, [foldToggleSettling]); + + // An in-session interrupt leaves its turn expanded so the user keeps their + // place; the next turn (or a reload, since this is local state) folds it. + const previousLatestTurnRef = useRef(latestTurn); + useEffect(() => { + const previous = previousLatestTurnRef.current; + previousLatestTurnRef.current = latestTurn; + if (!latestTurn || previous?.turnId === undefined) { + return; + } + if (latestTurn.turnId === previous.turnId) { + if (previous.state === "running" && latestTurn.state === "interrupted") { + setExpandedTurnIds((existing) => { + const next = new Set(existing); + next.add(latestTurn.turnId); + return next; + }); + } + return; + } + setExpandedTurnIds((existing) => { + if (!existing.has(previous.turnId)) { + return existing; + } + const next = new Set(existing); + next.delete(previous.turnId); + return next; + }); + }, [latestTurn]); + const rawRows = useMemo( () => deriveMessagesTimelineRows({ timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + latestTurn, + expandedTurnIds, isWorking, - activeTurnInProgress, - activeTurnId: activeTurnId ?? null, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, revertTurnCountByUserMessageId, }), [ timelineEntries, - completionDividerBeforeEntryId, - completionSummary, + latestTurn, + expandedTurnIds, isWorking, - activeTurnInProgress, - activeTurnId, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, revertTurnCountByUserMessageId, @@ -231,6 +308,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onToggleTurnFold, }), [ timestampFormat, @@ -243,14 +321,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onToggleTurnFold, ], ); const activityState = useMemo( () => ({ isWorking, isRevertingCheckpoint, + activeTurnInProgress, }), - [isRevertingCheckpoint, isWorking], + [activeTurnInProgress, isRevertingCheckpoint, isWorking], ); // Stable renderItem — no closure deps. Row components read shared state @@ -284,11 +364,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({ renderItem={renderItem} estimatedItemSize={90} initialScrollAtEnd - maintainScrollAtEnd + maintainScrollAtEnd={!foldToggleSettling} maintainScrollAtEndThreshold={0.1} maintainVisibleContentPosition onScroll={handleScroll} - className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5" + className="scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5" ListHeaderComponent={TIMELINE_LIST_HEADER} ListFooterComponent={TIMELINE_LIST_FOOTER} /> @@ -314,7 +394,12 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time return (
    {row.kind === "work" ? : null} + {row.kind === "turn-fold" ? : null} {row.kind === "message" && row.message.role === "user" ? : null} {row.kind === "message" && row.message.role === "assistant" ? ( @@ -341,8 +427,8 @@ function UserTimelineRow({ row }: { row: Extract -
    +
    +
    {userImages.length > 0 && (
    {userImages.map((image: NonNullable[number]) => ( @@ -380,21 +466,27 @@ function UserTimelineRow({ row }: { row: Extract -
    - {displayedUserMessage.copyText && ( - - )} - {canRevertAgentWork && } -
    -

    - {formatTimestamp(row.message.createdAt, ctx.timestampFormat)} -

    - - } + markdownCwd={ctx.markdownCwd} />
    +
    +
    + + }> + {formatShortTimestamp(row.message.createdAt, ctx.timestampFormat)} + + + {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)} + + +
    + {canRevertAgentWork && } + {displayedUserMessage.copyText && ( + + )} +
    +
    +
    ); } @@ -404,16 +496,43 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) { const activity = use(TimelineRowActivityCtx); return ( - + + ctx.onRevertUserMessage(messageId)} + aria-label="Revert to this message" + /> + } + > + + + Revert to this message + + ); +} + +function TurnFoldTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const Icon = row.expanded ? ChevronDownIcon : ChevronRightIcon; + + return ( +
    + +
    ); } @@ -423,10 +542,7 @@ function AssistantTimelineRow({ row }: { row: Extract - {row.showCompletionDivider && ( - - )} -
    +
    -
    -

    - {row.message.streaming ? ( - - ) : ( - formatMessageMeta( - row.message.createdAt, - formatElapsed(row.durationStart, row.message.completedAt), - ctx.timestampFormat, - ) + {row.showAssistantMeta ? ( +

    + + {!row.message.streaming && ( + + } + > + {formatShortTimestamp( + row.message.completedAt ?? row.message.createdAt, + ctx.timestampFormat, + )} + + + {formatChatTimestampTooltip( + row.message.completedAt ?? row.message.createdAt, + ctx.timestampFormat, + )} + + )} -

    - -
    +
    + ) : null}
    ); } -function AssistantCompletionDivider({ completionSummary }: { completionSummary: string | null }) { - return ( -
    - - - {completionSummary ? `Response • ${completionSummary}` : "Response"} - - -
    - ); -} - function AssistantCopyButton({ row }: { row: Extract }) { const assistantCopyState = resolveAssistantMessageCopyState({ text: row.message.text ?? null, @@ -485,16 +594,7 @@ function AssistantCopyButton({ row }: { row: Extract - -
    - ); + return ; } function ProposedPlanTimelineRow({ @@ -519,7 +619,7 @@ function ProposedPlanTimelineRow({ function WorkingTimelineRow({ row }: { row: Extract }) { return (
    -
    +
    @@ -560,41 +660,11 @@ function WorkingTimer({ createdAt }: { createdAt: string }) { return () => clearInterval(id); }, [createdAt]); - return {initialText}; -} - -/** Live timestamp + elapsed duration for a streaming assistant message. */ -function LiveMessageMeta({ - createdAt, - durationStart, - timestampFormat, -}: { - createdAt: string; - durationStart: string | null | undefined; - timestampFormat: TimestampFormat; -}) { - const textRef = useRef(null); - const initialText = formatLiveMessageMetaNow(createdAt, durationStart, timestampFormat); - - useEffect(() => { - const updateText = () => { - if (textRef.current) { - textRef.current.textContent = formatLiveMessageMetaNow( - createdAt, - durationStart, - timestampFormat, - ); - } - }; - updateText(); - if (!durationStart) { - return; - } - const id = setInterval(updateText, 1000); - return () => clearInterval(id); - }, [createdAt, durationStart, timestampFormat]); - - return {initialText}; + return ( + + {initialText} + + ); } // --------------------------------------------------------------------------- @@ -602,8 +672,7 @@ function LiveMessageMeta({ // re-render only the affected row, not the entire list. // --------------------------------------------------------------------------- -/** Owns its own expand/collapse state so toggling re-renders only this row. - * State resets on unmount which is fine — work groups start collapsed. */ +/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */ const WorkGroupSection = memo(function WorkGroupSection({ groupedEntries, }: { @@ -611,47 +680,116 @@ const WorkGroupSection = memo(function WorkGroupSection({ }) { const { workspaceRoot } = use(TimelineRowCtx); const [isExpanded, setIsExpanded] = useState(false); - const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; + const sectionRef = useRef(null); + const anchorBottomBeforeToggleRef = useRef(null); + const nonEmptyEntries = useMemo( + () => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)), + [groupedEntries], + ); + const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES; const visibleEntries = hasOverflow && !isExpanded - ? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) - : groupedEntries; - const hiddenCount = groupedEntries.length - visibleEntries.length; - const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool"); - const showHeader = hasOverflow || !onlyToolEntries; - const groupLabel = onlyToolEntries ? "Tool calls" : "Work log"; + ? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) + : nonEmptyEntries; + const hiddenCount = nonEmptyEntries.length - visibleEntries.length; + const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry)); + const groupLabel = onlyToolEntries + ? nonEmptyEntries.length === 1 + ? "1 tool call" + : `${nonEmptyEntries.length} tool calls` + : "work log"; + + useLayoutEffect(() => { + const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current; + anchorBottomBeforeToggleRef.current = null; + + if (anchorBottomBeforeToggle === null) { + return; + } + + const section = sectionRef.current; + if (!section) { + return; + } + + const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle; + if (Math.abs(delta) < 0.5) { + return; + } + + const scroller = findNearestVerticalScroller(section); + if (scroller) { + scroller.scrollTop += delta; + } else { + window.scrollBy(0, delta); + } + }, [isExpanded]); + + const toggleExpanded = () => { + anchorBottomBeforeToggleRef.current = + sectionRef.current?.getBoundingClientRect().bottom ?? null; + setIsExpanded((v) => !v); + }; + + if (nonEmptyEntries.length === 0) return null; return ( -
    - {showHeader && ( -
    -

    - {groupLabel} ({groupedEntries.length}) -

    - {hasOverflow && ( - - )} -
    +
    + {!onlyToolEntries && ( +

    + {groupLabel} +

    )} -
    +
    {visibleEntries.map((workEntry) => ( ))}
    -
    + {hasOverflow && ( + + )} +
    ); }); +function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null { + let parent = element.parentElement; + while (parent) { + const { overflowY } = window.getComputedStyle(parent); + if ( + (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") && + parent.scrollHeight > parent.clientHeight + ) { + return parent; + } + parent = parent.parentElement; + } + return null; +} + /** Subscribes directly to the UI state store for expand/collapse state, * so toggling re-renders only this component — not the entire list. */ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({ @@ -781,6 +919,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop text: string; terminalContexts: ParsedTerminalContextEntry[]; skills: ReadonlyArray>; + markdownCwd: string | undefined; footer?: ReactNode; }) { const [expanded, setExpanded] = useState(false); @@ -810,6 +949,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop text={props.text} terminalContexts={props.terminalContexts} skills={props.skills} + markdownCwd={props.markdownCwd} />
    ) : null} @@ -847,7 +987,34 @@ const UserMessageBody = memo(function UserMessageBody(props: { text: string; terminalContexts: ParsedTerminalContextEntry[]; skills: ReadonlyArray>; + markdownCwd: string | undefined; }) { + const renderInlineMarkdownSegment = (text: string, key: string) => { + const leadingWhitespace = /^\s+/.exec(text)?.[0] ?? ""; + const textWithoutLeadingWhitespace = text.slice(leadingWhitespace.length); + const trailingWhitespace = /\s+$/.exec(textWithoutLeadingWhitespace)?.[0] ?? ""; + const content = textWithoutLeadingWhitespace.slice( + 0, + textWithoutLeadingWhitespace.length - trailingWhitespace.length, + ); + + return ( + + {leadingWhitespace ? : null} + {content ? ( + + ) : null} + {trailingWhitespace ? : null} + + ); + }; + const reviewCommentSegments = parseReviewCommentMessageSegments(props.text); if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) { return ( @@ -855,8 +1022,14 @@ const UserMessageBody = memo(function UserMessageBody(props: { {reviewCommentSegments.map((segment) => segment.kind === "text" ? ( segment.text.trim().length > 0 ? ( -
    - +
    +
    ) : null ) : ( @@ -887,9 +1060,10 @@ const UserMessageBody = memo(function UserMessageBody(props: { } if (matchIndex > cursor) { inlineNodes.push( - - - , + renderInlineMarkdownSegment( + props.text.slice(cursor, matchIndex), + `user-terminal-context-inline-before:${context.header}:${cursor}`, + ), ); } inlineNodes.push( @@ -904,9 +1078,10 @@ const UserMessageBody = memo(function UserMessageBody(props: { if (inlineNodes.length > 0) { if (cursor < props.text.length) { inlineNodes.push( - - - , + renderInlineMarkdownSegment( + props.text.slice(cursor), + `user-message-terminal-context-inline-rest:${cursor}`, + ), ); } @@ -934,9 +1109,14 @@ const UserMessageBody = memo(function UserMessageBody(props: { if (props.text.length > 0) { inlineNodes.push( - - - , + , ); } else if (inlinePrefix.length === 0) { return null; @@ -954,9 +1134,13 @@ const UserMessageBody = memo(function UserMessageBody(props: { } return ( -
    - -
    + ); }); @@ -1054,59 +1238,77 @@ function formatWorkingTimerNow(startIso: string): string { return formatWorkingTimer(startIso, new Date().toISOString()) ?? "0s"; } -function formatLiveMessageMetaNow( - createdAt: string, - durationStart: string | null | undefined, - timestampFormat: TimestampFormat, -): string { - const elapsed = durationStart ? formatElapsed(durationStart, new Date().toISOString()) : null; - return formatMessageMeta(createdAt, elapsed, timestampFormat); -} +type WorkEntryIconName = + | "bot" + | "check" + | "circle-alert" + | "eye" + | "globe" + | "hammer" + | "message-circle" + | "square-pen" + | "terminal" + | "wrench" + | "x" + | "zap"; -function formatMessageMeta( - createdAt: string, - duration: string | null, - timestampFormat: TimestampFormat, -): string { - if (!duration) return formatTimestamp(createdAt, timestampFormat); - return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`; +function WorkEntryIconSvg({ name, className }: { name: WorkEntryIconName; className: string }) { + switch (name) { + case "bot": + return ; + case "check": + return ; + case "circle-alert": + return ; + case "eye": + return ; + case "globe": + return ; + case "hammer": + return ; + case "message-circle": + return ; + case "square-pen": + return ; + case "terminal": + return ; + case "wrench": + return ; + case "x": + return ; + case "zap": + return ; + } } function workToneIcon(tone: TimelineWorkEntry["tone"]): { - icon: LucideIcon; + iconName: WorkEntryIconName; className: string; } { if (tone === "error") { return { - icon: CircleAlertIcon, + iconName: "circle-alert", className: "text-foreground/92", }; } if (tone === "thinking") { return { - icon: BotIcon, + iconName: "bot", className: "text-foreground/92", }; } if (tone === "info") { return { - icon: CheckIcon, - className: "text-foreground/92", + iconName: "check", + className: "text-muted-foreground", }; } return { - icon: ZapIcon, + iconName: "zap", className: "text-foreground/92", }; } -function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string { - if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50"; - if (tone === "tool") return "text-muted-foreground/70"; - if (tone === "thinking") return "text-muted-foreground/50"; - return "text-muted-foreground/40"; -} - function workEntryPreview( workEntry: Pick, workspaceRoot: string | undefined, @@ -1132,29 +1334,58 @@ function workEntryRawCommand( return rawCommand === workEntry.command.trim() ? null : rawCommand; } -function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon { - if (workEntry.requestKind === "command") return TerminalIcon; - if (workEntry.requestKind === "file-read") return EyeIcon; - if (workEntry.requestKind === "file-change") return SquarePenIcon; +function buildToolCallExpandedBody( + workEntry: TimelineWorkEntry, + workspaceRoot: string | undefined, +): string | null { + const raw = workEntryRawCommand(workEntry); + if (raw?.trim()) { + return raw.trim(); + } + if (workEntry.command?.trim()) { + return workEntry.command.trim(); + } + if (workEntry.detail?.trim()) { + return workEntry.detail.trim(); + } + const changedFiles = workEntry.changedFiles ?? []; + if (changedFiles.length > 0) { + return changedFiles + .map((filePath) => formatWorkspaceRelativePath(filePath, workspaceRoot)) + .join("\n"); + } + return null; +} + +function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName { + if ( + workEntry.sourceActivityKind === "user-input.requested" || + workEntry.sourceActivityKind === "user-input.resolved" + ) { + return "message-circle"; + } + if (workEntry.requestKind === "command") return "terminal"; + if (workEntry.requestKind === "file-read") return "eye"; + if (workEntry.requestKind === "file-change") return "square-pen"; if (workEntry.itemType === "command_execution" || workEntry.command) { - return TerminalIcon; + return "terminal"; } if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) { - return SquarePenIcon; + return "square-pen"; } - if (workEntry.itemType === "web_search") return GlobeIcon; - if (workEntry.itemType === "image_view") return EyeIcon; + if (workEntry.itemType === "web_search") return "globe"; + if (workEntry.itemType === "image_view") return "eye"; switch (workEntry.itemType) { case "mcp_tool_call": - return WrenchIcon; + return "wrench"; case "dynamic_tool_call": case "collab_agent_tool_call": - return HammerIcon; + return "hammer"; } - return workToneIcon(workEntry.tone).icon; + return workToneIcon(workEntry.tone).iconName; } function capitalizePhrase(value: string): string { @@ -1172,13 +1403,18 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string { return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle)); } +const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation(); + const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { workEntry: TimelineWorkEntry; workspaceRoot: string | undefined; }) { const { workEntry, workspaceRoot } = props; + const activity = use(TimelineRowActivityCtx); + const [expanded, setExpanded] = useState(false); const iconConfig = workToneIcon(workEntry.tone); - const EntryIcon = workEntryIcon(workEntry); + const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning"; + const entryIconName = showWarningIndicator ? "x" : workEntryIconName(workEntry); const heading = toolWorkEntryHeading(workEntry); const rawPreview = workEntryPreview(workEntry, workspaceRoot); const preview = @@ -1187,108 +1423,143 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { normalizeCompactToolLabel(heading).toLowerCase() ? null : rawPreview; - const rawCommand = workEntryRawCommand(workEntry); const displayText = preview ? `${heading} - ${preview}` : heading; - const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0; - const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail; + const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot); + const canExpand = expandedBody !== null; + const showFailedIndicator = workEntryIndicatesToolFailure(workEntry); + const showDestructiveRowStyle = + showFailedIndicator && + (workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry)); + const iconWrapperClass = cn( + "flex size-5 shrink-0 items-center justify-center", + showWarningIndicator + ? "text-destructive" + : showDestructiveRowStyle + ? "text-destructive" + : workEntry.tone === "tool" || showFailedIndicator + ? "text-muted-foreground/65" + : iconConfig.className, + ); + const headingClass = showWarningIndicator + ? "font-medium text-warning" + : showDestructiveRowStyle + ? "font-medium text-destructive" + : "font-medium text-foreground/82"; + const turnSettled = !activity.activeTurnInProgress; + const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry); + const showSuccessIndicator = + workEntryIndicatesToolSuccess(workEntry) || + (turnSettled && workEntryIndicatesToolNeutralStatus(workEntry)); + const rowToggleProps = canExpand + ? { + role: "button" as const, + tabIndex: 0 as const, + "aria-label": displayText, + onClick: () => setExpanded((v) => !v), + onKeyDown: (e: KeyboardEvent) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + setExpanded((v) => !v); + } + }, + } + : {}; return ( -
    -
    - - +
    +
    + + -
    - {rawCommand ? ( -
    -

    - - {heading} - - {preview && ( - - - {" "} - - {preview} - - } - /> - -

    - {rawCommand} -
    - - - )} -

    -
    - ) : ( - - -

    +

    +

    + {heading} + {preview && ( + {preview} + )} +

    +
    +
    + + {canExpand ? ( + - - {heading} - - {preview && - {preview}} -

    - - -

    - {displayText} -

    -
    - - )} + aria-hidden + /> + ) : null} +
    + + {showFailedIndicator ? ( + + + } + > + + + Failed + + ) : showSuccessIndicator ? ( + + } + > + + + + + Completed + + ) : showNeutralIndicator ? ( + + } + > + + + Empty + + ) : null} + +
    - {hasChangedFiles && !previewIsChangedFiles && ( -
    - {workEntry.changedFiles?.slice(0, 4).map((filePath) => { - const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot); - return ( - - {displayPath} - - ); - })} - {(workEntry.changedFiles?.length ?? 0) > 4 && ( - - +{(workEntry.changedFiles?.length ?? 0) - 4} - - )} + {expanded && canExpand && expandedBody ? ( +
    +
    +            {expandedBody}
    +          
    - )} + ) : null}
    ); }); diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 064df338e4..740b54d9c5 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -1,6 +1,6 @@ import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts"; import { memo } from "react"; -import { StarIcon } from "lucide-react"; +import { CheckIcon, StarIcon } from "lucide-react"; import { getDisplayModelName, getTriggerDisplayModelLabel, @@ -27,11 +27,13 @@ export const ModelListRow = memo(function ModelListRow(props: { providerDisplayName: string; providerAccentColor?: string | undefined; isFavorite: boolean; + isSelected: boolean; showProvider: boolean; preferShortName?: boolean; useTriggerLabel?: boolean; showNewBadge?: boolean; jumpLabel?: string | null; + disabledReason?: string | null; onToggleFavorite: () => void; }) { const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; @@ -39,85 +41,100 @@ export const ModelListRow = memo(function ModelListRow(props: { ? `${props.providerDisplayName} · ${props.model.subProvider}` : props.providerDisplayName; - return ( + const row = ( - - { - event.stopPropagation(); - props.onToggleFavorite(); - }} - onKeyDown={(event) => { - event.stopPropagation(); - }} - type="button" - aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"} - > - - - } - /> - - {props.isFavorite ? "Remove from favorites" : "Add to favorites"} - - -
    -
    -
    - - {props.useTriggerLabel - ? getTriggerDisplayModelLabel(props.model) - : getDisplayModelName( - props.model, - props.preferShortName ? { preferShortName: true } : undefined, - )} - - {props.showNewBadge ? ( - - New - - ) : null} +
    +
    + {props.useTriggerLabel + ? getTriggerDisplayModelLabel(props.model) + : getDisplayModelName( + props.model, + props.preferShortName ? { preferShortName: true } : undefined, + )}
    - {props.jumpLabel ? ( - - {props.jumpLabel} - + {props.isSelected ? : null} + {props.showNewBadge ? ( + + New + ) : null}
    {props.showProvider && ( -
    +
    {ProviderIcon ? : null} - {props.providerAccentColor ? ( - - ) : null} - + {providerLabel}
    )}
    + +
    + {props.jumpLabel ? ( + {props.jumpLabel} + ) : null} + + { + event.stopPropagation(); + props.onToggleFavorite(); + }} + onKeyDown={(event) => { + event.stopPropagation(); + }} + disabled={Boolean(props.disabledReason)} + type="button" + aria-label={props.isFavorite ? "Remove from favorites" : "Add to favorites"} + > + + + } + /> + + {props.isFavorite ? "Remove from favorites" : "Add to favorites"} + + +
    ); + + if (!props.disabledReason) { + return row; + } + + return ( + + + + {props.disabledReason} + + + ); }); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index c9fbd2b0fc..3a9b421de0 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -4,14 +4,15 @@ import { type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; import { resolveSelectableModel } from "@t3tools/shared/model"; +import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react"; import { SearchIcon } from "lucide-react"; import { ModelListRow } from "./ModelListRow"; import { ModelPickerSidebar } from "./ModelPickerSidebar"; import { isModelPickerNewModel } from "./modelPickerModelHighlights"; import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch"; -import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxList } from "../ui/combobox"; -import { ModelEsque, PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; +import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxListVirtualized } from "../ui/combobox"; +import { ModelEsque } from "./providerIconUtils"; import { modelPickerJumpCommandForIndex, modelPickerJumpIndexFromCommand, @@ -81,17 +82,21 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelOptionsByInstance: ReadonlyMap>; terminalOpen: boolean; onRequestClose?: () => void; + getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; }) { const { keybindings: providedKeybindings, modelOptionsByInstance, instanceEntries, + getModelDisabledReason, onInstanceModelChange, } = props; const [searchQuery, setSearchQuery] = useState(""); + const [showTopScrollFade, setShowTopScrollFade] = useState(false); + const [showBottomScrollFade, setShowBottomScrollFade] = useState(false); const searchInputRef = useRef(null); - const listRegionRef = useRef(null); + const modelListRef = useRef(null); const highlightedModelKeyRef = useRef(null); const favorites = useSettings((s) => s.favorites ?? []); const [selectedInstanceId, setSelectedInstanceId] = useState( @@ -213,16 +218,34 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const isLocked = props.lockedProvider !== null; const isSearching = searchQuery.trim().length > 0; - const lockedInstanceEntries = useMemo( - () => - props.lockedProvider ? instanceEntries.filter((entry) => matchesLockedProvider(entry)) : [], - [instanceEntries, matchesLockedProvider, props.lockedProvider], - ); - const showLockedInstanceSidebar = isLocked && lockedInstanceEntries.length > 1; - const showSidebar = !isSearching && (!isLocked || showLockedInstanceSidebar); - const sidebarInstanceEntries = showLockedInstanceSidebar - ? lockedInstanceEntries - : instanceEntries; + const lockedDisabledInstanceIds = useMemo(() => { + if (!isLocked) { + return undefined; + } + const disabled = new Set(); + for (const entry of instanceEntries) { + if (!matchesLockedProvider(entry)) { + disabled.add(entry.instanceId); + } + } + return disabled; + }, [instanceEntries, isLocked, matchesLockedProvider]); + const sidebarInstanceEntries = useMemo(() => { + if (!isLocked) { + return instanceEntries; + } + const available: ProviderInstanceEntry[] = []; + const disabled: ProviderInstanceEntry[] = []; + for (const entry of instanceEntries) { + if (matchesLockedProvider(entry)) { + available.push(entry); + } else { + disabled.push(entry); + } + } + return [...available, ...disabled]; + }, [instanceEntries, isLocked, matchesLockedProvider]); + const showSidebar = !isSearching && sidebarInstanceEntries.length > 0; const instanceOrder = useMemo( () => instanceEntries.map((entry) => entry.instanceId), [instanceEntries], @@ -308,7 +331,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { if (props.lockedProvider !== null) { result = result.filter((m) => matchesLockedProvider(m)); - if (showLockedInstanceSidebar) { + if (selectedInstanceId === "favorites") { + result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug))); + } else { result = result.filter((m) => m.instanceId === selectedInstanceId); } } else if (selectedInstanceId === "favorites") { @@ -329,12 +354,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { matchesLockedProvider, props.lockedProvider, searchQuery, - showLockedInstanceSidebar, selectedInstanceId, ]); const handleModelSelect = useCallback( (modelSlug: string, instanceId: ProviderInstanceId) => { + if (getModelDisabledReason?.(instanceId, modelSlug)) { + return; + } const options = modelOptionsByInstance.get(instanceId); if (!options) { return; @@ -351,7 +378,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { onInstanceModelChange(instanceId, resolvedModel); } }, - [entryByInstanceId, modelOptionsByInstance, onInstanceModelChange], + [entryByInstanceId, getModelDisabledReason, modelOptionsByInstance, onInstanceModelChange], ); const toggleFavorite = useCallback( @@ -368,39 +395,25 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { [favorites, updateSettings], ); - const LockedProviderIcon = - isLocked && props.lockedProvider ? PROVIDER_ICON_BY_PROVIDER[props.lockedProvider] : null; - // Header label for locked mode. Use the active instance's displayName - // when the lock narrows to exactly one instance (so "Codex Personal" - // shows instead of the generic driver label); fall back to the first - // matching entry otherwise. - const lockedHeaderLabel = useMemo(() => { - if (!isLocked || !props.lockedProvider) return null; - const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry)); - if (matches.length === 0) return null; - const active = matches.find((entry) => entry.instanceId === props.activeInstanceId); - return (active ?? matches[0])?.displayName ?? null; - }, [ - isLocked, - matchesLockedProvider, - props.lockedProvider, - props.activeInstanceId, - instanceEntries, - ]); const modelJumpCommandByKey = useMemo(() => { const mapping = new Map< string, NonNullable> >(); - for (const [visibleModelIndex, model] of filteredModels.entries()) { - const jumpCommand = modelPickerJumpCommandForIndex(visibleModelIndex); + let selectableModelIndex = 0; + for (const model of filteredModels) { + if (getModelDisabledReason?.(model.instanceId, model.slug)) { + continue; + } + const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex); if (!jumpCommand) { return mapping; } mapping.set(`${model.instanceId}:${model.slug}`, jumpCommand); + selectableModelIndex += 1; } return mapping; - }, [filteredModels]); + }, [filteredModels, getModelDisabledReason]); const modelJumpModelKeys = useMemo( () => [...modelJumpCommandByKey.keys()], [modelJumpCommandByKey], @@ -418,6 +431,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { new Map(filteredModels.map((model) => [`${model.instanceId}:${model.slug}`, model] as const)), [filteredModels], ); + const updateModelListScrollFades = useCallback(() => { + const scrollElement = modelListRef.current?.getScrollableNode(); + if (!(scrollElement instanceof HTMLElement)) { + return; + } + const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight); + setShowTopScrollFade(scrollElement.scrollTop > 1); + setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); + }, []); const modelJumpShortcutContext = useMemo( () => ({ @@ -478,72 +500,40 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]); useLayoutEffect(() => { - const listRegion = listRegionRef.current; - if (!listRegion) { - return; - } - - let cancelled = false; - let frame = 0; + setShowTopScrollFade(false); + setShowBottomScrollFade(filteredModelKeys.length > 5); let nestedFrame = 0; - let timeout = 0; - - const measureScrollArea = () => { - if (cancelled) { - return; - } - const viewport = listRegion.querySelector('[data-slot="scroll-area-viewport"]'); - if (!viewport || viewport.scrollHeight <= viewport.clientHeight) { - return; - } - const originalScrollTop = viewport.scrollTop; - const maxScrollTop = viewport.scrollHeight - viewport.clientHeight; - if (maxScrollTop <= 0) { - return; - } - viewport.scrollTop = Math.min(originalScrollTop + 1, maxScrollTop); - viewport.scrollTop = originalScrollTop; - }; - - queueMicrotask(measureScrollArea); - frame = window.requestAnimationFrame(() => { - measureScrollArea(); - nestedFrame = window.requestAnimationFrame(measureScrollArea); + const frame = window.requestAnimationFrame(() => { + updateModelListScrollFades(); + nestedFrame = window.requestAnimationFrame(updateModelListScrollFades); }); - timeout = window.setTimeout(measureScrollArea, 0); - return () => { - cancelled = true; window.cancelAnimationFrame(frame); window.cancelAnimationFrame(nestedFrame); - window.clearTimeout(timeout); }; - }, [filteredModelKeys]); + }, [filteredModelKeys, updateModelListScrollFades]); return (
    - {/* Locked provider header (only shown in locked mode) */} - {isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && ( -
    - - {lockedHeaderLabel} -
    - )} - - {/* Sidebar (only in unlocked mode) */} + {/* Sidebar */} {showSidebar && ( + `${entry.displayName} is unavailable in this thread. Start a new thread to switch providers.`, + } + : {})} /> )} @@ -555,9 +545,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { filter={null} autoHighlight open + virtualized value={`${props.activeInstanceId}:${props.model}`} - onItemHighlighted={(modelKey) => { + onItemHighlighted={(modelKey, eventDetails) => { highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null; + if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) { + modelListRef.current?.scrollIndexIntoView?.({ + index: eventDetails.index, + animated: false, + }); + } }} onValueChange={(modelKey) => { if (typeof modelKey !== "string") { @@ -569,79 +566,101 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { >
    {/* Search bar */} -
    - } - value={searchQuery} - onChange={(e) => setSearchQuery(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - props.onRequestClose?.(); - return; +
    +
    + } - if (e.key === "Enter" && highlightedModelKeyRef.current) { - ( - e as typeof e & { preventBaseUIHandler?: () => void } - ).preventBaseUIHandler?.(); - e.preventDefault(); + value={searchQuery} + onChange={(e) => setSearchQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + props.onRequestClose?.(); + return; + } + if (e.key === "Enter" && highlightedModelKeyRef.current) { + ( + e as typeof e & { preventBaseUIHandler?: () => void } + ).preventBaseUIHandler?.(); + e.preventDefault(); + e.stopPropagation(); + const { instanceId, slug } = splitInstanceModelKey( + highlightedModelKeyRef.current, + ); + handleModelSelect(slug, instanceId); + return; + } e.stopPropagation(); - const { instanceId, slug } = splitInstanceModelKey( - highlightedModelKeyRef.current, - ); - handleModelSelect(slug, instanceId); - return; - } - e.stopPropagation(); - }} - onMouseDown={(e) => e.stopPropagation()} - onTouchStart={(e) => e.stopPropagation()} - size="sm" - /> + }} + onMouseDown={(e) => e.stopPropagation()} + onTouchStart={(e) => e.stopPropagation()} + size="sm" + unstyled + /> +
    {/* Model list */} -
    - - {filteredModelKeys.map((modelKey, index) => { - const model = filteredModelByKey.get(modelKey); - if (!model) { - return null; - } - return ( - toggleFavorite(model.instanceId, model.slug)} - /> - ); - })} - +
    + + + ref={modelListRef} + data={filteredModelKeys} + extraData={favoritesSet} + keyExtractor={(modelKey) => modelKey} + renderItem={({ item: modelKey, index }) => { + const model = filteredModelByKey.get(modelKey); + if (!model) { + return null; + } + const disabledReason = + getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + return ( + toggleFavorite(model.instanceId, model.slug)} + /> + ); + }} + estimatedItemSize={60} + drawDistance={480} + recycleItems + onLayout={updateModelListScrollFades} + onScroll={updateModelListScrollFades} + className={cn( + "scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]", + showTopScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]", + showBottomScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]", + )} + /> +
    No models found diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx index 121b5267a3..ea1693492f 100644 --- a/apps/web/src/components/chat/ModelPickerSidebar.tsx +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -1,9 +1,8 @@ import { type ProviderInstanceId } from "@t3tools/contracts"; -import { memo, useMemo } from "react"; +import { memo, useLayoutEffect, useMemo, useRef, useState } from "react"; import { Clock3Icon, SparklesIcon, StarIcon } from "lucide-react"; import { Gemini, GithubCopilotIcon } from "../Icons"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; -import { ScrollArea } from "../ui/scroll-area"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import type { ProviderInstanceEntry } from "../../providerInstances"; @@ -30,9 +29,8 @@ function describeUnavailableInstance(entry: ProviderInstanceEntry): string { return msg ? `${label} — ${kind}. ${msg}` : `${label} — ${kind}.`; } -const SELECTED_BUTTON_CLASS = "bg-background text-foreground shadow-sm"; const SELECTED_INDICATOR_CLASS = - "pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.5 -translate-y-1/2 rounded-l-full bg-primary"; + "pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.75 -translate-y-1/2 rounded-l-full bg-primary"; const BADGE_BASE_CLASS = "pointer-events-none absolute -right-0.5 top-0.5 z-10 flex size-3.5 items-center justify-center rounded-full bg-transparent shadow-sm "; const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-amber-600 dark:text-amber-300 `; @@ -40,6 +38,7 @@ const SOON_BADGE_CLASS = `${BADGE_BASE_CLASS} text-muted-foreground `; /** Opens toward the rail so the list stays readable (not over the model names). */ const PICKER_TOOLTIP_SIDE = "left" as const; +const PICKER_TOOLTIP_SIDE_OFFSET = 8; const PICKER_TOOLTIP_CLASS = "max-w-64 text-balance font-normal leading-snug"; export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { @@ -56,6 +55,9 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { showFavorites?: boolean; /** Render non-configured coming-soon provider entries. Hidden in scoped rails. */ showComingSoon?: boolean; + /** Instance ids shown in the rail but unavailable for the current picker context. */ + disabledInstanceIds?: ReadonlySet; + getDisabledInstanceTooltip?: (entry: ProviderInstanceEntry) => string; /** * Instance id values that should render the "new" sparkle badge. Callers * pass the subset of default built-in ids they want flagged (custom @@ -68,6 +70,9 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { }; const showFavorites = props.showFavorites ?? true; const showComingSoon = props.showComingSoon ?? true; + const [hoveredInstanceId, setHoveredInstanceId] = useState(null); + const sidebarContentRef = useRef(null); + const [selectedIndicatorTop, setSelectedIndicatorTop] = useState(null); const duplicateDriverCounts = useMemo(() => { const counts = new Map(); for (const entry of props.instanceEntries) { @@ -76,188 +81,248 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { return counts; }, [props.instanceEntries]); + useLayoutEffect(() => { + const content = sidebarContentRef.current; + if (!content) { + return; + } + const selectedButton = Array.from( + content.querySelectorAll("[data-model-picker-provider]"), + ).find((button) => button.dataset.modelPickerProvider === props.selectedInstanceId); + if (!selectedButton) { + setSelectedIndicatorTop(null); + return; + } + const contentRect = content.getBoundingClientRect(); + const selectedButtonRect = selectedButton.getBoundingClientRect(); + setSelectedIndicatorTop( + selectedButtonRect.top - + contentRect.top + + content.scrollTop + + selectedButtonRect.height / 2 - + 10, + ); + }, [props.instanceEntries, props.selectedInstanceId, showFavorites]); + return ( - -
    - {/* Favorites section */} - {showFavorites ? ( -
    -
    - {props.selectedInstanceId === "favorites" && ( -
    +
    +
    + {selectedIndicatorTop !== null ? ( +
    + ) : null} + {/* Favorites section */} + {showFavorites ? ( +
    +
    + + handleSelect("favorites")} + type="button" + data-model-picker-provider="favorites" + aria-label="Favorites" + > + + + } + /> + + Favorites + + +
    +
    + ) : null} + + {/* Instance buttons (one per configured instance — built-in + custom) */} + {props.instanceEntries.map((entry) => { + const isUnavailable = !entry.isAvailable || entry.status !== "ready"; + const isContextDisabled = props.disabledInstanceIds?.has(entry.instanceId) ?? false; + const isDisabled = isUnavailable || isContextDisabled; + const isSelected = props.selectedInstanceId === entry.instanceId; + const isHovered = hoveredInstanceId === entry.instanceId; + const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false; + const showInstanceBadge = + Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1; + + const tooltip = isUnavailable + ? describeUnavailableInstance(entry) + : isContextDisabled + ? (props.getDisabledInstanceTooltip?.(entry) ?? entry.displayName) + : showNewBadge + ? `${entry.displayName} — New` + : entry.displayName; + + const button = ( + + ); + + const trigger = isDisabled ? ( + {button} + ) : ( + button + ); + + return ( +
    + + + + {tooltip} + + +
    + ); + })} + + {showComingSoon ? ( + <> + {/* Gemini button (coming soon) */} handleSelect("favorites")} - type="button" - data-model-picker-provider="favorites" - aria-label="Favorites" - > - - + + + } /> - Favorites + Gemini — Coming soon -
    -
    - ) : null} - - {/* Instance buttons (one per configured instance — built-in + custom) */} - {props.instanceEntries.map((entry) => { - const isDisabled = !entry.isAvailable || entry.status !== "ready"; - const isSelected = props.selectedInstanceId === entry.instanceId; - const showNewBadge = props.newBadgeInstanceIds?.has(entry.instanceId) ?? false; - const showInstanceBadge = - Boolean(entry.accentColor) || (duplicateDriverCounts.get(entry.driverKind) ?? 0) > 1; - - const tooltip = isDisabled - ? describeUnavailableInstance(entry) - : showNewBadge - ? `${entry.displayName} — New` - : entry.displayName; - - const button = ( - - ); - - const trigger = isDisabled ? ( - {button} - ) : ( - button - ); - - return ( -
    - {isSelected &&
    } + {/* Github Copilot button (coming soon) */} - + + + + } + /> - {tooltip} + Github Copilot — Coming soon -
    - ); - })} - - {showComingSoon ? ( - <> - {/* Gemini button (coming soon) */} - - - - - } - /> - - Gemini — Coming soon - - - {/* Github Copilot button (coming soon) */} - - - - - } - /> - - Github Copilot — Coming soon - - - - ) : null} + + ) : null} +
    - +
    ); }); diff --git a/apps/web/src/components/chat/ProviderInstanceIcon.tsx b/apps/web/src/components/chat/ProviderInstanceIcon.tsx index 154cada19a..a58e29fe11 100644 --- a/apps/web/src/components/chat/ProviderInstanceIcon.tsx +++ b/apps/web/src/components/chat/ProviderInstanceIcon.tsx @@ -19,20 +19,24 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { displayName: string; accentColor?: string | undefined; showBadge?: boolean; + badgeContent?: "initials" | "none"; className?: string; iconClassName?: string; badgeClassName?: string; statusDotClassName?: string; + indicatorBackground?: string; }) { const Icon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; + const indicatorBackground = props.indicatorBackground ?? "var(--card)"; const accentStyle = props.accentColor ? ({ "--provider-accent": props.accentColor } as CSSProperties) : undefined; + const badgeContent = props.badgeContent ?? "initials"; return ( ) : null} {props.showBadge ? ( - {providerInstanceInitials(props.displayName)} + {badgeContent === "initials" ? providerInstanceInitials(props.displayName) : null} ) : null} diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index c84eb34735..1952d77d4f 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -255,6 +255,7 @@ async function mountPicker(props: { providers?: ReadonlyArray; settings?: UnifiedSettings; triggerVariant?: "ghost" | "outline"; + getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; }) { const host = document.createElement("div"); document.body.append(host); @@ -277,6 +278,9 @@ async function mountPicker(props: { instanceEntries={instanceEntries} modelOptionsByInstance={modelOptionsByInstance} triggerVariant={props.triggerVariant} + {...(props.getModelDisabledReason + ? { getModelDisabledReason: props.getModelDisabledReason } + : {})} onInstanceModelChange={onInstanceModelChange} />, { container: host }, @@ -461,7 +465,7 @@ describe("ProviderModelPicker", () => { } }); - it("shows locked provider header and only its models in locked mode", async () => { + it("keeps the full provider rail in locked mode and only lists compatible models", async () => { localStorage.setItem( "t3code:client-settings:v1", JSON.stringify({ @@ -484,8 +488,21 @@ describe("ProviderModelPicker", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; - // Should show locked provider label expect(text).toContain("Claude"); + // Locked-compatible instances render first, then disabled ones. + expect(getSidebarProviderOrder().slice(0, 3)).toEqual([ + "favorites", + "claudeAgent", + "codex", + ]); + expect( + document.querySelector('[data-model-picker-provider="codex"]') + ?.disabled, + ).toBe(true); + expect( + document.querySelector('[data-model-picker-provider="claudeAgent"]') + ?.disabled, + ).toBe(false); expect(getVisibleModelNames()).toEqual([ "Claude Sonnet 4.6", "Claude Opus 4.6", @@ -559,7 +576,21 @@ describe("ProviderModelPicker", () => { await page.getByRole("button").click(); await vi.waitFor(() => { - expect(getSidebarProviderOrder()).toEqual(["codex", "codex_personal"]); + expect(getSidebarProviderOrder().slice(0, 5)).toEqual([ + "favorites", + "codex", + "codex_personal", + "codex_isolated", + "claudeAgent", + ]); + expect( + document.querySelector('[data-model-picker-provider="codex_isolated"]') + ?.disabled, + ).toBe(true); + expect( + document.querySelector('[data-model-picker-provider="claudeAgent"]') + ?.disabled, + ).toBe(true); expect(getModelPickerListText()).not.toContain("Codex Isolated"); expect( document.querySelector('[data-model-picker-provider="codex_personal"]') @@ -625,7 +656,7 @@ describe("ProviderModelPicker", () => { } }); - it("uses the trigger label for locked opencode rows", async () => { + it("shows the plain model name in the trigger and provider details on locked opencode rows", async () => { const providers: ReadonlyArray = [ buildOpenCodeProvider([ { @@ -658,14 +689,15 @@ describe("ProviderModelPicker", () => { const trigger = document.querySelector( '[data-chat-provider-model-picker="true"]', ); - expect(trigger?.textContent).toContain("GitHub Copilot"); expect(trigger?.textContent).toContain("Opus 4.5"); + expect(trigger?.textContent).not.toContain("GitHub Copilot"); }); await page.getByRole("button").click(); await vi.waitFor(() => { - expect(getVisibleModelNames()).toEqual(["GitHub Copilot · Opus 4.5"]); + expect(getVisibleModelNames()).toEqual(["Claude Opus 4.5"]); + expect(getModelPickerListText()).toContain("OpenCode · GitHub Copilot"); }); } finally { await mounted.cleanup(); @@ -961,27 +993,30 @@ describe("ProviderModelPicker", () => { expect(text).toContain("Claude Opus 4.6"); }); - const getFirstStarButton = () => { - const starButton = document.querySelector( + const getFavoriteButton = () => { + const modelRow = Array.from(document.querySelectorAll('[role="option"]')).find( + (row) => row.textContent?.includes("Claude Opus 4.6"), + ); + const starButton = modelRow?.querySelector( 'button[aria-label*="favorites"]', ); expect(starButton).not.toBeNull(); return starButton!; }; - const firstStar = getFirstStarButton(); - const initialAriaLabel = firstStar.getAttribute("aria-label"); + const favoriteButton = getFavoriteButton(); + const initialAriaLabel = favoriteButton.getAttribute("aria-label"); expect( initialAriaLabel === "Add to favorites" || initialAriaLabel === "Remove from favorites", ).toBe(true); - await page.getByRole("button", { name: initialAriaLabel! }).first().click(); + await userEvent.click(favoriteButton); const expectedAriaLabel = initialAriaLabel === "Add to favorites" ? "Remove from favorites" : "Add to favorites"; await vi.waitFor(() => { - expect(getFirstStarButton().getAttribute("aria-label")).toBe(expectedAriaLabel); + expect(getFavoriteButton().getAttribute("aria-label")).toBe(expectedAriaLabel); }); } finally { await mounted.cleanup(); @@ -1050,6 +1085,38 @@ describe("ProviderModelPicker", () => { } }); + it("filters favorites to compatible models in locked mode", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + favorites: [ + { provider: "codex", model: "gpt-5.3-codex" }, + { provider: "claudeAgent", model: "claude-sonnet-4-6" }, + ], + }), + ); + + const mounted = await mountPicker({ + activeInstanceId: CLAUDE_INSTANCE_ID, + model: "claude-opus-4-6", + lockedProvider: ProviderDriverKind.make("claudeAgent"), + }); + + try { + await page.getByRole("button").click(); + await page.getByRole("button", { name: "Favorites", exact: true }).click(); + + await vi.waitFor(() => { + expect(getVisibleModelNames()).toEqual(["Claude Sonnet 4.6"]); + expect(getModelPickerListText()).not.toContain("GPT-5.3 Codex"); + }); + } finally { + await mounted.cleanup(); + localStorage.removeItem("t3code:client-settings:v1"); + } + }); + it("dispatches callback with correct provider and model when selected", async () => { const mounted = await mountPicker({ activeInstanceId: CLAUDE_INSTANCE_ID, @@ -1079,6 +1146,29 @@ describe("ProviderModelPicker", () => { } }); + it("does not select models blocked by the provider", async () => { + const disabledReason = + "This provider does not allow switching models after a conversation has started. Start a new thread to use this model."; + const mounted = await mountPicker({ + activeInstanceId: CLAUDE_INSTANCE_ID, + model: "claude-opus-4-6", + lockedProvider: ProviderDriverKind.make("claudeAgent"), + getModelDisabledReason: (instanceId, model) => + instanceId === CLAUDE_INSTANCE_ID && model !== "claude-opus-4-6" ? disabledReason : null, + }); + + try { + await page.getByRole("button").click(); + + const blockedModel = page.getByText("Claude Sonnet 4.6").first(); + await blockedModel.click(); + expect(mounted.onProviderModelChange).not.toHaveBeenCalled(); + expect(document.querySelector(".model-picker-list")).not.toBeNull(); + } finally { + await mounted.cleanup(); + } + }); + it("only shows codex spark when the server reports it", async () => { const providersWithoutSpark: ReadonlyArray = [ buildCodexProvider([ diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 4a2860ee46..7cb5158a2c 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -41,6 +41,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { triggerVariant?: VariantProps["variant"]; triggerClassName?: string; onOpenChange?: (open: boolean) => void; + getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; }) { const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); @@ -65,7 +66,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { selectedInstanceOptions.find((option) => option.slug === props.model) ?? selectedInstanceOptions[0]; const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model; - const triggerSubtitle = selectedModel?.subProvider; const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model; const duplicateDriverCount = props.instanceEntries.filter( (entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind, @@ -86,6 +86,54 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { }; }, [isMenuOpen]); + useEffect(() => { + if (!isMenuOpen) { + return; + } + + const { documentElement, body } = document; + const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior; + const previousBodyOverflow = body.style.overflow; + const previousBodyPaddingRight = body.style.paddingRight; + const scrollbarWidth = window.innerWidth - documentElement.clientWidth; + + documentElement.style.overscrollBehavior = "contain"; + body.style.overflow = "hidden"; + if (scrollbarWidth > 0) { + body.style.paddingRight = `${scrollbarWidth}px`; + } + + const shouldAllowOverlayScroll = (target: EventTarget | null) => { + return target instanceof Element && target.closest("[data-model-picker-content]"); + }; + const preventBackgroundWheel = (event: WheelEvent) => { + if (shouldAllowOverlayScroll(event.target)) { + return; + } + event.preventDefault(); + }; + const preventBackgroundTouchMove = (event: TouchEvent) => { + if (shouldAllowOverlayScroll(event.target)) { + return; + } + event.preventDefault(); + }; + + document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false }); + document.addEventListener("touchmove", preventBackgroundTouchMove, { + capture: true, + passive: false, + }); + + return () => { + document.removeEventListener("wheel", preventBackgroundWheel, { capture: true }); + document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true }); + documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior; + body.style.overflow = previousBodyOverflow; + body.style.paddingRight = previousBodyPaddingRight; + }; + }, [isMenuOpen]); + const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => { if (props.disabled) return; props.onInstanceModelChange(instanceId, model); @@ -110,7 +158,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { variant={props.triggerVariant ?? "ghost"} data-chat-provider-model-picker="true" className={cn( - "min-w-0 justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 [&_svg]:mx-0", + "min-w-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80", props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3", props.triggerClassName, )} @@ -118,12 +166,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { /> } > - + {activeEntry ? ( ) : null} - - } - > - {triggerSubtitle ? ( - <> - {triggerSubtitle} - - {triggerTitle} - - ) : ( - triggerTitle - )} + }> + {triggerTitle} {triggerLabel} - + setIsMenuOpen(false)} + {...(props.getModelDisabledReason + ? { getModelDisabledReason: props.getModelDisabledReason } + : {})} onInstanceModelChange={handleInstanceModelChange} /> diff --git a/apps/web/src/components/chat/ProviderStatusBanner.tsx b/apps/web/src/components/chat/ProviderStatusBanner.tsx index a882942585..c725b3e275 100644 --- a/apps/web/src/components/chat/ProviderStatusBanner.tsx +++ b/apps/web/src/components/chat/ProviderStatusBanner.tsx @@ -1,8 +1,9 @@ import { type ServerProvider } from "@t3tools/contracts"; import { memo } from "react"; -import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; -import { CircleAlertIcon } from "lucide-react"; +import { InfoIcon } from "lucide-react"; +import { cn } from "~/lib/utils"; import { formatProviderDriverKindLabel } from "../../providerModels"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export const ProviderStatusBanner = memo(function ProviderStatusBanner({ status, @@ -13,22 +14,42 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({ return null; } - const providerLabel = status.displayName?.trim() || formatProviderDriverKindLabel(status.driver); - const defaultMessage = - status.status === "error" - ? `${providerLabel} provider is unavailable.` - : `${providerLabel} provider has limited availability.`; - const title = `${providerLabel} provider status`; + const providerName = status.displayName?.trim() || formatProviderDriverKindLabel(status.driver); + const isUnauthenticated = status.status === "error" && status.auth.status === "unauthenticated"; + const title = isUnauthenticated + ? `${providerName} is unauthenticated` + : `${providerName} provider status`; + const message = isUnauthenticated + ? "Sign in via the CLI to authenticate again." + : (status.message ?? + (status.status === "error" + ? `${providerName} provider is unavailable.` + : `${providerName} provider has limited availability.`)); return ( -
    - - - {title} - - {status.message ?? defaultMessage} - - +
    +
    + +
    +
    {title}
    + + {message}
    } + /> + + {message} + + +
    +
    ); }); diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx index 0c1abbd40d..444f35b425 100644 --- a/apps/web/src/components/chat/SkillInlineText.tsx +++ b/apps/web/src/components/chat/SkillInlineText.tsx @@ -3,11 +3,12 @@ import type { ServerProviderSkill } from "@t3tools/contracts"; import { formatProviderSkillDisplayName } from "../../providerSkillPresentation"; import { + CHAT_INLINE_CHIP_CLASS_NAME, + CHAT_INLINE_CHIP_LABEL_CLASS_NAME, COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, - COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, - COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME, SKILL_CHIP_ICON_SVG, } from "../composerInlineChip"; +import { cn } from "~/lib/utils"; const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g; @@ -70,15 +71,19 @@ export function renderSkillInlineMarkdownChildren( function SkillChip(props: { skill: InlineSkill; rawText: string }) { return ( - - {props.rawText} -
    diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 89b070c931..659823aec7 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -805,9 +805,19 @@ function KeybindingTableRow({
    -
    - {commandLabel(row.command)} -
    + + + } + > + {commandLabel(row.command)} + + {row.command} +
    diff --git a/apps/web/src/components/settings/ProviderAccentColorPicker.tsx b/apps/web/src/components/settings/ProviderAccentColorPicker.tsx new file mode 100644 index 0000000000..d352257257 --- /dev/null +++ b/apps/web/src/components/settings/ProviderAccentColorPicker.tsx @@ -0,0 +1,335 @@ +"use client"; + +import { PipetteIcon, XIcon } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent } from "react"; + +import { ColorSelector } from "../color-selector"; +import { Button } from "../ui/button"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { normalizeProviderAccentColor } from "../../providerInstances"; +import { cn } from "../../lib/utils"; + +const PROVIDER_ACCENT_SWATCHES = [ + "#2563eb", + "#16a34a", + "#ea580c", + "#dc2626", + "#7c3aed", + "#0891b2", +] as const; + +const FALLBACK_ACCENT_COLOR = PROVIDER_ACCENT_SWATCHES[0]; + +function clamp(value: number, min = 0, max = 1) { + return Math.min(max, Math.max(min, value)); +} + +function hexToHsv(hex: string) { + const normalized = normalizeProviderAccentColor(hex) ?? FALLBACK_ACCENT_COLOR; + const numeric = Number.parseInt(normalized.slice(1), 16); + const red = ((numeric >> 16) & 255) / 255; + const green = ((numeric >> 8) & 255) / 255; + const blue = (numeric & 255) / 255; + const max = Math.max(red, green, blue); + const min = Math.min(red, green, blue); + const delta = max - min; + + let hue = 0; + if (delta !== 0) { + if (max === red) { + hue = ((green - blue) / delta) % 6; + } else if (max === green) { + hue = (blue - red) / delta + 2; + } else { + hue = (red - green) / delta + 4; + } + hue *= 60; + if (hue < 0) hue += 360; + } + + return { + h: hue, + s: max === 0 ? 0 : delta / max, + v: max, + }; +} + +function hsvToHex(hue: number, saturation: number, value: number) { + const chroma = value * saturation; + const x = chroma * (1 - Math.abs(((hue / 60) % 2) - 1)); + const match = value - chroma; + const [red, green, blue] = + hue < 60 + ? [chroma, x, 0] + : hue < 120 + ? [x, chroma, 0] + : hue < 180 + ? [0, chroma, x] + : hue < 240 + ? [0, x, chroma] + : hue < 300 + ? [x, 0, chroma] + : [chroma, 0, x]; + + return `#${[red, green, blue] + .map((channel) => + Math.round((channel + match) * 255) + .toString(16) + .padStart(2, "0"), + ) + .join("")}`; +} + +function ProviderCustomColorPanel(props: { + readonly value: string; + readonly onCommit: (value: string) => void; +}) { + const { onCommit } = props; + const initialHsv = useMemo(() => hexToHsv(props.value), [props.value]); + const [hsv, setHsv] = useState(initialHsv); + const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v); + + const commitHsv = useCallback( + (nextHsv: typeof hsv) => { + setHsv(nextHsv); + onCommit(hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v)); + }, + [onCommit], + ); + + const updateFromPlane = useCallback( + (event: PointerEvent) => { + const bounds = event.currentTarget.getBoundingClientRect(); + const saturation = clamp((event.clientX - bounds.left) / bounds.width); + const value = 1 - clamp((event.clientY - bounds.top) / bounds.height); + commitHsv({ ...hsv, s: saturation, v: value }); + }, + [commitHsv, hsv], + ); + + const updateFromHue = useCallback( + (event: PointerEvent) => { + const bounds = event.currentTarget.getBoundingClientRect(); + commitHsv({ ...hsv, h: clamp((event.clientX - bounds.left) / bounds.width) * 360 }); + }, + [commitHsv, hsv], + ); + + const handlePointerDown = (handler: (event: PointerEvent) => void) => { + return (event: PointerEvent) => { + event.currentTarget.setPointerCapture(event.pointerId); + handler(event); + }; + }; + + return ( +
    +
    { + if (event.currentTarget.hasPointerCapture(event.pointerId)) { + updateFromPlane(event); + } + }} + > + +
    +
    +
    { + if (event.currentTarget.hasPointerCapture(event.pointerId)) { + updateFromHue(event); + } + }} + > + +
    + { + const nextColor = event.currentTarget.value; + if (!/^#[\da-f]{6}$/i.test(nextColor)) return; + setHsv(hexToHsv(nextColor)); + props.onCommit(nextColor); + }} + className="h-8 rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground outline-none transition-colors focus:border-ring" + aria-label="Custom hex accent color" + spellCheck={false} + /> +
    +
    + ); +} + +function ProviderCustomColorPicker(props: { + readonly displayName: string; + readonly value: string | undefined; + readonly selected: boolean; + readonly onCommit: (value: string) => void; +}) { + const normalized = normalizeProviderAccentColor(props.value) ?? FALLBACK_ACCENT_COLOR; + + return ( + + + + + } + /> + + + + + ); +} + +export function ProviderAccentColorPicker(props: { + readonly displayName: string; + readonly value: string | undefined; + readonly onCommit: (value: string) => void; + readonly description?: string; + readonly commitDelayMs?: number; +}) { + const { commitDelayMs = 0, description, displayName, onCommit, value } = props; + const [optimisticValue, setOptimisticValue] = useState(() => value ?? ""); + const commitTimeoutRef = useRef | null>(null); + const pendingCommitRef = useRef(null); + const onCommitRef = useRef(onCommit); + + useEffect(() => { + onCommitRef.current = onCommit; + }, [onCommit]); + + useEffect(() => { + if (pendingCommitRef.current !== null) return; + setOptimisticValue(value ?? ""); + }, [value]); + + useEffect(() => { + return () => { + if (commitTimeoutRef.current !== null) { + clearTimeout(commitTimeoutRef.current); + } + const pendingCommit = pendingCommitRef.current; + if (pendingCommit !== null) { + onCommitRef.current(pendingCommit); + } + }; + }, []); + + const commitAccentColor = useCallback( + (value: string) => { + const normalizedValue = normalizeProviderAccentColor(value) ?? ""; + setOptimisticValue(normalizedValue); + + if (commitDelayMs <= 0) { + pendingCommitRef.current = null; + if (commitTimeoutRef.current !== null) { + clearTimeout(commitTimeoutRef.current); + commitTimeoutRef.current = null; + } + onCommit(normalizedValue); + return; + } + + pendingCommitRef.current = normalizedValue; + if (commitTimeoutRef.current !== null) { + clearTimeout(commitTimeoutRef.current); + } + commitTimeoutRef.current = setTimeout(() => { + commitTimeoutRef.current = null; + const pendingCommit = pendingCommitRef.current; + pendingCommitRef.current = null; + if (pendingCommit !== null) { + onCommitRef.current(pendingCommit); + } + }, commitDelayMs); + }, + [commitDelayMs, onCommit], + ); + + const normalized = normalizeProviderAccentColor(optimisticValue); + const selectedValue = + normalized && + PROVIDER_ACCENT_SWATCHES.includes(normalized as (typeof PROVIDER_ACCENT_SWATCHES)[number]) + ? normalized + : ""; + const customSelected = Boolean(normalized && selectedValue === ""); + + return ( +
    + Accent color +
    + + + +
    + {description ? {description} : null} +
    + ); +} diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index ba3feddb46..823f8f968a 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -28,17 +28,20 @@ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { normalizeProviderAccentColor } from "../../providerInstances"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; +import { Checkbox } from "../ui/checkbox"; import { Collapsible, CollapsibleContent } from "../ui/collapsible"; import { DraftInput } from "../ui/draft-input"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { ScrollArea } from "../ui/scroll-area"; import { Switch } from "../ui/switch"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { DriverOption } from "./providerDriverMeta"; import { ProviderSettingsForm } from "./ProviderSettingsForm"; import { ProviderModelsSection } from "./ProviderModelsSection"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker"; import { RedactedSensitiveText } from "./RedactedSensitiveText"; import { getProviderVersionAdvisoryPresentation, @@ -48,15 +51,6 @@ import { type ProviderStatusKey, } from "./providerStatus"; -const PROVIDER_ACCENT_SWATCHES = [ - "#2563eb", - "#16a34a", - "#ea580c", - "#dc2626", - "#7c3aed", - "#0891b2", -] as const; - const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/; let environmentVariableDraftId = 0; @@ -159,94 +153,6 @@ function ProviderAuthEmail(props: { ); } -function ProviderAccentColorPicker(props: { - readonly displayName: string; - readonly value: string | undefined; - readonly onCommit: (value: string) => void; -}) { - const [draft, setDraft] = useState(props.value ?? ""); - const [isEditing, setIsEditing] = useState(false); - const draftColor = normalizeProviderAccentColor(draft); - - useEffect(() => { - if (isEditing) return; - setDraft(props.value ?? ""); - }, [isEditing, props.value]); - - const commitDraft = () => { - setIsEditing(false); - props.onCommit(draftColor ?? ""); - }; - - const commitSwatch = (swatch: string) => { - setIsEditing(false); - setDraft(swatch); - props.onCommit(swatch); - }; - - return ( -
    - Accent color -
    - setIsEditing(true)} - onInput={(event) => { - setIsEditing(true); - setDraft(event.currentTarget.value); - }} - onChange={(event) => { - setIsEditing(true); - setDraft(event.currentTarget.value); - }} - onBlur={commitDraft} - aria-label={`Accent color for ${props.displayName}`} - className="h-8 w-10 cursor-pointer rounded border border-input bg-background p-0.5" - /> -
    - {PROVIDER_ACCENT_SWATCHES.map((swatch) => { - const selected = draftColor?.toLowerCase() === swatch; - return ( -
    - {draftColor ? ( - - ) : null} -
    - - Used to distinguish this instance in picker rails and model lists. - -
    - ); -} - function ProviderEnvironmentSection(props: { readonly environment: ReadonlyArray; readonly onChange: (environment: ReadonlyArray) => void; @@ -330,59 +236,83 @@ function ProviderEnvironmentSection(props: { Add variables to pass API keys, base URLs, or other per-instance CLI settings.

    ) : ( -
    - {rows.map((variable, index) => ( -
    - updateVariable(variable.id, { name: name.trim() })} - placeholder="VARIABLE_NAME" - spellCheck={false} - aria-label={`Environment variable name ${index + 1}`} - /> - updateVariable(variable.id, { value })} - type={variable.sensitive ? "password" : undefined} - autoComplete="off" - placeholder={ - variable.valueRedacted ? "Stored secret - enter a new value to replace" : "Value" - } - spellCheck={false} - aria-label={`Environment variable value ${index + 1}`} - /> - - -
    - ))} +
    + + + + Variable + Value + Sensitive + + Options + + + + + {rows.map((variable, index) => ( + + + updateVariable(variable.id, { name: name.trim() })} + placeholder="VARIABLE_NAME" + spellCheck={false} + aria-label={`Environment variable name ${index + 1}`} + /> + + + updateVariable(variable.id, { value })} + type={variable.sensitive ? "password" : undefined} + autoComplete="off" + placeholder={ + variable.valueRedacted + ? "Stored secret - enter a new value to replace" + : "Value" + } + spellCheck={false} + aria-label={`Environment variable value ${index + 1}`} + /> + + +
    + { + const sensitive = Boolean(checked); + updateVariable(variable.id, { + sensitive, + ...(sensitive && variable.valueRedacted === undefined + ? {} + : { valueRedacted: sensitive ? variable.valueRedacted : false }), + }); + }} + aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`} + /> +
    +
    + +
    + +
    +
    +
    + ))} +
    +
    )} @@ -582,16 +512,17 @@ export function ProviderInstanceCard({ accentColor={accentColor} showBadge={Boolean(accentColor)} statusDotClassName={statusStyle.dot} + indicatorBackground="var(--card)" className="size-5" iconClassName="size-4 text-foreground/80" - badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]" + badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]" /> ) : FallbackIconComponent ? (
    diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index e3c8efeeb1..54f73e3b35 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -149,12 +149,16 @@ const authAccessHarness = vi.hoisted(() => { const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn()); const mockGetClerkToken = vi.hoisted(() => vi.fn(async () => null)); +const mockOpenClerkWaitlist = vi.hoisted(() => vi.fn()); vi.mock("@clerk/react", () => ({ useAuth: () => ({ getToken: mockGetClerkToken, isSignedIn: false, }), + useClerk: () => ({ + openWaitlist: mockOpenClerkWaitlist, + }), })); vi.mock("../../environments/runtime", () => { diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index c0238a4651..6774b6f333 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -3,7 +3,6 @@ import { ArchiveIcon, ArrowLeftIcon, BotIcon, - CloudIcon, GitBranchIcon, KeyboardIcon, Link2Icon, @@ -21,15 +20,13 @@ import { SidebarSeparator, useSidebar, } from "../ui/sidebar"; -import { Badge } from "../ui/badge"; -import { hasCloudPublicConfig } from "../../cloud/publicConfig"; +import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn"; export type SettingsSectionPath = | "/settings/general" | "/settings/keybindings" | "/settings/providers" | "/settings/source-control" - | "/settings/cloud" | "/settings/connections" | "/settings/archived"; @@ -37,13 +34,11 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{ label: string; to: SettingsSectionPath; icon: ComponentType<{ className?: string }>; - badgeLabel?: string; }> = [ { label: "General", to: "/settings/general", icon: Settings2Icon }, { label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon }, { label: "Providers", to: "/settings/providers", icon: BotIcon }, { label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon }, - { label: "T3 Cloud", to: "/settings/cloud", icon: CloudIcon, badgeLabel: "Private Beta" }, { label: "Connections", to: "/settings/connections", icon: Link2Icon }, { label: "Archive", to: "/settings/archived", icon: ArchiveIcon }, ]; @@ -77,9 +72,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { - {SETTINGS_NAV_ITEMS.filter( - (item) => item.to !== "/settings/cloud" || hasCloudPublicConfig(), - ).map((item) => { + {SETTINGS_NAV_ITEMS.map((item) => { const Icon = item.icon; const isActive = pathname === item.to; return ( @@ -102,11 +95,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { } /> {item.label} - {item.badgeLabel ? ( - - {item.badgeLabel} - - ) : null} ); @@ -117,18 +105,22 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { - - - - - Back - - - + +
    + + + + + Back + + + + +
    ); diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx index a825463b3e..add6954fd0 100644 --- a/apps/web/src/components/settings/settingsLayout.tsx +++ b/apps/web/src/components/settings/settingsLayout.tsx @@ -38,7 +38,7 @@ export function SettingsSection({
    {headerAction}
    -
    +
    {children}
    diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/web/src/components/ui/alert-dialog.tsx index 84bcff9631..c92f1b8082 100644 --- a/apps/web/src/components/ui/alert-dialog.tsx +++ b/apps/web/src/components/ui/alert-dialog.tsx @@ -17,8 +17,9 @@ function AlertDialogTrigger(props: AlertDialogPrimitive.Trigger.Props) { function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backdrop.Props) { return ( svg]:has-data-[slot=alert-action]:grid-cols-[calc(var(--spacing)*4)_1fr_auto] has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-data-[slot=alert-action]:grid-cols-[1fr_auto] has-[>svg]:gap-x-2 [&>svg]:h-lh [&>svg]:w-4", - { - defaultVariants: { - variant: "default", - }, - variants: { - variant: { - default: "bg-transparent dark:bg-input/32 [&>svg]:text-muted-foreground", - error: "border-destructive/32 bg-destructive/4 [&>svg]:text-destructive", - info: "border-info/32 bg-info/4 [&>svg]:text-info", - success: "border-success/32 bg-success/4 [&>svg]:text-success", - warning: "border-warning/32 bg-warning/4 [&>svg]:text-warning", - }, +const alertVariants = cva("relative rounded-xl border px-3.5 py-3 text-card-foreground text-sm", { + defaultVariants: { + variant: "default", + }, + variants: { + variant: { + default: "bg-transparent dark:bg-input/32 [&_svg]:text-muted-foreground", + error: + "border-destructive/32 bg-destructive/4 text-destructive-foreground [&_[data-slot=alert-description]]:text-destructive-foreground/80 [&_svg]:text-destructive", + info: "border-info/32 bg-info/4 [&_svg]:text-info", + success: "border-success/32 bg-success/4 [&_svg]:text-success", + warning: "border-warning/32 bg-warning/4 [&_svg]:text-warning", }, }, -); +}); + +function alertChildSlot(child: React.ReactElement): string | undefined { + const propsSlot = (child.props as Record)["data-slot"]; + if (propsSlot) { + return propsSlot; + } + + const type = child.type as { displayName?: string; name?: string }; + switch (type.displayName ?? type.name) { + case "AlertAction": + return "alert-action"; + case "AlertTitle": + return "alert-title"; + case "AlertDescription": + return "alert-description"; + default: + return undefined; + } +} function Alert({ className, variant, + children, ...props }: React.ComponentProps<"div"> & VariantProps) { + const icon: React.ReactNode[] = []; + const content: React.ReactNode[] = []; + const action: React.ReactNode[] = []; + + Children.forEach(children, (child) => { + if (!isValidElement(child)) { + content.push(child); + return; + } + const slot = alertChildSlot(child); + if (slot === "alert-action") { + action.push(child); + } else if (slot === "alert-title" || slot === "alert-description") { + content.push(child); + } else { + icon.push(child); + } + }); + return (
    + > +
    + {icon.length > 0 && ( +
    + {icon} +
    + )} + {content.length > 0 && ( +
    {content}
    + )} + {action.length > 0 && ( +
    {action}
    + )} +
    +
    ); } function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { - return ( -
    - ); + return
    ; } function AlertDescription({ className, ...props }: React.ComponentProps<"div">) { return (
    @@ -57,16 +103,11 @@ function AlertDescription({ className, ...props }: React.ComponentProps<"div">) } function AlertAction({ className, ...props }: React.ComponentProps<"div">) { - return ( -
    - ); + return
    ; } +AlertTitle.displayName = "AlertTitle"; +AlertDescription.displayName = "AlertDescription"; +AlertAction.displayName = "AlertAction"; + export { Alert, AlertTitle, AlertDescription, AlertAction }; diff --git a/apps/web/src/components/ui/autocomplete.tsx b/apps/web/src/components/ui/autocomplete.tsx index d6db87d48c..2d099762f2 100644 --- a/apps/web/src/components/ui/autocomplete.tsx +++ b/apps/web/src/components/ui/autocomplete.tsx @@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti return ( & { inputClassName?: string; @@ -67,6 +68,7 @@ function ComboboxInput({ showClear?: boolean; startAddon?: React.ReactNode; size?: "sm" | "default" | "lg" | number; + unstyled?: boolean; ref?: React.Ref; }) { const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number; @@ -97,6 +99,7 @@ function ComboboxInput({ className={cn("has-disabled:opacity-100", inputClassName)} nativeInput size={sizeValue} + unstyled={unstyled} /> } {...props} @@ -208,9 +211,11 @@ function ComboboxItem({
    {children}
    diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsx index 9a9a57ef0f..ad05bc2a63 100644 --- a/apps/web/src/components/ui/command.tsx +++ b/apps/web/src/components/ui/command.tsx @@ -30,7 +30,7 @@ function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.B return ( svg]:-mx-0.5 flex min-h-8 cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-inset:ps-8 data-[variant=destructive]:text-destructive-foreground data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&>svg:not([class*='opacity-'])]:opacity-80 [&>svg:not([class*='size-'])]:size-4.5 sm:[&>svg:not([class*='size-'])]:size-4 [&>svg]:pointer-events-none [&>svg]:shrink-0", + "[&>svg]:-mx-0.5 flex min-h-8 cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-inset:ps-8 data-[variant=destructive]:text-destructive-foreground data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&>svg:not([class*='opacity-'])]:opacity-80 [&>svg:not([class*='size-'])]:size-4.5 sm:[&>svg:not([class*='size-'])]:size-4 [&>svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:[&>svg:not([class*='text-'])]:text-current [&>svg]:pointer-events-none [&>svg]:shrink-0", className, )} data-inset={inset} @@ -235,7 +235,7 @@ function MenuSubTrigger({ return ( diff --git a/apps/web/src/components/ui/select.tsx b/apps/web/src/components/ui/select.tsx index 3649a567f7..7761b03597 100644 --- a/apps/web/src/components/ui/select.tsx +++ b/apps/web/src/components/ui/select.tsx @@ -21,7 +21,7 @@ const selectTriggerVariants = cva( variants: { variant: { default: - "w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none", + "w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-muted-foreground [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none", ghost: "border-transparent text-muted-foreground/70 focus-visible:ring-2 focus-visible:ring-ring data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent [:hover,[data-pressed]]:text-foreground/80", }, @@ -54,7 +54,7 @@ function SelectButton({ className, size, variant, render, children, ...props }: {children} {variant === "ghost" ? ( - + ) : ( )} @@ -87,7 +87,7 @@ function SelectTrigger({ > {children} - + ); @@ -138,7 +138,7 @@ function SelectPopup({ sideOffset={sideOffset} > @@ -210,7 +210,10 @@ function SelectItem({ )} {children} diff --git a/apps/web/src/components/ui/sheet.tsx b/apps/web/src/components/ui/sheet.tsx index dfa3d6db14..9d0436b661 100644 --- a/apps/web/src/components/ui/sheet.tsx +++ b/apps/web/src/components/ui/sheet.tsx @@ -22,7 +22,7 @@ function SheetBackdrop({ className, ...props }: SheetPrimitive.Backdrop.Props) { return (