diff --git a/.github/scripts/ci-changes.cjs b/.github/scripts/ci-changes.cjs index 77a526076de4d..0f817be60c35d 100644 --- a/.github/scripts/ci-changes.cjs +++ b/.github/scripts/ci-changes.cjs @@ -27,6 +27,8 @@ const EXTRA_OWNERS = [ [/^native\/browser-secret\//, ["@t3tools/desktop"]], [/^native\/kde-snap-shot\//, ["@t3tools/desktop"]], [/^native\/libghostty-vt\//, ["@t3tools/web"]], + // apps/server/src/cloud/ConnectReachability.test.ts checks the guide's headings. + [/^docs\/user\/t3-connect-troubleshooting\.md$/, ["t3"]], ]; const RUST = /^native\/(resource-monitor|kde-snap-shot|hyprland-snap-shot)\//; @@ -92,11 +94,11 @@ function readWorkspace() { // [] means inert; null means unknown and requires every job. function ownersOf(file, packages) { - if (INERT.some((pattern) => pattern.test(file))) return []; + const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : [])); + if (INERT.some((pattern) => pattern.test(file))) return extra; // A manifest can change dependencies or versions other packages read. if (path.posix.basename(file) === "package.json") return null; if (RUNS_EVERYTHING.some((pattern) => pattern.test(file))) return null; - const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : [])); // scripts/build-desktop-artifact.test.ts reads the crates' sources. if (RUST.test(file)) return ["@t3tools/scripts", ...extra]; diff --git a/.macroscope/check-run-agents/ui-consistency.md b/.macroscope/check-run-agents/ui-consistency.md index 047dafbdd4be1..905823d1d1a9e 100644 --- a/.macroscope/check-run-agents/ui-consistency.md +++ b/.macroscope/check-run-agents/ui-consistency.md @@ -44,7 +44,7 @@ The reference for how this codebase wants UI built is the composer banner system - `ComposerBanner.tsx` exports one object of small slot components (`Root`, `Row`, `Icon`, `Content`, `Actions`, `Dismiss`, `Children`, and so on). Each slot owns its own Tailwind classes, exposes a `data-slot` attribute, takes `className` and spreads the rest of its props, and uses `cn` so callers can adjust without overriding. Variants and density are props on `Root`, not ad hoc class strings at call sites. Where a slot needs a real control it renders `Button` from `ui/` rather than a styled `"); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label"); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 88308ed691eed..d573cd6387c8b 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -583,6 +583,7 @@ const capture = async ( }); return { ...page, + url: withoutDataPayload(page.url), // Mask text before truncating so a value crossing the cut cannot leak its prefix. visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH), accessibilityTree, diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 3262c555bcf8c..1b724c17010d8 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -5,6 +5,7 @@ import * as ConfigProvider from "effect/ConfigProvider"; import * as Deferred from "effect/Deferred"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -714,6 +715,79 @@ it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launc }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect( + "memoizes editor discovery and refreshes in the background after the cache window", + () => { + let statCalls = 0; + const rescanned = Deferred.makeUnsafe(); + let initialScanDone = false; + const fileInfo = { type: "File" } as FileSystem.File.Info; + const layerLauncher = ExternalLauncher.layer.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + stat: () => + Effect.sync(() => { + statCalls += 1; + return fileInfo; + }).pipe( + Effect.tap(() => + initialScanDone ? Deferred.succeed(rescanned, undefined) : Effect.void, + ), + ), + }), + Path.layer, + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())), + ), + ), + ), + ); + + return Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + + const first = yield* launcher.resolveAvailableEditors(); + assert.equal(first.includes("vscode"), true); + const statCallsAfterFirstScan = statCalls; + initialScanDone = true; + assert.isAbove(statCallsAfterFirstScan, 0); + + // Past the shared command-resolution cache TTL (30s) but within the + // discovery cache window: the memoized set is reused without any scan. + yield* TestClock.adjust("31 seconds"); + const second = yield* launcher.resolveAvailableEditors(); + assert.deepEqual([...second], [...first]); + assert.equal(statCalls, statCallsAfterFirstScan); + + // Past the discovery cache window the next call still answers from the + // memoized set and rescans in the background. + yield* TestClock.adjust("30 seconds"); + const third = yield* launcher.resolveAvailableEditors(); + assert.deepEqual([...third], [...first]); + yield* Deferred.await(rescanned); + assert.isAbove(statCalls, statCallsAfterFirstScan); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerLauncher, + Layer.succeed(HostProcess.Platform, "win32"), + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + PATH: "C:\\t3-editor-discovery-cache-test", + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }, + }), + ), + TestClock.layer(), + ), + ), + ); + }, +); + it.effect("keeps scanning after the caller is interrupted and shares that scan", () => { const fileInfo = { type: "File" } as FileSystem.File.Info; const release = Deferred.makeUnsafe(); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 6a2eb145162e2..7f4417d1fb67a 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -19,24 +19,20 @@ import { resolveSpawnCommand, withPathDirectoryListings, } from "@t3tools/shared/shell"; -import * as Clock from "effect/Clock"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; -import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; -import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { makeStaleWhileRevalidate } from "../environment/staleWhileRevalidate.ts"; export { ExternalLauncherError, ExternalLauncherBrowserSpawnError, @@ -447,13 +443,7 @@ const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileMana }, ); -// Shared scans must survive caller timeouts/disconnects; monotonic expiry prevents clock rollback extending stale entries. -const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n; - -interface EditorDiscoveryCacheEntry { - readonly scan: Deferred.Deferred>; - readonly expiresAtNanos: bigint | undefined; -} +const EDITOR_DISCOVERY_CACHE_TTL = "60 seconds"; export class ExternalLauncher extends Context.Service< ExternalLauncher, @@ -817,69 +807,27 @@ export const make = Effect.gen(function* () { Effect.provideService(Path.Path, path), ); - const scope = yield* Scope.Scope; - const editorDiscoveryCache = yield* Ref.make>( - Option.none(), - ); - const runEditorDiscovery = (scan: Deferred.Deferred>) => + const cachedAvailableEditors = yield* makeStaleWhileRevalidate( provideCommandResolutionServices(resolveAvailableEditors()).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.onExit((exit) => - Effect.gen(function* () { - const expiresAtNanos = - (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS; - yield* Ref.update(editorDiscoveryCache, (current) => - Option.isNone(current) || current.value.scan !== scan - ? current - : Exit.isSuccess(exit) - ? Option.some({ scan, expiresAtNanos }) - : Option.none(), - ); - yield* Deferred.done(scan, exit); - }), - ), - Effect.interruptible, - Effect.forkIn(scope), - ); - // Claim and start atomically; interruption between them would leave an entry waiting on no scan. - const acquireEditorDiscovery = Effect.gen(function* () { - const nowNanos = yield* Clock.monotonicTimeNanos; - const [scan, isNewScan] = yield* Ref.modify( - editorDiscoveryCache, - ( - current, - ): [ - [EditorDiscoveryCacheEntry["scan"], boolean], - Option.Option, - ] => { - if ( - Option.isSome(current) && - (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos) - ) { - return [[current.value.scan, false], current]; - } - const scan = Deferred.makeUnsafe>(); - return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })]; - }, - ); - if (isNewScan) { - yield* runEditorDiscovery(scan); - } - return scan; - }).pipe(Effect.uninterruptible); - const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await); + ), + EDITOR_DISCOVERY_CACHE_TTL, + ); + const cachedFileManagerRevealKind = yield* makeStaleWhileRevalidate( + provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + EDITOR_DISCOVERY_CACHE_TTL, + ); // Forwarders retain the underlying launcher and discovery spans. return ExternalLauncher.of({ resolveAvailableEditors: Effect.fnUntraced(function* () { return yield* cachedAvailableEditors; }), - resolveFileManagerRevealKind: Effect.fnUntraced( - function* () { - return yield* provideCommandResolutionServices(resolveFileManagerRevealKind()); - }, - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), + resolveFileManagerRevealKind: Effect.fnUntraced(function* () { + return yield* cachedFileManagerRevealKind; + }), launchBrowser: Effect.fnUntraced( function* (target) { return yield* launchBrowser(target); diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 4248e51b55977..0e3a3c67a7666 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -75,6 +75,7 @@ function candidate( model: modelSelection.model, createdAt: timestamp, updatedAt: timestamp, + omittedMessageCount: 0, messages: [ { role: "user" as const, text: "Fix it", createdAt: timestamp }, { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, @@ -273,6 +274,7 @@ it.effect( "claudeAgent", ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); + unowned.thread.omittedMessageCount = 1; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); const importer = yield* makeImporter([ active, @@ -307,9 +309,23 @@ it.effect( const threadId = importId(source); const records = yield* projections.getThreadRecords(threadId, [ "messages", + "turnItems", "providerThreads", ]); expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); + const notices = records.turnItems.filter((item) => item.type === "system_notice"); + if (source === unowned) { + expect(records.turnItems[0]).toBe(notices[0]); + expect(notices).toMatchObject([ + { + ordinal: 1, + runId: null, + message: expect.stringContaining("1 earlier message was not imported"), + }, + ]); + } else { + expect(notices).toEqual([]); + } expect(records.thread.historyOrigin).toBe("v1_import"); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 038b488635053..a3f587c1c6d49 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -365,6 +365,34 @@ const make = Effect.gen(function* () { occurredAt: createdAt, payload: appThread, }, + ...(thread.omittedMessageCount > 0 + ? [ + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + type: "turn-item.updated" as const, + threadId, + occurredAt: createdAt, + payload: { + id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "system_notice" as const, + message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`, + }, + }, + ] + : []), ...thread.messages.flatMap((message, index) => messageEvents({ threadId, index, message }), ), diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 039393eb52a6d..688b974e7658d 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1823,6 +1823,48 @@ describe("parseAgentSessionTranscript", () => { }, ); + it.each([199, 200, 201, 205])( + "counts only omitted conversation messages for a %s-message Claude transcript", + (count) => { + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: [ + ...Array.from({ length: count }, (_, index) => + encodeTranscriptRecord({ + type: index === 0 ? "user" : "assistant", + sessionId: "claude-session", + message: { content: `Message ${index}` }, + }), + ), + encodeTranscriptRecord({ type: "user", isMeta: true, message: { content: "Setup" } }), + encodeTranscriptRecord({ + type: "user", + isCompactSummary: true, + message: { content: "Summary" }, + }), + encodeTranscriptRecord({ + type: "assistant", + isSidechain: true, + message: { content: "Sidechain" }, + }), + encodeTranscriptRecord({ + type: "assistant", + message: { content: [{ type: "tool_use" }] }, + }), + "malformed", + ].join("\n"), + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), + }); + + expect(thread?.omittedMessageCount).toBe(Math.max(0, count - 200)); + expect(thread?.messages).toHaveLength(Math.min(200, count)); + expect(thread?.messages[0]?.text).toBe("Message 0"); + expect(thread?.messages.at(-1)?.text).toBe(`Message ${count - 1}`); + }, + ); + it("keeps Claude text and titles while dropping malformed and tool records", () => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: [ @@ -1974,10 +2016,10 @@ describe("parseAgentSessionTranscript", () => { ]); }); - it("keeps the canonical first prompt after long Codex transcripts are capped", () => { + it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => { const canonicalPrompt = "\n Keep the canonical prompt \n"; const canonicalTimestamp = "2026-08-24T10:01:00.000Z"; - const laterAssistantMessages = Array.from({ length: 200 }, (_, index) => + const laterAssistantMessages = Array.from({ length: count }, (_, index) => encodeTranscriptRecord({ type: "response_item", timestamp: `2026-08-24T11:${String(index % 60).padStart(2, "0")}:00.000Z`, @@ -2013,6 +2055,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); + expect(thread?.omittedMessageCount).toBe(count - 199); expect(thread?.messages).toHaveLength(200); expect(thread?.messages[0]).toMatchObject({ role: "user", @@ -2075,6 +2118,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); + expect(thread?.omittedMessageCount).toBe(1); expect(thread?.messages).toHaveLength(200); expect(thread?.messages[0]).toMatchObject({ role: "user", diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 639241db037a4..bbd3ba5a631e0 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -155,6 +155,7 @@ export interface AgentSessionThread { readonly createdAt: string; readonly updatedAt: string; readonly messages: ReadonlyArray; + readonly omittedMessageCount: number; } export type AgentSessionRecentThread = @@ -449,6 +450,7 @@ function parseAgentSessionRecords( finishCodexTurn(); } + let conversationMessageCount = 0; const retainMessage = ( message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean }, ) => { @@ -458,6 +460,7 @@ function parseAgentSessionRecords( if (derivedTitle === undefined && message.role === "user") { derivedTitle = deriveTitle(input.source, message.text); } + conversationMessageCount += 1; messages.push(message); if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift(); }; @@ -529,6 +532,7 @@ function parseAgentSessionRecords( if (message?.codexResponseUser === true && message.text.trim() === text.trim()) { if (firstUserMessage === message) firstUserMessage = undefined; messages.splice(index, 1); + conversationMessageCount -= 1; break; } } @@ -583,6 +587,7 @@ function parseAgentSessionRecords( createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, messages: retainedMessages, + omittedMessageCount: conversationMessageCount - retainedMessages.length, }; } diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 7cd1cc82d6fec..0cef7d96bbdfe 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -156,25 +156,43 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); - it.effect("returns null for non-git folders and repos without remotes", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const nonGitDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-repository-identity-non-git-", - }); - const gitDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-repository-identity-no-remote-", - }); + it.effect( + "returns null for non-git, missing and no-remote folders, probing only what can exist", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nonGitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-non-git-", + }); + const gitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-no-remote-", + }); + + yield* git(gitDir, ["init"]); + + const runner = yield* ProcessRunner.ProcessRunner; + const runs: Array> = []; + const resolver = yield* RepositoryIdentityResolver.make().pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: (input) => + Effect.suspend(() => { + runs.push(input.args); + return runner.run(input); + }), + }), + ); + const bareProbes = () => + runs.filter((args) => args.some((arg) => arg.startsWith("--git-dir="))); - yield* git(gitDir, ["init"]); + expect(yield* resolver.resolve(path.join(nonGitDir, "deleted"))).toBeNull(); + expect(runs).toEqual([]); - const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const nonGitIdentity = yield* resolver.resolve(nonGitDir); - const noRemoteIdentity = yield* resolver.resolve(gitDir); + expect(yield* resolver.resolve(nonGitDir)).toBeNull(); + expect(bareProbes()).toEqual([]); - expect(nonGitIdentity).toBeNull(); - expect(noRemoteIdentity).toBeNull(); - }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + expect(yield* resolver.resolve(gitDir)).toBeNull(); + }).pipe(Effect.provide(ProcessRunner.layer)), ); it.effect("ignores local-path remotes such as GitButler's gb-local", () => diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 659ace3fd2b49..cdf9dc5e1b309 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -6,7 +6,9 @@ import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as ProcessRunner from "../processRunner.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; @@ -138,8 +140,18 @@ class RepositoryIdentityCacheKey extends Data.Class<{ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( function* (cwd: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform); + // `git -C` cannot enter a missing folder or a file, so every probe below would fail. + const isFolder = yield* fileSystem.stat(cwd).pipe( + Effect.map((info) => info.type === "Directory"), + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), + Effect.orElseSucceed(() => true), + ); + if (!isFolder) return null; + // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization. const topLevelResult = yield* processRunner .run({ @@ -160,7 +172,25 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. } // Explicit Git directories preserve safe.bareRepository=explicit for both layouts. - for (const gitDir of [".", ".git"]) { + for (const [gitDir, entry] of [ + [".", "HEAD"], + [".git", ".git"], + ] as const) { + // An explicit --git-dir fails unless the folder has this entry; a symlink counts even + // when its target is missing, as git reads a symlinked HEAD's target text. + const target = path.join(cwd, entry); + const hasEntry = yield* fileSystem.exists(target).pipe( + Effect.flatMap((exists) => + exists + ? Effect.succeed(true) + : fileSystem.readLink(target).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + ), + Effect.orElseSucceed(() => true), + ); + if (!hasEntry) continue; const bareResult = yield* processRunner .run({ command: "git", @@ -224,6 +254,8 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( options: RepositoryIdentityResolverOptions = {}, ) { const processRunner = yield* ProcessRunner.ProcessRunner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY; const refine = options.refine ?? Effect.succeed; const timeToLive = (exit: Exit.Exit) => @@ -237,6 +269,8 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( (cwd) => resolveRepositoryIdentityCacheKey(cwd).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), ), { capacity: cacheCapacity, timeToLive }, ); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index bc7c14d3b3c8a..e6835159f9e7f 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -229,6 +229,7 @@ describe("ACP Registry probe", () => { { id: "medium", label: "Medium" }, { id: "high", label: "High" }, ], + role: "reasoning", }, ]); }); diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 4ecc0ad28971b..8139df621f98c 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -129,9 +129,9 @@ describe("buildGrokModelCapabilities", () => { type: "select", currentValue: "medium", options: [ - { id: "xhigh", label: "Extra High Effort", isDefault: true }, - { id: "high", label: "High Effort" }, { id: "medium", label: "Medium Effort" }, + { id: "high", label: "High Effort" }, + { id: "xhigh", label: "Extra High Effort", isDefault: true }, ], }, ]); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 07830f90d0567..8f73039d971e7 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 5129, - "codexAdditionalContextBytes": 6859, - "mcpToolListJsonBytes": 46109 + "claudeSystemAppendBytes": 5153, + "codexAdditionalContextBytes": 6883, + "mcpToolListJsonBytes": 47020 } diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 9b7d1ffb35d41..6f3e49e4d4c46 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -15,6 +16,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -755,6 +757,41 @@ describe("providerMaintenanceRunner", () => { ), ); + // A native updater such as `claude update` downloads a ~300 MB binary and + // prints nothing while it does. Killed mid-download, it leaves a truncated + // binary behind that later updates mistake for an install. + it.effect.each([ + { runFor: "6 minutes", status: "succeeded", message: "Provider updated." }, + { runFor: "31 minutes", status: "failed", message: "Update timed out after 30 minutes." }, + ] as const)("lets a slow installer run for $runFor", ({ runFor, status, message }) => { + const started = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseNativeCliProvider); + const updater = yield* makeTestRunner(registry); + + const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(started); + yield* TestClock.adjust(runFor); + const result = yield* Fiber.join(update); + + assert.strictEqual(result.providers[0]?.updateState?.status, status); + assert.strictEqual(result.providers[0]?.updateState?.message, message); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ + exitCode: Deferred.succeed(started, undefined).pipe( + Effect.andThen(Effect.sleep(runFor)), + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + })), + ), + ), + ); + }); + it.effect("prevents concurrent updates for the same provider", () => { const startedLatch: { resolve: () => void } = { resolve: () => {} }; const releaseLatch: { resolve: () => void } = { resolve: () => {} }; @@ -856,17 +893,31 @@ describe("providerMaintenanceRunner", () => { ), ); - it.effect("resolves npm to a .cmd shim and routes through the shell on win32", () => { + it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { const captured: Array<{ readonly command: string; readonly args: ReadonlyArray; readonly shell: boolean | string | undefined; + readonly env: NodeJS.ProcessEnv | undefined; }> = []; return Effect.gen(function* () { const { registry } = yield* makeRegistry(baseProvider, { installedVersionAfterUpdate: "1.0.0", }); - const runner = yield* makeTestRunner(registry); + const runner = yield* makeTestRunner({ + ...registry, + getProviderMaintenanceCapabilitiesForInstance: () => + Effect.succeed( + makeProviderMaintenanceCapabilities({ + provider: CODEX_DRIVER, + packageName: "@openai/codex", + updateExecutable: "npm", + updateArgs: ["install", "-g", "@openai/codex@latest"], + updateLockKey: "npm-global", + env: { PATH: "C:\\fake\\npm" }, + }), + ), + }); const result = yield* runner.updateProvider(CODEX_DRIVER); @@ -879,17 +930,21 @@ describe("providerMaintenanceRunner", () => { ); assert.deepEqual(call.args, []); assert.strictEqual(call.shell, true); + assert.deepStrictEqual(call.env, { PATH: "C:\\fake\\npm" }); assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); }).pipe( Effect.provide( Layer.mergeAll( Layer.succeed(HostProcess.Platform, "win32"), + // Only the provider's PATH has npm. Layer.succeed(HostProcess.Environment, { - PATH: "C:\\fake\\npm", + PATH: "C:\\Windows\\System32", PATHEXT: ".COM;.EXE;.BAT;.CMD", }), - Layer.succeed(SpawnExecutableResolution, (command) => - command === "npm" ? "C:\\fake\\npm\\npm.cmd" : undefined, + Layer.succeed(SpawnExecutableResolution, (command, _platform, env) => + command === "npm" && env.PATH === "C:\\fake\\npm" + ? "C:\\fake\\npm\\npm.cmd" + : undefined, ), layerLatestVersionHttpClient("1.0.0"), Layer.succeed( @@ -898,12 +953,16 @@ describe("providerMaintenanceRunner", () => { const childProcess = command as unknown as { readonly command: string; readonly args: ReadonlyArray; - readonly options: { readonly shell?: boolean | string | undefined }; + readonly options: { + readonly shell?: boolean | string | undefined; + readonly env?: NodeJS.ProcessEnv | undefined; + }; }; captured.push({ command: childProcess.command, args: childProcess.args, shell: childProcess.options.shell, + env: childProcess.options.env, }); return Effect.succeed(mockHandle({ stdout: "updated" })); }), diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index c2347da003300..ee7709e710eda 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -41,7 +41,11 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); -const UPDATE_TIMEOUT_MS = 5 * 60_000; +// Native updaters (`claude update`) download a ~300 MB binary without printing +// progress, and killing one mid-download leaves a truncated binary that the +// next run treats as installed. Allow a slow connection to finish. +const UPDATE_TIMEOUT_MINUTES = 30; +const UPDATE_TIMEOUT_MS = UPDATE_TIMEOUT_MINUTES * 60_000; const UPDATE_OUTPUT_MAX_BYTES = 10_000; // Sample installer output because every progress update resends the provider list to all clients. const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1); @@ -98,13 +102,14 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR }) { const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")( function* () { + const env = input.env ? { env: input.env, extendEnv: true } : {}; // Windows batch shims require shell dispatch through resolveSpawnCommand. - const resolved = yield* resolveSpawnCommand(input.command, input.args); + const resolved = yield* resolveSpawnCommand(input.command, input.args, env); const child = yield* input.spawner .spawn( ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell, - ...(input.env ? { env: input.env, extendEnv: true } : {}), + ...env, }), ) .pipe( @@ -259,7 +264,7 @@ function lastOutputLine(result: ProviderMaintenanceCommandResult): string | null function failureMessage(result: ProviderMaintenanceCommandResult): string { if (result.timedOut) { - return "Update timed out."; + return `Update timed out after ${UPDATE_TIMEOUT_MINUTES} minutes.`; } const summary = result.exitCode !== null && result.exitCode !== 0 diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts index a47743b34263a..92704c51102fe 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts @@ -152,6 +152,48 @@ describe("normalizeReviewGuide", () => { expect(result.stops).toHaveLength(1); }); + it("merges excerpts that a later excerpt bridges into one", () => { + const result = normalizeReviewGuide( + guide({ + stops: [ + stop({ + excerpts: [ + excerpt("src/a.ts", 40, 41), + { ...excerpt("src/a.ts", 50, 51), caption: "Second" }, + excerpt("src/a.ts", 41, 50), + ], + }), + ], + }), + change, + ); + expect(result.stops[0]?.excerpts).toEqual([ + { ...excerpt("src/a.ts", 40, 51), caption: "Second" }, + ]); + + const tailNote = { path: "src/a.ts", line: 40, title: "Tail", body: "Keep this note." }; + const wide = normalizeReviewGuide( + guide({ + stops: [ + stop({ + excerpts: [ + excerpt("src/a.ts", 1, 25), + { ...excerpt("src/a.ts", 30, 45), caption: "Second" }, + excerpt("src/a.ts", 24, 32), + ], + notes: [tailNote], + }), + ], + }), + parseReviewGuideChange( + "src/a.ts\0", + "diff --git a/src/a.ts b/src/a.ts\n--- a/src/a.ts\n+++ b/src/a.ts\n@@ -0,0 +1,60 @@\n+added", + ), + ); + expect(wide.stops[0]?.excerpts).toEqual([{ ...excerpt("src/a.ts", 1, 25), caption: "Second" }]); + expect(wide.stops[0]?.notes).toEqual([]); + }); + it("drops notes outside the stop's remaining excerpts", () => { const result = normalizeReviewGuide( guide({ diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts index 184908e4bd7f2..82edfc5fb8159 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts @@ -87,26 +87,29 @@ function clampExcerpt( function mergeExcerpts( excerpts: ReadonlyArray, ): Array { - const merged: Array = []; + let merged: Array = []; for (const excerpt of excerpts) { - const index = merged.findIndex( - (other) => - other.path === excerpt.path && - other.side === excerpt.side && - other.start <= excerpt.end + 1 && - excerpt.start <= other.end + 1, - ); - const other = merged[index]; - if (other === undefined) { + const touches = (other: PullRequestReviewGuideExcerpt) => + other.path === excerpt.path && + other.side === excerpt.side && + other.start <= excerpt.end + 1 && + excerpt.start <= other.end + 1; + // An excerpt can bridge several earlier ones; fold them all into the first. + const group = merged.filter(touches); + const first = group[0]; + if (first === undefined) { merged.push(excerpt); continue; } - merged[index] = { - ...other, - start: Math.min(other.start, excerpt.start), - end: Math.max(other.end, excerpt.end), - caption: other.caption || excerpt.caption, + const combined = { + ...first, + start: Math.min(excerpt.start, ...group.map((other) => other.start)), + end: Math.max(excerpt.end, ...group.map((other) => other.end)), + caption: group.find((other) => other.caption)?.caption ?? excerpt.caption, }; + merged = merged.flatMap((other) => + other === first ? [combined] : touches(other) ? [] : [other], + ); } return merged.map((excerpt) => ({ ...excerpt, diff --git a/apps/server/src/scheduledTasks/webhookFilter.test.ts b/apps/server/src/scheduledTasks/webhookFilter.test.ts index 1194a1aed5177..2c7f2cc4062e8 100644 --- a/apps/server/src/scheduledTasks/webhookFilter.test.ts +++ b/apps/server/src/scheduledTasks/webhookFilter.test.ts @@ -16,6 +16,28 @@ const issueComment: WebhookRequest = { }; describe("findFailedWebhookFilter", () => { + it("matches exists on wildcard object values", () => { + assert.isNull( + findFailedWebhookFilter([{ path: "body.issue.labels[]", op: "exists" }], issueComment), + ); + assert.isNull( + findFailedWebhookFilter([{ path: "body.issues[].labels", op: "exists" }], { + ...issueComment, + bodyText: JSON.stringify({ issues: [{ labels: [] }] }), + }), + ); + }); + + it("rejects exists when wildcard values are all null or missing", () => { + assert.deepEqual( + findFailedWebhookFilter([{ path: "body.issues[].labels", op: "exists" }], { + ...issueComment, + bodyText: JSON.stringify({ issues: [{ labels: null }, {}] }), + }), + { index: 0, path: "body.issues[].labels" }, + ); + }); + it("matches a wildcard path when any element matches", () => { assert.isNull( findFailedWebhookFilter( diff --git a/apps/server/src/scheduledTasks/webhookFilter.ts b/apps/server/src/scheduledTasks/webhookFilter.ts index 882f300364288..2ad0e0237e079 100644 --- a/apps/server/src/scheduledTasks/webhookFilter.ts +++ b/apps/server/src/scheduledTasks/webhookFilter.ts @@ -36,6 +36,8 @@ function matchesScalar(filter: ScheduledTaskWebhookFilter, text: string): boolea */ function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean { if (Array.isArray(value) && /\[\]/.test(filter.path)) { + if (filter.op === "exists") + return value.some((element) => element !== null && element !== undefined); const texts = value.map(scalarText).filter((text): text is string => text !== undefined); if (filter.op === "notEquals") return texts.every((text) => text !== filter.value); return texts.some((text) => matchesScalar(filter, text)); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 8e1a2d2f7ec3e..2b08e4f51e5a5 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -765,6 +765,30 @@ it.layer( }), ); + it.effect("labels a running command by its whole process name, spaces included", () => + Effect.gen(function* () { + const { manager } = yield* createManager(5, { + subprocessPollIntervalMs: 1_000, + processKillGraceMs: 0, + processTable: Effect.succeed([ + { pid: 9000, ppid: 1, name: "zsh" }, + { pid: 200, ppid: 9000, name: "Google Chrome" }, + ]), + }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); + const label = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "activity" + ? Deferred.succeed(label, event.label).pipe(Effect.asVoid) + : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + yield* manager.open(openInput()); + yield* TestClock.adjust("1 second"); + + expect(yield* Deferred.await(label)).toBe("Google Chrome"); + }).pipe(Effect.provide(TestClock.layer())), + ); + // Answers process-table queries after `queryDuration`, honoring the caller's // timeout the way ProcessRunner's `timedOutResult` mode does. const slowProcessTable = ( diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 9d3942c6cb62b..c881dbd7b19a8 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -365,10 +365,9 @@ function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): stri ) { trimmed = trimmed.slice(1, -1).trim(); } - const firstToken = (trimmed.split(/\s+/)[0] ?? trimmed).trim(); - if (firstToken.length === 0) return null; + // Process names and macOS `comm` paths can contain spaces ("Google Chrome"). const separators = platform === "win32" ? /[\\/]/ : /\//; - const base = firstToken.split(separators).at(-1) ?? firstToken; + const base = (trimmed.split(separators).at(-1) ?? trimmed).trim(); const withoutExe = platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base; return withoutExe.length > 0 ? withoutExe : null; diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts index 3fcafcc151789..7e1f1446d1a55 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts @@ -5,6 +5,7 @@ import { ProviderInstanceId, ProviderSetupError, } from "@t3tools/contracts"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -60,6 +61,7 @@ const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function* readonly startError?: AcpError; readonly rejectAdmission?: boolean; readonly sessionId?: string; + readonly startupSkills?: boolean; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -135,6 +137,13 @@ const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function* start: () => Effect.gen(function* () { if (options.startError) return yield* options.startError; + if (options.startupSkills) { + for (const directory of [".agents", ".gemini"]) { + yield* fs + .makeDirectory(path.join(cwd, directory, "skills"), { recursive: true }) + .pipe(Effect.orDie); + } + } yield* fs.makeDirectory(brainDirectory, { recursive: true }).pipe(Effect.orDie); yield* fs.writeFileString(`${sessionBase}.db`, "helper session").pipe(Effect.orDie); yield* fs.writeFileString(`${sessionBase}.db-wal`, "helper journal").pipe(Effect.orDie); @@ -279,11 +288,12 @@ const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function* }); it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { - it.effect( - "generates all helper types in empty workspaces and removes only owned session files", - () => + it.effect.each([false, true])( + "generates all helper types and cleans up with startupSkills=%s", + (startupSkills) => Effect.gen(function* () { const fixture = yield* makeFixture({ + startupSkills, outputs: [ '{"subject":" Repair Google login.\\nExtra line","body":" Keep the remote callback. ","branch":"Repair Login"}', '```json\n{"title":" Repair Google login\\nExtra line","body":" ## Summary\\nSupport remote callbacks. "}\n```', @@ -442,29 +452,51 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("rejects a helper that writes files in its temporary workspace", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const fixture = yield* makeFixture({ - prompt: ({ cwd, emit }) => - Effect.gen(function* () { - yield* fs - .writeFileString(path.join(cwd, "unexpected.txt"), "unexpected") - .pipe(Effect.orDie); - yield* emit({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: '{"title":"Ignored output"}' }, - }); - return { stopReason: "end_turn" }; - }), - }); - const error = yield* fixture.textGeneration - .generateThreadTitle(fixture.titleInput) - .pipe(Effect.flip); - expect(error.detail).toContain("wrote files"); - yield* fixture.assertCleaned; - }).pipe(Effect.scoped), + it.effect.each([ + { relativePath: "unexpected.txt", kind: "file" }, + { relativePath: ".agents/skills/unexpected.txt", kind: "file" }, + { relativePath: ".gemini/unexpected", kind: "directory" }, + { relativePath: ".agents/skills", kind: "file" }, + ...(symlinksSupported ? [{ relativePath: ".gemini/skills", kind: "symlink" }] : []), + ])( + "rejects an unexpected $kind at $relativePath in its temporary workspace", + ({ relativePath, kind }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const target = + kind === "symlink" + ? yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-link-test-" }) + : undefined; + const fixture = yield* makeFixture({ + startupSkills: true, + prompt: ({ cwd, emit }) => + Effect.gen(function* () { + const entry = path.join(cwd, relativePath); + if (yield* fs.exists(entry).pipe(Effect.orDie)) { + yield* fs.remove(entry, { recursive: true }).pipe(Effect.orDie); + } + yield* ( + target !== undefined + ? fs.symlink(target, entry) + : kind === "directory" + ? fs.makeDirectory(entry) + : fs.writeFileString(entry, "unexpected") + ).pipe(Effect.orDie); + yield* emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: '{"title":"Ignored output"}' }, + }); + return { stopReason: "end_turn" }; + }), + }); + const error = yield* fixture.textGeneration + .generateThreadTitle(fixture.titleInput) + .pipe(Effect.flip); + expect(error.detail).toContain("wrote files"); + if (target !== undefined) expect(yield* fs.exists(target)).toBe(true); + yield* fixture.assertCleaned; + }).pipe(Effect.scoped), ); it.effect("uses the native default without sending T3's default selection as a model ID", () => @@ -576,3 +608,15 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); }); + +it.effect("retains filesystem services supplied only during construction", () => + Effect.gen(function* () { + const fixture = yield* makeFixture({ startupSkills: true }).pipe( + Effect.provide(NodeServices.layer), + ); + expect(yield* fixture.textGeneration.generateThreadTitle(fixture.titleInput)).toEqual({ + title: "Repair login", + }); + yield* fixture.assertCleaned; + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.ts index 921a2f118e34a..22fce172b1836 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.ts @@ -94,6 +94,34 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const hasOnlyRuntimeDirectories = Effect.fn( + "AntigravityTextGeneration.hasOnlyRuntimeDirectories", + )(function* (cwd: string) { + const root = yield* fs.realPath(cwd); + // ACP creates these empty skill directories before the first prompt. + const allowed = new Set([ + path.join(root, ".agents"), + path.join(root, ".agents", "skills"), + path.join(root, ".gemini"), + path.join(root, ".gemini", "skills"), + ]); + const directories = [root]; + for (const directory of directories) { + for (const name of yield* fs.readDirectory(directory)) { + const entry = path.join(directory, name); + if ( + !allowed.has(entry) || + (yield* fs.realPath(entry)) !== entry || + (yield* fs.stat(entry)).type !== "Directory" + ) { + return false; + } + directories.push(entry); + } + } + return true; + }); + const available = isAntigravityTextGenerationAvailable(options.profileDirectory).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), @@ -253,7 +281,7 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener ); }).pipe(Effect.scoped); - if ((yield* fs.readDirectory(cwd)).length > 0) { + if (!(yield* hasOnlyRuntimeDirectories(cwd))) { return yield* new TextGenerationError({ operation, detail: "Antigravity wrote files during text generation.", diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 9600f0a45adfb..07a78dc6d50de 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -1462,6 +1462,37 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.effect("ignores a stale macOS Keychain login when Cursor is not installed", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const cursor = makeFakeCursor(); + cursor.state.error = "Sign in to Cursor again to read account usage."; + const readCursorSource = Effect.gen(function* () { + const service = yield* makeWithCursor(cursor.read); + const summary = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + return cursorSource(summary); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cursor-keychain-uninstalled", + home, + settings: { ...settings, cursorKeychainUsageEnabled: true }, + platform: "darwin", + environment: {}, + }), + ), + ); + + assert.isUndefined(yield* readCursorSource); + assert.lengthOf(cursor.state.calls, 0); + + yield* Effect.promise(() => NodeFSP.mkdir(NodePath.join(home, ".cursor"))); + const installed = yield* readCursorSource; + assert.strictEqual(installed?.message, "Sign in to Cursor again to read account usage."); + assert.lengthOf(cursor.state.calls, 1); + }).pipe(Effect.scoped), + ); + it.live("ignores stale Cursor file logins when the active credential store differs", () => Effect.gen(function* () { const { settings, home } = yield* setup; diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts index 0119adfd940f3..4a76d32c15dea 100644 --- a/apps/server/src/usage/cliproxyApi.test.ts +++ b/apps/server/src/usage/cliproxyApi.test.ts @@ -345,6 +345,70 @@ describe("CLIProxyAPI built-in management API", () => { }), ); + it.effect.each([ + { + name: "spend budget", + budget: { + spend: { + enabled: true, + used: { amount_minor: 4_631, currency: "USD", exponent: 2 }, + limit: { amount_minor: 50_000, currency: "USD", exponent: 2 }, + }, + }, + }, + { + name: "extra usage", + budget: { + extra_usage: { + is_enabled: true, + used_credits: 4_631, + monthly_limit: 50_000, + utilization: 9, + }, + }, + }, + ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) => + Effect.gen(function* () { + const test = fixture({ + accounts: [{ ...accounts[0]!, provider: "claude" }], + upstream: () => ({ + status: 200, + body: { five_hour: { utilization: 10, resets_at: null }, ...budget }, + }), + }); + const result = yield* (yield* test.api).readAccounts(config); + expect( + result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]), + ).toEqual([ + ["five_hour", 10], + ["monthly_spend", expect.closeTo(9.262, 10)], + ]); + }), + ); + + it.effect("omits disabled Claude budgets without losing rolling windows", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [{ ...accounts[0]!, provider: "claude" }], + upstream: () => ({ + status: 200, + body: { + five_hour: { utilization: 10, resets_at: null }, + spend: { enabled: false, used: null, limit: null }, + extra_usage: { + is_enabled: false, + used_credits: null, + monthly_limit: null, + utilization: null, + }, + }, + }), + }); + const result = yield* (yield* test.api).readAccounts(config); + expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]); + }), + ); + it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () => Effect.gen(function* () { const test = fixture(); diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index 91504d8002295..eb956a67a31d0 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -55,6 +55,17 @@ const ClaudeWindow = Schema.Struct({ const ClaudeUsage = Schema.Struct({ five_hour: Schema.optional(Schema.NullOr(ClaudeWindow)), seven_day: Schema.optional(Schema.NullOr(ClaudeWindow)), + spend: Schema.optional(Schema.Unknown), + extra_usage: Schema.optional( + Schema.NullOr( + Schema.Struct({ + is_enabled: Schema.Boolean, + monthly_limit: Schema.NullOr(Schema.Number), + used_credits: Schema.NullOr(Schema.Number), + utilization: Schema.NullOr(Schema.Number), + }), + ), + ), limits: Schema.optional( Schema.Array( Schema.Struct({ @@ -279,6 +290,13 @@ export const makeCliproxyApi = Effect.gen(function* () { ] : [], ); + const rateLimits = { + five_hour: usage.five_hour ?? null, + seven_day: usage.seven_day ?? null, + model_scoped, + spend: usage.spend, + extra_usage: usage.extra_usage ?? null, + }; return { ...base, plan: "Claude Subscription", @@ -286,11 +304,7 @@ export const makeCliproxyApi = Effect.gen(function* () { checkedAt, response: { rate_limits_available: true, - rate_limits: { - five_hour: usage.five_hour ?? null, - seven_day: usage.seven_day ?? null, - model_scoped, - }, + rate_limits: rateLimits, }, }).limits, }; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8363e16c32476..d9a48457f8a38 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2577,6 +2577,39 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reads range patches from source without running textconv", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["config", "diff.probe.textconv", "touch textconv-ran; echo converted"]); + yield* git(cwd, ["checkout", "-b", "feature/range"]); + yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); + yield* writeTextFile(cwd, "notes.doc", "source line\n"); + yield* writeTextFile(cwd, "plain.txt", "plain line\n"); + yield* writeTextFile(cwd, "binary.dat", "binary\0data"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "range files"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + + const context = yield* driver.readRangeContext(cwd, initialBranch); + + assert.include(context.diffPatch, "+source line"); + assert.notInclude(context.diffPatch, "converted"); + assert.include(context.diffPatch, "+plain line"); + assert.include(context.diffPatch, "Binary files /dev/null and b/binary.dat differ"); + assert.include(context.diffSummary, "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + + yield* writeTextFile(cwd, "notes.doc", "updated source line\n"); + const staged = yield* driver.prepareCommitContext(cwd, ["notes.doc"]); + assert.include(staged?.stagedPatch ?? "", "+updated source line"); + assert.notInclude(staged?.stagedPatch ?? "", "converted"); + assert.include(staged?.stagedSummary ?? "", "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + }), + ); + it.effect("loads new and deleted files without reading their missing side", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3662,6 +3695,47 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("flattens a generated name when a branch at its parent path blocks it", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + // A local `t3` branch is why launches start on the flat `t3-` temporary branch. + yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); + yield* git(cwd, ["branch", "t3-fix-login"]); + + const renamed = yield* driver.renameBranch({ + cwd, + oldBranch: "t3-abcd1234", + newBranch: "t3/fix-login", + }); + + assert.equal(renamed.branch, "t3-fix-login-1"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + }), + ); + + it.effect("skips a flattened name that a nested branch blocks", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); + yield* git(cwd, ["branch", "t3-fix-login/child"]); + + const renamed = yield* driver.renameBranch({ + cwd, + oldBranch: "t3-abcd1234", + newBranch: "t3/fix-login", + }); + + assert.equal(renamed.branch, "t3-fix-login-1"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4777,6 +4851,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("commit context", () => { + it.effect("prepares source patches without running textconv", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["config", "diff.probe.textconv", "touch textconv-ran; echo converted"]); + yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); + yield* writeTextFile(cwd, "notes.doc", "original source\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "source document"]); + yield* writeTextFile(cwd, "notes.doc", "updated source\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + + const context = yield* driver.prepareCommitContext(cwd, ["notes.doc"]); + + assert.include(context?.stagedPatch ?? "", "-original source"); + assert.include(context?.stagedPatch ?? "", "+updated source"); + assert.notInclude(context?.stagedPatch ?? "", "converted"); + assert.include(context?.stagedSummary ?? "", "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + }), + ); + it.effect("can omit the patch while preserving change detection and the real index", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 71945b0b6f71c..11580f4c26e18 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1247,16 +1247,37 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( cwd: string, - desiredBranch: string, + requestedBranch: string, ) { - const isDesiredTaken = yield* branchExists(cwd, desiredBranch); + // A branch at a parent path (such as `t3`) blocks every ref nested under it, so no suffix + // would help; flatten to a sibling the way temporary worktree branches already do. + const segments = requestedBranch.split("/"); + let blockedByParent = false; + for (let index = 1; index < segments.length && !blockedByParent; index += 1) { + blockedByParent = yield* branchExists(cwd, segments.slice(0, index).join("/")); + } + const desiredBranch = blockedByParent ? segments.join("-") : requestedBranch; + // A branch nested under the name (`t3-fix/child`) blocks it as surely as one with the name. + const isBranchNameTaken = (name: string) => + Effect.zipWith( + branchExists(cwd, name), + runGitStdout( + "GitVcsDriver.branchExists", + cwd, + ["for-each-ref", "--count=1", "--format=%(refname)", `refs/heads/${name}/`], + true, + ), + (exists, nested) => exists || nested.trim().length > 0, + ); + + const isDesiredTaken = yield* isBranchNameTaken(desiredBranch); if (!isDesiredTaken) { return desiredBranch; } for (let suffix = 1; suffix <= 100; suffix += 1) { const candidate = `${desiredBranch}-${suffix}`; - const isCandidateTaken = yield* branchExists(cwd, candidate); + const isCandidateTaken = yield* isBranchNameTaken(candidate); if (!isCandidateTaken) { return candidate; } @@ -2502,7 +2523,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stagedPatch = yield* runGitStdoutWithOptions( "GitVcsDriver.prepareCommitContext.stagedPatch", cwd, - ["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"], + ["diff", "--no-ext-diff", "--no-textconv", "--cached", "--patch", "--minimal"], { env, maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, @@ -2913,7 +2934,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* runGitStdoutWithOptions( "GitVcsDriver.readRangeContext.diffPatch", cwd, - ["diff", "--no-ext-diff", "--patch", "--minimal", "--end-of-options", diffRange], + [ + "diff", + "--no-ext-diff", + "--no-textconv", + "--patch", + "--minimal", + "--end-of-options", + diffRange, + ], { maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, appendTruncationMarker: true, diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 6bef5f04263c6..d861935fe17cc 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFSP from "node:fs/promises"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { FileFinder } from "@ff-labs/fff-node"; import { it, afterEach, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -673,6 +674,53 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(match.lineContent.slice(range.start, range.end)).toBe("wörld"); }), ); + + it.effect("keeps answering from the live index when a refresh outlasts the scan wait", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-refresh-" }); + yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n"); + let scansOutlastWait = false; + let finders = 0; + let rescans = 0; + const createFinder = FileFinder.create.bind(FileFinder); + vi.spyOn(FileFinder, "create").mockImplementation((options) => { + const created = createFinder(options); + if (created.ok) { + const finder = created.value; + finders += 1; + const scanFiles = finder.scanFiles.bind(finder); + finder.scanFiles = () => { + rescans += 1; + return scanFiles(); + }; + const waitForIndexReady = finder.waitForIndexReady.bind(finder); + finder.waitForIndexReady = (timeoutMs) => + scansOutlastWait + ? Promise.resolve({ ok: true, value: false }) + : waitForIndexReady(timeoutMs); + } + return created; + }); + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searchNeedle = workspaceEntries.searchContents({ + cwd, + query: "needle", + limit: 100, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }); + yield* searchNeedle; + + scansOutlastWait = true; + yield* workspaceEntries.refresh(cwd); + const result = yield* searchNeedle; + + expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]); + // The second search ran on the rescanned live finder, not a rebuild. + expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 }); + }), + ); }); describe("browse", () => { diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 8f2b64cf26a34..d5539e2f4e718 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -117,10 +117,7 @@ export class WorkspaceSearchIndex extends Context.Service< readonly searchContents: ( input: Omit, ) => Effect.Effect; - readonly refresh: () => Effect.Effect< - void, - WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut - >; + readonly refresh: () => Effect.Effect; } >()("t3/workspace/WorkspaceSearchIndex") {} @@ -419,6 +416,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( reason: result.error, }); } + // A rescan that outlasts the wait keeps running, and the finder answers + // from its previous index until it finishes, so the index stays usable. yield* waitForIndexReady( cwd, finder, @@ -428,7 +427,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( reason, cause, }), - ); + ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); }); const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 641845f322ea6..ba647514ecef4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -123,6 +123,7 @@ import * as ProjectEnrichment from "./project/ProjectEnrichmentService.ts"; import * as ProjectService from "./project/ProjectService.ts"; import { layerWsRpc, + resolveOpenDiscoveryForConfig, subscribeOrchestrationV2Shell, subscribeOrchestrationV2Thread, WS_RPC_SERVER_OPTIONS, @@ -188,6 +189,38 @@ it.effect("resends a file manager reveal kind that missed the snapshot", () => }), ); +it.effect("runs editor, remote open target and direct endpoint discovery side by side", () => + Effect.gen(function* () { + // Each discovery finishes only once the other two have started, so a + // config that ran them one after another would never resolve. + const editorsStarted = yield* Deferred.make(); + const targetsStarted = yield* Deferred.make(); + const endpointsStarted = yield* Deferred.make(); + const startThenAwait = (started: Deferred.Deferred, value: A) => + Deferred.succeed(started, undefined).pipe( + Effect.andThen( + Effect.forEach([editorsStarted, targetsStarted, endpointsStarted], Deferred.await), + ), + Effect.as(value), + ); + + const discovery = yield* resolveOpenDiscoveryForConfig({ + editors: startThenAwait(editorsStarted, ["file-manager" as const]), + fileManagerRevealKind: Effect.succeed("finder" as const), + remoteOpenTargets: startThenAwait(targetsStarted, []), + directEndpoints: startThenAwait(endpointsStarted, []), + }); + + assert.deepEqual(discovery, { + availableEditors: ["file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "finder", + remoteOpenTargets: [], + directEndpoints: [], + }); + }), +); + const ReplayTestLayer = OrchestrationEventStore.layer.pipe( Layer.provideMerge(SqlitePersistence.layerMemory), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 4781fcf78dde6..8373bbfae0c55 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -324,7 +324,8 @@ export const withLateEditorConfig = ( editors.join() !== config.availableEditors.join() || (editors.includes("file-manager") && config.shellRevealInFileManagerKind === undefined), ), - // Leave the unshared reveal probe unbounded so timeouts cannot cancel every attempt on slow hosts. + // Unbounded, unlike the snapshot: this exists to deliver a probe that + // outlasts the snapshot's timeout. Stream.mapEffect((editors) => resolveEditorConfig(editors, launcher.resolveFileManagerRevealKind()), ), @@ -366,6 +367,31 @@ export const withLateEditorConfig = ( ); }; +// Discoveries run side by side so the slowest one, not their sum, bounds the +// server config snapshot. Each degrades on timeout rather than failing it. +export const resolveOpenDiscoveryForConfig = (discovery: { + readonly editors: Effect.Effect, E1, R1>; + readonly fileManagerRevealKind: Effect.Effect; + readonly remoteOpenTargets: Effect.Effect, E3, R3>; + readonly directEndpoints: Effect.Effect, E4, R4>; +}) => + Effect.all( + { + editorConfig: resolveAvailableEditorsForConfig(discovery.editors).pipe( + Effect.flatMap((availableEditors) => + resolveEditorConfig( + availableEditors, + resolveFileManagerRevealKindForConfig(discovery.fileManagerRevealKind), + ), + ), + ), + // Same discovery-with-timeout treatment as editors: a slow probe must + // not stall server.getConfig, so it degrades to an empty list. + remoteOpenTargets: resolveAvailableEditorsForConfig(discovery.remoteOpenTargets), + directEndpoints: resolveAvailableEditorsForConfig(discovery.directEndpoints), + }, + { concurrency: "unbounded" }, + ).pipe(Effect.map(({ editorConfig, ...endpoints }) => ({ ...editorConfig, ...endpoints }))); function withoutWorkspaceSnapshots(providers: ReadonlyArray): ServerProvider[] { return providers.map(({ workspaceSnapshots: _workspaceSnapshots, ...provider }) => provider); } @@ -1744,10 +1770,12 @@ export const layerWsRpc = ( const auth = yield* serverAuth.getDescriptor(); const scratchWorkspaceRoot = yield* managedFolders.scratchRoot; const lastEventLoopStall = yield* eventLoopMonitor.latestNoticeableStall; - const editorConfig = yield* resolveEditorConfig( - yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()), - resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()), - ); + const discovery = yield* resolveOpenDiscoveryForConfig({ + editors: externalLauncher.resolveAvailableEditors(), + fileManagerRevealKind: externalLauncher.resolveFileManagerRevealKind(), + remoteOpenTargets: remoteOpenTargets.resolveTargets(), + directEndpoints: directEndpoints.resolve(), + }); return { environment, @@ -1757,11 +1785,7 @@ export const layerWsRpc = ( keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, providers, - ...editorConfig, - remoteOpenTargets: yield* resolveAvailableEditorsForConfig( - remoteOpenTargets.resolveTargets(), - ), - directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()), + ...discovery, observability: { logsDirectoryPath: config.logsDir, localTracingEnabled: true, diff --git a/apps/web/package.json b/apps/web/package.json index 4407645ea143f..3cb58dec9cd6c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -41,12 +41,14 @@ "@tanstack/react-router": "^1.160.2", "@tiptap/core": "^3.31.3", "@tiptap/extension-blockquote": "^3.31.3", + "@tiptap/extension-bold": "^3.31.3", "@tiptap/extension-code": "^3.31.3", "@tiptap/extension-code-block": "^3.31.3", "@tiptap/extension-heading": "^3.31.3", "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", "@tiptap/pm": "^3.31.3", diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 95848c209d8c5..8f6ffdf0a119e 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -726,11 +726,7 @@ export function BranchToolbarBranchSelector({ )} /> - + diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx index 41bd2b008be89..ca511de43642c 100644 --- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -73,7 +73,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe if (envLocked || forceNewWorktree) { const lockedRow = ( {activeWorktreePath ? ( diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx index 4dfe1ae50f024..66232885fb280 100644 --- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -68,7 +68,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir if (envLocked || (onEnvironmentChange === undefined && onAddToMachine === undefined)) { const lockedRow = ( expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })} + onExpand={(src) => + expandMedia({ + images: [{ src, name: "Mermaid diagram", mimeType: "image/svg+xml" }], + index: 0, + }) + } > {highlightedCode} diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 14125c684045d..e7781653f8e99 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -193,6 +193,40 @@ describe("hasServerAcknowledgedLocalDispatch", () => { ).toBe(false); }); + it.each([ + ["queued", "message-queued", true], + ["queued", "message-before-send", false], + ["preparing", "message-queued", false], + ["starting", "message-queued", false], + ] as const)("acknowledges %s with latest message %s: %s", (status, messageId, acknowledged) => { + const localDispatch = createLocalDispatchSnapshot( + makeThread({ latestRun: completedTurn, runtime: readySession }), + { latestUserMessageId: MessageId.make("message-before-send") }, + ); + // The shell hides the silent compaction run, so its runtime reports the queued message's run. + const queuedRun = { + ...completedTurn, + runId: RunId.make("turn-queued"), + status: "queued" as const, + requestedAt: "2026-03-29T00:01:00.000Z", + startedAt: null, + completedAt: null, + }; + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "running", + latestRun: queuedRun, + latestUserMessageId: MessageId.make(messageId), + runtime: { ...readySession, status }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(acknowledged); + }); + it("waits for the matching running turn before acknowledging", () => { const localDispatch = createLocalDispatchSnapshot( makeThread({ latestRun: completedTurn, runtime: readySession }), diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 49fe3a441fbb8..c289976d3b039 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1101,14 +1101,15 @@ export function hasServerAcknowledgedLocalDispatch(input: { if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) { return true; } + const latestUserMessageChanged = + input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") { - return false; + // A message queued behind other work, such as an idle compaction the shell hides, has landed. + return input.runtime?.status === "queued" && latestUserMessageChanged; } const latestRun = input.latestRun ?? null; const runtime = input.runtime ?? null; - const latestUserMessageChanged = - input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); const latestRunChanged = input.localDispatch.latestRunId !== (latestRun?.runId ?? null) || input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) || diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d2a176a444369..ea477b9144791 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -42,10 +42,6 @@ import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent"; import { usePendingThreadRequests } from "./chat/usePendingThreadRequests"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; -import { - latestExecutedRun, - latestRootProviderFailure, -} from "@t3tools/shared/orchestrationV2ThreadError"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; @@ -77,6 +73,7 @@ import { import { deriveProviderSubagentStatus, deriveReportedModelSelection, + deriveResumableRunId, formatModelSelectionEffort, deriveRunlessWorkStartedAt, deriveThreadActivityRun, @@ -815,16 +812,10 @@ export default function ChatView(props: ChatViewProps) { isServerThread && serverProjection?.runs.some((run) => run.status === "queued" && run.queueHeld === true) === true; - const resumableRunId = (() => { - if (!isServerThread || serverProjection === null) return null; - const run = latestExecutedRun(serverProjection.runs); - if (run?.status === "interrupted") return run.id; - return run?.status === "failed" && - serverRuntime?.lastErrorClass === "usage_limit" && - latestRootProviderFailure(run, serverProjection.turnItems)?.class === "usage_limit" - ? run.id - : null; - })(); + const resumableRunId = + !isServerThread || serverProjection === null + ? null + : deriveResumableRunId(serverProjection, serverRuntime); const parentSubagentThreadId = activeThread?.lineage.relationshipToParent === "subagent" ? activeThread.lineage.parentThreadId @@ -3186,6 +3177,11 @@ export default function ChatView(props: ChatViewProps) { (folders: Parameters[0]) => composerRef.current?.addDroppedFolders(folders), ); + // Above the early return, where React Compiler can cache it for the side chat pane. + const sideChatParentPanel = { + openToolDiff: onOpenToolDiffStable, + runShellCommand: runSideChatShellCommandStable, + }; if (!activeThread) { return embedded ? null : ; @@ -3205,10 +3201,7 @@ export default function ChatView(props: ChatViewProps) { getShortcutContext={getShortcutContextStable} onSendAnnotation={sendPreviewAnnotationStable} onCloseSurface={closeRightPanelSurface} - sideChatParentPanel={{ - openToolDiff: onOpenToolDiffStable, - runShellCommand: runSideChatShellCommandStable, - }} + sideChatParentPanel={sideChatParentPanel} terminal={{ launchContext: activeTerminalLaunchContext ?? null, keybindings, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index bd85fc76ff948..0d8b769f25746 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -32,6 +32,7 @@ import { createBrowseNavigationCoordinator, filterFilesystemBrowseEntries, getFilesystemBrowsePath, + getFilesystemBrowseTabCompletion, } from "@t3tools/client-runtime/state/filesystem"; import { isAtomCommandInterrupted, @@ -2508,6 +2509,30 @@ function OpenCommandPaletteDialog(props: { } if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; + + if (event.key === "Tab" && isBrowsing && !relativePathNeedsActiveProject) { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); + event.preventDefault(); + if (highlightedItemValue === "browse:up") { + void browseUp(); + return; + } + const highlightedEntry = visibleBrowseEntries.find( + (entry) => `browse:${entry.fullPath}` === highlightedItemValue, + ); + const completion = highlightedEntry + ? { name: highlightedEntry.name, isComplete: true } + : getFilesystemBrowseTabCompletion(visibleBrowseEntries, browsePath.filterQuery); + if (completion?.isComplete) { + void browseTo(completion.name); + } else if (completion && !pinnedCloneDirectoryName) { + setHighlightedItemValue(null); + setQuery(`${getBrowseDirectoryPath(query)}${completion.name}`); + } + return; + } + const firstItemValue = autoHighlightsFirstRow ? resultRows.itemValues[0] : undefined; if ( event.key === "ArrowDown" && diff --git a/apps/web/src/components/ComposerContextLabel.tsx b/apps/web/src/components/ComposerContextLabel.tsx index 30567ac355f8a..89b54d5419821 100644 --- a/apps/web/src/components/ComposerContextLabel.tsx +++ b/apps/web/src/components/ComposerContextLabel.tsx @@ -24,7 +24,7 @@ export function ComposerContextLabel({ data-composer-label-motion className={cn( "block w-full min-w-0 truncate", - displayMode === "panel" && THREAD_DETAILS_PANEL_LABEL_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, displayMode === "toolbar" && "max-w-[240px] transition-opacity duration-180 ease-drawer group-data-[compact]/composer-context:opacity-0 motion-reduce:transition-none", )} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index abc9549ee3d00..fe78eaacbe850 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -73,7 +73,9 @@ import { ComposerBoldSelectionOnlyExtension, convertBulletItemToTask, ComposerCodeExtension, + ComposerBoldExtension, ComposerItalicExtension, + ComposerStrikeExtension, ComposerTaskItemExtension, ComposerTaskListExtension, flatToMarkdown, @@ -831,7 +833,8 @@ function createComposerExtensions(richText: boolean) { listKeymap: false, undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY }, italic: false, - ...(richText ? {} : { bold: false, strike: false }), + bold: false, + strike: false, }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, @@ -844,6 +847,8 @@ function createComposerExtensions(richText: boolean) { ? [ ComposerBoldSelectionOnlyExtension, ComposerItalicExtension, + ComposerBoldExtension, + ComposerStrikeExtension, ComposerCodeExtension, ComposerCodeBlockExtension.extend({ addNodeView() { diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index 43c466184bf2c..91d4a54fd9e64 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -124,7 +124,7 @@ function CustomSnoozeDialog() {
{mode === "date" ? (
-
+
= Atom.Atom>; + +const state = vi.hoisted(() => ({ + thread: null as ReturnType | null, + threadRef: null as ScopedThreadRef | null, + previews: new Map>(), + config: null as unknown as Atom.Atom, + status: null as unknown as ResultAtom, + localRefs: null as unknown as ResultAtom, + remoteRefs: null as unknown as ResultAtom, + commits: null as unknown as ResultAtom, +})); + +vi.mock("~/state/server", () => ({ + serverEnvironment: { configValueAtom: () => state.config }, +})); +vi.mock("~/state/review", () => ({ + reviewEnvironment: { + diffPreview: ({ input }: { input: { baseRef?: string } }) => + state.previews.get(input.baseRef ?? null)!, + branchCommits: () => state.commits, + diffFileContents: {}, + }, +})); +vi.mock("~/state/vcs", () => ({ + vcsEnvironment: { + status: () => state.status, + listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) => + input.refKind === "local" ? state.localRefs : state.remoteRefs, + }, +})); +vi.mock("~/state/entities", () => ({ + useQuietThreadShell: () => state.thread, + useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }), + useThreadCheckpointSummaries: () => [], + useQuietThreadVisibleTurnItems: () => [], +})); +vi.mock("~/state/filesystem", () => ({ + useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), +})); +vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef })); +vi.mock("~/hooks/useSettings", () => ({ + useClientSettings: (select: (settings: ClientSettings) => unknown) => + select(DEFAULT_CLIENT_SETTINGS), + updateClientSettings: async () => {}, +})); +vi.mock("~/hooks/useTheme", () => ({ useRenderedAppearance: () => "dark" })); +vi.mock("~/state/queries", () => ({ + useCheckpointDiff: () => ({ data: null, error: null, isPending: false }), + useTurnItemDetail: () => ({ data: null, error: null, isPending: false }), +})); +vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} })); +vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} })); +vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} })); +vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} })); +// The test drives comparison controls, without mounting virtualized diff viewers or their workers. +vi.mock("./diffs/AnnotatableCodeView", () => ({ AnnotatableCodeView: () => null })); +vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null })); +vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null })); + +import DiffPanel from "./DiffPanel"; +import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore"; + +const cwd = "/project-worktree"; +const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD."; + +function preview(): ReviewDiffPreviewResult { + return { + cwd, + generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"), + sources: [ + { + id: "branch", + kind: "branch-range", + title: "Changes", + baseRef: "main", + headRef: "dev", + diff: "", + diffHash: "empty", + truncated: false, + }, + ], + }; +} + +function setup(failedBaseRef: string | null) { + const reset = () => { + useDiffPanelStore.setState({ + byThreadKey: {}, + branchBaseRefByThreadKey: {}, + keepSelectionOnOpenThreadKey: null, + }); + useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); + }; + reset(); + state.threadRef = { + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + }; + state.thread = makeThreadFixture({ + ...state.threadRef, + id: state.threadRef.threadId, + projectId: ProjectId.make("project"), + branch: "dev", + worktreePath: cwd, + }); + state.previews.clear(); + state.previews.set(null, Atom.make(AsyncResult.success(preview()))); + state.previews.set("main", Atom.make(AsyncResult.success(preview()))); + state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage)))); + state.config = Atom.make(null); + state.status = Atom.make( + AsyncResult.success({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "dev", + hasWorkingTreeChanges: false, + workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); + const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({ + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: names.length, + refs: names.map((name) => ({ + name, + isRemote, + ...(isRemote ? { remoteName: "origin" } : {}), + current: name === "dev", + isDefault: name === "main", + worktreePath: null, + })), + }); + state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false))); + state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true))); + state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false })); + useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef); + const registry = AtomRegistry.make(); + return { + registry, + threadRef: state.threadRef, + [Symbol.dispose]() { + registry.dispose(); + reset(); + }, + }; +} + +it.each([ + { + name: "a saved unrelated branch", + failedBaseRef: "origin/orphan", + recovery: "Automatic", + baseRef: null, + }, + { + name: "an automatic base with unrelated history", + failedBaseRef: null, + recovery: "main", + baseRef: "main", + }, +])( + "recovers from $name without leaving the diff panel", + async ({ failedBaseRef, recovery, baseRef }) => { + using context = setup(failedBaseRef); + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible(); + const selector = screen.getByRole("combobox", { name: /Change comparison target/ }); + await vi.waitFor(() => expect(selector.query()).not.toBeNull()); + await userEvent.click(selector); + await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible(); + await userEvent.click(page.getByRole("option", { name: recovery, exact: true })); + await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible(); + await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument(); + const key = scopedThreadKey(context.threadRef); + await vi.waitFor(() => { + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef }); + expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef); + }); + }, +); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index ef95c24d578a2..0f1d1e9e28379 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -67,6 +67,7 @@ import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./Dif import { DiffStatLabel } from "./chat/DiffStatLabel"; import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView"; import { DiffFileTree } from "./diffs/DiffFileTree"; +import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; import { Button } from "./ui/button"; import { MorphIcon } from "~/components/MorphIcon"; @@ -403,6 +404,8 @@ export default function DiffPanel({ ? "commit" : "branch-range"), ); + const comparisonHeadRef = selectedGitSource?.headRef ?? gitStatusQuery.data?.refName ?? "HEAD"; + const comparisonBaseRef = selectedGitSource?.baseRef ?? selectedBaseRef ?? "Automatic"; const selectedCommitSubject = selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha ? selectedGitSource.commitSubject @@ -518,12 +521,14 @@ export default function DiffPanel({ } return currentLoadDiffFiles(fileDiff); }); + const canSelectBranchBase = canReadFiles && canRefreshGitDiff && selectedGitScope === "branch"; + const branchRefsCwd = branchDiffPreview.data?.cwd ?? activeCwd; const localBranchRefs = useEnvironmentQuery( - isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd + canSelectBranchBase && activeThread && branchRefsCwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { - cwd: branchDiffPreview.data.cwd, + cwd: branchRefsCwd, includeMatchingRemoteRefs: true, refKind: "local", ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}), @@ -533,11 +538,11 @@ export default function DiffPanel({ : null, ); const remoteBranchRefs = useEnvironmentQuery( - isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd + canSelectBranchBase && activeThread && branchRefsCwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { - cwd: branchDiffPreview.data.cwd, + cwd: branchRefsCwd, includeMatchingRemoteRefs: true, refKind: "remote", ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}), @@ -547,7 +552,7 @@ export default function DiffPanel({ : null, ); const baseRefChoices = buildBaseRefChoices( - localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [], + localBranchRefs.data?.refs.filter((ref) => ref.name !== comparisonHeadRef) ?? [], remoteBranchRefs.data?.refs ?? [], ); const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery); @@ -949,10 +954,10 @@ export default function DiffPanel({ - {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( + {canSelectBranchBase && (
} > - - {selectedGitSource.headRef ?? "HEAD"} - + {comparisonHeadRef} - {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`} + {`${comparisonHeadRef} → ${comparisonBaseRef}`} @@ -978,7 +981,7 @@ export default function DiffPanel({ vs - {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`} + {`${comparisonHeadRef} → ${comparisonBaseRef}`} } className="min-w-9 max-w-48 shrink-0" - aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`} + aria-label={`Change comparison target. Currently ${comparisonBaseRef}`} > - {selectedGitSource.baseRef} + {comparisonBaseRef}
{fileTreeOpen ? ( - + ) : null}
) : ( diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx new file mode 100644 index 0000000000000..b2e6fcaaaf402 --- /dev/null +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; + +const navigateHistory = vi.hoisted(() => vi.fn()); +vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory })); + +function swipe(target: Element, deltaX: number) { + for (const delta of [deltaX, 0]) { + target.dispatchEvent(new WheelEvent("wheel", { deltaX: delta, bubbles: true, composed: true })); + } +} + +describe("HistorySwipeNavigation", () => { + it.each([ + ["scrolling left inside a shadow-root scroller keeps the thread", "shadow", 100, -130, false], + ["scrolling right inside a shadow-root scroller keeps the thread", "shadow", 100, 130, false], + [ + "scrolling after a shadow scroller remount keeps the thread", + "shadow-remount", + 100, + 130, + false, + ], + ["scrolling left inside a scroller keeps the thread", "light", 100, -130, false], + ["swiping back at a shadow-root scroller's left edge navigates", "shadow", 0, -130, true], + ["swiping back over a panel without overflow navigates", "none", 0, -130, true], + ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], + ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { + navigateHistory.mockReset(); + await using screen = await render(); + const panel = screen.container.appendChild(document.createElement("div")); + const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; + const viewport = root.appendChild(document.createElement("div")); + const noOverflow = scroller === "none" || scroller === "closed-dialog"; + viewport.style.cssText = `width: 200px; overflow-x: ${noOverflow ? "visible" : "auto"}`; + const content = viewport.appendChild(document.createElement("div")); + content.style.cssText = `height: 20px; width: ${noOverflow ? 100 : 1000}px`; + viewport.scrollLeft = scrollLeft; + + if (scroller === "closed-dialog") { + panel.setAttribute("role", "dialog"); + content.dispatchEvent(new WheelEvent("wheel", { deltaX: -1, bubbles: true, composed: true })); + panel.remove(); + screen.container.appendChild(viewport); + } + + if (scroller === "shadow-remount") { + content.dispatchEvent(new WheelEvent("wheel", { deltaX: 1, bubbles: true, composed: true })); + const replacement = viewport.cloneNode(true) as HTMLDivElement; + viewport.replaceWith(replacement); + replacement.scrollLeft = scrollLeft; + swipe(replacement, deltaX); + } else { + swipe(content, deltaX); + } + + expect(navigateHistory).toHaveBeenCalledTimes(navigates ? 1 : 0); + }); +}); diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index c020878b25363..767b4285c696f 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -11,7 +11,7 @@ const MOMENTUM_SAMPLE_SIZE = 5; type SwipeBounds = { left: number; top: number; width: number; height: number }; type SwipeGesture = - | { kind: "pending"; target: EventTarget | null; y: number; sumX: number; sumY: number } + | { kind: "pending"; path: EventTarget[]; y: number; sumX: number; sumY: number } | { kind: "tracking"; direction: HistoryDirection; @@ -37,13 +37,10 @@ function readMainContentBounds(): SwipeBounds { return { left, top, width, height }; } -function canScrollHorizontally(target: EventTarget | null, deltaX: number): boolean { - for ( - let element = target instanceof Element ? target : null; - element; - element = element.parentElement - ) { - if (element.scrollWidth <= element.clientWidth) continue; +// `event.target` stops at a shadow host; the composed path also reaches scrollers inside it. +function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean { + for (const element of path) { + if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue; const { overflowX } = getComputedStyle(element); if (overflowX !== "auto" && overflowX !== "scroll") continue; const canScroll = @@ -58,10 +55,12 @@ function canScrollHorizontally(target: EventTarget | null, deltaX: number): bool function lockSwipeAxis( pending: Extract, ): Exclude { - const { target, sumX, sumY } = pending; + const { path, sumX, sumY } = pending; if (Math.abs(sumX) <= Math.abs(sumY)) return { kind: "ignored" }; - if (target instanceof Element && target.closest('[role="dialog"]')) return { kind: "ignored" }; - if (canScrollHorizontally(target, sumX)) return { kind: "ignored" }; + if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { + return { kind: "ignored" }; + } + if (canScrollHorizontally(path, sumX)) return { kind: "ignored" }; const direction = sumX < 0 ? "back" : "forward"; if (!canNavigateHistory(direction)) return { kind: "ignored" }; return { @@ -119,14 +118,14 @@ export function HistorySwipeNavigation() { gesture = event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL ? { kind: "ignored" } - : { kind: "pending", target: event.target, y: event.clientY, sumX: 0, sumY: 0 }; + : { kind: "pending", path: event.composedPath(), y: event.clientY, sumX: 0, sumY: 0 }; } if (gesture.kind === "ignored") return; if (gesture.kind === "pending") { gesture.sumX += event.deltaX; gesture.sumY += event.deltaY; if (Math.abs(gesture.sumX) + Math.abs(gesture.sumY) < SWIPE_AXIS_LOCK_DISTANCE) return; - gesture = lockSwipeAxis(gesture); + gesture = lockSwipeAxis({ ...gesture, path: [...gesture.path, ...event.composedPath()] }); if (gesture.kind === "ignored") return; } else { const delta = gesture.direction === "back" ? -event.deltaX : event.deltaX; diff --git a/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx b/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx new file mode 100644 index 0000000000000..d6ca540686f0e --- /dev/null +++ b/apps/web/src/components/ProviderUpdatesAction.browser.test.tsx @@ -0,0 +1,153 @@ +import { RegistryContext } from "@effect/atom-react"; +import { + AuthProvidersManageScope, + type AuthSessionState, + EnvironmentId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useEffect } from "react"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../test/render"; + +const state = vi.hoisted(() => ({ + environments: [] as { + environmentId: EnvironmentId; + label: string; + connection: { phase: "connected" | "disconnected" }; + }[], + providers: new Map>(), + requests: [] as EnvironmentId[], + sessions: new Map>>(), +})); + +vi.mock(import("~/state/environments"), () => ({ + useEnvironments: (() => ({ environments: state.environments })) as never, + useEnvironmentProviders: () => state.providers, +})); +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => { + const actual = await original(); + return { + ...actual, + createEnvironmentSessionAtoms: (( + ...args: Parameters + ) => ({ + ...actual.createEnvironmentSessionAtoms(...args), + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!, + })) as typeof actual.createEnvironmentSessionAtoms, + }; +}); +vi.mock(import("~/state/server"), () => ({ + serverEnvironment: { updateProvider: {} } as never, +})); +vi.mock(import("~/state/use-atom-command"), () => ({ + useAtomCommand: (() => + async ({ environmentId }: { environmentId: EnvironmentId }) => { + state.requests.push(environmentId); + return AsyncResult.success(undefined); + }) as never, +})); + +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { useProviderUpdates } from "./ProviderUpdatesAction"; + +const provider: ServerProvider = { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-10-21T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + versionAdvisory: { + status: "behind_latest", + currentVersion: "1.0.0", + latestVersion: "1.1.0", + updateCommand: "npm install -g @openai/codex", + canUpdate: true, + checkedAt: "2026-10-21T00:00:00.000Z", + message: "Update available.", + }, +}; + +function session( + scopes: NonNullable, +): AsyncResult.AsyncResult { + return AsyncResult.success({ + authenticated: true, + scopes, + auth: { + policy: "remote-reachable", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["bearer-access-token"], + sessionCookieName: "t3_session", + }, + }); +} + +function setup() { + state.environments = [ + { environmentId: EnvironmentId.make("read-only"), label: "Read only" }, + { environmentId: EnvironmentId.make("writable"), label: "Writable" }, + { environmentId: EnvironmentId.make("unresolved"), label: "Unresolved" }, + ].map((environment) => ({ ...environment, connection: { phase: "connected" } })); + state.providers = new Map( + state.environments.map(({ environmentId }) => [environmentId, [provider]]), + ); + state.requests = []; + const sessions = new Map>>( + [ + [state.environments[0]!.environmentId, Atom.make(session(["orchestration:read"]))], + [state.environments[1]!.environmentId, Atom.make(session([AuthProvidersManageScope]))], + [ + state.environments[2]!.environmentId, + Atom.make>( + AsyncResult.initial(), + ), + ], + ], + ); + state.sessions = sessions; + return { sessions }; +} + +it("bulk provider updates exclude connections without a confirmed management grant", async () => { + const fixture = setup(); + let updates!: ReturnType; + function Probe() { + const nextUpdates = useProviderUpdates(); + useEffect(() => { + updates = nextUpdates; + }, [nextUpdates]); + return null; + } + await using _screen = await render( + + + , + ); + + const writableId = state.environments[1]!.environmentId; + expect(updates.machines.map(({ environmentId }) => environmentId)).toEqual([writableId]); + await act(async () => { + await updates.updateAll({ quiet: true }); + }); + expect(state.requests).toEqual([writableId]); + + await act(() => { + appAtomRegistry.set(fixture.sessions.get(writableId)!, session(["orchestration:read"])); + }); + expect(updates.machines).toEqual([]); + state.requests = []; + await act(async () => { + await updates.updateAll({ quiet: true }); + }); + expect(state.requests).toEqual([]); +}); diff --git a/apps/web/src/components/ProviderUpdatesAction.tsx b/apps/web/src/components/ProviderUpdatesAction.tsx index 8d45d66b71213..57573806e45db 100644 --- a/apps/web/src/components/ProviderUpdatesAction.tsx +++ b/apps/web/src/components/ProviderUpdatesAction.tsx @@ -1,9 +1,10 @@ -import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; +import { AuthProvidersManageScope, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import { useRef, useState } from "react"; import { useEnvironmentProviders, useEnvironments } from "~/state/environments"; import { serverEnvironment } from "~/state/server"; +import { useEnvironmentsWithScope } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { canOneClickUpdateProviderCandidate, @@ -17,13 +18,17 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; export function useProviderUpdates() { const { environments } = useEnvironments(); + const manageableIds = useEnvironmentsWithScope(environments, AuthProvidersManageScope); const providersByEnvironment = useEnvironmentProviders(); const updateProvider = useAtomCommand(serverEnvironment.updateProvider, { reportFailure: false, }); const machines = environments.flatMap((environment) => { const providers = providersByEnvironment.get(environment.environmentId) ?? []; - if (environment.connection.phase !== "connected") { + if ( + environment.connection.phase !== "connected" || + !manageableIds.has(environment.environmentId) + ) { return []; } const candidates = collectProviderUpdateCandidates(providers).filter((candidate) => diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index c388ec33af0b5..5dc65e57f1ca3 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -265,4 +265,11 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); + it("forwards address-bar focus from a focused desktop page", async () => { + setup(); + await using _shortcut = await renderShortcut(); + expect(state.setShortcuts).toHaveBeenLastCalledWith( + expect.arrayContaining([expect.objectContaining({ command: "preview.focusUrl" })]), + ); + }); }); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index ce187f5db5e96..77cc7b3d3068d 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -43,12 +43,13 @@ import { } from "../threadRoutes"; import { toastManager } from "./ui/toast"; -const PREVIEW_FORWARDED_LAYOUT_COMMANDS = [ +const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", "sidebar.toggle", "rightPanel.toggle", "rightPanel.toggleMaximized", + "preview.focusUrl", ] as const; const isGlobalPullRequests = (ref: ScopedThreadRef) => @@ -205,7 +206,7 @@ export function ReopenClosedViewShortcut() { // Guest browser processes miss app keydown listeners; desktop forwards the chords as menu actions. const commands = [ ...(hasHistory ? (["view.reopenClosed"] as const) : []), - ...PREVIEW_FORWARDED_LAYOUT_COMMANDS, + ...PREVIEW_FORWARDED_COMMANDS, ]; void preview .setForwardedShortcuts( diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 4e948a3464c52..15910b9f14c35 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -12,6 +12,8 @@ import { getFallbackThreadIdAfterDelete, hasUnseenCompletion, resolveSidebarRowThreadId, + belongsInSidebarWorkingShelf, + isSidebarEnvironmentDisconnected, orderItemsByPreferredIds, pinOrderKeyBetween, resolveProjectStatusIndicator, @@ -1089,6 +1091,38 @@ describe("Working shelf (beta)", () => { ).toBe(false); }); + it.each([ + ["connected", true, false], + ["connected", false, true], + ["connecting", false, false], + ["reconnecting", false, true], + ["offline", false, true], + ["error", false, true], + ["unsupported", false, true], + ["available", false, true], + ] as const)( + "lists threads outside the shelf on a %s environment: %s", + (phase, shellIsLive, disconnected) => { + expect(isSidebarEnvironmentDisconnected(phase, shellIsLive)).toBe(disconnected); + }, + ); + + it("lists a running thread outside the shelf while its environment is disconnected", () => { + const thread = { ...idle, runtime, environmentId: localEnvironmentId }; + const shelve = (disconnected: ReadonlyArray, enabled = true) => + belongsInSidebarWorkingShelf(thread, { + enabled, + disconnectedEnvironmentIds: new Set(disconnected), + isWorking: isSidebarThreadWorking, + }); + + expect(shelve([])).toBe(true); + expect(shelve([localEnvironmentId])).toBe(false); + expect(shelve([])).toBe(true); + expect(shelve([EnvironmentId.make("environment-other")])).toBe(true); + expect(shelve([], false)).toBe(false); + }); + describe("sortInboxThreadsByReturn", () => { const thread = ( id: string, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 0ab965e775c78..04a821c8b206f 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -16,6 +16,7 @@ import { type ThreadSearchShell, } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; +import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { isListedThreadLineage, type ContextMenuItem, @@ -185,6 +186,29 @@ export function resolveSidebarThreadSection(input: { return "active"; } +// Keep cached placement on the first connection attempt, matching mobile's threadRouteIsHydrating. +export function isSidebarEnvironmentDisconnected( + phase: EnvironmentConnectionPhase, + shellIsLive: boolean, +): boolean { + return phase !== "connecting" && (phase !== "connected" || !shellIsLive); +} + +export function belongsInSidebarWorkingShelf( + thread: T, + input: { + readonly enabled: boolean; + readonly disconnectedEnvironmentIds: ReadonlySet; + readonly isWorking: (thread: T) => boolean; + }, +): boolean { + return ( + input.enabled && + !input.disconnectedEnvironmentIds.has(thread.environmentId) && + input.isWorking(thread) + ); +} + const SIDEBAR_MARKER_PREFIX = "sidebar-marker-"; export type SidebarListMarker = diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index d569f7ec09b0c..d3442863e2ba2 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,3 +1,4 @@ +import { liveShellEnvironmentIdsAtom } from "../state/shell"; import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -138,6 +139,7 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { useEnvironmentIdentities, useConnectedEnvironmentIds, + useEnvironmentConnectionSummaries, useEnvironmentMachines, usePrimaryEnvironmentId, } from "../state/environments"; @@ -185,6 +187,8 @@ import { deleteSelectedThreadEntries, filterSidebarProjectScopeItems, firstValidTimestampMs, + belongsInSidebarWorkingShelf, + isSidebarEnvironmentDisconnected, isSidebarNestedLinkClick, isTrailingDoubleClick, orderItemsByPreferredIds, @@ -355,12 +359,17 @@ interface SidebarThreadPartitionInput { readonly workingShelfEnabled: boolean; /** Boring mode: folders list active threads by the user's latest message. */ readonly sortActiveBySend: boolean; + readonly disconnectedEnvironmentIds: ReadonlySet; // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend // on the clock, so the minute tick, the precise snooze-wake tick and the inbox // tracker's expiry version are inputs: a new key repartitions. readonly clockKey: string; } +function scrollSidebarToTop(content: HTMLElement | null) { + content?.closest("[data-slot=scroll-area-viewport]")?.scrollTo({ top: 0 }); +} + function threadShellKey(thread: Pick): string { return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); } @@ -436,6 +445,18 @@ function useSidebarThreads(input: { // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; + const environmentConnections = useEnvironmentConnectionSummaries(); + const liveShellEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom); + const disconnectedEnvironmentIds = new Set( + environmentConnections + .filter((environment) => + isSidebarEnvironmentDisconnected( + environment.connectionState, + liveShellEnvironmentIds.has(environment.environmentId), + ), + ) + .map((environment) => environment.environmentId), + ); const inboxReturnsVersion = useSyncExternalStore( inboxReturns.subscribe, inboxReturns.getSnapshot, @@ -485,6 +506,7 @@ function useSidebarThreads(input: { optimisticDrop, workingShelfEnabled, sortActiveBySend: folderGroups !== null, + disconnectedEnvironmentIds, clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); @@ -636,6 +658,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { optimisticDrop, workingShelfEnabled, sortActiveBySend, + disconnectedEnvironmentIds, } = input; const preciseNow = new Date().toISOString(); const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); @@ -647,8 +670,11 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) => botShelfName(thread) !== null ? bots - : workingShelfEnabled && - (manuallyMoved ? isThreadWorking(thread) : inboxObservation.isWorking(thread)) + : belongsInSidebarWorkingShelf(thread, { + enabled: workingShelfEnabled, + disconnectedEnvironmentIds, + isWorking: manuallyMoved ? isThreadWorking : inboxObservation.isWorking, + }) ? working : active; const snoozed: EnvironmentThreadShell[] = []; @@ -1061,6 +1087,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const [renamingTitle, setRenamingTitle] = useState(""); const settlingThreadKeysRef = useRef(new Set()); const threadListRef = useRef(null); + const sidebarContentRef = useRef(null); const dragLabelOffsetRef = useRef(0); const listMotionRef = useRef | null>(null); const [dragState, setDragState] = useState<{ @@ -1086,9 +1113,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; // A selection made under one scope can hold threads the next scope hides. + // The viewport outlives the scope and does not anchor, so a new list starts at the top. const setProjectScopeKeys = (keys: readonly string[]) => { clearSelection(); setPersistedProjectScopeKeys(keys); + scrollSidebarToTop(sidebarContentRef.current); }; // A scope whose project is gone reads as all projects once every snapshot has // loaded. The stored keys are left alone, so the scope returns with its project. @@ -2006,10 +2035,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0; // Cache on both fields so layout-key changes trigger the effect even when animate is unchanged. const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate }; + const shelfExpansionKey = [workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded].join( + ":", + ); + const previousShelfExpansionKeyRef = useRef(shelfExpansionKey); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the list motion controller to animate or not after each layout-affecting commit useLayoutEffect(() => { - listMotionRef.current?.update(listMotionPass.animate); - }, [listMotionPass]); + // Shelf rows would travel over stationary headers below the bottom-anchored shelf. + const shelvesUnchanged = previousShelfExpansionKeyRef.current === shelfExpansionKey; + previousShelfExpansionKeyRef.current = shelfExpansionKey; + listMotionRef.current?.update(listMotionPass.animate && shelvesUnchanged); + }, [listMotionPass, shelfExpansionKey]); const handleThreadDragOver = (event: DragOverEvent) => { const target = event.over ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id)) @@ -2986,6 +3022,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 3d5c27a5021ac..c9254d0d82aed 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -122,6 +122,8 @@ export function startThreadNotifications( ) : status === "approval" ? ( + ) : status === "limited" ? ( + ) : status === "failed" ? ( ) : ( diff --git a/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx b/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx new file mode 100644 index 0000000000000..2f690d88f5b9d --- /dev/null +++ b/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx @@ -0,0 +1,66 @@ +import { EnvironmentId, type ThreadPullRequestLink } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; +import { makeThreadFixture } from "../test-fixtures"; +import { ThreadRowLeadingStatus } from "./ThreadStatusIndicators"; + +const environmentId = EnvironmentId.make("environment-test"); + +vi.mock(import("../state/entities"), async (original) => ({ + ...(await original()), + useProject: () => null, + useServerConfigs: (() => + new Map([ + [environmentId, { environment: { capabilities: { threadPullRequests: true } } }], + ])) as never, +})); + +it("updates palette PR status from linked snapshots without a legacy link or branch PR", async () => { + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "example/repo", + number: 7, + url: "https://github.com/example/repo/pull/7", + source: "manual", + linkedAt: "2026-01-01T00:00:00Z", + stack: null, + snapshot: { + state: "merged", + title: "Linked change", + headBranch: "deleted-branch", + baseBranch: "main", + isDraft: false, + updatedAt: null, + syncedAt: "2026-01-03T00:00:00Z", + }, + }; + const row = (pullRequest: ThreadPullRequestLink) => ( + + + + ); + await using screen = await render(row(link)); + await expect.element(screen.getByLabelText("PR #7 - Merged: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("PR #7, status pending")).not.toBeInTheDocument(); + + await screen.rerender(row({ ...link, snapshot: null })); + await expect.element(screen.getByLabelText("PR #7, status pending")).toBeVisible(); + await expect + .element(screen.getByLabelText("PR #7 - Merged: Linked change")) + .not.toBeInTheDocument(); + + await screen.rerender( + row({ ...link, snapshot: { ...link.snapshot!, state: "open", isDraft: true } }), + ); + await expect.element(screen.getByLabelText("PR #7 - Draft: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("PR #7, status pending")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 0af0e063bdea3..ea49b01665b64 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -674,6 +674,8 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar thread.environmentId, thread.linkedPullRequest, leaseLiveStatus, + thread.pullRequests, + thread.branchPullRequest, ); const gitStatus = useEnvironmentQuery( leaseLiveStatus && @@ -696,8 +698,11 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar linkedPullRequest: thread.linkedPullRequest, linkedPullRequestStatus: linkedPullRequest, }; - const pr = resolveDisplayedThreadPr(displayedPrInput); - const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput)); + const pr = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput); + const prStatus = prStatusIndicator( + pr, + linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput), + ); const threadStatus = resolveThreadStatusPill({ thread: { ...thread, diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx index cbe5ad8cddb24..2b90b09f68e77 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.tsx @@ -31,6 +31,7 @@ import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCom import { observeAssistantCitationCommentSource } from "./AssistantCitationSource"; import { composerFloatingLayerProps } from "./composerEventScope"; import { observeResize } from "~/lib/observeResize"; +import { textDirection } from "~/textDirection"; export function AssistantCitationChip({ citation, @@ -130,7 +131,9 @@ export function AssistantCitationChip({ aria-label={`View cited assistant text: ${label}`} >
); } diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index d9fd60645618e..0a8357bb9baba 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -1,5 +1,6 @@ import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; import { useState, type Ref } from "react"; +import { textDirection } from "~/textDirection"; import { Button } from "../ui/button"; @@ -51,6 +52,7 @@ export function AssistantCitationCommentEditor({ aria-invalid={commentTooLong || undefined} placeholder="Add an optional comment..." rows={2} + dir={textDirection(comment)} className="field-sizing-content block max-h-40 min-h-16 w-full resize-none bg-transparent px-1 py-1.5 text-base outline-none placeholder:text-muted-foreground sm:text-sm" value={comment} onChange={(event) => { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index c423773fb6fc6..82b6b9617c1b0 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -934,11 +934,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const selectedProviderSlashCommands = selectedProviderStatus ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SLASH_COMMANDS; - const refreshWorkspaceSnapshotOnTyping = useProviderWorkspaceSnapshotRefresh({ - environmentId, - gitCwd, - instanceId: selectedProviderEntry?.instanceId, - }); + const { refresh: refreshWorkspaceSnapshotOnTyping, scanning: workspaceSkillsScanning } = + useProviderWorkspaceSnapshotRefresh({ + environmentId, + gitCwd, + instanceId: selectedProviderEntry?.instanceId, + }); const selectedPromptEffort = composerProviderState.promptEffort; const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; @@ -1139,6 +1140,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedProviderSkills, selectedProviderSlashCommands, showSkillsInSlashMenu: settings.showSkillsInSlashMenu, + workspaceSkillsScanning, questionAttachmentTarget, }); @@ -3289,7 +3291,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? isComposerMenuLoading ? composerTriggerKind === "pull-request" ? "Finding pull request..." - : "Searching workspace files..." + : composerTriggerKind === "skill" || composerTriggerKind === "slash-command" + ? "Searching workspace skills..." + : "Searching workspace files..." : composerMenuEmptyState : ""}
diff --git a/apps/web/src/components/chat/ChatHeader.browser.test.tsx b/apps/web/src/components/chat/ChatHeader.browser.test.tsx new file mode 100644 index 0000000000000..115de39efe25d --- /dev/null +++ b/apps/web/src/components/chat/ChatHeader.browser.test.tsx @@ -0,0 +1,73 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +const persisted = vi.hoisted(() => ({ title: "" })); +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, + readEnvironmentScope: () => true, +})); +vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({ + ...(await importOriginal()), + useOrchestrationCommand: (() => + async ({ input }: { input: { title: string } }) => { + persisted.title = input.title; + return { _tag: "Success" }; + }) as never, +})); +vi.mock(import("~/hooks/useThreadActionMenu"), () => ({ + useThreadActionMenu: () => ({ openMenu: () => {}, closeMenu: () => {} }), +})); + +import { render } from "../../../test/render"; +import { ChatHeader } from "./ChatHeader"; + +function header(title: string) { + return ( + <> + {}} + rightPanelOpen={false} + onNewThreadInProject={() => {}} + /> +
Outside rename
+ + ); +} + +it.each(["blur", "Enter"] as const)( + "preserves a concurrent title update when an untouched rename ends with %s", + async (finish) => { + persisted.title = "New thread"; + await using screen = await render(header(persisted.title)); + await screen.getByRole("button", { name: "Thread actions for New thread" }).dblClick(); + const input = screen.getByRole("textbox", { name: "Thread title" }); + await expect.element(input).toHaveValue("New thread"); + + persisted.title = "Fix login redirect"; + await screen.rerender(header(persisted.title)); + if (finish === "Enter") await userEvent.keyboard("{Enter}"); + else await screen.getByText("Outside rename").click(); + + await expect.element(input).not.toBeInTheDocument(); + expect(persisted.title).toBe("Fix login redirect"); + + await screen.rerender(header(persisted.title)); + await screen.getByRole("button", { name: "Thread actions for Fix login redirect" }).dblClick(); + await screen.getByRole("textbox", { name: "Thread title" }).fill("My edited title"); + persisted.title = "Another concurrent title"; + await screen.rerender(header(persisted.title)); + await userEvent.keyboard("{Enter}"); + await expect + .element(screen.getByRole("textbox", { name: "Thread title" })) + .not.toBeInTheDocument(); + expect(persisted.title).toBe("My edited title"); + }, +); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 144402d1dfe9f..49f21a1ddc829 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -175,7 +175,10 @@ export const ChatHeader = memo(function ChatHeader({ const commitRename = (title: string) => { setRenaming(null); if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return; - const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle }); + const resolution = resolveRenameCommit({ + title, + originalTitle: renamingTitle ?? activeThreadTitle, + }); if (resolution.action === "reject-empty") { toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); return; diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx index bf83b014b7f6f..4c9702abe5f31 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx @@ -1,6 +1,7 @@ import { InfoIcon } from "lucide-react"; import type { ReactNode } from "react"; import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; @@ -123,3 +124,28 @@ it("shows the details button while text or nested text is cut, until it fits aga await screen.rerender({noticeRow("4rem", "Ready")}); await expect.element(details).not.toBeInTheDocument(); }); + +it("opens the details of a long notice right above its button", async () => { + const viewport = { width: window.innerWidth, height: window.innerHeight }; + await page.viewport(1280, 800); + await using _viewport = { + [Symbol.asyncDispose]: () => page.viewport(viewport.width, viewport.height), + }; + const script = Array.from({ length: 400 }, (_, line) => `echo "line ${line}"`).join("\n"); + const container = document.createElement("div"); + container.style.cssText = "position: fixed; bottom: 4rem; right: 4rem;"; + await using screen = await render(noticeRow("40rem", script), { container }); + const details = screen.getByRole("button", { name: "Show details" }); + await userEvent.hover(details); + const popup = page.getByLabelText("Notice details"); + await expect.element(popup).toBeVisible(); + + // A positioner sized to the unscrolled text flips beside the button and covers it. + await vi.waitFor(() => { + const gap = + details.element().getBoundingClientRect().top - + popup.element().getBoundingClientRect().bottom; + expect(gap).toBeGreaterThanOrEqual(0); + expect(gap).toBeLessThan(8); + }); +}); diff --git a/apps/web/src/components/chat/ComposerBannerStack.tsx b/apps/web/src/components/chat/ComposerBannerStack.tsx index 61778f817dc37..ee602dcdac1eb 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.tsx @@ -155,9 +155,7 @@ export function NoticeText({ side="top" className="max-w-[min(30rem,calc(100vw-2rem))] whitespace-normal wrap-anywhere [--inline-button-text-align:start] [--inline-button-white-space:normal] [&_[data-slot=inline-button]]:max-w-full" > - - {children} - + {children} ) : null} diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index afa058587b553..0b9dda460d8ef 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -152,7 +152,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {

{props.isLoading - ? props.triggerKind === "skill" + ? props.triggerKind === "skill" || props.triggerKind === "slash-command" ? "Searching workspace skills..." : props.triggerKind === "pull-request" ? "Finding pull request..." diff --git a/apps/web/src/components/chat/ComposerControl.tsx b/apps/web/src/components/chat/ComposerControl.tsx index 139e80d081e4e..9c1e92d93641f 100644 --- a/apps/web/src/components/chat/ComposerControl.tsx +++ b/apps/web/src/components/chat/ComposerControl.tsx @@ -12,7 +12,7 @@ function composerControlClassName(size: ComposerControlSize, className?: string) "relative inline-flex shrink-0 cursor-pointer items-center justify-center whitespace-nowrap rounded-(--control-radius) border border-transparent text-base outline-none hover:bg-accent data-pressed:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-disabled:pointer-events-none data-disabled:opacity-64 pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 [&:active:not([aria-haspopup])]:scale-[0.97] [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:-mx-0.5 [&_svg[data-composer-control-icon]]:mx-0", "[&_:is([data-composer-control-label],[data-chat-provider-model-picker-label])]:[text-box:trim-both_cap_alphabetic] supports-[text-box:trim-both_cap_alphabetic]:[&_:is([data-composer-control-label],[data-chat-provider-model-picker-label])]:py-1.5", size === "xs" - ? "h-7 gap-1 px-1.75 font-normal text-foreground/70 text-sm hover:text-foreground dark:text-muted-foreground sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5 [&_svg]:mx-0 [&_svg[data-composer-control-chevron]]:ms-0 [&_svg[data-composer-control-chevron]]:-me-1" + ? "h-7 gap-1 has-[[data-composer-label]]:gap-1.5 px-1.75 font-normal text-foreground/70 text-sm hover:text-foreground dark:text-muted-foreground sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5 [&_svg]:mx-0 [&_svg[data-composer-control-chevron]]:ms-0 [&_svg[data-composer-control-chevron]]:-me-1" : "h-7 gap-1.5 px-2 font-medium text-foreground/80 [&_svg:not([class*='text-'])]:text-muted-foreground hover:text-foreground sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4", "aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80", className, diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index 8523c25927fa4..0002beeaf9fef 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -193,6 +193,8 @@ export function ComposerControlsBar(props: { environmentId={environmentId} compact={false} isComposerOwned + // The trigger grows away from this edge when its model or effort label changes. + popupAlign={composerControlsCollapsed ? "start" : "end"} disabled={providerCatalogPending || isSendBusy} multipleModelsEnabled={multipleModelsEnabled} multipleModelSelections={multipleModelSelections} diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx index e9de2aa93b302..68158c7151b2f 100644 --- a/apps/web/src/components/chat/ComposerImageThumbnail.tsx +++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx @@ -1,24 +1,15 @@ -import { memo, Suspense, use, type ReactNode } from "react"; +import { memo, useLayoutEffect, useState, type ReactNode } from "react"; + +import { cn } from "~/lib/utils"; import { createComposerImageThumbnail, + isHeicImageFile, + MAX_COMPRESSIBLE_SOURCE_BYTES, readComposerImageThumbnail, } from "../../lib/imageCompression"; -export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: { - file: File; - alt: string; - className: string; - fallback: ReactNode; -}) { - return ( - - - - ); -}); - -function ThumbnailImage({ +export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ file, alt, className, @@ -29,8 +20,63 @@ function ThumbnailImage({ className: string; fallback: ReactNode; }) { - // A settled thumbnail paints synchronously instead of suspending for a tick. - const settled = readComposerImageThumbnail(file); - const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled; - return src ? {alt} : fallback; -} + const [preview, setPreview] = useState(() => ({ + file, + src: readComposerImageThumbnail(file), + })); + const [loadedSrc, setLoadedSrc] = useState(null); + const [failedSrc, setFailedSrc] = useState(null); + const src = preview.file === file ? preview.src : readComposerImageThumbnail(file); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the local blob URL and decodes its replacement before swapping the visible image + useLayoutEffect(() => { + let disposed = false; + let localUrl: string | undefined; + const cached = readComposerImageThumbnail(file); + if ( + file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES && + !isHeicImageFile(file) && + cached === undefined + ) { + localUrl = URL.createObjectURL(file); + // oxlint-disable-next-line react/set-state-in-effect -- the blob URL is created and revoked by this effect + setPreview({ file, src: localUrl }); + } + if (cached === undefined) { + void createComposerImageThumbnail(file).then(async (thumbnail) => { + if (disposed) return; + if (!thumbnail) { + if (!localUrl) setPreview({ file, src: null }); + return; + } + const image = new Image(); + image.src = thumbnail; + try { + await image.decode(); + if (!disposed) setPreview({ file, src: thumbnail }); + } catch { + // Keep the local preview if the thumbnail cannot be decoded. + } + }); + } + return () => { + disposed = true; + if (localUrl) URL.revokeObjectURL(localUrl); + }; + }, [file]); + + return src && failedSrc !== src ? ( + { + if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src); + }} + src={src} + alt={alt} + onLoad={() => setLoadedSrc(src)} + onError={() => setFailedSrc(src)} + className={cn(className, loadedSrc !== src && "invisible")} + /> + ) : src === undefined ? null : ( + fallback + ); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx new file mode 100644 index 0000000000000..3d704b5209305 --- /dev/null +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -0,0 +1,125 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ProviderOptionSelection, + type ServerProviderModel, +} from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; +import { useState } from "react"; +import { expect, it } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { ComposerEffortColumn, describeComposerEffort } from "./ComposerModelEffort"; +import type { TraitsSelectionInput } from "./TraitsPicker"; + +// Shaped like Devin over ACP: its session mode comes first, and its reasoning id is its own. +const models: ReadonlyArray = [ + { + slug: "fusion", + name: "Fusion (Claude Opus 5.5 Medium + SWE-2 High)", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { + id: "mode", + label: "Session Mode", + type: "select", + currentValue: "bypass", + options: [ + { id: "code", label: "Code" }, + { id: "plan", label: "Plan" }, + { id: "bypass", label: "Bypass Permissions" }, + ], + }, + { + id: "thought_level", + label: "Thinking", + type: "select", + role: "reasoning", + currentValue: "medium", + options: [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High" }, + ], + }, + { + id: "speed", + label: "Speed", + type: "select", + currentValue: "standard", + options: [ + { id: "standard", label: "Standard" }, + { id: "fast", label: "Fast" }, + ], + }, + { id: "auto_approve", label: "Auto-approve tools", type: "boolean", currentValue: false }, + ], + }), + }, +]; + +function traitsInput( + modelOptions: ReadonlyArray, + onModelOptionsChange: (next: ReadonlyArray | undefined) => void, +): TraitsSelectionInput { + return { + provider: ProviderDriverKind.make("acpRegistry"), + instanceId: ProviderInstanceId.make("devin"), + models, + model: "fusion", + modelOptions, + planModeEnabled: false, + onModelOptionsChange, + }; +} + +function Column() { + const [options, setOptions] = useState>([]); + const traits = traitsInput(options, (next) => setOptions(next ?? [])); + return ( + <> +

+ +
+

{describeComposerEffort(traits, "bars", "sm").suffix}

+ + ); +} + +it("draws an agent's reasoning as bars and keeps its mode out of the levels", async () => { + await using screen = await render(, { router: false }); // no routes involved + const status = screen.getByRole("status"); + expect(status.element().querySelector("[data-composer-effort-glyph]")).not.toBeNull(); + await expect.element(status).toHaveTextContent(""); + + const levels = screen.getByRole("radiogroup", { name: "Thinking" }); + await expect.element(levels.getByRole("radio")).toHaveLength(3); + await expect.element(screen.getByRole("radio", { name: "Plan" })).not.toBeInTheDocument(); + + // Up and Down walk from the levels through the option rows without opening their menus. + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("{ArrowDown}{ArrowDown}{ArrowDown}"); + const speed = screen.getByRole("button", { name: "Speed: Standard" }); + await expect.element(speed).toHaveFocus(); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); + await userEvent.keyboard("{ArrowRight}"); + await expect.element(page.getByRole("menuitemradio", { name: "Standard" })).toHaveFocus(); + await userEvent.keyboard("{ArrowLeft}"); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); + await expect.element(speed).toHaveFocus(); + + await userEvent.click(screen.getByText("Auto-approve tools")); + await expect + .element(screen.getByRole("switch", { name: "Auto-approve tools" })) + .toHaveAttribute("aria-checked", "true"); + + await userEvent.click(screen.getByRole("button", { name: "Session Mode: Bypass Permissions" })); + await userEvent.click(page.getByRole("menuitemradio", { name: "Plan" })); + await expect + .element(screen.getByRole("button", { name: "Session Mode: Plan" })) + .toBeInTheDocument(); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 015801b3033e2..3a863936101b2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -1,16 +1,25 @@ import { buildTraitsTriggerDisplay, getDescriptorStringValue, - REASONING_SELECT_DESCRIPTOR_IDS, + isReasoningControl, selectableProviderOptionChoices, } from "@t3tools/client-runtime/model-traits"; import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts"; import type { EffortDisplay } from "@t3tools/contracts/settings"; -import { CheckIcon, ChevronUpIcon } from "lucide-react"; -import { type KeyboardEvent, type ReactNode, use, useRef } from "react"; +import { getProviderOptionCurrentLabel } from "@t3tools/shared/model"; +import { CheckIcon, ChevronRightIcon, ChevronUpIcon } from "lucide-react"; +import { type KeyboardEvent, type ReactNode, use, useRef, useState } from "react"; import { cn } from "~/lib/utils"; -import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; +import { + Menu, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuRadioItemIndicator, + MenuTrigger, +} from "../ui/menu"; +import { Switch } from "../ui/switch"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerControlSize } from "./ComposerControl"; import { ComposerPermissionsSection, type RuntimeModeOption } from "./ComposerFooterControls"; @@ -51,8 +60,8 @@ type ColumnControl = | { kind: "boolean"; descriptor: BooleanDescriptor }; /** - * The column lists the model's reasoning control first, under the header that names it, then - * its other options. + * The column lists the model's reasoning levels under the header that names it. Other options, + * such as an agent's session mode, sit below as one row each. */ function columnControls( provider: TraitsSelectionInput["provider"], @@ -64,8 +73,7 @@ function columnControls( ...columnSelects.map((descriptor) => ({ kind: "select" as const, descriptor })), ...columnToggles.map((descriptor) => ({ kind: "boolean" as const, descriptor })), ]; - const effort = - controls.find((control) => REASONING_SELECT_DESCRIPTOR_IDS.has(control.descriptor.id)) ?? null; + const effort = controls.find((control) => isReasoningControl(control.descriptor)) ?? null; return { effort, others: controls.filter((control) => control !== effort) }; } @@ -94,20 +102,40 @@ export function describeComposerEffort( modelSelection, reportedModelSelection: traits.reportedModelSelection, }); + // The same reasoning control the column lists, wherever the agent put it among its options. + const reasoning = + columnControls(traits.provider, visibility.selectDescriptors, visibility.booleanDescriptors) + .effort?.descriptor ?? null; + const ultrathink = visibility.ultrathinkPromptControlled && reasoning === primary; const glyph = - primary && REASONING_SELECT_DESCRIPTOR_IDS.has(primary.id) + reasoning?.type === "select" ? resolveEffortGlyph( - primary, - visibility.ultrathinkPromptControlled + reasoning, + ultrathink ? "ultrathink" - : getDescriptorStringValue(primary, modelSelection, traits.reportedModelSelection), + : getDescriptorStringValue(reasoning, modelSelection, traits.reportedModelSelection), ) : null; - // Without a reasoning select the whole label is the word; it already names speed and the rest. // Workflow levels such as Ultracode always show their name; the setting names every level. const word = glyph ? (glyph.special ?? (effortDisplay === "label" ? glyph.label : null)) - : display.label; + : !reasoning + ? null + : reasoning.type === "boolean" + ? `${reasoning.label} ${reasoning.currentValue === true ? "On" : "Off"}` + : ultrathink + ? "Ultrathink" + : getProviderOptionCurrentLabel(reasoning, modelSelection, traits.reportedModelSelection); + const fast = display.speedLabel === "Fast" || display.speedLabel === "Ultrafast"; + // Agent options such as modes live in the picker; the trigger adds only the context window. + const contextWindow = + visibility.contextWindowDescriptor && + getProviderOptionCurrentLabel( + visibility.contextWindowDescriptor, + modelSelection, + traits.reportedModelSelection, + ); + if (!word && !glyph && !fast && !contextWindow) return { suffix: null, detail: display.label }; return { detail: display.label, suffix: ( @@ -118,22 +146,22 @@ export function describeComposerEffort( size === "sm" && "-ms-0.5", )} > - {word !== null ? ( - {word} + {word ? ( + + {word} + ) : glyph ? ( ) : null} - {glyph && (display.speedLabel === "Fast" || display.speedLabel === "Ultrafast") ? ( - - ) : null} - {glyph && display.otherLabels.length > 0 ? ( + {fast ? : null} + {contextWindow ? ( - {display.otherLabels.join(" · ")} + {contextWindow} ) : null} @@ -150,10 +178,10 @@ function ColumnRow(props: { /** Shown on hover; the column is too narrow to print it under the label. */ description?: string | undefined; selected: boolean; + /** The column's one tab stop: the selected level, else the first when none shows as selected. */ + tabStop: boolean; isDefault?: boolean | undefined; disabled?: boolean; - /** A level of the reasoning control, where focus lands after a model pick. */ - level: boolean; onPick: () => void; }) { const rowProps = { @@ -162,17 +190,24 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - "data-effort-level": props.level || undefined, - // The reasoning control holds the column's one tab stop; Up and Down move between rows. - tabIndex: props.selected && props.level ? 0 : -1, + // Focus lands on a level after a model pick. + "data-effort-level": true, + // Up and Down move between rows. + tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, onClick: props.onPick, } as const; const content = ( <> {props.label} - {props.isDefault ? Default : null} -