diff --git a/README.md b/README.md index 14a37ca74579a..1596bd1fdcfee 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ This is a personal fork of [pingdotgg/t3code](https://github.com/pingdotgg/t3cod - **Snooze until it's done** — an "Until it's done" preset, offered while the agent is mid-turn or its subagents are still working, hides the thread until that work ends, including the agent's follow-up on the subagents' results. Watch loops such as a dev server don't hold it. The thread returns when the agent finishes, is interrupted, fails, or asks you something. Threads with queued messages can be snoozed too, and "Until it's done" covers the queued follow-ups as well. These rows sit at the top of the Snoozed section. Web, desktop, and mobile. On web and desktop, a thread that woke because its work ended shows a green Woke status; timer wakes stay orange. - **Working and Monitoring** — when a turn ends while work it started keeps running, the thread list on web, desktop, and mobile shows **Working** for live subagents and workflows and **Monitoring** when only watch loops such as a monitor, a pull request watch, or a command left running (a test run, a dev server) remain. -- **Pull request watches wake on merge** — upstream ends a `watch_pull_request` watch silently when the pull request merges and lets the thread settle at once. The fork wakes the agent once with the merge and the base branch, as it already did for a closed pull request, so an agent waiting on auto-merge can clean up. +- **Pull request watches hold until merge** — upstream lets a thread settle once a watched pull request's checks pass. In the fork, every `watch_pull_request` watch keeps the thread working until the pull request merges or closes, or the agent unwatches it. - **Conversation forking** — fork a whole conversation into a new thread from the thread menus, the chat header, the command palette, or mobile. Providers that can fork their native session, such as Claude, Codex, and OpenCode, keep the full history in the new thread; the others carry the conversation over as context. An imported Claude or Codex session can be forked right away; a thread carried over from before the v2 upgrade can be forked after its first new message. Forks are titled with a (🔱) prefix, keep that title when the first message is sent, and join the source thread's group. - **Two-pane split view** — web and desktop can show a second thread beside the routed one, including a thread from a different environment. Open it from the chat header button or the command palette's "Open thread in split view..." action. Hovering the divider reveals controls to swap the two threads (also `mod+shift+\`), switch the right pane's thread, and close the split. Sidebar clicks, sidebar thread shortcuts (next, previous, numbered jumps), palette picks, palette project results, and forks open into the active pane; a draft opened while the right pane is focused closes the split. The sidebar highlights both open threads, marks them with pane glyphs, and clears filters that would hide either one. `mod+\` jumps between panes, and window shortcuts act only on the active pane. Each pane's header keeps its own panel toggles, and `mod+w` with no panel tab open closes the active pane's thread, leaving the other one as the only pane; snoozing either thread, or archiving it yourself, does the same. The divider drags and remembers its position. Tag hiding applies to both open panes. - **Hideable panel toggles** — Settings → Extras → Panels can hide the terminal drawer and right panel toggles from the thread header, in single and split view, for keyboard-driven use; the header then stops reserving room for them and the shortcuts keep working. They show by default. diff --git a/apps/server/src/git/Utils.test.ts b/apps/server/src/git/Utils.test.ts index 8c8dc533a1ab3..b14f4c1b8841c 100644 --- a/apps/server/src/git/Utils.test.ts +++ b/apps/server/src/git/Utils.test.ts @@ -1,72 +1,6 @@ -// @effect-diagnostics nodeBuiltinImport:off import { expect, it } from "@effect/vitest"; -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import { - isSameDirectory, - readCheckedOutBranch, - readGitCommonDir, - sanitizeGitRepositoryEnvironment, -} from "./Utils.ts"; - -function makeTempDir(): string { - return NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-git-utils-")); -} - -it("reads the branch from a primary checkout", () => { - const root = makeTempDir(); - NodeFS.mkdirSync(NodePath.join(root, ".git")); - NodeFS.writeFileSync(NodePath.join(root, ".git", "HEAD"), "ref: refs/heads/dev\n"); - - expect(readCheckedOutBranch(root)).toBe("dev"); -}); - -it("follows a linked worktree's gitdir pointer to its own HEAD", () => { - const root = makeTempDir(); - const gitDir = NodePath.join(root, "repo.git", "worktrees", "feature"); - NodeFS.mkdirSync(gitDir, { recursive: true }); - NodeFS.writeFileSync(NodePath.join(gitDir, "HEAD"), "ref: refs/heads/fix/nested/name\n"); - - const worktree = NodePath.join(root, "worktree"); - NodeFS.mkdirSync(worktree); - NodeFS.writeFileSync(NodePath.join(worktree, ".git"), `gitdir: ${gitDir}\n`); - - expect(readCheckedOutBranch(worktree)).toBe("fix/nested/name"); -}); - -it("reports no branch for a detached HEAD, a non-repository, or a missing directory", () => { - const detached = makeTempDir(); - NodeFS.mkdirSync(NodePath.join(detached, ".git")); - NodeFS.writeFileSync( - NodePath.join(detached, ".git", "HEAD"), - "9fceb02f1a3b4c5d6e7f8091a2b3c4d5e6f70819\n", - ); - - expect(readCheckedOutBranch(detached)).toBeNull(); - expect(readCheckedOutBranch(makeTempDir())).toBeNull(); - expect(readCheckedOutBranch(NodePath.join(makeTempDir(), "absent"))).toBeNull(); -}); - -it("treats trailing separators and symlinked paths as the same directory", () => { - const root = makeTempDir(); - const target = NodePath.join(root, "target"); - NodeFS.mkdirSync(target); - const link = NodePath.join(root, "link"); - NodeFS.symlinkSync(target, link); - - expect(isSameDirectory(target, `${target}${NodePath.sep}`)).toBe(true); - expect(isSameDirectory(link, target)).toBe(true); - expect(isSameDirectory(target, NodePath.join(root, "other"))).toBe(false); -}); - -it("compares deleted directories textually", () => { - const removed = NodePath.join(makeTempDir(), "gone"); - - expect(isSameDirectory(removed, removed)).toBe(true); - expect(isSameDirectory(removed, `${removed}-other`)).toBe(false); -}); +import { sanitizeGitRepositoryEnvironment } from "./Utils.ts"; it("removes repository-scoping Git variables without dropping ordinary configuration", () => { expect( @@ -83,23 +17,3 @@ it("removes repository-scoping Git variables without dropping ordinary configura PATH: "/usr/bin", }); }); - -it("resolves a linked worktree and its primary checkout to the same repository", () => { - const root = makeTempDir(); - const repo = NodePath.join(root, "project"); - NodeFS.mkdirSync(NodePath.join(repo, ".git", "worktrees", "feature"), { recursive: true }); - - const worktree = NodePath.join(root, "feature"); - NodeFS.mkdirSync(worktree); - NodeFS.writeFileSync( - NodePath.join(worktree, ".git"), - `gitdir: ${NodePath.join(repo, ".git", "worktrees", "feature")}\n`, - ); - - const foreign = NodePath.join(root, "other-project"); - NodeFS.mkdirSync(NodePath.join(foreign, ".git"), { recursive: true }); - - expect(readGitCommonDir(worktree)).toBe(readGitCommonDir(repo)); - expect(readGitCommonDir(foreign)).not.toBe(readGitCommonDir(repo)); - expect(readGitCommonDir(makeTempDir())).toBeNull(); -}); diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index aeeb3e3a4dba5..e5487d588a415 100644 --- a/apps/server/src/git/Utils.ts +++ b/apps/server/src/git/Utils.ts @@ -1,85 +1,3 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodePath from "node:path"; - -/** - * Compare two directory paths for identity, resolving symlinks when both sides - * still exist. Falls back to a normalized textual comparison so a directory - * that has since been deleted can still be recognized. - */ -export function isSameDirectory(left: string, right: string): boolean { - if (NodePath.resolve(left) === NodePath.resolve(right)) return true; - return canonicalizeDirectory(left) === canonicalizeDirectory(right); -} - -/** - * Falls back to a normalized path when the directory cannot be resolved. Persisted worktree paths - * are compared with strict equality, so storing an alias (`/tmp` for `/private/tmp`, a symlinked - * parent) makes later comparisons miss. - */ -function canonicalizeDirectory(value: string): string { - try { - return NodeFS.realpathSync(value); - } catch { - return NodePath.resolve(value); - } -} - -/** - * The shared git directory backing `cwd`, or `null` when it is not a checkout. A linked - * worktree's `gitdir` sits under `/.git/worktrees/`, two levels below it. Checkouts - * of the same repository share this value, unlike unrelated clones. - */ -export function readGitCommonDir(cwd: string): string | null { - try { - const dotGit = NodePath.join(cwd, ".git"); - const stats = NodeFS.statSync(dotGit, { throwIfNoEntry: false }); - if (!stats) return null; - if (stats.isDirectory()) return canonicalizeDirectory(dotGit); - - const pointer = NodeFS.readFileSync(dotGit, "utf8").trim(); - const match = /^gitdir:\s*(.+)$/.exec(pointer); - if (!match?.[1]) return null; - const target = match[1].trim(); - const gitDir = NodePath.isAbsolute(target) ? target : NodePath.resolve(cwd, target); - const parent = NodePath.dirname(gitDir); - return NodePath.basename(parent) === "worktrees" - ? canonicalizeDirectory(NodePath.dirname(parent)) - : canonicalizeDirectory(gitDir); - } catch { - return null; - } -} - -/** - * Reads `HEAD` without shelling out; `.git` is a directory in a primary checkout and a `gitdir:` - * file in a linked worktree. Returns `null` for a detached HEAD, a non-repository, or any - * unparseable layout: callers treat it as "branch unknown", never an error. - */ -export function readCheckedOutBranch(cwd: string): string | null { - try { - const dotGit = NodePath.join(cwd, ".git"); - const stats = NodeFS.statSync(dotGit, { throwIfNoEntry: false }); - if (!stats) return null; - - let gitDir = dotGit; - if (!stats.isDirectory()) { - const pointer = NodeFS.readFileSync(dotGit, "utf8").trim(); - const match = /^gitdir:\s*(.+)$/.exec(pointer); - if (!match?.[1]) return null; - const target = match[1].trim(); - gitDir = NodePath.isAbsolute(target) ? target : NodePath.resolve(cwd, target); - } - - const head = NodeFS.readFileSync(NodePath.join(gitDir, "HEAD"), "utf8").trim(); - const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head); - const branch = ref?.[1]?.trim(); - return branch && branch.length > 0 ? branch : null; - } catch { - return null; - } -} - const REPOSITORY_SCOPING_GIT_ENVIRONMENT_KEYS = [ "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CEILING_DIRECTORIES", diff --git a/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.test.ts b/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.test.ts index 21b752a47ca1f..0c509aaf7e144 100644 --- a/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.test.ts +++ b/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.test.ts @@ -192,6 +192,21 @@ it.layer(TestLayer)("archive worktree removal", (it) => { }).pipe(Effect.scoped), ); + it.effect("removes a linked worktree whose .git git-annex replaced with a symlink", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const removal = yield* ArchiveWorktreeRemoval; + const { worktreePath } = yield* setup("feature/annexed"); + const adminDir = yield* git(worktreePath, ["rev-parse", "--absolute-git-dir"]); + yield* fs.remove(path.join(worktreePath, ".git")); + yield* fs.symlink(adminDir, path.join(worktreePath, ".git")); + assert.isNull(yield* removal.blocker(threadId)); + assert.isNull(yield* removal.remove({ threadId, worktreePath })); + assert.isFalse(yield* fs.exists(worktreePath)); + }).pipe(Effect.scoped), + ); + it.effect("keeps a dirty worktree, though a running turn may still clean it", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.ts b/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.ts index 2832bc3ea8095..557fce150076f 100644 --- a/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.ts +++ b/apps/server/src/orchestration-v2/ArchiveWorktreeRemoval.ts @@ -16,6 +16,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { mayBeSpLabWorktree } from "../labs/labWorktree.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import { isLinkedWorktree } from "../vcs/worktreeRemoval.ts"; import { canonicalWorkspacePath, reserveWorkspace, @@ -94,9 +95,9 @@ const make = Effect.gen(function* () { beforeArchive = false, ) { const root = yield* canonicalWorkspacePath(worktreePath); - // A linked worktree has a `.git` file; a main checkout has a directory. - const gitEntry = yield* fs.stat(path.join(root, ".git")).pipe(Effect.orElseSucceed(() => null)); - if (gitEntry?.type !== "File") return WORKTREE_KEPT_DETAIL.notWorktree; + if (!(yield* isLinkedWorktree(root).pipe(Effect.orElseSucceed(() => false)))) { + return WORKTREE_KEPT_DETAIL.notWorktree; + } if (yield* mayBeSpLabWorktree(fs, path, root)) return WORKTREE_KEPT_DETAIL.labWorktree; const projectShells = yield* projects.listShells(); for (const project of projectShells) { diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 464c9fcdb064c..7590ee3c11b3e 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -234,12 +234,6 @@ function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatc ); } -/** - * Wakes a thread's agent when a watched pull request finishes checks, gets someone else's comment, - * starts to conflict, or merges or closes without the agent's own command. A two-minute pass reads - * each moved pull request once per project. Settling or archiving the thread, or a merge or close, - * ends a watch; each end is logged once. - */ export class PullRequestWatchReactor extends Context.Service< PullRequestWatchReactor, { diff --git a/apps/server/src/orchestration-v2/SessionWorkspaceFollow.test.ts b/apps/server/src/orchestration-v2/SessionWorkspaceFollow.test.ts index 9caf2b9b55298..341986ba12b4d 100644 --- a/apps/server/src/orchestration-v2/SessionWorkspaceFollow.test.ts +++ b/apps/server/src/orchestration-v2/SessionWorkspaceFollow.test.ts @@ -29,7 +29,9 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as ServerConfig from "../config.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; @@ -383,6 +385,11 @@ it.live("a followed move keeps the session; a T3 move restarts it in the new wor ), ); +const platformLayer = GitVcsDriver.layer.pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-follow-config-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + const makeRepository = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -402,29 +409,47 @@ const makeRepository = Effect.gen(function* () { .pipe(Effect.flatMap((code) => (Number(code) === 0 ? Effect.void : Effect.die(args)))); const root = path.join(scratch, "repo"); const worktree = path.join(scratch, "repo-feature"); + const detached = path.join(scratch, "repo-detached"); + const annexed = path.join(scratch, "repo-annexed"); const other = path.join(scratch, "other"); yield* fileSystem.makeDirectory(path.join(root, "src"), { recursive: true }); yield* fileSystem.makeDirectory(other); yield* git(root, "init", "--quiet"); yield* git(root, "commit", "--allow-empty", "--quiet", "-m", "init"); yield* git(root, "worktree", "add", "--quiet", "-b", "feature", worktree); + yield* git(root, "worktree", "add", "--quiet", "--detach", detached); + yield* git(root, "worktree", "add", "--quiet", "-b", "annexed", annexed); + // git-annex replaces a linked worktree's `.git` file with a symlink to its admin directory. + yield* fileSystem.remove(path.join(annexed, ".git")); + yield* fileSystem.symlink( + path.join(root, ".git", "worktrees", "repo-annexed"), + path.join(annexed, ".git"), + ); yield* git(other, "init", "--quiet"); - return { scratch, root, worktree, other, path }; + return { scratch, root, worktree, detached, annexed, other, path }; }); it.effect("follows only into existing checkouts of the project's repository", () => Effect.gen(function* () { - const { scratch, root, worktree, other, path } = yield* makeRepository; + const { scratch, root, worktree, detached, annexed, other, path } = yield* makeRepository; const follow = (cwd: string) => resolveFollowedWorkspace({ workspaceRoot: root, cwd }); assert.deepEqual( yield* follow(worktree), Option.some({ worktreePath: worktree, branch: "feature" }), ); + assert.deepEqual( + yield* follow(detached), + Option.some({ worktreePath: detached, branch: null }), + ); + assert.deepEqual( + yield* follow(annexed), + Option.some({ worktreePath: annexed, branch: "annexed" }), + ); assert.deepEqual(yield* follow(root), Option.some({ worktreePath: null, branch: null })); assert.isTrue(Option.isNone(yield* follow(path.join(root, "src")))); assert.isTrue(Option.isNone(yield* follow(other))); assert.isTrue(Option.isNone(yield* follow(path.join(scratch, "removed")))); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + }).pipe(Effect.scoped, Effect.provide(platformLayer)), ); it.effect("follows only for the process that moved, while the thread is open", () => @@ -489,7 +514,7 @@ it.effect("follows only for the process that moved, while the thread is open", ( yield* plan({ thread: { ...thread, worktreePath: worktree, branch: "feature" } }), ), ); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + }).pipe(Effect.scoped, Effect.provide(platformLayer)), ); it.live("the follow worker moves the thread for the live process only", () => @@ -633,7 +658,7 @@ it.live("the follow worker moves the thread for the live process only", () => assert.deepEqual((yield* Ref.get(state)).openedCwds, [root]); }), - ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ).pipe(Effect.provide(platformLayer)), ); // Fork (DECISIONS 2.5 x 5.8): a completed agent-requested switch is a T3 move, @@ -807,5 +832,5 @@ it.live("a completed worktree switch restarts the session in the new worktree", assert.deepEqual(captured.openedCwds, [root, worktree]); assert.deepEqual(captured.startedCwds, [root, worktree]); }), - ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ).pipe(Effect.provide(platformLayer)), ); diff --git a/apps/server/src/orchestration-v2/SessionWorkspaceFollow.ts b/apps/server/src/orchestration-v2/SessionWorkspaceFollow.ts index 38b8658ecfea9..c95debc3f968b 100644 --- a/apps/server/src/orchestration-v2/SessionWorkspaceFollow.ts +++ b/apps/server/src/orchestration-v2/SessionWorkspaceFollow.ts @@ -13,6 +13,7 @@ import * as Path from "effect/Path"; import { isExistingDirectory } from "@t3tools/provider-core/server/pathExpansion"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { @@ -96,6 +97,7 @@ export const workerLive = Layer.effectDiscard( const ids = yield* IdAllocator.IdAllocatorV2; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; const follow = Effect.fn("SessionWorkspaceFollow.follow")(function* ( observation: ProviderSessionCwdObservation, @@ -116,6 +118,7 @@ export const workerLive = Layer.effectDiscard( }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), + Effect.provideService(GitVcsDriver.GitVcsDriver, git), ); if (Option.isNone(plan)) { yield* Effect.logDebug("orchestration-v2.session-workspace-follow.skipped", { diff --git a/apps/server/src/orchestration-v2/ThreadWorktreeSwitchScheduler.ts b/apps/server/src/orchestration-v2/ThreadWorktreeSwitchScheduler.ts index db62ce1cf3892..fdc6063249b56 100644 --- a/apps/server/src/orchestration-v2/ThreadWorktreeSwitchScheduler.ts +++ b/apps/server/src/orchestration-v2/ThreadWorktreeSwitchScheduler.ts @@ -24,6 +24,7 @@ import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; import { forkParked } from "../serverActivation.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { isThreadPayloadEvent } from "./DeferredArchive.ts"; import { evaluateWorktreeSwitch, pendingWorktreeSwitch } from "./DeferredWorktreeSwitch.ts"; @@ -84,10 +85,12 @@ export const make = Effect.gen(function* () { const random = yield* SecureRandom.SecureRandom; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; const providePlatform = (effect: Effect.Effect) => effect.pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), + Effect.provideService(GitVcsDriver.GitVcsDriver, git), ); const newCommandId = (prefix: string, threadId: ThreadId) => random diff --git a/apps/server/src/orchestration-v2/worktreeSwitch.ts b/apps/server/src/orchestration-v2/worktreeSwitch.ts index 1957e4e70cc5b..251a0f7e52ac2 100644 --- a/apps/server/src/orchestration-v2/worktreeSwitch.ts +++ b/apps/server/src/orchestration-v2/worktreeSwitch.ts @@ -2,7 +2,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import { readCheckedOutBranch, readGitCommonDir } from "../git/Utils.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; export class WorktreeSwitchError extends Schema.TaggedError()( "WorktreeSwitchError", @@ -16,6 +16,7 @@ export const resolveWorktreeSwitchTarget = Effect.fn("resolveWorktreeSwitchTarge ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; if (!path.isAbsolute(targetPath)) { return yield* new WorktreeSwitchError({ message: "Pass an absolute path to an existing worktree.", @@ -30,16 +31,39 @@ export const resolveWorktreeSwitchTarget = Effect.fn("resolveWorktreeSwitchTarge new WorktreeSwitchError({ message: "The project or target directory no longer exists." }), ), ); - const repository = readGitCommonDir(root); - if (repository === null || readGitCommonDir(target) !== repository) { + // Git ends each answer with one LF; anything before it, newlines included, is the path. + const run = (cwd: string, args: ReadonlyArray) => + git + .execute({ operation: "resolveWorktreeSwitchTarget", cwd, args, allowNonZeroExit: true }) + .pipe( + Effect.map((result) => + result.exitCode === 0 && result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : null, + ), + Effect.orElseSucceed(() => null), + ); + // Git resolves the common directory for every layout (git-annex symlinks `.git` to its admin + // directory); null unless `cwd`, a physical path, is a checkout's top level. + const commonDir = Effect.fn("resolveWorktreeSwitchTarget.commonDir")(function* (cwd: string) { + const [topLevel, gitCommonDir] = yield* Effect.all([ + run(cwd, ["rev-parse", "--show-toplevel"]), + run(cwd, ["rev-parse", "--git-common-dir"]), + ]); + if (!topLevel || !gitCommonDir) return null; + const canonical = (target: string) => + fs.realPath(path.resolve(cwd, target)).pipe(Effect.orElseSucceed(() => null)); + // Compare canonical forms: Git and Node may spell a case-insensitive path differently. + if ((yield* canonical(topLevel)) !== cwd) return null; + return yield* canonical(gitCommonDir); + }); + const [repository, targetRepository] = yield* Effect.all([commonDir(root), commonDir(target)]); + if (repository === null || targetRepository !== repository) { return yield* new WorktreeSwitchError({ message: "The target must be a checkout of this thread's repository, not a subdirectory or another clone.", }); } - return { - targetPath: target, - worktreePath: target === root ? null : target, - branch: target === root ? null : readCheckedOutBranch(target), - }; + if (target === root) return { targetPath: target, worktreePath: null, branch: null }; + const head = yield* run(target, ["symbolic-ref", "--quiet", "HEAD"]); + const branch = /^refs\/heads\/(.+)$/u.exec(head ?? "")?.[1] ?? null; + return { targetPath: target, worktreePath: target, branch }; }); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 0d582063958ac..89290d593e203 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2975,52 +2975,10 @@ describe("UsageService", () => { } }); yield* Effect.gen(function* () { - const { stateDir } = yield* ServerConfig.ServerConfig; - const mtimeMs = yield* Clock.currentTimeMillis; - const databasePath = yield* Effect.promise(() => NodeFSP.realpath(database)); - const saved = (id: string, sessionId: string): UsageRecord => ({ - provider: "opencode", - timestampMs: created, - model: "example-model", - sessionId, - totals: { - uncachedInputTokens: 10, - cachedInputTokens: 0, - cacheCreationTokens: 0, - outputTokens: 5, - reasoningTokens: 0, - }, - reportedCostUsd: null, - speed: "standard", - dedupeKey: `opencode:${id}`, - }); - // A cache saved before copies were recognized holds both rows. - const cache = makeScanCacheWriter()( - new Map([ - [ - databasePath, - { - size: 0, - mtimeMs, - provider: "opencode" as const, - records: [saved("original", "parent"), saved("copy", "fork")], - tailRecords: [], - malformedRecords: 0, - tailMalformedRecords: 0, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }, - ], - ]), - {}, - ); - yield* Effect.promise(async () => { - await NodeFSP.mkdir(stateDir, { recursive: true }); - await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache); - }); const service = yield* UsageService.make; assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 5); - // Deleting the parent removes the lineage, so the reader now returns the copy itself. + // The reader now returns the copy itself, under the key saved history holds for the original. yield* Effect.promise(async () => { const db = new NodeSqlite.DatabaseSync(database); try { diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 267cab593fd2c..2f4dc80b193c6 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -43,7 +43,6 @@ import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/ import type { ProviderUsageInstance, ProviderUsageScan, - ProviderUsageScanFile, TranscriptUsageFormat, UsageRecord, } from "@t3tools/provider-core/server/usage"; @@ -746,50 +745,23 @@ export const make = Effect.gen(function* () { /** * Merges a local scan source's read into the scan cache. Records it no longer returns stay - * until retention, unless the reader names them as copies or another session still returns - * the same request under a new key. These readers report read errors, not malformed counts. + * until retention; a reader keys copies like their originals (OpenCode keys forks by lineage). + * These readers report read errors, not malformed counts. */ const cacheReaderFiles = ( provider: UsageProviderKind, - files: readonly ProviderUsageScanFile[], + files: NonNullable, unreadable: boolean, retentionCutoffMs: number, ): ScannedFile[] => files.map((file) => { const cached = fileCache.get(file.path); - const superseded = new Set(file.supersededKeys); const keyOf = (record: UsageRecord) => record.dedupeKey ?? encodeUsageRecordKey(record); - // An OpenCode fork copies its parent's messages, data and creation time included, into its - // own session under new ids; once the parent is deleted the reader returns the copy instead. - const requestOf = (record: UsageRecord) => - encodeUsageRecordKey([ - record.timestampMs, - record.model, - record.rateModel, - record.totals, - record.cacheCreation1hTokens, - record.reportedCostUsd, - record.speed, - ]); - const returnedKeys = new Set(file.records.map(keyOf)); - const returnedSessions = new Map>(); - for (const record of file.records) { - if (record.dedupeKey === null) continue; - const request = requestOf(record); - const sessions = returnedSessions.get(request) ?? new Set(); - returnedSessions.set(request, sessions.add(record.sessionId)); - } const recordsByKey = new Map(); const expired = new Set(); for (const record of cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : []) { - if (record.dedupeKey !== null && superseded.has(record.dedupeKey)) continue; - const copiedSessions = - record.dedupeKey === null || returnedKeys.has(record.dedupeKey) - ? undefined - : returnedSessions.get(requestOf(record)); - if (copiedSessions !== undefined && !copiedSessions.has(record.sessionId)) continue; const key = keyOf(record); if (record.timestampMs < retentionCutoffMs) expired.add(key); recordsByKey.set(key, record); diff --git a/docs/user/usage.md b/docs/user/usage.md index ed96c0db06992..8067a3cb05e77 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -35,8 +35,10 @@ prunes older history on the next refresh, and raising it again does not bring pr While `settings.json` cannot be read, nothing is pruned. OpenCode reads its SQLite database and older JSON history. Antigravity reads local conversation -databases, including T3-managed profiles. These readers use the server’s environment, not individual account settings. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the -server to read a different data directory; comma-separated paths read multiple directories. +databases, including T3-managed profiles. These readers use the server’s environment and each +configured account's environment variables. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the +server or on an account to read a different data directory; comma-separated paths read multiple +directories. Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as `CURSOR_API_KEY`. This includes headless T3 sessions and desktop usage across machines; the same diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index 3d85aace3cb64..62613cab6b3a8 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -106,17 +106,12 @@ export interface ProviderUsageScan { readonly hostId?: string; readonly status?: UsageSource["status"]; readonly message?: string; - readonly files: readonly ProviderUsageScanFile[] | null; + readonly files: + | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[] + | null; readonly refreshing?: true; } -export interface ProviderUsageScanFile { - readonly path: string; - readonly records: readonly UsageRecord[]; - /** Keys of earlier records the reader now identifies as copies of another record. */ - readonly supersededKeys?: readonly string[]; -} - export interface ProviderUsageScanInput { readonly instances: ReadonlyArray>; readonly settings: ServerSettings; diff --git a/packages/provider-opencode/src/server/usage.test.ts b/packages/provider-opencode/src/server/usage.test.ts index df27a1f1ac3c2..85ee43661810e 100644 --- a/packages/provider-opencode/src/server/usage.test.ts +++ b/packages/provider-opencode/src/server/usage.test.ts @@ -398,8 +398,8 @@ describe("readOpenCodeUsage", () => { assert.deepStrictEqual( records.map((record) => [record.dedupeKey, record.sessionId]), [ - [`opencode:${openCodeForkSourceAssistantId}`, openCodeForkSourceSessionId], - ["opencode:msg_continuationassistant00001", openCodeForkContinuationSessionId], + [`opencode:${openCodeForkSourceSessionId}:2`, openCodeForkSourceSessionId], + [`opencode:${openCodeForkContinuationSessionId}:8`, openCodeForkContinuationSessionId], ], ); assert.deepStrictEqual(records[0]?.totals, { @@ -410,11 +410,6 @@ describe("readOpenCodeUsage", () => { reasoningTokens: 0, }); assert.strictEqual(records[0]?.reportedCostUsd, 0.01); - // Saved history may still hold the copies, so the scan names them. - assert.sameMembers( - result.files.flatMap((file) => file.supersededKeys ?? []), - ["opencode:msg_1607ab38e001GxURO0NU4GY4Az_2", "opencode:msg_1607b8a6d001MA7a5GgmyUywMf_2"], - ); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -444,17 +439,47 @@ describe("readOpenCodeUsage", () => { [source.id, fork.id, sibling.id], ); - // Deleting the source leaves the first fork holding the only copy. + // Deleting the source leaves the first fork holding the only copy, still keyed by lineage. yield* db.unsafe("DELETE FROM session_message WHERE session_id = ?", [source.id]); yield* db.unsafe("DELETE FROM session_v2 WHERE id = ?", [source.id]); const remaining = (yield* readOpenCodeUsage(dir, 0)).files.flatMap((file) => file.records); - assert.includeMembers( - remaining.map((record) => record.dedupeKey), - ["opencode:msg_1607ab38e001GxURO0NU4GY4Az_2", "opencode:msg_forkreply000000000000003"], + assert.deepStrictEqual( + remaining.map((record) => [record.dedupeKey, record.sessionId]), + [ + [`opencode:${source.id}:2`, fork.id], + [`opencode:${fork.id}:3`, fork.id], + [`opencode:${sibling.id}:3`, sibling.id], + ], ); - assert.notInclude( - remaining.map((record) => record.dedupeKey), - "opencode:msg_1607b8a6d001MA7a5GgmyUywMf_2", + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("counts a reply in both message tables once under its message id", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "usage-reader-test-" }); + const db = yield* openDatabase(path.join(dir, "opencode.db")); + const data = JSON.stringify({ + role: "assistant", + modelID: "big-pickle", + time: { created: 1780000000000 }, + tokens: { input: 100, output: 20, reasoning: 0, cache: { read: 0, write: 0 } }, + }); + yield* db.unsafe("CREATE TABLE message (id TEXT, session_id TEXT, data TEXT)"); + yield* db.unsafe( + "CREATE TABLE session_message (id TEXT, session_id TEXT, type TEXT, seq INTEGER, data TEXT)", + ); + yield* db.unsafe("INSERT INTO message VALUES ('msg-1', 'session-1', ?)", [data]); + yield* db.unsafe( + "INSERT INTO session_message VALUES ('msg-1', 'session-1', 'assistant', 1, ?)", + [data], + ); + + const records = (yield* readOpenCodeUsage(dir, 0)).files.flatMap((file) => file.records); + assert.deepStrictEqual( + records.map((record) => record.dedupeKey), + ["opencode:msg-1"], ); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -509,8 +534,8 @@ describe("readOpenCodeUsage", () => { assert.deepStrictEqual( records.map((record) => [record.dedupeKey, record.model, record.reportedCostUsd]), [ - ["opencode:assistant-1", "big-pickle", 0.02], - ["opencode:compaction-1", "big-pickle", 0.5], + ["opencode:session-1:2", "big-pickle", 0.02], + ["opencode:session-1:3", "big-pickle", 0.5], ], ); assert.deepStrictEqual(records[1]?.totals, { diff --git a/packages/provider-opencode/src/server/usage.ts b/packages/provider-opencode/src/server/usage.ts index 7309f97b58951..df65aa16068fa 100644 --- a/packages/provider-opencode/src/server/usage.ts +++ b/packages/provider-opencode/src/server/usage.ts @@ -2,7 +2,6 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import { totalTokens, type ProviderUsageReader, - type ProviderUsageScanFile, type UsageRecord, } from "@t3tools/provider-core/server/usage"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -89,14 +88,8 @@ function parseOpenCodeMessage( }; } -interface OpenCodeScanFile { - readonly path: string; - readonly records: UsageRecord[]; - supersededKeys?: string[]; -} - export interface OpenCodeUsageReadResult { - readonly files: readonly ProviderUsageScanFile[]; + readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]; readonly missing: boolean; readonly error: boolean; } @@ -140,7 +133,7 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( ): Effect.fn.Return { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const files: OpenCodeScanFile[] = []; + const files: { path: string; records: UsageRecord[] }[] = []; const seen = new Set(); let found = false; let error = false; @@ -183,7 +176,7 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( ); for (const name of databases) { found = true; - const file: OpenCodeScanFile = { path: path.join(root, name), records: [] }; + const file = { path: path.join(root, name), records: [] as UsageRecord[] }; files.push(file); // Taken before the snapshot opens, so a write that races the scan invalidates its rows. const [main, wal] = yield* Effect.forEach([file.path, `${file.path}-wal`], (target) => @@ -217,7 +210,8 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( .pipe(Effect.map((rows) => new Set(rows.map((row) => row.name)))); // A fork copies its parent's messages through the boundary under new ids, keeping // seq, creation time and data. Resolve each fork to its last copied seq so a copy - // names its original as (session, seq). A fork whose boundary is gone keeps its usage. + // names its original as (session, seq). Fork: a fork whose boundary is gone keeps its + // parent, so its copies keep the lineage keys saved history holds for the deleted originals. const forks = new Map< string, { readonly parent: string; readonly lastCopiedSeq: number; readonly created: number } @@ -242,16 +236,16 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( WHEN 'before' THEN copied.seq < boundary.seq END) AS last_copied_seq FROM session_v2 AS fork - JOIN session_message AS boundary + LEFT JOIN session_message AS boundary ON boundary.session_id = fork.fork_session_id AND boundary.id = json_extract(fork.fork_boundary, '$.messageID') WHERE fork.fork_session_id IS NOT NULL AND json_valid(fork.fork_boundary)`, ); for (const row of resolved) { - if (typeof row.last_copied_seq !== "number" || typeof row.created !== "number") continue; + if (typeof row.created !== "number") continue; forks.set(text(row.id), { parent: text(row.parent), - lastCopiedSeq: row.last_copied_seq, + lastCopiedSeq: typeof row.last_copied_seq === "number" ? row.last_copied_seq : Infinity, created: row.created, }); } @@ -278,8 +272,7 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( const columns = yield* columnsOf(table); const timestamp = columns.has("time_created") ? "time_created" : "NULL"; const updated = columns.has("time_updated") ? "time_updated" : "NULL"; - const lineage = - table === "session_message" && forks.size > 0 && columns.has("seq") ? "seq" : "NULL"; + const lineage = table === "session_message" && columns.has("seq") ? "seq" : "NULL"; // Without time_updated an in-place edit can keep the length, so any database write counts. const version = updated === "NULL" ? `${identity}/${stamp(wal!)}` : identity; // OpenCode 2 records a compaction request's spend on its compaction message. @@ -366,12 +359,16 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( const record = cached.get(row.row_id)!.record; if (record !== null && typeof row.seq === "number") { const copyOf = original(record.sessionId, row.seq, record.timestampMs); - if (originals.has(copyOf)) { - // Saved history from before copies were recognized may still hold this one. - if (record.dedupeKey !== null) (file.supersededKeys ??= []).push(record.dedupeKey); - continue; - } + if (originals.has(copyOf)) continue; originals.add(copyOf); + // Fork: keyed by lineage, so retained history meets a copy once its original is gone; + // a row already counted under its message id (migrated from `message`) stays counted once. + if (record.dedupeKey !== null) { + if (seen.has(record.dedupeKey)) continue; + seen.add(record.dedupeKey); + } + append(file.records, { ...record, dedupeKey: `opencode:${copyOf}` }); + continue; } append(file.records, record); } diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index 51a117aeda96b..58649888035ff 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -44,7 +44,6 @@ import { resolveMacPasskeySigningConfiguration, resolveMergedStageDependencies, resolveBuildOptions, - resolveDesktopBuildIconAssets, resolveDesktopProductName, stageWslRuntimeArchive, ancestorNodeModulesPaths, @@ -70,7 +69,6 @@ import { WSL_RUNTIME_ARCHIVE_NAME, wslRuntimeArchiveStem, } from "./build-desktop-artifact.ts"; -import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts"; import { ReleasePackageManifestError, releasePackageFiles, @@ -507,13 +505,8 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { }), ); - it("keeps Dev packaging on the release product name and artwork", () => { + it("keeps Dev packaging on the release product name", () => { assert.equal(resolveDesktopProductName("0.0.17", "dev"), "T3 Code (Dev)"); - assert.deepStrictEqual(resolveDesktopBuildIconAssets("0.0.17", "dev"), { - macIconPng: BRAND_ASSET_PATHS.productionMacIconPng, - linuxIconPng: BRAND_ASSET_PATHS.productionLinuxIconPng, - windowsIconIco: BRAND_ASSET_PATHS.productionWindowsIconIco, - }); }); it.effect("creates an isolated macOS dev package identity without an update feed", () => diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 97f556d5cc3bc..54086b4a51e58 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2792,10 +2792,7 @@ export function resolveDesktopWebAssetBrand(version: string): WebAssetBrand { return resolveWebAssetBrandForChannel(resolveDesktopUpdateChannel(version)); } -export function resolveDesktopBuildIconAssets( - version: string, - _flavor: typeof DesktopBuildFlavor.Type = "release", -): DesktopBuildIconAssets { +export function resolveDesktopBuildIconAssets(version: string): DesktopBuildIconAssets { if (resolveDesktopUpdateChannel(version) === "nightly") { return { macIconPng: BRAND_ASSET_PATHS.nightlyMacIconPng, @@ -3799,7 +3796,7 @@ const buildDesktopArtifactUnlocked = Effect.fn("buildDesktopArtifactUnlocked")(f const appVersion = options.version ?? resolveTaggedSourceVersion(repoRoot, serverPackageJson.version); - const iconAssets = resolveDesktopBuildIconAssets(appVersion, options.flavor); + const iconAssets = resolveDesktopBuildIconAssets(appVersion); const commitHash = yield* resolveGitCommitHash(repoRoot); const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped; const stageRoot = yield* mkdir({