diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index b34c27bd471f3..4a5a16298b956 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -91,6 +91,7 @@ import IconListNumbers from "@tabler/icons-react-native/IconListNumbers"; import IconMenu2 from "@tabler/icons-react-native/IconMenu2"; import IconMessageCircleQuestion from "@tabler/icons-react-native/IconMessageCircleQuestion"; import IconMessage from "@tabler/icons-react-native/IconMessage"; +import IconMail from "@tabler/icons-react-native/IconMail"; import IconMessageDots from "@tabler/icons-react-native/IconMessageDots"; import IconMessagePlus from "@tabler/icons-react-native/IconMessagePlus"; import IconMinus from "@tabler/icons-react-native/IconMinus"; @@ -208,6 +209,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { ellipsis: IconDots, moon: IconMoon, "ellipsis.circle": IconDotsCircleHorizontal, + "envelope.badge": IconMail, "exclamationmark.triangle": IconAlertTriangle, "exclamationmark.circle": IconAlertCircle, eye: IconEye, diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 01bd49b028468..aa12551f9ce1f 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -799,6 +799,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { }); const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); + const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false }); const handleAcknowledgeWoke = useCallback(() => { if (props.wokeAt === null) return; void visitThread({ @@ -945,6 +946,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { supported: props.titleRegenerationSupported, isRegenerating: isRegeneratingTitle, }), + { id: "mark-unread", title: "Mark unread", image: "envelope.badge" }, ...(canTurnIntoProject ? [ { @@ -1059,6 +1061,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { if (nativeEvent.event === "rename") handleRename(); if (nativeEvent.event === "regenerate-title") handleRegenerateTitle(); if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread); + if (nativeEvent.event === "mark-unread") { + void markThreadUnread({ + environmentId: thread.environmentId, + input: { threadId: thread.id }, + }); + } if (nativeEvent.event === "copy-thread") { const target = threadChipCopyTarget( { environmentId: thread.environmentId, threadId: thread.id }, @@ -1107,6 +1115,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { handleUnpin, handleUnsettle, handleUnsnooze, + markThreadUnread, setCustomSnoozeOpen, snoozePresets, props.snoozePresets, diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts index 9619030be2fab..255dae1884bb9 100644 --- a/apps/server/src/cli/pair.test.ts +++ b/apps/server/src/cli/pair.test.ts @@ -623,6 +623,72 @@ describe("t3 pair", () => { assert.include(String(error), "127.0.0.2"); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + + // regression: #37459 - on Linux without an operator, tailscaled refuses Serve config + // from a normal user, and the CLI must say how to fix it. + it.effect("explains the operator fix when Tailscale denies the Serve config", () => + Effect.gen(function* () { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-")); + yield* persistServerRuntimeState({ + path: NodePath.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }), + }); + const spawner = ChildProcessSpawner.make((command) => { + const { args } = command as unknown as { readonly args: ReadonlyArray }; + const serve = args[0] === "serve" && args[1] !== "status"; + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(serve ? 1 : 0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make( + new TextEncoder().encode( + serve + ? "" + : args[0] === "status" + ? '{"Self":{"DNSName":"pair-test.tail.ts.net."}}' + : "{}", + ), + ), + stderr: Stream.make( + new TextEncoder().encode( + serve + ? "sending serve config: Access denied: serve config denied\n\nUse 'sudo tailscale serve --https=443 --bg http://127.0.0.1:3773'.\nTo not require root, use 'sudo tailscale set --operator=$USER' once.\n" + : "", + ), + ), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }); + + const error = yield* provideCliTestLayers( + runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(FetchHttpClient.Fetch, async (input) => { + if (String(input) === "http://127.0.0.1:3773/.well-known/t3/environment") { + return Response.json(testDescriptor); + } + assert.equal(String(input), "https://pair-test.tail.ts.net/.well-known/t3/environment"); + return new Response(null, { status: 503 }); + }), + Effect.flip, + ), + ); + + assert.include(String(error), "sudo tailscale set --operator=$USER"); + assert.notInclude(String(error), "by hand to see why"); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); describe("auth scope options", () => { diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index 4b563155c6bfe..2d45d45befeec 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -143,6 +143,15 @@ export class TailscaleServeFailedError extends Schema.TaggedError()( + "TailscaleOperatorRequiredError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Tailscale refused the Serve config because this user is not its operator. Run `sudo tailscale set --operator=$USER` once, then run this command again."; + } +} + export class TailscaleServeTargetRefusedError extends Schema.TaggedError()( "TailscaleServeTargetRefusedError", { localHost: Schema.String }, @@ -425,6 +434,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase" } // The probe above fails whenever this host cannot reach its own MagicDNS name, so the Serve // config, not the probe, decides whether the port is free. + const platform = yield* HostProcess.Platform; const holder = yield* readTailscaleServeRootHolder(input.servePort, { host: (localTarget.localHost ?? "127.0.0.1").replace(/^\[|\]$/gu, ""), port: localTarget.localPort, @@ -437,13 +447,18 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase" servePort: input.servePort, ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}), }).pipe( - Effect.mapError((cause) => - cause._tag === "TailscaleCommandExitError" && - cause.stderrDiagnostic === "unsupported-target" && - localTarget.localHost !== undefined - ? new TailscaleServeTargetRefusedError({ localHost: localTarget.localHost }) - : new TailscaleServeFailedError({ servePort: input.servePort, cause }), - ), + Effect.mapError((cause) => { + const diagnostic = + cause._tag === "TailscaleCommandExitError" ? cause.stderrDiagnostic : undefined; + if (diagnostic === "unsupported-target" && localTarget.localHost !== undefined) { + return new TailscaleServeTargetRefusedError({ localHost: localTarget.localHost }); + } + // Only Linux tailscaled has an operator; elsewhere a denial needs another fix. + if (diagnostic === "permission-denied" && platform === "linux") { + return new TailscaleOperatorRequiredError({ cause }); + } + return new TailscaleServeFailedError({ servePort: input.servePort, cause }); + }), ); notes.push( `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} --set-path=/ off\`.`, diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 27c1cd15a8d79..2ea6d98c083c5 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -1375,48 +1375,15 @@ it.layer( ); }); - it("drops Grok models a completed probe no longer advertises", () => { + it.each([ + ["grok", "warning"], + ["cursor", "error"], + ["muse", "error"], + ["fx", "warning"], + ] as const)("drops %s models a completed listing no longer returns", (driver, failedStatus) => { const previousProvider = { - instanceId: ProviderInstanceId.make("grok"), - driver: ProviderDriverKind.make("grok"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-09-30T00:00:00.000Z", - version: "1.0.44", - models: [ - { slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }, - { slug: "codexhub-removed", name: "Removed", isCustom: false, capabilities: null }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshedProvider = { - ...previousProvider, - checkedAt: "2026-09-30T00:01:00.000Z", - models: [previousProvider.models[0]], - } satisfies ServerProvider; - const acpFailedProvider = { - ...refreshedProvider, - status: "warning", - message: "Grok CLI is installed but ACP initialize failed.", - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models, - [previousProvider.models[0]], - ); - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, acpFailedProvider).models, - [...previousProvider.models], - ); - }); - - it("drops Cursor models a completed catalog read no longer returns", () => { - const previousProvider = { - instanceId: ProviderInstanceId.make("cursor"), - driver: ProviderDriverKind.make("cursor"), + instanceId: ProviderInstanceId.make(driver), + driver: ProviderDriverKind.make(driver), status: "ready", enabled: true, installed: true, @@ -1424,8 +1391,8 @@ it.layer( checkedAt: "2026-10-30T00:00:00.000Z", version: "1.0.0", models: [ - { slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: null }, - { slug: "retired-model-x", name: "Retired", isCustom: false, capabilities: null }, + { slug: "current-model", name: "Current", isCustom: false, capabilities: null }, + { slug: "retired-model", name: "Retired", isCustom: false, capabilities: null }, ], slashCommands: [], skills: [], @@ -1437,9 +1404,7 @@ it.layer( } satisfies ServerProvider; const failedProvider = { ...refreshedProvider, - status: "error", - auth: { status: "unknown" }, - message: "Cursor SDK model discovery timed out.", + status: failedStatus, } satisfies ServerProvider; assert.deepStrictEqual( @@ -1452,6 +1417,38 @@ it.layer( ); }); + it.each(["kiro", "claudeAgent"] as const)( + "keeps %s models a ready probe can omit", + (driver) => { + const previousProvider = { + instanceId: ProviderInstanceId.make(driver), + driver: ProviderDriverKind.make(driver), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-10-30T00:00:00.000Z", + version: "1.0.0", + models: [ + { slug: "built-in-model", name: "Built-in", isCustom: false, capabilities: null }, + { slug: "listed-model", name: "Listed", isCustom: false, capabilities: null }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const partialProvider = { + ...previousProvider, + checkedAt: "2026-10-30T00:01:00.000Z", + models: [previousProvider.models[0]], + } satisfies ServerProvider; + + assert.deepStrictEqual( + ProviderRegistry.mergeProviderSnapshot(previousProvider, partialProvider).models, + [...previousProvider.models], + ); + }, + ); + it("retains stale OpenCode models when a refresh fails or lists none", () => { const previousProvider = { instanceId: ProviderInstanceId.make("opencode"), diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index f1ae2e51637cc..f23058f1b88c5 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -210,20 +210,26 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => ); } - if ( - provider.driver === ProviderDriverKind.make("grok") || - provider.driver === ProviderDriverKind.make("cursor") - ) { - // Grok and Cursor report ready only after they discover a model list; the pending, - // failed, empty-inventory, and logged-out probes are warning/error. - return !(provider.installed && provider.status === "ready"); + if (provider.driver === ProviderDriverKind.make("kiro")) { + // Kiro is ready once `whoami` confirms the account, even when `--list-models` failed and + // the snapshot fell back to the built-in list. + return true; + } + + if (provider.driver === ProviderDriverKind.make("claudeAgent")) { + // Claude Code keeps one gateway model cache per Claude home, for one base URL at a time, so a + // ready probe can omit this instance's gateway models after another instance or a terminal + // `claude` on a different gateway rewrote that cache. + return true; } const isAntigravity = provider.driver === ProviderDriverKind.make("antigravity"); const isCodex = provider.driver === ProviderDriverKind.make("codex"); const isOpenCode = provider.driver === ProviderDriverKind.make("opencode"); if (!isAntigravity && !isCodex && !isOpenCode) { - return true; + // Any other driver must report ready only after a completed model listing, or opt out above: + // a ready list is authoritative, and warning/error probes keep the old models. + return !(provider.installed && provider.status === "ready"); } if ( diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 9e5b20205fefb..efaf9826408cd 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -9744,7 +9744,7 @@ describe("Windows long path configuration", () => { }); }); -it.layer(layerTest)("branch change totals after a failed untracked listing", (it) => { +it.layer(layerTest)("branch change totals after a failed read", (it) => { it.effect("do not list untracked files again on every status read", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -9799,4 +9799,85 @@ it.layer(layerTest)("branch change totals after a failed untracked listing", (it assert.deepStrictEqual(status.branchChanges, { baseRef: null, insertions: 2, deletions: 0 }); }), ); + + it.effect("back off a timed-out branch diff until it expires or HEAD moves", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir("git-branch-totals-timeout-"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(cwd, ["checkout", "-b", "feature"]); + yield* writeTextFile(cwd, "feature.txt", "one\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature"]); + + let diffs = 0; + let hang = true; + const diffStarted = yield* Queue.unbounded(); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + Effect.suspend(() => { + // Status diffs the working tree against HEAD; the branch totals diff the merge base. + if ( + !ChildProcess.isStandardCommand(command) || + !command.args.includes("diff-index") || + command.args.includes("HEAD") + ) { + return delegate.spawn(command); + } + diffs++; + if (!hang) return delegate.spawn(command); + return Queue.offer(diffStarted, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + isRunning: Effect.succeed(true), + exitCode: Effect.never, + }), + ), + ); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const read = driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + + const first = yield* read.pipe(Effect.forkChild); + yield* Queue.take(diffStarted); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(first)).branchChanges, undefined); + assert.strictEqual(diffs, 1); + assert.strictEqual((yield* read).branchChanges, undefined); + assert.strictEqual(diffs, 1, "the same HEAD and base are not diffed within the backoff"); + + hang = false; + yield* TestClock.adjust("1 minute"); + assert.deepStrictEqual((yield* read).branchChanges, { + baseRef: "main", + insertions: 1, + deletions: 0, + }); + assert.strictEqual(diffs, 2, "it is retried once the backoff passes"); + + hang = true; + const again = yield* read.pipe(Effect.forkChild); + yield* Queue.take(diffStarted); + yield* TestClock.adjust("30 seconds"); + yield* Fiber.join(again); + yield* read; + assert.strictEqual(diffs, 3); + + hang = false; + yield* writeTextFile(cwd, "feature.txt", "one\ntwo\n"); + yield* git(cwd, ["commit", "-am", "more"]); + const status = yield* read; + assert.strictEqual(diffs, 4, "a new HEAD diffs again within the backoff"); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "main", + insertions: 2, + deletions: 0, + }); + }), + ); }); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index da1794188b0b2..89bb1fa039ddd 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1736,6 +1736,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* readonly detail: string; } >(); + // Keyed by cwd: the HEAD and merge base whose totals diff failed, retried after a backoff. + const branchTotalsDiffFailures = new Map< + string, + { + readonly key: string; + readonly count: number; + readonly retryAt: number; + readonly detail: string; + } + >(); const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) => `${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`; const recordStatusRemoteRefreshFailure = Effect.fn( @@ -2484,6 +2494,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // and also for an unborn HEAD, which can still track a fetched upstream. let upstreamRefExists = false; let isUnbornHead = false; + let headOid: string | null = null; let aheadCount = 0; let behindCount = 0; let aheadOfDefaultCount = 0; @@ -2498,6 +2509,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* isUnbornHead = true; continue; } + if (line.startsWith("# branch.oid ")) { + headOid = line.slice("# branch.oid ".length).trim(); + continue; + } if (line.startsWith("# branch.head ")) { const value = line.slice("# branch.head ".length).trim(); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. @@ -2553,6 +2568,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? readBranchChangeTotals(repositoryPaths?.worktreeRoot ?? cwd, refName, { knownOriginDefaultBranch: defaultBranch, untrackedRoots, + headOid, }).pipe(Effect.orElseSucceed(() => undefined)) : Effect.undefined, ], @@ -3847,6 +3863,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* options?: { readonly knownOriginDefaultBranch: string | null; readonly untrackedRoots: ReadonlyArray; + readonly headOid: string | null; }, ) { const resolved = yield* resolveReviewMergeBase( @@ -3860,6 +3877,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch === null || (yield* branchExists(cwd, branch)) ? resolved : { baseRef: null, mergeBase: "HEAD" }; + // A moved HEAD or merge base skips the backoff and diffs again. + const diffKey = options?.headOid ? `${options.headOid}\0${mergeBase}` : null; + const diffFailure = branchTotalsDiffFailures.get(cwd); + if ( + diffFailure !== undefined && + diffFailure.key === diffKey && + (yield* Clock.currentTimeMillis) < diffFailure.retryAt + ) { + return yield* new GitCommandError({ + operation: "GitVcsDriver.readBranchChangeTotals", + command: "git diff --numstat", + cwd, + detail: diffFailure.detail, + }); + } const roots = options?.untrackedRoots ?? []; // Bound pathspec matching work and stay below Windows' command-line limit. const pathspecs = @@ -3921,7 +3953,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* env: untracked.env, }, ); - let result = yield* readNumstat(mergeBase); + let result = yield* readNumstat(mergeBase).pipe( + Effect.tapError((error) => + Effect.gen(function* () { + if (diffKey === null) return; + const count = diffFailure?.key === diffKey ? diffFailure.count + 1 : 1; + branchTotalsDiffFailures.delete(cwd); + branchTotalsDiffFailures.set(cwd, { + key: diffKey, + count, + retryAt: + (yield* Clock.currentTimeMillis) + + Math.min( + UNTRACKED_TOTALS_RETRY_MIN_MS * 2 ** (count - 1), + UNTRACKED_TOTALS_RETRY_MAX_MS, + ), + detail: error.detail, + }); + if (branchTotalsDiffFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) { + const oldestKey = branchTotalsDiffFailures.keys().next().value; + if (oldestKey !== undefined) branchTotalsDiffFailures.delete(oldestKey); + } + }), + ), + ); + branchTotalsDiffFailures.delete(cwd); if (result.exitCode !== 0 && mergeBase === "HEAD" && isUnbornHeadStderr(result.stderr)) { result = yield* readNumstat(yield* readEmptyTreeHash(cwd)); } diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 13ccf443fb108..8c42fcf52aabf 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -170,7 +170,7 @@ it.effect("fetches past a first page of Git-ignored results", () => ok: true as const, value: { isScanning: false }, }), - watch: () => ({ ok: true as const, value: () => undefined }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), fileSearchAsync: fileSearch, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -197,7 +197,7 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( ok: true as const, value: { isScanning: false }, }), - watch: () => ({ ok: true as const, value: () => undefined }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), fileSearchAsync: vi.fn(async () => ({ ok: true as const, value: { items, scores: [], totalMatched: 1, totalFiles: 1 }, @@ -264,7 +264,7 @@ it.effect("continues whole-word searches after a filtered grep page", () => ok: true as const, value: { isScanning: false }, }), - watch: () => ({ ok: true as const, value: () => undefined }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), grepAsync: grep, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -333,7 +333,7 @@ it.live("answers content searches with git grep while a slow content index build ok: true as const, value: { isScanning: false, isWarmupComplete }, }), - watch: () => ({ ok: true as const, value: () => undefined }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), grepAsync: grep, } as unknown as FileFinder; const noPcreFinder = { @@ -512,10 +512,14 @@ function fakeSymlinkFinder( ok: true as const, value: { isScanning: false }, }), - watch: (callback: (events: ReadonlyArray) => void) => { + // fff's watch waits on the picker lock on the JS thread. + watch: () => { + throw new Error("watch must not run on the JS thread"); + }, + watchAsync: async (callback: (events: ReadonlyArray) => void) => { if (watchFailures > 0) { watchFailures -= 1; - throw new Error("File system watcher is not ready"); + return { ok: false as const, error: "File system watcher is not ready" }; } watchers.push(callback); return { ok: true as const, value: () => undefined }; diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 858c420c72fb0..b33ceade77fa5 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1030,38 +1030,36 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( if (!editsOnly) invalidateSymlinkScan(); }; // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so - // each read retries until one is in place. + // each read retries until one is in place. Subscribing waits on fff's picker lock, which its + // watcher holds while it indexes a new folder, so it runs off the JS thread. let unwatch: WatchUnsubscribe | undefined; yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.())); - const ensureWatching = () => { + const ensureWatching = Effect.fn("WorkspaceSearchIndex.ensureWatching")(function* () { if (unwatch) return true; - try { - const result = finder.watch(onWatchBatch); - if (result.ok) unwatch = result.value; - } catch { - // Not ready yet; the next read tries again. - } + const result = yield* Effect.promise(() => + finder.watchAsync(onWatchBatch).catch(() => undefined), + ); + if (result?.ok) unwatch = result.value; return unwatch !== undefined; - }; + }); const indexScope = yield* Effect.scope; const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () { symlinkScanStale = false; - // Subscribing before the scan starts means no change during it goes unseen. - const watched = ensureWatching(); const done = yield* Deferred.make(); pendingSymlinkScan = done; - yield* scanSymlinkEntries().pipe( - Effect.tap((result) => - Effect.gen(function* () { - lastSymlinkScan = result; - knownLinkPaths = result.linkPaths; - // Without a watcher, or before fff has seen every folder, the result is kept only briefly. - lastSymlinkScanExpiresAt = - watched && result.indexComplete - ? undefined - : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS; - }), - ), + yield* Effect.gen(function* () { + // Subscribing before the scan starts means no change during it goes unseen. + const watched = yield* ensureWatching(); + const result = yield* scanSymlinkEntries(); + lastSymlinkScan = result; + knownLinkPaths = result.linkPaths; + // Without a watcher, or before fff has seen every folder, the result is kept only briefly. + lastSymlinkScanExpiresAt = + watched && result.indexComplete + ? undefined + : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS; + return result; + }).pipe( Effect.onExit((exit) => Effect.sync(() => { pendingSymlinkScan = undefined; diff --git a/packages/provider-fx/src/server/status.test.ts b/packages/provider-fx/src/server/status.test.ts index 3f9ae01ae969a..1fc41ccf03385 100644 --- a/packages/provider-fx/src/server/status.test.ts +++ b/packages/provider-fx/src/server/status.test.ts @@ -38,21 +38,27 @@ function processHandle(stdout: string, code: number, answered: Effect.Effect +const check = ( + statusJson: string, + versionDelay: Duration.Input = 0, + modelsJson: string = FX_MODELS_JSON, +) => Effect.gen(function* () { const outputs: Record = { "--version": "fx 0.0.13\n", "status --json": statusJson, - // `fx models --json` from fx 0.0.13, ids trimmed. - "models --json": JSON.stringify({ - kind: "models", - count: 2, - shown_count: 2, - more_count: 0, - private_models_hidden: false, - ids: ["anthropic/claude-sonnet-5.5", "anthropic/claude-opus-5.5"], - }), + "models --json": modelsJson, }; const invoked: Array = []; const spawner = ChildProcessSpawner.make((command) => { @@ -150,4 +156,20 @@ describe("checkFxProviderStatus", () => { assert.equal(unknown.draft.auth.status, "unknown"); }), ); + + // A ready snapshot drops models it does not list, so only a real listing may report ready. + it.effect("treats `fx models` output without ids as a failed listing", () => + Effect.gen(function* () { + const signedIn = JSON.stringify({ kind: "status", auth: "fx login" }); + const reshaped = yield* check(signedIn, 0, JSON.stringify({ kind: "models", models: [] })); + assert.equal(reshaped.draft.status, "warning"); + assert.deepEqual( + reshaped.draft.models.map((model) => model.slug), + ["default"], + ); + + const empty = yield* check(signedIn, 0, JSON.stringify({ kind: "models", ids: [] })); + assert.equal(empty.draft.status, "ready"); + }), + ); }); diff --git a/packages/provider-fx/src/server/status.ts b/packages/provider-fx/src/server/status.ts index 581b9549199e3..fb32eced1d190 100644 --- a/packages/provider-fx/src/server/status.ts +++ b/packages/provider-fx/src/server/status.ts @@ -131,9 +131,7 @@ const FxStatus = Schema.fromJsonString( }), ); const decodeFxStatus = Schema.decodeUnknownOption(FxStatus); -const FxModels = Schema.fromJsonString( - Schema.Struct({ ids: Schema.optional(Schema.Array(Schema.String)) }), -); +const FxModels = Schema.fromJsonString(Schema.Struct({ ids: Schema.Array(Schema.String) })); const decodeFxModels = Schema.decodeUnknownOption(FxModels); const VERSION_PROBE_TIMEOUT_MS = 10_000; @@ -203,7 +201,7 @@ export const checkFxProviderStatus = Effect.fn("checkFxProviderStatus")(function ); const status = Option.flatMap(yield* read(["status", "--json"]), decodeFxStatus); const listed = Option.flatMap(yield* read(["models", "--json"]), decodeFxModels).pipe( - Option.map((models) => models.ids?.flatMap((id) => nonEmptyTrimmed(id) ?? []) ?? []), + Option.map((models) => models.ids.flatMap((id) => nonEmptyTrimmed(id) ?? [])), ); const auth = fxAuth(Option.getOrUndefined(status)?.auth); const defaultModel = nonEmptyTrimmed(Option.getOrUndefined(status)?.model); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 8787495bb0e54..ae7aab45d5d6b 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -183,7 +183,7 @@ interface FakePi { /** T3 extension's service tier as each prompt was sent; Pi resets it with each session. */ readonly promptServiceTiers: ReadonlyArray; /** Pi reloads extensions without the adapter seeing it, e.g. a user extension's ctx.newSession(). */ - readonly reloadExtensions: () => void; + readonly reloadExtensions: (newSessionFile?: string) => void; /** Pi before 0.99 acknowledges prompts without a disposition. */ readonly omitPromptDisposition: () => void; readonly queueStats: (data: unknown) => void; @@ -433,8 +433,9 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { promptThinkingLevels, promptModels, promptServiceTiers, - reloadExtensions: () => { + reloadExtensions: (newSessionFile) => { serviceTier = null; + if (newSessionFile !== undefined) sessionFile = newSessionFile; }, omitPromptDisposition: () => { promptDisposition = false; @@ -2763,6 +2764,46 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("tracks the session file a user extension switches to during a turn", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + assert.equal(providerThread.nativeThreadRef?.nativeId, FAKE_SESSION_FILE); + const childFile = "/fake/extension-child.jsonl"; + + // An extension command such as /handoff calls ctx.newSession(); later prompts go to its file. + yield* startTurn(runtime, providerThread, "default", [], "/handoff", undefined, 1); + yield* fake.takeRequest("prompt"); + fake.reloadExtensions(childFile); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* takeEvent((event) => event.type === "turn.terminal"); + + yield* startTurn(runtime, providerThread, "default", [], "prompt B", undefined, 2); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "agent_settled" }); + const idle = yield* takeEvent( + (event) => + event.type === "provider_thread.updated" && event.providerThread.status === "idle", + ); + yield* takeEvent((event) => event.type === "turn.terminal"); + + // The persisted ref is what a later resume passes to switch_session. + assert.equal( + idle.type === "provider_thread.updated" + ? idle.providerThread.nativeThreadRef?.nativeId + : undefined, + childFile, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each([false, true, "previous"] as const)( "resets applied thinking when returning to Pi default (failed first restore: %s)", (failFirstRestore) => @@ -3174,6 +3215,7 @@ describe("PiAdapterV2", () => { const cases = [ { toolName: "read", + args: { path: "/workspace/screens/shot.png" }, result: { content, structuredContent: { ...image, note } }, expected: { content }, }, @@ -3230,6 +3272,7 @@ describe("PiAdapterV2", () => { type: `tool_execution_${phase}`, toolCallId: `image-${index}`, toolName: test.toolName, + ...("args" in test ? { args: test.args } : {}), ...(phase === "end" ? { result: test.result } : { partialResult: test.result }), isError: false, }); @@ -3247,7 +3290,10 @@ describe("PiAdapterV2", () => { ? [{ mimeType: "image/png", data: image.data }] : [], ); - if (index === 0) assert.equal(turnItemOutputText(event.turnItem), note); + if (index === 0) { + assert.equal(turnItemOutputText(event.turnItem), note); + assert.equal(event.turnItem.viewedImagePath, "/workspace/screens/shot.png"); + } if (index === 5) assert.equal(turnItemOutputText(event.turnItem), "first\nsecond"); if (index === 2) { assert.deepEqual(compactDynamicToolOutput(event.turnItem.output), { diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index ff7725191e621..626ddbd4ce5e9 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3,6 +3,7 @@ import * as NodeUtil from "node:util"; import { AgentScope } from "@t3tools/shared/AgentScope"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { readToolOutputImage } from "@t3tools/shared/toolOutput"; +import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; import * as Predicate from "effect/Predicate"; import { ProviderDriverKind, @@ -430,8 +431,14 @@ interface PiPromptSend { interface PiThreadState { providerThread: OrchestrationV2ProviderThread; activeTurn: ActivePiTurn | null; + /** Files an extension moved this thread off (ctx.newSession); queued turns may still name them. */ + readonly supersededSessionFiles: Set; } +const isLiveSessionOf = (state: PiThreadState, nativeId: string | null | undefined) => + nativeId === state.providerThread.nativeThreadRef?.nativeId || + (nativeId != null && state.supersededSessionFiles.has(nativeId)); + interface PiWake { readonly state: PiThreadState; readonly events: Array; @@ -1409,6 +1416,17 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } } const output = piToolOutput(resultRecord, toolName); + const readPath = + toolName === "read" + ? (recordString(args, "path") ?? recordString(args, "file_path"))?.trim() + : undefined; + const viewedImagePath = + readPath && + readPath.length <= 4096 && + !/[\r\n]/.test(readPath) && + isWorkspaceImagePreviewPath(readPath) + ? readPath + : undefined; yield* emit({ type: "turn_item.updated", driver: PI_PROVIDER, @@ -1420,6 +1438,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( toolName, input: args ?? {}, ...(output === undefined ? {} : { output }), + ...(viewedImagePath === undefined ? {} : { viewedImagePath }), }, }); if (toolName === "subagent") { @@ -2676,7 +2695,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( (recordNumber(data, "pendingMessageCount") ?? 0) === 0 ) { turn.settleWhenIdle = false; - if (state !== null) yield* finalizeTurn(state); + if (state === null) return; + // Extensions can move Pi to another session file (ctx.newSession); resume that one. + const sessionFile = recordString(data, "sessionFile"); + const previousFile = state.providerThread.nativeThreadRef?.nativeId; + if (sessionFile !== undefined && sessionFile !== previousFile) { + if (previousFile != null) state.supersededSessionFiles.add(previousFile); + state.supersededSessionFiles.delete(sessionFile); + state.providerThread = { + ...state.providerThread, + nativeThreadRef: providerRef(sessionFile), + }; + lastNativeThreadId = sessionFile; + } + yield* finalizeTurn(state); } return; } @@ -3007,7 +3039,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( "Cannot switch Pi threads while native work is awaiting a turn", ); } - threadState = { providerThread, activeTurn: null }; + threadState = { providerThread, activeTurn: null, supersededSessionFiles: new Set() }; } const baselineEntries = yield* request({ type: "get_entries" }).pipe( Effect.orElseSucceed(() => undefined), @@ -3224,10 +3256,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (pendingPromptResponsesDrained === null) break; yield* Deferred.await(pendingPromptResponsesDrained); } - if ( - state.providerThread.nativeThreadRef?.nativeId !== - turnInput.providerThread.nativeThreadRef?.nativeId - ) { + if (!isLiveSessionOf(state, turnInput.providerThread.nativeThreadRef?.nativeId)) { return yield* protocolError("Pi turn requested for a different native session"); } // Fork adoption uses the orchestrator-allocated row; preserve that identity in later updates. @@ -3310,8 +3339,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( closed || stopRequested || rollbackBarrier !== null || - state.providerThread.nativeThreadRef?.nativeId !== - turnInput.providerThread.nativeThreadRef?.nativeId + !isLiveSessionOf(state, turnInput.providerThread.nativeThreadRef?.nativeId) ) { return yield* protocolError("Pi turn ownership changed before it could start"); } @@ -3321,7 +3349,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return yield* protocolError("Pi native wake belongs to a different app thread"); } pendingWake = null; - state.providerThread = turnInput.providerThread; + state.providerThread = { + ...turnInput.providerThread, + nativeThreadRef: state.providerThread.nativeThreadRef, + }; state.activeTurn = activeTurn; activeTurn.adoptedWake = wake !== null && !continuation; if (compactCommand !== null) { diff --git a/patches/@ff-labs__fff-node@0.11.0.patch b/patches/@ff-labs__fff-node@0.11.0.patch index 198ac430e0d18..8e4cb2179d4c1 100644 --- a/patches/@ff-labs__fff-node@0.11.0.patch +++ b/patches/@ff-labs__fff-node@0.11.0.patch @@ -30,7 +30,7 @@ index 0f90eedca20655ccd30b8f28e433b2094341fbdf..c2ef86927d6e3ab0e8584330fa0ac3fd /** Total number of items (files + dirs) that matched */ totalMatched: number; diff --git a/dist/finder.d.ts b/dist/finder.d.ts -index 452102d720cc19b0560cfc9e2f1a320687047c92..490dba5277c8d751b53ed239c0ce77f3e11f9c43 100644 +index 452102d720cc19b0560cfc9e2f1a320687047c92..704b52c3d076c50c3bf15e96a574385c9862670c 100644 --- a/dist/finder.d.ts +++ b/dist/finder.d.ts @@ -242,6 +242,18 @@ export declare class FileFinder implements FileFinderApi { @@ -63,8 +63,17 @@ index 452102d720cc19b0560cfc9e2f1a320687047c92..490dba5277c8d751b53ed239c0ce77f3 /** * Wait for the initial file scan to complete. * Non-blocking: polls `isScanning` and yields to the event loop between checks. +@@ -360,6 +376,8 @@ export declare class FileFinder implements FileFinderApi { + */ + watch(callback: WatchBatchCallback, options?: WatchOptions): Result; + watch(pattern: string, callback: WatchBatchCallback, options?: WatchOptions): Result; ++ /** `watch(callback)` without blocking the JS thread. Patched in T3 Code. */ ++ watchAsync(callback: WatchBatchCallback, options?: WatchOptions): Promise>; + /** + * Get health check information. + * diff --git a/dist/index.js b/dist/index.js -index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414498bde57 100644 +index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..69bfa2cc9023103f52cc469bbec917eab68fa806 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,7 +1,7 @@ @@ -116,14 +125,14 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 const { rawPtr, struct: structData } = callRaw(funcName, paramsType, paramsValue); + return envelopeFromRaw(rawPtr, structData); +} -+async function readResultEnvelopeOnNativeThread(funcName, handle) { ++async function readResultEnvelopeOnNativeThread(funcName, paramsType, paramsValue) { + loadLibrary(); + const rawPtr = await load({ + library: LIBRARY_KEY, + funcName, + retType: DataType.External, -+ paramsType: [DataType.External], -+ paramsValue: [handle], ++ paramsType, ++ paramsValue, + freeResultMemory: false, + runInNewThread: true + }); @@ -137,7 +146,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 if (structData.success === 0) { const errorStr = readCString(structData.error); freeResult(rawPtr); -@@ -311,7 +342,9 @@ function readResultEnvelope(funcName, paramsType, paramsValue) { +@@ -311,13 +342,17 @@ function readResultEnvelope(funcName, paramsType, paramsValue) { return { rawPtr, struct: structData }; } function callVoidResult(funcName, paramsType, paramsValue) { @@ -148,7 +157,16 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 if ("ok" in res) return res; freeResult(res.rawPtr); return { ok: true, value: void 0 }; -@@ -417,18 +450,20 @@ function ffiCreate(basePath, frecencyDbPath, historyDbPath, _useUnsafeNoLock, en + } + function callIntResult(funcName, paramsType, paramsValue) { +- const res = readResultEnvelope(funcName, paramsType, paramsValue); ++ return intResultFromEnvelope(readResultEnvelope(funcName, paramsType, paramsValue)); ++} ++function intResultFromEnvelope(res) { + if ("ok" in res) return res; + const value = Number(res.struct.int_value); + freeResult(res.rawPtr); +@@ -417,18 +452,20 @@ function ffiCreate(basePath, frecencyDbPath, historyDbPath, _useUnsafeNoLock, en } function ffiDestroy(handle) { loadLibrary(); @@ -174,7 +192,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 size: DataType.U64, modified: DataType.U64, access_frecency_score: DataType.I64, -@@ -445,8 +480,9 @@ var FFF_SCORE_STRUCT = { +@@ -445,8 +482,9 @@ var FFF_SCORE_STRUCT = { distance_penalty: DataType.I32, current_file_penalty: DataType.I32, combo_match_boost: DataType.I32, @@ -185,7 +203,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 }; var FFF_SEARCH_RESULT_STRUCT = { items: DataType.External, -@@ -462,8 +498,8 @@ var FFF_SEARCH_RESULT_STRUCT = { +@@ -462,8 +500,8 @@ var FFF_SEARCH_RESULT_STRUCT = { location_end_col: DataType.I32 }; var FFF_DIR_ITEM_STRUCT = { @@ -196,7 +214,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 max_access_frecency: DataType.I32 }; var FFF_DIR_SEARCH_RESULT_STRUCT = { -@@ -475,9 +511,9 @@ var FFF_DIR_SEARCH_RESULT_STRUCT = { +@@ -475,9 +513,9 @@ var FFF_DIR_SEARCH_RESULT_STRUCT = { }; var FFF_MIXED_ITEM_STRUCT = { item_type: DataType.U8, @@ -209,7 +227,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 size: DataType.U64, modified: DataType.U64, access_frecency_score: DataType.I64, -@@ -500,10 +536,10 @@ var FFF_MIXED_SEARCH_RESULT_STRUCT = { +@@ -500,10 +538,10 @@ var FFF_MIXED_SEARCH_RESULT_STRUCT = { location_end_col: DataType.I32 }; var FFF_GREP_MATCH_STRUCT = { @@ -224,7 +242,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 match_ranges: DataType.External, context_before: DataType.External, context_after: DataType.External, -@@ -598,18 +634,13 @@ function readMixedItemFromRaw(raw) { +@@ -598,18 +636,13 @@ function readMixedItemFromRaw(raw) { } function callAccessor(funcName, resultPtr, index, structDef) { loadLibrary(); @@ -245,7 +263,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } function ptrOffset(base, bytes) { return load({ -@@ -766,6 +797,7 @@ function parseSearchResult(rawPtr) { +@@ -766,6 +799,7 @@ function parseSearchResult(rawPtr) { } const items = []; const scores = []; @@ -253,7 +271,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 for (let i = 0; i < count; i++) { const rawItem = callAccessor( "fff_search_result_get_item", -@@ -774,13 +806,15 @@ function parseSearchResult(rawPtr) { +@@ -774,13 +808,15 @@ function parseSearchResult(rawPtr) { FFF_FILE_ITEM_STRUCT ); items.push(readFileItemFromRaw(rawItem)); @@ -276,7 +294,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } load({ library: LIBRARY_KEY, -@@ -824,6 +858,7 @@ function parseDirSearchResult(rawPtr) { +@@ -824,6 +860,7 @@ function parseDirSearchResult(rawPtr) { const count = sr.count; const items = []; const scores = []; @@ -284,7 +302,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 for (let i = 0; i < count; i++) { const rawItem = callAccessor( "fff_dir_search_result_get_item", -@@ -832,13 +867,15 @@ function parseDirSearchResult(rawPtr) { +@@ -832,13 +869,15 @@ function parseDirSearchResult(rawPtr) { FFF_DIR_ITEM_STRUCT ); items.push(readDirItemFromRaw(rawItem)); @@ -307,7 +325,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } load({ library: LIBRARY_KEY, -@@ -897,6 +934,7 @@ function parseMixedSearchResult(rawPtr) { +@@ -897,6 +936,7 @@ function parseMixedSearchResult(rawPtr) { } const items = []; const scores = []; @@ -315,7 +333,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 for (let i = 0; i < count; i++) { const rawItem = callAccessor( "fff_mixed_search_result_get_item", -@@ -905,13 +943,15 @@ function parseMixedSearchResult(rawPtr) { +@@ -905,13 +945,15 @@ function parseMixedSearchResult(rawPtr) { FFF_MIXED_ITEM_STRUCT ); items.push(readMixedItemFromRaw(rawItem)); @@ -338,7 +356,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } load({ library: LIBRARY_KEY, -@@ -932,7 +972,7 @@ function parseMixedSearchResult(rawPtr) { +@@ -932,7 +974,7 @@ function parseMixedSearchResult(rawPtr) { } return { ok: true, value: result }; } @@ -347,7 +365,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 loadLibrary(); const rawPtr = load({ library: LIBRARY_KEY, -@@ -966,9 +1006,10 @@ function ffiSearch(handle, query, currentFile, maxThreads, pageIndex, pageSize, +@@ -966,9 +1008,10 @@ function ffiSearch(handle, query, currentFile, maxThreads, pageIndex, pageSize, comboBoostMultiplier, minComboCount ], @@ -360,7 +378,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } function ffiGlob(handle, pattern, currentFile, maxThreads, pageIndex, pageSize) { loadLibrary(); -@@ -995,7 +1036,7 @@ function ffiGlob(handle, pattern, currentFile, maxThreads, pageIndex, pageSize) +@@ -995,7 +1038,7 @@ function ffiGlob(handle, pattern, currentFile, maxThreads, pageIndex, pageSize) }); return parseSearchResult(rawPtr); } @@ -369,7 +387,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 loadLibrary(); const rawPtr = load({ library: LIBRARY_KEY, -@@ -1016,11 +1057,12 @@ function ffiSearchDirectories(handle, query, currentFile, maxThreads, pageIndex, +@@ -1016,11 +1059,12 @@ function ffiSearchDirectories(handle, query, currentFile, maxThreads, pageIndex, // page_size ], paramsValue: [handle, query, currentFile ?? "", maxThreads, pageIndex, pageSize], @@ -385,7 +403,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 loadLibrary(); const rawPtr = load({ library: LIBRARY_KEY, -@@ -1054,11 +1096,12 @@ function ffiSearchMixed(handle, query, currentFile, maxThreads, pageIndex, pageS +@@ -1054,11 +1098,12 @@ function ffiSearchMixed(handle, query, currentFile, maxThreads, pageIndex, pageS comboBoostMultiplier, minComboCount ], @@ -401,7 +419,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 loadLibrary(); const rawPtr = load({ library: LIBRARY_KEY, -@@ -1107,9 +1150,10 @@ function ffiLiveGrep(handle, query, mode, maxFileSize, maxMatchesPerFile, smartC +@@ -1107,9 +1152,10 @@ function ffiLiveGrep(handle, query, mode, maxFileSize, maxMatchesPerFile, smartC afterContext, classifyDefinitions ], @@ -414,7 +432,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 } function ffiMultiGrep(handle, patternsJoined, constraints, maxFileSize, maxMatchesPerFile, smartCase, fileOffset, pageLimit, timeBudgetMs, enforceTimeBudget, beforeContext, afterContext, classifyDefinitions) { loadLibrary(); -@@ -1188,7 +1232,11 @@ var FFF_SCAN_PROGRESS_STRUCT = { +@@ -1188,7 +1234,11 @@ var FFF_SCAN_PROGRESS_STRUCT = { }; function ffiGetScanProgress(handle) { loadLibrary(); @@ -427,7 +445,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 if ("ok" in res) return res; const handlePtr = res.struct.handle; freeResult(res.rawPtr); -@@ -1429,6 +1477,10 @@ var FileFinder = class _FileFinder { +@@ -1429,6 +1479,10 @@ var FileFinder = class _FileFinder { handle; /** Native ids of this instance's active watch subscriptions. */ watchers = /* @__PURE__ */ new Set(); @@ -438,7 +456,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 constructor(handle) { this.handle = handle; } -@@ -1485,12 +1537,115 @@ var FileFinder = class _FileFinder { +@@ -1485,11 +1539,147 @@ var FileFinder = class _FileFinder { destroy() { if (this.handle !== null) { const handle = this.handle; @@ -460,8 +478,8 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 + } else { + release(); + } - } - } ++ } ++ } + /** + * Patched in T3 Code: runs a handle-only call on a libuv pool thread so waiting on fff's + * picker lock never blocks the JS thread. Concurrent callers share one call, so one finder @@ -472,15 +490,16 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 + if (!guard.ok) return Promise.resolve(guard); + const pending = this.nativeThreadCalls.get(funcName); + if (pending) return pending; -+ const call = readResultEnvelopeOnNativeThread(funcName, guard.value).then(fromEnvelope, (cause) => err(String(cause))).finally(() => { ++ const call = readResultEnvelopeOnNativeThread(funcName, [DataType.External], [guard.value]).then(fromEnvelope, (cause) => err(String(cause))).finally(() => { + this.nativeThreadCalls.delete(funcName); + }); + this.nativeThreadCalls.set(funcName, call); + return call; + } + /** -+ * Patched in T3 Code: runs a search on a libuv pool thread. Searches on one finder run one at -+ * a time, so while fff's watcher holds the picker lock a finder holds at most one pool thread. ++ * Patched in T3 Code: runs a search or subscription on a libuv pool thread. They run one at a ++ * time per finder, so while fff's watcher holds the picker lock a finder holds at most one pool ++ * thread. + */ + searchOnNativeThread(search) { + const guard = this.ensureAlive(); @@ -535,6 +554,38 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 + true + )); + } ++ /** ++ * Patched in T3 Code: `watch` without blocking the JS thread. Subscribing takes the picker lock, ++ * which fff's watcher holds while it indexes a new directory. ++ */ ++ watchAsync(callback, options) { ++ if (typeof callback !== "function") { ++ return Promise.resolve(err("watch callback must be a function")); + } ++ const ignore = options?.ignore ?? []; ++ return this.searchOnNativeThread(async (handle) => { ++ const registered = ensureWatchCallbackRegistered(handle); ++ if (!registered.ok) return registered; ++ const created = intResultFromEnvelope(await readResultEnvelopeOnNativeThread( ++ "fff_watch_args", ++ [DataType.External, DataType.String, DataType.StringArray, DataType.U32], ++ [handle, "", ignore, ignore.length] ++ )); ++ if (!created.ok) return created; ++ // fff_destroy drops the native subscription of a finder destroyed meanwhile. ++ if (this.handle !== handle) return this.ensureAlive(); ++ const watchId = created.value; ++ watchHandlers.set(watchId, callback); ++ this.watchers.add(watchId); ++ return { ++ ok: true, ++ value: () => { ++ if (!this.watchers.delete(watchId)) return; ++ if (this.handle !== null) ffiUnwatch(this.handle, watchId); ++ } ++ }; ++ }); ++ } + /** Patched in T3 Code: `grep` without blocking the JS thread. */ + grepAsync(query, options) { + return this.searchOnNativeThread((handle) => ffiLiveGrep( @@ -553,11 +604,10 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 + options?.classifyDefinitions ?? false, + true + )); -+ } + } /** * Check if this instance has been destroyed. - */ -@@ -1757,6 +1912,18 @@ var FileFinder = class _FileFinder { +@@ -1757,6 +1947,18 @@ var FileFinder = class _FileFinder { if (!guard.ok) return guard; return ffiScanFiles(guard.value); } @@ -576,7 +626,7 @@ index 7c1d722eabc8d8eb98998eb48c5fe9d70b749d10..5d9fbf45095bd2b2ff1c321c03b85414 /** * Check if a scan is currently in progress. */ -@@ -1838,7 +2005,8 @@ var FileFinder = class _FileFinder { +@@ -1838,7 +2040,8 @@ var FileFinder = class _FileFinder { if (!guard.ok) return guard; const deadline = Date.now() + timeoutMs; while (true) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15b8786867bf7..22be5da14a34e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -369,7 +369,7 @@ patchedDependencies: '@effect/platform-node-shared@4.1.2': 06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14 '@effect/vitest@4.1.2': 299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f - '@ff-labs/fff-node@0.11.0': 3be7107340e5f388114da259637828cd47f2b32eb8ae572440715c4e38cffe6e + '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 '@legendapp/list@3.7.2': 3c68607b8bb7a531873bcbe0b197d163ef1fdb4d4cf52a4ddf9d2b3804671658 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': dd078a7448ce6727aaaa8b8b6702fe0ff02e85f18efa7c441a768530cabbe0cc @@ -862,7 +862,7 @@ importers: version: 4.1.2(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.3)(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 - version: 0.11.0(patch_hash=3be7107340e5f388114da259637828cd47f2b32eb8ae572440715c4e38cffe6e) + version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) '@muse-code/sdk': specifier: 1.4.6 version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4) @@ -15177,7 +15177,7 @@ snapshots: '@ff-labs/fff-bin-win32-x64@0.11.0': optional: true - '@ff-labs/fff-node@0.11.0(patch_hash=3be7107340e5f388114da259637828cd47f2b32eb8ae572440715c4e38cffe6e)': + '@ff-labs/fff-node@0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252)': dependencies: ffi-rs: 1.3.2 optionalDependencies: