Merge origin/main into t3code/effect-tracing-observability

Resolve startup and git observability conflicts while preserving mainline behavior.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-04-02 13:16:41 -07:00
commit 772ba77281
65 files changed
+6309 -1587

No files matched your search

@@ -289,9 +289,10 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
@@ -333,7 +334,9 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = orchestrationReactorLayer.pipe(
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
@@ -1,83 +1,38 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import {
ProjectionSnapshotQuery,
type ProjectionThreadCheckpointContext,
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
function makeSnapshot(input: {
function makeThreadCheckpointContext(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): OrchestrationReadModel {
}): ProjectionThreadCheckpointContext {
return {
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
threadId: input.threadId,
projectId: input.projectId,
workspaceRoot: input.workspaceRoot,
worktreePath: input.worktreePath,
checkpoints: [
{
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
};
@@ -95,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly cwd: string;
}> = [];
const snapshot = makeSnapshot({
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
@@ -125,7 +80,12 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(snapshot),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
}),
),
);
@@ -175,12 +135,11 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
);
@@ -4,11 +4,11 @@ import {
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import { Effect, Layer, Option, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import {
CheckpointDiffQuery,
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = thread.checkpoints.reduce(
const maxTurnCount = threadContext.value.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
});
}
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: thread.checkpoints.find(
: threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
});
}
const toCheckpointRef = thread.checkpoints.find(
const toCheckpointRef = threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
+289 -70
View File
@@ -59,6 +59,23 @@ function git(
});
}
function configureRemote(
cwd: string,
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
return yield* git(cwd, [
"config",
"--replace-all",
`remote.${remoteName}.fetch`,
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
]);
});
}
function runShellCommand(input: {
command: string;
cwd: string;
@@ -369,6 +386,36 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("paginates branch results and returns paging metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });
const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });
expect(firstPage.totalCount).toBe(4);
expect(firstPage.nextCursor).toBe(2);
expect(firstPage.branches.map((branch) => branch.name)).toEqual([
initialBranch,
"feature-a",
]);
const secondPage = yield* (yield* GitCore).listBranches({
cwd: tmp,
cursor: firstPage.nextCursor ?? 0,
limit: 2,
});
expect(secondPage.totalCount).toBe(4);
expect(secondPage.nextCursor).toBeNull();
expect(secondPage.branches.map((branch) => branch.name)).toEqual([
"feature-b",
"feature-c",
]);
}),
);
it.effect("parses separate branch names when column.ui is always enabled", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -514,6 +561,41 @@ it.layer(TestLayer)("git integration", (it) => {
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
it.effect(
"filters branch queries before pagination and dedupes origin refs with local matches",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
const result = yield* (yield* GitCore).listBranches({
cwd: tmp,
query: "feature/",
limit: 10,
});
expect(result.totalCount).toBe(2);
expect(result.nextCursor).toBeNull();
expect(result.branches.map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
}),
);
});
// ── checkoutGitBranch ──
@@ -587,7 +669,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("keeps checkout successful when upstream refresh fails", () =>
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -612,7 +694,7 @@ it.layer(TestLayer)("git integration", (it) => {
const realGitCore = yield* GitCore;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
refreshFetchAttempts += 1;
return Effect.fail(
new GitCommandError({
@@ -626,16 +708,15 @@ it.layer(TestLayer)("git integration", (it) => {
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(refreshFetchAttempts).toBe(1);
}),
);
const status = yield* core.statusDetails(source);
expect(refreshFetchAttempts).toBe(1);
expect(status.branch).toBe(featureBranch);
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
}),
);
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
it.effect("defers upstream refresh until statusDetails is requested", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -657,10 +738,10 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchArgs = [...input.args];
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
refreshFetchAttempts += 1;
return Effect.succeed({
code: 0,
stdout: "",
@@ -672,73 +753,137 @@ it.layer(TestLayer)("git integration", (it) => {
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchArgs).not.toBeNull();
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
expect(fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
expect(refreshFetchAttempts).toBe(0);
const status = yield* core.statusDetails(source);
expect(status.branch).toBe(featureBranch);
expect(refreshFetchAttempts).toBe(1);
}),
);
it.effect("returns checkout result before background upstream refresh completes", () =>
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature/background-refresh";
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchStarted = false;
let releaseFetch!: () => void;
const waitForReleasePromise = new Promise<void>((resolve) => {
releaseFetch = resolve;
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "fetch") {
fetchStarted = true;
return Effect.promise(() =>
waitForReleasePromise.then(() => ({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
})),
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
expect(input.cwd).toBe("/repo");
return ok();
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in shared refresh cache test.",
}),
);
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
);
}
return realGitCore.execute(input);
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchStarted).toBe(true);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
releaseFetch();
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
@@ -779,16 +924,21 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(source, remoteName, remote, remoteName);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
@@ -805,6 +955,34 @@ it.layer(TestLayer)("git integration", (it) => {
});
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchArgs = [...input.args];
return Effect.succeed({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
}
return realGitCore.execute(input);
});
const status = yield* core.statusDetails(source);
expect(status.branch).toBe("upstream/feature");
expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`);
expect(fetchArgs).toEqual([
"--git-dir",
path.join(source, ".git"),
"fetch",
"--quiet",
"--no-tags",
remoteName,
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
]);
}),
);
@@ -1691,6 +1869,47 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature/slash-remote-push";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(tmp, remoteName, remote, remoteName);
yield* git(tmp, ["push", "-u", remoteName, initialBranch]);
yield* git(tmp, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature base"]);
yield* git(tmp, ["push", "-u", remoteName, featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature update"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(false);
expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`${remoteName}/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+179 -89
View File
@@ -18,7 +18,8 @@ import {
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { compactTraceAttributes } from "../../observability/Attributes.ts";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
import {
@@ -29,6 +30,11 @@ import {
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
import {
parseRemoteNames,
parseRemoteNamesInGitOrder,
parseRemoteRefWithRemoteNames,
} from "../remoteRefs.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
@@ -43,8 +49,10 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
type TraceTailState = {
processedChars: number;
@@ -52,7 +60,7 @@ type TraceTailState = {
};
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
gitCommonDir: string;
upstreamRef: string;
remoteName: string;
upstreamBranch: string;
@@ -179,12 +187,38 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
function filterBranchesForListQuery(
branches: ReadonlyArray<GitBranch>,
query?: string,
): ReadonlyArray<GitBranch> {
if (!query) {
return branches;
}
const normalizedQuery = query.toLowerCase();
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
}
function paginateBranches(input: {
branches: ReadonlyArray<GitBranch>;
cursor?: number | undefined;
limit?: number | undefined;
}): {
branches: ReadonlyArray<GitBranch>;
nextCursor: number | null;
totalCount: number;
} {
const cursor = input.cursor ?? 0;
const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
const totalCount = input.branches.length;
const branches = input.branches.slice(cursor, cursor + limit);
const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null;
return {
branches,
nextCursor,
totalCount,
};
}
function sanitizeRemoteName(value: string): string {
@@ -219,30 +253,41 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
return remotes;
}
function parseRemoteRefWithRemoteNames(
branchName: string,
function parseUpstreamRefWithRemoteNames(
upstreamRef: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
if (!parsed) {
return null;
}
return null;
return {
upstreamRef,
remoteName: parsed.remoteName,
upstreamBranch: parsed.branchName,
};
}
function parseUpstreamRefByFirstSeparator(
upstreamRef: string,
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex).trim();
const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim();
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
}
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
@@ -835,45 +880,27 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return null;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNames),
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
);
return (
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
parseUpstreamRefByFirstSeparator(upstreamRef)
);
});
const fetchUpstreamRef = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
return runGit(
"GitCore.fetchUpstreamRef",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
true,
);
};
const fetchUpstreamRefForStatus = (
cwd: string,
gitCommonDir: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
"GitCore.fetchUpstreamRefForStatus",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
{
allowNonZeroExit: true,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -881,10 +908,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
).pipe(Effect.asVoid);
};
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
const gitCommonDir = yield* runGitStdout("GitCore.resolveGitCommonDir", cwd, [
"rev-parse",
"--git-common-dir",
]).pipe(Effect.map((stdout) => stdout.trim()));
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
cacheKey: StatusUpstreamRefreshCacheKey,
) {
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
upstreamRef: cacheKey.upstreamRef,
remoteName: cacheKey.remoteName,
upstreamBranch: cacheKey.upstreamBranch,
@@ -895,8 +930,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const statusUpstreamRefreshCache = yield* Cache.makeWith({
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: refreshStatusUpstreamCacheEntry,
// Keep successful refreshes warm; drop failures immediately so next request can retry.
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
? STATUS_UPSTREAM_REFRESH_INTERVAL
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
});
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
@@ -904,10 +942,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusUpstreamRefreshCache,
new StatusUpstreamRefreshCacheKey({
cwd,
gitCommonDir,
upstreamRef: upstream.upstreamRef,
remoteName: upstream.remoteName,
upstreamBranch: upstream.upstreamBranch,
@@ -915,14 +954,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
);
});
const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* (
cwd: string,
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
@@ -962,7 +993,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
Effect.map(parseRemoteNamesInGitOrder),
);
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
@@ -1149,15 +1180,52 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
],
{ concurrency: "unbounded" },
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
{
allowNonZeroExit: true,
},
);
if (statusResult.code !== 0) {
const stderr = statusResult.stderr.trim();
return yield* createGitCommandError(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
stderr || "git status failed",
);
}
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
"diff",
"--cached",
"--numstat",
]),
executeGit(
"GitCore.statusDetails.defaultRef",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
allowNonZeroExit: true,
},
),
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
],
{ concurrency: "unbounded" },
);
const statusStdout = statusResult.stdout;
const defaultBranch =
defaultRefResult.code === 0
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
@@ -1224,6 +1292,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
files.sort((a, b) => a.path.localeCompare(b.path));
return {
isRepo: true,
hasOriginRemote,
isDefaultBranch:
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master"))),
branch,
upstreamRef,
hasWorkingTreeChanges,
@@ -1241,6 +1315,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const status: GitCoreShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
isRepo: details.isRepo,
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
@@ -1619,7 +1696,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false, hasOriginRemote: false };
return {
branches: [],
isRepo: false,
hasOriginRemote: false,
nextCursor: null,
totalCount: 0,
};
}
return yield* createGitCommandError(
"GitCore.listBranches",
@@ -1783,9 +1866,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
})
: [];
const branches = [...localBranches, ...remoteBranches];
const branches = paginateBranches({
branches: filterBranchesForListQuery(
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
input.query,
),
cursor: input.cursor,
limit: input.limit,
});
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
return {
branches: [...branches.branches],
isRepo: true,
hasOriginRemote: remoteNames.includes("origin"),
nextCursor: branches.nextCursor,
totalCount: branches.totalCount,
};
});
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
@@ -1982,12 +2078,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
},
);
+1 -1
View File
@@ -187,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
+719 -26
View File
@@ -25,6 +25,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
interface FakeGhScenario {
prListSequence?: string[];
prListByHeadSelector?: Record<string, string>;
prListSequenceByHeadSelector?: Record<string, string[]>;
createdPrUrl?: string;
defaultBranch?: string;
pullRequest?: {
@@ -77,6 +78,72 @@ interface FakeGitTextGeneration {
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
function normalizeFakePullRequestSummary(raw: unknown): GitHubPullRequestSummary | null {
if (!raw || typeof raw !== "object") {
return null;
}
const record = raw as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
const headRepository =
typeof record.headRepository === "object" && record.headRepository !== null
? (record.headRepository as Record<string, unknown>)
: null;
const headRepositoryOwner =
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
? (record.headRepositoryOwner as Record<string, unknown>)
: null;
if (
typeof number !== "number" ||
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
return null;
}
const state =
typeof record.state === "string"
? record.state === "OPEN" || record.state === "open"
? "open"
: record.state === "CLOSED" || record.state === "closed"
? "closed"
: "merged"
: undefined;
const isCrossRepository =
typeof record.isCrossRepository === "boolean" ? record.isCrossRepository : undefined;
const headRepositoryNameWithOwner =
typeof record.headRepositoryNameWithOwner === "string"
? record.headRepositoryNameWithOwner
: typeof headRepository?.nameWithOwner === "string"
? headRepository.nameWithOwner
: undefined;
const headRepositoryOwnerLogin =
typeof record.headRepositoryOwnerLogin === "string"
? record.headRepositoryOwnerLogin
: typeof headRepositoryOwner?.login === "string"
? headRepositoryOwner.login
: undefined;
return {
number,
title,
url,
baseRefName,
headRefName,
...(state ? { state } : {}),
...(isCrossRepository !== undefined ? { isCrossRepository } : {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
const result = spawnSync("git", args, {
cwd,
@@ -159,6 +226,23 @@ function createBareRemote(): Effect.Effect<
});
}
function configureRemote(
cwd: string,
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
"config",
"--replace-all",
`remote.${remoteName}.fetch`,
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
]);
});
}
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: (input) =>
@@ -236,6 +320,12 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
ghCalls: string[];
} {
const prListQueue = [...(scenario.prListSequence ?? [])];
const prListQueueByHeadSelector = new Map(
Object.entries(scenario.prListSequenceByHeadSelector ?? {}).map(([headSelector, values]) => [
headSelector,
[...values],
]),
);
const ghCalls: string[] = [];
const execute: GitHubCliShape["execute"] = (input) => {
@@ -252,11 +342,15 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
headSelectorIndex >= 0 && headSelectorIndex < args.length - 1
? args[headSelectorIndex + 1]
: undefined;
const mappedQueue =
typeof headSelector === "string"
? prListQueueByHeadSelector.get(headSelector)?.shift()
: undefined;
const mappedStdout =
typeof headSelector === "string"
? scenario.prListByHeadSelector?.[headSelector]
: undefined;
const stdout = (mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
const stdout = (mappedQueue ?? mappedStdout ?? prListQueue.shift() ?? "[]") + "\n";
return Effect.succeed({
stdout,
stderr: "",
@@ -410,11 +504,14 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map(
(result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,
Effect.map((result) => JSON.parse(result.stdout) as unknown[]),
Effect.map((raw) =>
raw
.map((entry) => normalizeFakePullRequestSummary(entry))
.filter((entry): entry is GitHubPullRequestSummary => entry !== null),
),
),
createPullRequest: (input) =>
@@ -473,7 +570,7 @@ function runStackedAction(
manager: GitManagerShape,
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
action: "commit" | "push" | "create_pr" | "commit_push" | "commit_push_pr";
actionId?: string;
commitMessage?: string;
featureBranch?: boolean;
@@ -563,6 +660,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
@@ -575,6 +675,104 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status returns an explicit non-repo result for non-git directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
const { manager } = yield* makeManager();
const status = yield* manager.status({ cwd });
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
});
}),
);
it.effect("status briefly caches repeated lookups for the same cwd", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/status-cache"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-cache"]);
const existingPr = {
number: 113,
title: "Cached PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/113",
baseRefName: "main",
headRefName: "feature/status-cache",
};
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [JSON.stringify([existingPr]), JSON.stringify([existingPr])],
},
});
const first = yield* manager.status({ cwd: repoDir });
const second = yield* manager.status({ cwd: repoDir });
expect(first.pr?.number).toBe(113);
expect(second.pr?.number).toBe(113);
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(1);
}),
);
it.effect(
"status ignores unrelated fork PRs when the current branch tracks the same repository",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 1661,
title: "Fork PR from main",
url: "https://github.com/pingdotgg/t3code/pull/1661",
baseRefName: "main",
headRefName: "main",
state: "OPEN",
updatedAt: "2026-04-01T15:00:00Z",
isCrossRepository: true,
headRepository: {
nameWithOwner: "lnieuwenhuis/t3code",
},
headRepositoryOwner: {
login: "lnieuwenhuis",
},
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.pr).toBeNull();
}),
);
it.effect(
"status detects cross-repo PRs from the upstream remote URL owner",
() =>
@@ -610,6 +808,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
headRefName: "statemachine",
state: "OPEN",
updatedAt: "2026-03-10T07:00:00Z",
isCrossRepository: true,
headRepository: {
nameWithOwner: "jasonLaster/codething-mvp",
},
headRepositoryOwner: {
login: "jasonLaster",
},
},
]),
],
@@ -627,12 +832,120 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
state: "open",
});
expect(ghCalls).toContain(
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
);
}),
12_000,
);
it.effect(
"status ignores synthetic local branch aliases when the upstream remote name contains slashes",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const upstreamDir = yield* createBareRemote();
yield* configureRemote(repoDir, "origin", originDir, "origin");
yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream");
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"effect-atom": JSON.stringify([
{
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseRefName: "main",
headRefName: "effect-atom",
state: "OPEN",
updatedAt: "2026-03-01T10:00:00Z",
},
]),
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
"pingdotgg:effect-atom": JSON.stringify([]),
"my-org/upstream:effect-atom": JSON.stringify([]),
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
},
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseBranch: "main",
headBranch: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
false,
);
expect(
ghCalls.some((call) => call.includes("pr list --head pingdotgg:upstream/effect-atom ")),
).toBe(false);
expect(
ghCalls.some((call) =>
call.includes("pr list --head my-org/upstream:upstream/effect-atom "),
),
).toBe(false);
}),
12_000,
);
it.effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -758,6 +1071,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
expect(result.toast).toMatchObject({
description: "Implement stacked git actions",
cta: {
kind: "run_action",
label: "Push",
action: {
kind: "push",
},
},
});
expect(result.toast.title).toMatch(/^Committed [0-9a-f]{7}$/);
expect(
yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
Effect.map((result) => result.stdout.trim()),
@@ -867,6 +1191,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.toast).toMatchObject({
description: "Implement stacked git actions",
cta: {
kind: "run_action",
label: "Create PR",
action: {
kind: "create_pr",
},
},
});
expect(result.toast.title).toMatch(
/^Pushed [0-9a-f]{7} to origin\/feature\/implement-stacked-git-actions$/,
);
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
Effect.map((result) => result.stdout.trim()),
@@ -1063,6 +1400,80 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("pushes existing clean commits without rerunning commit logic", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/push-only"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-only.txt"), "push only\n");
yield* runGit(repoDir, ["add", "push-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push only branch"]);
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "push",
});
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("pushed");
expect(result.pr.status).toBe("skipped_not_requested");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toBe("origin/feature/push-only");
}),
);
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/create-pr-only"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "create-pr-only.txt"), "create pr\n");
yield* runGit(repoDir, ["add", "create-pr-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Create PR only branch"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 303,
title: "Create PR only branch",
url: "https://github.com/pingdotgg/codething-mvp/pull/303",
baseRefName: "main",
headRefName: "feature/create-pr-only",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "create_pr",
});
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(303);
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/create-pr-only"),
),
).toBe(true);
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1095,6 +1506,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(result.toast).toEqual({
title: "Opened PR #42",
description: "Existing PR",
cta: {
kind: "open_pr",
label: "View PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
},
});
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
}),
);
@@ -1126,6 +1546,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
},
]),
],
@@ -1149,6 +1577,98 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
12_000,
);
it.effect(
"returns the correct existing PR when a slash remote checks out to a synthetic local alias",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const upstreamDir = yield* createBareRemote();
yield* configureRemote(repoDir, "origin", originDir, "origin");
yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream");
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"effect-atom": JSON.stringify([
{
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseRefName: "main",
headRefName: "effect-atom",
},
]),
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
"pingdotgg:effect-atom": JSON.stringify([]),
"my-org/upstream:effect-atom": JSON.stringify([]),
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(1618);
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
false,
);
}),
12_000,
);
it.effect(
"prefers owner-qualified selectors before bare branch names for cross-repo PRs",
() =>
@@ -1187,6 +1707,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
},
]),
"fork-seed:statemachine": JSON.stringify([]),
@@ -1239,6 +1767,14 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
},
]),
"fork-seed:statemachine": JSON.stringify([]),
@@ -1256,9 +1792,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(142);
const prListCalls = ghCalls.filter((call) => call.startsWith("pr list "));
expect(prListCalls).toHaveLength(1);
expect(prListCalls[0]).toContain(
const openLookupCalls = ghCalls.filter((call) => call.includes("--state open --limit 1"));
expect(openLookupCalls).toHaveLength(1);
expect(openLookupCalls[0]).toContain(
"pr list --head octocat:statemachine --state open --limit 1",
);
}),
@@ -1302,6 +1838,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(result.branch.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
expect(
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
).toBe(true);
@@ -1309,6 +1846,78 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 1661,
title: "Fork PR with same branch name",
url: "https://github.com/pingdotgg/t3code/pull/1661",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "lnieuwenhuis/t3code",
},
headRepositoryOwner: {
login: "lnieuwenhuis",
},
},
]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: false,
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(188);
expect(result.toast).toEqual({
title: "Created PR #188",
description: "Add stacked git actions",
cta: {
kind: "open_pr",
label: "View PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
},
});
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-fork-match"),
),
).toBe(true);
}),
);
it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1330,23 +1939,30 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "statemachine",
},
]),
],
prListSequenceByHeadSelector: {
"octocat:statemachine": [
JSON.stringify([]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
},
]),
],
"fork-seed:statemachine": [JSON.stringify([])],
statemachine: [JSON.stringify([])],
},
},
});
@@ -2090,4 +2706,81 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
);
}),
);
it.effect("create_pr emits only the PR phase when the branch is already pushed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-only-follow-up"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "pr-only.txt"), "pr only\n");
yield* runGit(repoDir, ["add", "pr-only.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR only branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-only-follow-up"]);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([]),
JSON.stringify([
{
number: 201,
title: "PR only branch",
url: "https://github.com/pingdotgg/codething-mvp/pull/201",
baseRefName: "main",
headRefName: "feature/pr-only-follow-up",
state: "OPEN",
isCrossRepository: false,
},
]),
],
},
});
const events: GitActionProgressEvent[] = [];
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "create_pr",
},
{
actionId: "action-pr-only",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
);
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("created");
expect(
events.filter(
(event): event is Extract<GitActionProgressEvent, { kind: "phase_started" }> =>
event.kind === "phase_started",
),
).toEqual([
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Preparing PR...",
}),
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Generating PR content...",
}),
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
}),
]);
}),
);
});
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -56,7 +56,7 @@ export interface GitManagerShape {
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
+67
View File
@@ -0,0 +1,67 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
}
export function parseRemoteRefWithRemoteNames(
ref: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; branchName: string } | null {
const trimmedRef = ref.trim();
if (trimmedRef.length === 0) {
return null;
}
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedRef.startsWith(remotePrefix)) {
continue;
}
const branchName = trimmedRef.slice(remotePrefix.length).trim();
if (branchName.length === 0) {
return null;
}
return {
remoteRef: trimmedRef,
remoteName,
branchName,
};
}
return null;
}
export function extractBranchNameFromRemoteRef(
ref: string,
options?: {
remoteName?: string | null;
remoteNames?: ReadonlyArray<string>;
},
): string {
const normalized = ref.trim();
if (normalized.length === 0) {
return "";
}
if (normalized.startsWith("refs/remotes/")) {
return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options);
}
const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);
const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);
if (parsedRemoteRef) {
return parsedRemoteRef.branchName;
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
@@ -23,6 +23,7 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -249,6 +250,7 @@ describe("CheckpointReactor", () => {
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -8,7 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -21,11 +21,13 @@ import {
} from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -39,6 +41,7 @@ async function createOrchestrationSystem() {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -60,6 +63,105 @@ function now() {
}
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
append: () =>
Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append should not be called during bootstrap",
}),
),
readFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
new PersistenceSqlError({
operation: "test.readAll",
detail: "historical replay should not be used during bootstrap",
}),
),
};
const projectionSnapshot = {
snapshotSequence: 7,
updatedAt: "2026-03-03T00:00:04.000Z",
projects: [
{
id: asProjectId("project-bootstrap"),
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
createdAt: "2026-03-03T00:00:00.000Z",
updatedAt: "2026-03-03T00:00:01.000Z",
deletedAt: null,
},
],
threads: [
{
id: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
};
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(projectionSnapshot),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
Layer.succeed(OrchestrationProjectionPipeline, {
bootstrap: Effect.void,
projectEvent: () => Effect.void,
} satisfies OrchestrationProjectionPipelineShape),
),
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const readModel = await runtime.runPromise(engine.getReadModel());
expect(readModel.snapshotSequence).toBe(7);
expect(readModel.projects).toHaveLength(1);
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
expect(readModel.threads).toHaveLength(1);
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
await runtime.dispose();
});
it("returns deterministic read models for repeated reads", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
@@ -417,6 +519,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -512,6 +615,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -653,6 +757,7 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -24,6 +24,7 @@ import {
import { decideOrchestrationCommand } from "../decider.ts";
import { createEmptyReadModel, projectEvent } from "../projector.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -59,6 +60,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let readModel = createEmptyReadModel(new Date().toISOString());
@@ -217,13 +219,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
};
yield* projectionPipeline.bootstrap;
// bootstrap in-memory read model from event store
yield* Stream.runForEach(eventStore.readAll(), (event) =>
Effect.gen(function* () {
readModel = yield* projectEvent(readModel, event);
}),
);
readModel = yield* projectionSnapshotQuery.getSnapshot();
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
@@ -25,6 +25,7 @@ import {
ORCHESTRATION_PROJECTOR_NAMES,
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1841,6 +1842,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -623,24 +623,28 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
messageId: event.payload.messageId,
});
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
: existingMessage && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: previousMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
@@ -649,7 +653,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
@@ -338,4 +338,290 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-active',
'Active Project',
'/tmp/workspace',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-03-01T00:00:00.000Z',
'2026-03-01T00:00:01.000Z',
NULL
),
(
'project-deleted',
'Deleted Project',
'/tmp/deleted',
NULL,
'[]',
'2026-03-01T00:00:02.000Z',
'2026-03-01T00:00:03.000Z',
'2026-03-01T00:00:04.000Z'
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-first',
'project-active',
'First Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:05.000Z',
'2026-03-01T00:00:06.000Z',
NULL,
NULL
),
(
'thread-second',
'project-active',
'Second Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:07.000Z',
'2026-03-01T00:00:08.000Z',
NULL,
NULL
),
(
'thread-deleted',
'project-active',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:09.000Z',
'2026-03-01T00:00:10.000Z',
NULL,
'2026-03-01T00:00:11.000Z'
)
`;
const counts = yield* snapshotQuery.getCounts();
assert.deepEqual(counts, {
projectCount: 2,
threadCount: 3,
});
const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace");
assert.equal(project._tag, "Some");
if (project._tag === "Some") {
assert.equal(project.value.id, asProjectId("project-active"));
}
const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing");
assert.equal(missingProject._tag, "None");
const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId(
asProjectId("project-active"),
);
assert.equal(firstThreadId._tag, "Some");
if (firstThreadId._tag === "Some") {
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
}
}),
);
it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-context',
'Context Project',
'/tmp/context-workspace',
NULL,
'[]',
'2026-03-02T00:00:00.000Z',
'2026-03-02T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-context',
'project-context',
'Context Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
'feature/perf',
'/tmp/context-worktree',
NULL,
'2026-03-02T00:00:02.000Z',
'2026-03-02T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-context',
'turn-1',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
1,
'checkpoint-a',
'ready',
'[]'
),
(
'thread-context',
'turn-2',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
2,
'checkpoint-b',
'ready',
'[]'
)
`;
const context = yield* snapshotQuery.getThreadCheckpointContext(
ThreadId.makeUnsafe("thread-context"),
);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
threadId: ThreadId.makeUnsafe("thread-context"),
projectId: asProjectId("project-context"),
workspaceRoot: "/tmp/context-workspace",
worktreePath: "/tmp/context-worktree",
checkpoints: [
{
turnId: asTurnId("turn-1"),
checkpointTurnCount: 1,
checkpointRef: asCheckpointRef("checkpoint-a"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:04.000Z",
},
{
turnId: asTurnId("turn-2"),
checkpointTurnCount: 2,
checkpointRef: asCheckpointRef("checkpoint-b"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:05.000Z",
},
],
});
}
}),
);
});
@@ -7,7 +7,6 @@ import {
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -18,8 +17,10 @@ import {
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
@@ -40,6 +41,8 @@ import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.t
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
ProjectionSnapshotQuery,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
@@ -86,6 +89,29 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
threadCount: Schema.Number,
});
const WorkspaceRootLookupInput = Schema.Struct({
workspaceRoot: Schema.String,
});
const ProjectIdLookupInput = Schema.Struct({
projectId: ProjectId,
});
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
});
const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
});
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -319,6 +345,94 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const readProjectionCounts = SqlSchema.findOne({
Request: Schema.Void,
Result: ProjectionCountsRowSchema,
execute: () =>
sql`
SELECT
(SELECT COUNT(*) FROM projection_projects) AS "projectCount",
(SELECT COUNT(*) FROM projection_threads) AS "threadCount"
`,
});
const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({
Request: WorkspaceRootLookupInput,
Result: ProjectionProjectLookupRowSchema,
execute: ({ workspaceRoot }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
FROM projection_projects
WHERE workspace_root = ${workspaceRoot}
AND deleted_at IS NULL
ORDER BY created_at ASC, project_id ASC
LIMIT 1
`,
});
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
Request: ProjectIdLookupInput,
Result: ProjectionThreadIdLookupRowSchema,
execute: ({ projectId }) =>
sql`
SELECT
thread_id AS "threadId"
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
});
const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadCheckpointContextThreadRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
threads.thread_id AS "threadId",
threads.project_id AS "projectId",
projects.workspace_root AS "workspaceRoot",
threads.worktree_path AS "worktreePath"
FROM projection_threads AS threads
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
LIMIT 1
`,
});
const listCheckpointRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionCheckpointDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
checkpoint_turn_count AS "checkpointTurnCount",
checkpoint_ref AS "checkpointRef",
checkpoint_status AS "status",
checkpoint_files_json AS "files",
assistant_message_id AS "assistantMessageId",
completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
AND checkpoint_turn_count IS NOT NULL
ORDER BY checkpoint_turn_count ASC
`,
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql
.withTransaction(
@@ -593,8 +707,109 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
readProjectionCounts(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCounts:query",
"ProjectionSnapshotQuery.getCounts:decodeRow",
),
),
Effect.map(
(row): ProjectionSnapshotCounts => ({
projectCount: row.projectCount,
threadCount: row.threadCount,
}),
),
);
const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] =
(workspaceRoot) =>
getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query",
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",
),
),
Effect.map(
Option.map(
(row): OrchestrationProject => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
),
),
);
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
(projectId) =>
getFirstActiveThreadIdByProject({ projectId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query",
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow",
),
),
Effect.map(Option.map((row) => row.threadId)),
);
const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = (
threadId,
) =>
Effect.gen(function* () {
const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow",
),
),
);
if (Option.isNone(threadRow)) {
return Option.none<ProjectionThreadCheckpointContext>();
}
const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows",
),
),
);
return Option.some({
threadId: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceRoot: threadRow.value.workspaceRoot,
worktreePath: threadRow.value.worktreePath,
checkpoints: checkpointRows.map(
(row): OrchestrationCheckpointSummary => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
checkpointRef: row.checkpointRef,
status: row.status,
files: row.files,
assistantMessageId: row.assistantMessageId,
completedAt: row.completedAt,
}),
),
});
});
return {
getSnapshot,
getCounts,
getActiveProjectByWorkspaceRoot,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -30,6 +30,7 @@ import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -211,6 +212,7 @@ describe("ProviderCommandReactor", () => {
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -31,6 +31,7 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
@@ -197,6 +198,7 @@ describe("ProviderRuntimeIngestion", () => {
fs.mkdirSync(path.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -6,12 +6,32 @@
*
* @module ProjectionSnapshotQuery
*/
import type { OrchestrationReadModel } from "@t3tools/contracts";
import type {
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationReadModel,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
export interface ProjectionSnapshotCounts {
readonly projectCount: number;
readonly threadCount: number;
}
export interface ProjectionThreadCheckpointContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -23,6 +43,32 @@ export interface ProjectionSnapshotQueryShape {
* projector cursor state.
*/
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
/**
* Read aggregate projection counts without hydrating the full read model.
*/
readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;
/**
* Read the active project for an exact workspace root match.
*/
readonly getActiveProjectByWorkspaceRoot: (
workspaceRoot: string,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read the earliest active thread for a project.
*/
readonly getFirstActiveThreadIdByProjectId: (
projectId: ProjectId,
) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;
/**
* Read the checkpoint context needed to resolve a single thread diff.
*/
readonly getThreadCheckpointContext: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
}
/**
@@ -55,6 +55,13 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "updated");
assert.deepEqual(rowById.value.attachments, persistedAttachments);
}
}),
);
@@ -1,10 +1,11 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -19,6 +20,22 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
function toProjectionThreadMessage(
row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
): ProjectionThreadMessage {
return {
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
};
}
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -74,6 +91,27 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
},
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ messageId }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE message_id = ${messageId}
LIMIT 1
`,
});
const listProjectionThreadMessageRows = SqlSchema.findAll({
Request: ListProjectionThreadMessagesInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -109,24 +147,20 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadMessageRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) =>
rows.map((row) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
);
const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
@@ -138,6 +172,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
getByMessageId,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
@@ -31,6 +31,7 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -61,6 +62,7 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionSnapshotLookupIndexes", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,73 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("019_ProjectionSnapshotLookupIndexes", (it) => {
it.effect("creates indexes for targeted projection lookup filters", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 18 });
yield* runMigrations({ toMigrationInclusive: 19 });
const projectIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_projects)
`;
assert.ok(
projectIndexes.some(
(index) => index.name === "idx_projection_projects_workspace_root_deleted_at",
),
);
const projectIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at')
`;
assert.deepStrictEqual(
projectIndexColumns.map((column) => column.name),
["workspace_root", "deleted_at"],
);
const threadIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_threads)
`;
assert.ok(
threadIndexes.some(
(index) => index.name === "idx_projection_threads_project_deleted_created",
),
);
const threadIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_threads_project_deleted_created')
`;
assert.deepStrictEqual(
threadIndexColumns.map((column) => column.name),
["project_id", "deleted_at", "created_at"],
);
}),
);
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at
ON projection_projects(workspace_root, deleted_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created
ON projection_threads(project_id, deleted_at, created_at)
`;
});
@@ -8,13 +8,14 @@
*/
import {
ChatAttachment,
OrchestrationMessageRole,
MessageId,
OrchestrationMessageRole,
ThreadId,
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -37,6 +38,11 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
});
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
export const GetProjectionThreadMessageInput = Schema.Struct({
messageId: MessageId,
});
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
threadId: ThreadId,
});
@@ -55,6 +61,13 @@ export interface ProjectionThreadMessageRepositoryShape {
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Read a projected thread message by id.
*/
readonly getByMessageId: (
input: GetProjectionThreadMessageInput,
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* List projected thread messages for a thread.
*
+16
View File
@@ -831,6 +831,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
gitManager: {
status: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
@@ -851,6 +854,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
push: { status: "skipped_not_requested" as const },
pr: { status: "skipped_not_requested" as const },
toast: {
title: "Committed abc123",
description: "feat: demo",
cta: {
kind: "run_action" as const,
label: "Push",
action: {
kind: "push" as const,
},
},
},
};
yield* (
@@ -920,6 +934,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
],
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
}),
createWorktree: () =>
Effect.succeed({
+18 -6
View File
@@ -99,12 +99,24 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const OrchestrationLayerLive = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(OrchestrationEngineLive),
Layer.provideMerge(OrchestrationProjectionPipelineLive),
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
OrchestrationCommandReceiptRepositoryLive,
);
const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(
Layer.provide(OrchestrationEventStoreLive),
);
const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),
);
const CheckpointingLayerLive = Layer.empty.pipe(
+37 -4
View File
@@ -1,8 +1,13 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Fiber, Ref } from "effect";
import { TestClock } from "effect/testing";
import { Deferred, Effect, Fiber, Option, Ref } from "effect";
import { makeCommandGate, ServerRuntimeStartupError } from "./serverRuntimeStartup.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import {
launchStartupHeartbeat,
makeCommandGate,
ServerRuntimeStartupError,
} from "./serverRuntimeStartup.ts";
it.effect("enqueueCommand waits for readiness and then drains queued work", () =>
Effect.scoped(
@@ -14,7 +19,7 @@ it.effect("enqueueCommand waits for readiness and then drains queued work", () =
.enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1))
.pipe(Effect.forkScoped);
yield* TestClock.adjust("50 millis");
yield* Effect.yieldNow;
assert.equal(yield* Ref.get(executionCount), 0);
yield* commandGate.signalCommandReady;
@@ -47,3 +52,31 @@ it.effect("enqueueCommand fails queued work when readiness fails", () =>
}),
),
);
it.effect("launchStartupHeartbeat does not block the caller while counts are loading", () =>
Effect.scoped(
Effect.gen(function* () {
const releaseCounts = yield* Deferred.make<void, never>();
yield* launchStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
Effect.as({
projectCount: 2,
threadCount: 3,
}),
),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
Effect.provideService(AnalyticsService, {
record: () => Effect.void,
flush: Effect.void,
}),
);
}),
),
);
+36 -20
View File
@@ -5,7 +5,19 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Data, Deferred, Effect, Exit, Layer, Path, Queue, Ref, Scope, ServiceMap } from "effect";
import {
Data,
Deferred,
Effect,
Exit,
Layer,
Option,
Path,
Queue,
Ref,
Scope,
ServiceMap,
} from "effect";
import { ServerConfig } from "./config";
import { Keybindings } from "./keybindings";
@@ -105,17 +117,15 @@ export const makeCommandGate = Effect.gen(function* () {
} satisfies CommandGate;
});
const recordStartupHeartbeat = Effect.gen(function* () {
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.logWarning("failed to gather startup projection counts for telemetry", {
cause,
}).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
@@ -130,6 +140,14 @@ const recordStartupHeartbeat = Effect.gen(function* () {
});
});
export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
Effect.withSpan("server.startup.heartbeat.record"),
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
Effect.asVoid,
);
const autoBootstrapWelcome = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
@@ -141,14 +159,13 @@ const autoBootstrapWelcome = Effect.gen(function* () {
if (serverConfig.autoBootstrapProjectFromCwd) {
yield* Effect.gen(function* () {
const snapshot = yield* projectionReadModelQuery.getSnapshot();
const existingProject = snapshot.projects.find(
(project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null,
const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
serverConfig.cwd,
);
let nextProjectId: ProjectId;
let nextProjectDefaultModelSelection: ModelSelection;
if (!existingProject) {
if (Option.isNone(existingProject)) {
const createdAt = new Date().toISOString();
nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
@@ -166,17 +183,16 @@ const autoBootstrapWelcome = Effect.gen(function* () {
createdAt,
});
} else {
nextProjectId = existingProject.id;
nextProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
nextProjectId = existingProject.value.id;
nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? {
provider: "codex",
model: "gpt-5-codex",
};
}
const existingThread = snapshot.threads.find(
(thread) => thread.projectId === nextProjectId && thread.deletedAt === null,
);
if (!existingThread) {
const existingThreadId =
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
if (Option.isNone(existingThreadId)) {
const createdAt = new Date().toISOString();
const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID());
yield* orchestrationEngine.dispatch({
@@ -196,7 +212,7 @@ const autoBootstrapWelcome = Effect.gen(function* () {
bootstrapThreadId = createdThreadId;
} else {
bootstrapProjectId = nextProjectId;
bootstrapThreadId = existingThread.id;
bootstrapThreadId = existingThreadId.value;
}
});
}
@@ -343,7 +359,7 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
);
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* runStartupPhase("heartbeat.record", recordStartupHeartbeat);
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
yield* runStartupPhase("browser.open", maybeOpenBrowser);
yield* Effect.logDebug("startup phase: complete");
+4 -52
View File
@@ -1,5 +1,9 @@
import type { GitBranch } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "@t3tools/shared/git";
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
@@ -43,58 +47,6 @@ export function resolveBranchToolbarValue(input: {
return currentGitBranch ?? activeThreadBranch;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
if (branch.remoteName !== "origin") {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
@@ -1,5 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -15,7 +15,7 @@ import {
} from "react";
import {
gitBranchesQueryOptions,
gitBranchSearchInfiniteQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
@@ -23,7 +23,6 @@ import {
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveBranchSelectionTarget,
@@ -38,6 +37,7 @@ import {
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxStatus,
ComboboxTrigger,
} from "./ui/combobox";
import { toastManager } from "./ui/toast";
@@ -89,11 +89,33 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
useEffect(() => {
if (!branchCwd) return;
void queryClient.prefetchInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({ cwd: branchCwd, query: "" }),
);
}, [branchCwd, queryClient]);
const {
data: branchesSearchData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isPending: isBranchesSearchPending,
} = useInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
enabled: isBranchMenuOpen,
}),
);
const branches = useMemo(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
[branchesSearchData?.pages],
);
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
@@ -108,8 +130,6 @@ export function BranchToolbarBranchSelector({
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
[branches],
);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
const isSelectingWorktreeBase =
@@ -156,6 +176,14 @@ export function BranchToolbarBranchSelector({
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
? "Loading branches..."
: isFetchingNextPage
? "Loading more branches..."
: hasNextPage
? `Showing ${branches.length} of ${totalBranchCount} branches`
: null;
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
@@ -213,7 +241,7 @@ export function BranchToolbarBranchSelector({
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
const status = await api.git.status({ cwd: selectionTarget.checkoutCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
@@ -295,6 +323,24 @@ export function BranchToolbarBranchSelector({
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const maybeFetchNextBranchPage = useCallback(() => {
if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
return;
}
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement) {
return;
}
const distanceFromBottom =
scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
if (distanceFromBottom > 96) {
return;
}
void fetchNextPage().catch(() => undefined);
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: (index) =>
@@ -331,6 +377,35 @@ export function BranchToolbarBranchSelector({
shouldVirtualizeBranchList,
]);
useEffect(() => {
if (!isBranchMenuOpen) {
return;
}
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement || !isBranchMenuOpen) {
return;
}
const handleScroll = () => {
maybeFetchNextBranchPage();
};
scrollElement.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
return () => {
scrollElement.removeEventListener("scroll", handleScroll);
};
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
useEffect(() => {
maybeFetchNextBranchPage();
}, [branches.length, maybeFetchNextBranchPage]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
@@ -425,7 +500,7 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
>
<span className="max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon />
@@ -468,6 +543,7 @@ export function BranchToolbarBranchSelector({
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
)}
</ComboboxList>
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
);
@@ -632,6 +632,8 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [
{
name: "main",
@@ -644,6 +646,9 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: {
+3 -3
View File
@@ -26,7 +26,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { gitCreateWorktreeMutationOptions, gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -1201,7 +1201,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd));
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
@@ -1338,7 +1338,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}, [activeProjectCwd, activeThreadWorktreePath]);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
+3 -3
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -189,8 +189,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
const gitStatusQuery = useQuery(gitStatusQueryOptions(activeCwd ?? null));
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -0,0 +1,238 @@
import { ThreadId } from "@t3tools/contracts";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const THREAD_A = ThreadId.makeUnsafe("thread-a");
const THREAD_B = ThreadId.makeUnsafe("thread-b");
const GIT_CWD = "/repo/project";
const BRANCH_NAME = "feature/toast-scope";
const {
invalidateGitQueriesSpy,
invalidateGitStatusQuerySpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
toastCloseSpy,
toastPromiseSpy,
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
invalidateGitStatusQuerySpy: vi.fn(() => Promise.resolve()),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
toastCloseSpy: vi.fn(),
toastPromiseSpy: vi.fn(),
toastUpdateSpy: vi.fn(),
}));
vi.mock("@tanstack/react-query", async () => {
const actual =
await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
return {
...actual,
useIsMutating: vi.fn(() => 0),
useMutation: vi.fn((options: { __kind?: string }) => {
if (options.__kind === "run-stacked-action") {
return {
mutateAsync: runStackedActionMutateAsyncSpy,
isPending: false,
};
}
if (options.__kind === "pull") {
return {
mutateAsync: vi.fn(),
isPending: false,
};
}
return {
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
};
}),
useQuery: vi.fn((options: { queryKey?: string[] }) => {
if (options.queryKey?.[0] === "git-status") {
return {
data: {
branch: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
};
}
if (options.queryKey?.[0] === "git-branches") {
return {
data: {
isRepo: true,
hasOriginRemote: true,
branches: [
{
name: BRANCH_NAME,
current: true,
isDefault: false,
worktreePath: null,
},
],
},
error: null,
};
}
return { data: null, error: null };
}),
useQueryClient: vi.fn(() => ({})),
};
});
vi.mock("~/components/ui/toast", () => ({
toastManager: {
add: toastAddSpy,
close: toastCloseSpy,
promise: toastPromiseSpy,
update: toastUpdateSpy,
},
}));
vi.mock("~/editorPreferences", () => ({
openInPreferredEditor: vi.fn(),
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitBranchesQueryOptions: vi.fn(() => ({ queryKey: ["git-branches"] })),
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
runStackedAction: vi.fn(() => ["run-stacked-action"]),
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
gitStatusQueryOptions: vi.fn(() => ({ queryKey: ["git-status"] })),
invalidateGitQueries: invalidateGitQueriesSpy,
invalidateGitStatusQuery: invalidateGitStatusQuerySpy,
}));
vi.mock("~/lib/utils", async () => {
const actual = await vi.importActual<typeof import("~/lib/utils")>("~/lib/utils");
return {
...actual,
newCommandId: vi.fn(() => "command-1"),
randomUUID: vi.fn(() => "action-1"),
};
});
vi.mock("~/nativeApi", () => ({
readNativeApi: vi.fn(() => null),
}));
vi.mock("~/store", () => ({
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
threads: [
{ id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
{ id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
],
}),
}));
vi.mock("~/terminal-links", () => ({
resolvePathLinkTarget: vi.fn(),
}));
import GitActionsControl from "./GitActionsControl";
function findButtonByText(text: string): HTMLButtonElement | null {
return (Array.from(document.querySelectorAll("button")).find((button) =>
button.textContent?.includes(text),
) ?? null) as HTMLButtonElement | null;
}
function Harness() {
const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
return (
<>
<button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
Switch thread
</button>
<GitActionsControl gitCwd={GIT_CWD} activeThreadId={activeThreadId} />
</>
);
}
describe("GitActionsControl thread-scoped progress toast", () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
document.body.innerHTML = "";
});
it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
vi.useFakeTimers();
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<Harness />, { container: host });
try {
const quickActionButton = findButtonByText("Push & create PR");
expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy();
if (!(quickActionButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Push & create PR"');
}
quickActionButton.click();
expect(toastAddSpy).toHaveBeenCalledWith(
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
const switchThreadButton = findButtonByText("Switch thread");
expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
if (!(switchThreadButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Switch thread"');
}
switchThreadButton.click();
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
} finally {
await screen.unmount();
host.remove();
}
});
});
@@ -6,12 +6,16 @@ import {
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveLiveThreadBranchUpdate,
resolveQuickAction,
summarizeGitResult,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasWorkingTreeChanges: false,
workingTree: {
@@ -162,7 +166,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
}),
false,
);
assert.deepInclude(quick, { kind: "run_action", action: "commit_push", label: "Push" });
assert.deepInclude(quick, { kind: "run_action", action: "push", label: "Push" });
});
it("buildMenuItems enables push and keeps open PR available", () => {
@@ -213,7 +217,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
label: "Push & create PR",
});
});
@@ -585,7 +589,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
action: "push",
label: "Push",
disabled: false,
});
@@ -632,7 +636,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
label: "Push & create PR",
disabled: false,
});
@@ -801,9 +805,12 @@ describe("when: branch has no upstream configured", () => {
describe("requiresDefaultBranchConfirmation", () => {
it("requires confirmation for push actions on default branch", () => {
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
assert.isTrue(requiresDefaultBranchConfirmation("push", true));
assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
assert.isFalse(requiresDefaultBranchConfirmation("commit_push", false));
assert.isFalse(requiresDefaultBranchConfirmation("push", false));
});
});
@@ -855,26 +862,44 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
it("shows only push progress for explicit push actions", () => {
const stages = buildGitActionProgressStages({
action: "commit_push",
action: "push",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
hasWorkingTreeChanges: false,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
});
it("skips commit stages for create-pr flow when push-only is forced", () => {
it("shows push and PR progress for create-pr actions that still need a push", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
action: "create_pr",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: true,
forcePushOnly: true,
hasWorkingTreeChanges: false,
pushTarget: "origin/feature/test",
shouldPushBeforePr: true,
});
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
assert.deepEqual(stages, [
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("shows only PR progress when create-pr can skip the push", () => {
const stages = buildGitActionProgressStages({
action: "create_pr",
hasCustomCommitMessage: false,
hasWorkingTreeChanges: false,
shouldPushBeforePr: false,
});
assert.deepEqual(stages, [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("includes commit stages for commit+push when working tree is dirty", () => {
@@ -890,99 +915,110 @@ describe("buildGitActionProgressStages", () => {
"Pushing to origin/feature/test...",
]);
});
it("includes granular PR stages for commit+push+PR actions", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
hasCustomCommitMessage: true,
hasWorkingTreeChanges: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, [
"Committing...",
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
});
describe("summarizeGitResult", () => {
it("returns commit-focused toast for commit action", () => {
const result = summarizeGitResult({
action: "commit",
branch: { status: "skipped_not_requested" },
describe("resolveThreadBranchUpdate", () => {
it("returns a branch update when the action created a new branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push_pr",
branch: {
status: "created",
name: "feature/fix-toast-copy",
},
commit: {
status: "created",
commitSha: "0123456789abcdef",
subject: "feat: add optimistic UI for git action button",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "skipped_not_requested" },
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
toast: {
title: "Pushed 89abcde to origin/feature/fix-toast-copy",
cta: { kind: "none" },
},
});
assert.deepEqual(result, {
title: "Committed 0123456",
description: "feat: add optimistic UI for git action button",
assert.deepEqual(update, {
branch: "feature/fix-toast-copy",
});
});
it("returns push-focused toast for push action", () => {
const result = summarizeGitResult({
it("returns null when the action stayed on the existing branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push",
branch: { status: "skipped_not_requested" },
branch: {
status: "skipped_not_requested",
},
commit: {
status: "created",
commitSha: "abcdef0123456789",
subject: "fix: tighten quick action tooltip hover handling",
},
push: {
status: "pushed",
branch: "foo",
upstreamBranch: "origin/foo",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
toast: {
title: "Pushed 89abcde to origin/feature/fix-toast-copy",
cta: { kind: "none" },
},
});
assert.deepEqual(result, {
title: "Pushed abcdef0 to origin/foo",
description: "fix: tighten quick action tooltip hover handling",
assert.equal(update, null);
});
});
describe("resolveLiveThreadBranchUpdate", () => {
it("returns a branch update when live git status differs from stored thread metadata", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
gitStatus: status({ branch: "effect-atom" }),
});
assert.deepEqual(update, {
branch: "effect-atom",
});
});
it("returns PR-focused toast for created PR action", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: ship github shortcuts",
},
push: {
status: "pushed",
branch: "foo",
},
pr: {
status: "created",
number: 42,
title: "feat: ship github shortcuts and improve PR CTA in success toast",
},
it("returns null when live git status is unavailable", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
gitStatus: null,
});
assert.deepEqual(result, {
title: "Created PR #42",
description: "feat: ship github shortcuts and improve PR CTA in success toast",
});
assert.equal(update, null);
});
it("truncates long description text", () => {
const result = summarizeGitResult({
action: "commit_push_pr",
branch: { status: "skipped_not_requested" },
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "short subject",
},
push: { status: "pushed", branch: "foo" },
pr: {
status: "created",
number: 99,
title:
"feat: this title is intentionally extremely long so we can validate that toast descriptions are truncated with an ellipsis suffix",
},
it("returns null when the stored thread branch already matches git status", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: "effect-atom" }),
});
assert.deepEqual(result, {
title: "Created PR #99",
description: "feat: this title is intentionally extremely long so we can validate t...",
assert.equal(update, null);
});
it("returns null when git status is detached HEAD but the thread already has a branch", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: null }),
});
assert.equal(update, null);
});
});
@@ -31,83 +31,48 @@ export interface DefaultBranchActionDialogCopy {
continueLabel: string;
}
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
return sha.slice(0, SHORT_SHA_LENGTH);
}
function truncateText(
value: string | undefined,
maxLength = TOAST_DESCRIPTION_MAX,
): string | undefined {
if (!value) return undefined;
if (value.length <= maxLength) return value;
if (maxLength <= 3) return "...".slice(0, maxLength);
return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
}
export type DefaultBranchConfirmableAction =
| "push"
| "create_pr"
| "commit_push"
| "commit_push_pr";
export function buildGitActionProgressStages(input: {
action: GitStackedAction;
hasCustomCommitMessage: boolean;
hasWorkingTreeChanges: boolean;
forcePushOnly?: boolean;
pushTarget?: string;
featureBranch?: boolean;
shouldPushBeforePr?: boolean;
}): string[] {
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
const shouldIncludeCommitStages =
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
const prStages = [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
];
if (input.action === "push") {
return [pushStage];
}
if (input.action === "create_pr") {
return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages;
}
const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges;
const commitStages = !shouldIncludeCommitStages
? []
: input.hasCustomCommitMessage
? ["Committing..."]
: ["Generating commit message...", "Committing..."];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
if (input.action === "commit") {
return [...branchStages, ...commitStages];
}
if (input.action === "commit_push") {
return [...branchStages, ...commitStages, pushStage];
}
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
}
const withDescription = (title: string, description: string | undefined) =>
description ? { title, description } : { title };
export function summarizeGitResult(result: GitRunStackedActionResult): {
title: string;
description?: string;
} {
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
return withDescription(title, truncateText(result.pr.title));
}
if (result.push.status === "pushed") {
const shortSha = shortenSha(result.commit.commitSha);
const branch = result.push.upstreamBranch ?? result.push.branch;
const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
const branchPart = branch ? ` to ${branch}` : "";
return withDescription(
`Pushed${pushedCommitPart}${branchPart}`,
truncateText(result.commit.subject),
);
}
if (result.commit.status === "created") {
const shortSha = shortenSha(result.commit.commitSha);
const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
return withDescription(title, truncateText(result.commit.subject));
}
return { title: "Done" };
return [...branchStages, ...commitStages, pushStage, ...prStages];
}
export function buildMenuItems(
@@ -250,13 +215,18 @@ export function resolveQuickAction(
};
}
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
};
}
@@ -279,13 +249,18 @@ export function resolveQuickAction(
if (isAhead) {
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
action: "create_pr",
};
}
@@ -306,7 +281,12 @@ export function requiresDefaultBranchConfirmation(
isDefaultBranch: boolean,
): boolean {
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
return (
action === "push" ||
action === "create_pr" ||
action === "commit_push" ||
action === "commit_push_pr"
);
}
export function resolveDefaultBranchActionDialogCopy(input: {
@@ -317,7 +297,7 @@ export function resolveDefaultBranchActionDialogCopy(input: {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
if (input.action === "commit_push") {
if (input.action === "push" || input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
@@ -346,5 +326,38 @@ export function resolveDefaultBranchActionDialogCopy(input: {
};
}
export function resolveThreadBranchUpdate(
result: GitRunStackedActionResult,
): { branch: string } | null {
if (result.branch.status !== "created" || !result.branch.name) {
return null;
}
return {
branch: result.branch.name,
};
}
export function resolveLiveThreadBranchUpdate(input: {
threadBranch: string | null;
gitStatus: GitStatusResult | null;
}): { branch: string | null } | null {
if (!input.gitStatus) {
return null;
}
if (input.gitStatus.branch === null && input.threadBranch !== null) {
return null;
}
if (input.threadBranch === input.gitStatus.branch) {
return null;
}
return {
branch: input.gitStatus.branch,
};
}
// Re-export from shared for backwards compatibility in this module's exports
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
+175 -157
View File
@@ -1,5 +1,6 @@
import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
ThreadId,
@@ -17,8 +18,9 @@ import {
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveDefaultBranchActionDialogCopy,
resolveLiveThreadBranchUpdate,
resolveQuickAction,
summarizeGitResult,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
@@ -36,20 +38,20 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import { toastManager, type ThreadToastData } from "~/components/ui/toast";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
invalidateGitStatusQuery,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
import { useStore } from "~/store";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -61,7 +63,6 @@ interface PendingDefaultBranchAction {
branchName: string;
includesCommit: boolean;
commitMessage?: string;
forcePushOnlyProgress: boolean;
onConfirmed?: () => void;
filePaths?: string[];
}
@@ -70,6 +71,7 @@ type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
toastId: GitActionToastId;
toastData: ThreadToastData | undefined;
actionId: string;
title: string;
phaseStartedAtMs: number | null;
@@ -82,12 +84,10 @@ interface ActiveGitActionProgress {
interface RunGitActionWithToastInput {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
featureBranch?: boolean;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
}
@@ -196,7 +196,9 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
if (quickAction.action === "push" || quickAction.action === "commit_push") {
return <CloudUploadIcon className={iconClassName} />;
}
return <GitHubIcon className={iconClassName} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
@@ -208,6 +210,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const activeServerThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -216,6 +222,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
const updateActiveProgressToast = useCallback(() => {
const progress = activeGitActionProgressRef.current;
@@ -227,26 +234,52 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progress.title,
description: resolveProgressDescription(progress),
timeout: 0,
data: threadToastData,
data: progress.toastData,
});
}, [threadToastData]);
}, []);
const persistThreadBranchSync = useCallback(
(branch: string | null) => {
if (!activeThreadId || !activeServerThread || activeServerThread.branch === branch) {
return;
}
const worktreePath = activeServerThread.worktreePath;
const api = readNativeApi();
if (api) {
void api.orchestration
.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch,
worktreePath,
})
.catch(() => undefined);
}
setThreadBranch(activeThreadId, branch, worktreePath);
},
[activeServerThread, activeThreadId, setThreadBranch],
);
const syncThreadBranchAfterGitAction = useCallback(
(result: GitRunStackedActionResult) => {
const branchUpdate = resolveThreadBranchUpdate(result);
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch);
},
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
const gitStatusForActions = gitStatus;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
@@ -267,12 +300,31 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
useEffect(() => {
if (isGitActionRunning) {
return;
}
const branchUpdate = resolveLiveThreadBranchUpdate({
threadBranch: activeServerThread?.branch ?? null,
gitStatus: gitStatusForActions,
});
if (!branchUpdate) {
return;
}
persistThreadBranchSync(branchUpdate.branch);
}, [
activeServerThread?.branch,
gitStatusForActions,
isGitActionRunning,
persistThreadBranchSync,
]);
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
return gitStatusForActions?.isDefaultBranch ?? false;
}, [gitStatusForActions?.isDefaultBranch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
@@ -336,31 +388,36 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}, [gitStatusForActions, threadToastData]);
const runGitActionWithToast = useEffectEvent(
runGitActionWithToast = useEffectEvent(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
featureBranch = false,
isDefaultBranchOverride,
progressToastId,
filePaths,
}: RunGitActionWithToastInput) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch =
isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
const actionCanCommit =
action === "commit" || action === "commit_push" || action === "commit_push_pr";
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
actionCanCommit &&
(action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (action !== "commit_push" && action !== "commit_push_pr") {
if (
action !== "push" &&
action !== "create_pr" &&
action !== "commit_push" &&
action !== "commit_push_pr"
) {
return;
}
setPendingDefaultBranchAction({
@@ -368,7 +425,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
});
@@ -380,9 +436,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
featureBranch,
shouldPushBeforePr:
action === "create_pr" &&
(!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
});
const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
const actionId = randomUUID();
const resolvedProgressToastId =
progressToastId ??
@@ -391,11 +450,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
activeGitActionProgressRef.current = {
toastId: resolvedProgressToastId,
toastData: scopedToastData,
actionId,
title: progressStages[0] ?? "Running git action...",
phaseStartedAtMs: null,
@@ -411,7 +471,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
}
@@ -483,124 +543,97 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
try {
const result = await promise;
activeGitActionProgressRef.current = null;
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =
actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
(!actionIsDefaultBranch ||
result.pr.status === "created" ||
result.pr.status === "opened_existing");
const shouldOfferCreatePrCta =
action === "commit_push" &&
!prUrl &&
result.push.status === "pushed" &&
!actionIsDefaultBranch;
syncThreadBranchAfterGitAction(result);
const closeResultToast = () => {
toastManager.close(resolvedProgressToastId);
};
toastManager.update(resolvedProgressToastId, {
const toastCta = result.toast.cta;
let toastActionProps: {
children: string;
onClick: () => void;
} | null = null;
if (toastCta.kind === "run_action") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: toastCta.action.kind,
});
},
};
} else if (toastCta.kind === "open_pr") {
toastActionProps = {
children: toastCta.label,
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(toastCta.url);
},
};
}
const successToastBase = {
type: "success",
title: resultToast.title,
description: resultToast.description,
title: result.toast.title,
description: result.toast.description,
timeout: 0,
data: {
...threadToastData,
...scopedToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta
? {
actionProps: {
children: "Push",
onClick: () => {
void runGitActionWithToast({
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "View PR",
onClick: () => {
const api = readNativeApi();
if (!api) return;
closeResultToast();
void api.shell.openExternal(prUrl);
},
},
}
: shouldOfferCreatePrCta
? {
actionProps: {
children: "Create PR",
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: "commit_push_pr",
forcePushOnlyProgress: true,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
}
: {}),
});
} as const;
if (toastActionProps) {
toastManager.update(resolvedProgressToastId, {
...successToastBase,
actionProps: toastActionProps,
});
} else {
toastManager.update(resolvedProgressToastId, successToastBase);
}
} catch (err) {
activeGitActionProgressRef.current = null;
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
data: scopedToastData,
});
}
},
);
const continuePendingDefaultBranchAction = useCallback(() => {
const continuePendingDefaultBranchAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
const checkoutFeatureBranchAndContinuePendingAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
pendingDefaultBranchAction;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const runDialogActionOnNewBranch = useCallback(() => {
const runDialogActionOnNewBranch = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
@@ -616,9 +649,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
};
const runQuickAction = useCallback(() => {
const runQuickAction = () => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
return;
@@ -656,31 +689,28 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
};
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "commit_push_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
},
[openExistingPr, setIsCommitDialogOpen],
);
const openDialogForMenuItem = (item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "create_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
};
const runDialogAction = useCallback(() => {
const runDialogAction = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
@@ -692,14 +722,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
});
}, [
allSelected,
dialogCommitMessage,
isCommitDialogOpen,
selectedFiles,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
};
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -778,7 +801,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
if (open) void invalidateGitStatusQuery(queryClient, gitCwd);
}}
>
<MenuTrigger
@@ -842,11 +865,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
@@ -157,11 +157,16 @@ function resolveWsRpc(tag: string): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
+88 -53
View File
@@ -11,6 +11,7 @@ import {
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
@@ -45,10 +46,12 @@ describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
@@ -164,6 +167,68 @@ describe("resolveSidebarNewThreadEnvMode", () => {
});
});
describe("resolveSidebarNewThreadSeedContext", () => {
it("inherits the active server thread context when creating a new thread in the same project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
branch: "effect-atom",
worktreePath: null,
envMode: "local",
});
});
it("prefers the active draft thread context when it matches the target project", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-1",
defaultEnvMode: "local",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: {
projectId: "project-1",
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
},
}),
).toEqual({
branch: "feature/new-draft",
worktreePath: "/repo/worktree",
envMode: "worktree",
});
});
it("falls back to the default env mode when there is no matching active thread context", () => {
expect(
resolveSidebarNewThreadSeedContext({
projectId: "project-2",
defaultEnvMode: "worktree",
activeThread: {
projectId: "project-1",
branch: "effect-atom",
worktreePath: null,
},
activeDraftThread: null,
}),
).toEqual({
envMode: "worktree",
});
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
@@ -259,17 +324,14 @@ describe("getVisibleSidebarThreadIds", () => {
expect(
getVisibleSidebarThreadIds([
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
{ id: ThreadId.makeUnsafe("thread-10") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-12"),
ThreadId.makeUnsafe("thread-11"),
ThreadId.makeUnsafe("thread-10"),
],
},
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-8") },
{ id: ThreadId.makeUnsafe("thread-6") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-8"), ThreadId.makeUnsafe("thread-6")],
},
]),
).toEqual([
@@ -286,17 +348,14 @@ describe("getVisibleSidebarThreadIds", () => {
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-hidden-2"),
ThreadId.makeUnsafe("thread-hidden-1"),
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
@@ -337,10 +396,12 @@ describe("isContextMenuPointerDown", () => {
describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
@@ -353,9 +414,11 @@ describe("resolveThreadStatusPill", () => {
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
@@ -363,9 +426,10 @@ describe("resolveThreadStatusPill", () => {
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
@@ -374,8 +438,6 @@ describe("resolveThreadStatusPill", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
@@ -385,26 +447,14 @@ describe("resolveThreadStatusPill", () => {
resolveThreadStatusPill({
thread: {
...baseThread,
hasActionableProposedPlan: true,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: null,
implementationThreadId: null,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
@@ -415,25 +465,12 @@ describe("resolveThreadStatusPill", () => {
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: "2026-03-09T10:06:00.000Z",
implementationThreadId: "thread-implement" as never,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
@@ -452,8 +489,6 @@ describe("resolveThreadStatusPill", () => {
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
+56 -23
View File
@@ -1,12 +1,8 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import type { SidebarThreadSummary, Thread } from "../types";
import { cn } from "../lib/utils";
import {
findLatestProposedPlan,
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
import { isLatestTurnSettled } from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
@@ -47,8 +43,13 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
};
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
SidebarThreadSummary,
| "hasActionableProposedPlan"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "interactionMode"
| "latestTurn"
| "session"
> & {
lastVisitedAt?: string | undefined;
};
@@ -161,6 +162,46 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function resolveSidebarNewThreadSeedContext(input: {
projectId: string;
defaultEnvMode: SidebarNewThreadEnvMode;
activeThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
} | null;
activeDraftThread?: {
projectId: string;
branch: string | null;
worktreePath: string | null;
envMode: SidebarNewThreadEnvMode;
} | null;
}): {
branch?: string | null;
worktreePath?: string | null;
envMode: SidebarNewThreadEnvMode;
} {
if (input.activeDraftThread?.projectId === input.projectId) {
return {
branch: input.activeDraftThread.branch,
worktreePath: input.activeDraftThread.worktreePath,
envMode: input.activeDraftThread.envMode,
};
}
if (input.activeThread?.projectId === input.projectId) {
return {
branch: input.activeThread.branch,
worktreePath: input.activeThread.worktreePath,
envMode: input.activeThread.worktreePath ? "worktree" : "local",
};
}
return {
envMode: input.defaultEnvMode,
};
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
@@ -192,15 +233,11 @@ export function orderItemsByPreferredIds<TItem, TId>(input: {
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
renderedThreadIds: readonly TThreadId[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
);
}
@@ -273,12 +310,10 @@ export function resolveThreadRowClassName(input: {
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
const { thread } = input;
if (hasPendingApprovals) {
if (thread.hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
@@ -287,7 +322,7 @@ export function resolveThreadStatusPill(input: {
};
}
if (hasPendingUserInput) {
if (thread.hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
@@ -315,12 +350,10 @@ export function resolveThreadStatusPill(input: {
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
!thread.hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
hasActionableProposedPlan(
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
);
thread.hasActionableProposedPlan;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,116 @@
import { TurnId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { ChangedFilesTree } from "./ChangedFilesTree";
describe("ChangedFilesTree", () => {
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src"],
hiddenLabels: ["index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: ["apps/server/src"],
hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: ["README.md", "packages"],
hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"],
},
])(
"renders $name collapsed on the first render when collapse-all is active",
({ files, visibleLabels, hiddenLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded={false}
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
for (const label of hiddenLabels) {
expect(markup).not.toContain(label);
}
},
);
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src", "index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: [
"apps/server/src",
"git/Layers",
"provider/Layers",
"GitCore.ts",
"CodexAdapter.ts",
],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: [
"README.md",
"packages",
"shared/src",
"contracts/src",
"git.ts",
"orchestration.ts",
],
},
])(
"renders $name expanded on the first render when expand-all is active",
({ files, visibleLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
},
);
});
@@ -1,5 +1,5 @@
import { type TurnId } from "@t3tools/contracts";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useMemo, useState } from "react";
import { type TurnDiffFileChange } from "../../types";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
@@ -7,6 +7,8 @@ import { cn } from "~/lib/utils";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
@@ -20,32 +22,39 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
() => collectDirectoryPaths(treeNodes).join("\u0000"),
[treeNodes],
);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(() =>
buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
const [directoryExpansionState, setDirectoryExpansionState] = useState<{
key: string;
overrides: Record<string, boolean>;
}>(() => ({
key: expansionStateKey,
overrides: {},
}));
const expandedDirectories =
directoryExpansionState.key === expansionStateKey
? directoryExpansionState.overrides
: EMPTY_DIRECTORY_OVERRIDES;
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const toggleDirectory = useCallback(
(pathValue: string) => {
setDirectoryExpansionState((current) => {
const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
return {
key: expansionStateKey,
overrides: {
...nextOverrides,
[pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
},
};
});
},
[allDirectoriesExpanded, expansionStateKey],
);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
return (
<div key={`dir:${node.path}`}>
<button
@@ -53,7 +62,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
onClick={() => toggleDirectory(node.path)}
>
<ChevronRightIcon
aria-hidden="true"
@@ -124,14 +133,3 @@ function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[]
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
@@ -1,3 +1,11 @@
import { type MessageId } from "@t3tools/contracts";
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { estimateTimelineMessageHeight } from "../timelineHeight";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -5,6 +13,29 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
export type MessagesTimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: ChatMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: ProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
export function computeMessageDurationStart(
messages: ReadonlyArray<TimelineDurationMessage>,
): Map<string, string> {
@@ -27,3 +58,142 @@ export function computeMessageDurationStart(
export function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
isWorking: boolean;
activeTurnStartedAt: string | null;
}): MessagesTimelineRow[] {
const nextRows: MessagesTimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < input.timelineEntries.length; index += 1) {
const timelineEntry = input.timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < input.timelineEntries.length) {
const nextEntry = input.timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
input.completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (input.isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt,
});
}
return nextRows;
}
export function estimateMessagesTimelineRowHeight(
row: MessagesTimelineRow,
input: {
timelineWidthPx: number | null;
expandedWorkGroups?: Readonly<Record<string, boolean>>;
turnDiffSummaryByAssistantMessageId?: ReadonlyMap<MessageId, TurnDiffSummary>;
},
): number {
switch (row.kind) {
case "work":
return estimateWorkRowHeight(row, input);
case "proposed-plan":
return estimateTimelineProposedPlanHeight(row.proposedPlan);
case "working":
return 40;
case "message": {
let estimate = estimateTimelineMessageHeight(row.message, {
timelineWidthPx: input.timelineWidthPx,
});
const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id);
if (turnDiffSummary && turnDiffSummary.files.length > 0) {
estimate += estimateChangedFilesCardHeight(turnDiffSummary);
}
return estimate;
}
}
}
function estimateWorkRowHeight(
row: Extract<MessagesTimelineRow, { kind: "work" }>,
input: {
expandedWorkGroups?: Readonly<Record<string, boolean>>;
},
): number {
const isExpanded = input.expandedWorkGroups?.[row.id] ?? false;
const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length;
const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
// Card chrome, optional header, and one compact work-entry row per visible entry.
return 28 + (showHeader ? 26 : 0) + visibleEntries * 32;
}
function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number {
const treeNodes = buildTurnDiffTree(turnDiffSummary.files);
const visibleNodeCount = countTurnDiffTreeNodes(treeNodes);
// Card chrome: top/bottom padding, header row, and tree spacing.
return 60 + visibleNodeCount * 25;
}
function countTurnDiffTreeNodes(nodes: ReadonlyArray<TurnDiffTreeNode>): number {
let count = 0;
for (const node of nodes) {
count += 1;
if (node.kind === "directory") {
count += countTurnDiffTreeNodes(node.children);
}
}
return count;
}
+75 -102
View File
@@ -35,13 +35,18 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { clamp } from "effect/Number";
import { estimateTimelineMessageHeight } from "../timelineHeight";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
import {
MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
estimateMessagesTimelineRowHeight,
normalizeCompactToolLabel,
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import {
deriveDisplayedUserMessageState,
@@ -56,7 +61,6 @@ import {
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
interface MessagesTimelineProps {
@@ -81,6 +85,17 @@ interface MessagesTimelineProps {
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
onVirtualizerSnapshot?: (snapshot: {
totalSize: number;
measurements: ReadonlyArray<{
id: string;
kind: MessagesTimelineRow["kind"];
index: number;
size: number;
start: number;
end: number;
}>;
}) => void;
}
export const MessagesTimeline = memo(function MessagesTimeline({
@@ -105,6 +120,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
timestampFormat,
workspaceRoot,
onVirtualizerSnapshot,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
@@ -134,70 +150,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [hasMessages, isWorking]);
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < timelineEntries.length; index += 1) {
const timelineEntry = timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: activeTurnStartedAt,
});
}
return nextRows;
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
const rows = useMemo(
() =>
deriveMessagesTimelineRows({
timelineEntries,
completionDividerBeforeEntryId,
isWorking,
activeTurnStartedAt,
}),
[timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt],
);
const firstUnvirtualizedRowIndex = useMemo(() => {
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
@@ -241,19 +203,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
minimum: 0,
maximum: rows.length,
});
const virtualMeasurementScopeKey =
timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`;
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainer,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
// Scope cached row measurements to the current timeline width so offscreen
// rows do not keep stale heights after wrapping changes.
getItemKey: (index: number) => {
const rowId = rows[index]?.id ?? String(index);
return `${virtualMeasurementScopeKey}:${rowId}`;
},
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
if (row.kind === "working") return 40;
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
return estimateMessagesTimelineRowHeight(row, {
expandedWorkGroups,
timelineWidthPx,
turnDiffSummaryByAssistantMessageId,
});
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
@@ -295,6 +264,32 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
};
}, []);
useLayoutEffect(() => {
if (!onVirtualizerSnapshot) {
return;
}
onVirtualizerSnapshot({
totalSize: rowVirtualizer.getTotalSize(),
measurements: rowVirtualizer.measurementsCache
.slice(0, virtualizedRowCount)
.flatMap((measurement) => {
const row = rows[measurement.index];
if (!row) {
return [];
}
return [
{
id: row.id,
kind: row.kind,
index: measurement.index,
size: measurement.size,
start: measurement.start,
end: measurement.end,
},
];
}),
});
}, [onVirtualizerSnapshot, rowVirtualizer, rows, virtualizedRowCount]);
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -311,6 +306,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const renderRowContent = (row: TimelineRow) => (
<div
className="pb-4"
data-timeline-row-id={row.id}
data-timeline-row-kind={row.kind}
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
@@ -585,6 +581,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div
key={`virtual-row:${row.id}`}
data-index={virtualRow.index}
data-virtual-row-id={row.id}
data-virtual-row-kind={row.kind}
data-virtual-row-size={virtualRow.size}
data-virtual-row-start={virtualRow.start}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
@@ -605,35 +605,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
type TimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: TimelineWorkEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: TimelineMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: TimelineProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
type TimelineRow = MessagesTimelineRow;
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
File diff suppressed because it is too large. Load diff
@@ -25,6 +25,7 @@ import {
} from "../ui/dialog";
import { toastManager } from "../ui/toast";
import { readNativeApi } from "~/nativeApi";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
export const ProposedPlanCard = memo(function ProposedPlanCard({
planMarkdown,
@@ -39,6 +40,15 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
const [savePath, setSavePath] = useState("");
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const { copyToClipboard, isCopied } = useCopyToClipboard({
onError: (error) => {
toastManager.add({
type: "error",
title: "Could not copy plan",
description: error instanceof Error ? error.message : "An error occurred while copying.",
});
},
});
const savePathInputId = useId();
const title = proposedPlanTitle(planMarkdown) ?? "Proposed plan";
const lineCount = planMarkdown.split("\n").length;
@@ -54,6 +64,10 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
downloadPlanAsTextFile(downloadFilename, saveContents);
};
const handleCopyPlan = () => {
copyToClipboard(saveContents);
};
const openSaveDialog = () => {
if (!workspaceRoot) {
toastManager.add({
@@ -127,6 +141,9 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
<EllipsisIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={handleCopyPlan}>
{isCopied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem onClick={openSaveDialog} disabled={!workspaceRoot || isSavingToWorkspace}>
Save to workspace
@@ -11,7 +11,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "assistant",
text: "a".repeat(144),
}),
).toBe(122);
).toBe(86.5);
});
it("uses assistant sizing rules for system messages", () => {
@@ -20,7 +20,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "system",
text: "a".repeat(144),
}),
).toBe(122);
).toBe(86.5);
});
it("adds one attachment row for one or two user attachments", () => {
@@ -132,7 +132,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "a".repeat(200),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(154.75);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(86.5);
});
});
+9 -5
View File
@@ -3,8 +3,12 @@ import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContex
const ASSISTANT_CHARS_PER_LINE_FALLBACK = 72;
const USER_CHARS_PER_LINE_FALLBACK = 56;
const LINE_HEIGHT_PX = 22;
const ASSISTANT_BASE_HEIGHT_PX = 78;
const USER_LINE_HEIGHT_PX = 22;
const ASSISTANT_LINE_HEIGHT_PX = 22.75;
// Assistant rows render as markdown content plus a compact timestamp meta line.
// The DOM baseline is much smaller than the user bubble chrome, so model it
// separately instead of reusing the old shared constant.
const ASSISTANT_BASE_HEIGHT_PX = 41;
const USER_BASE_HEIGHT_PX = 96;
const ATTACHMENTS_PER_ROW = 2;
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
@@ -73,7 +77,7 @@ export function estimateTimelineMessageHeight(
if (message.role === "assistant") {
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
if (message.role === "user") {
@@ -92,12 +96,12 @@ export function estimateTimelineMessageHeight(
const attachmentCount = message.attachments?.length ?? 0;
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
return USER_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX + attachmentHeight;
return USER_BASE_HEIGHT_PX + estimatedLines * USER_LINE_HEIGHT_PX + attachmentHeight;
}
// `system` messages are not rendered in the chat timeline, but keep a stable
// explicit branch in case they are present in timeline data.
const charsPerLine = estimateCharsPerLineForAssistant(layout.timelineWidthPx);
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * LINE_HEIGHT_PX;
return ASSISTANT_BASE_HEIGHT_PX + estimatedLines * ASSISTANT_LINE_HEIGHT_PX;
}
+1 -1
View File
@@ -19,7 +19,7 @@ import { buttonVariants } from "~/components/ui/button";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = {
export type ThreadToastData = {
threadId?: ThreadId | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
+97 -1
View File
@@ -1,12 +1,42 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
vi.mock("../nativeApi", () => ({
ensureNativeApi: vi.fn(),
}));
vi.mock("../wsRpcClient", () => ({
getWsRpcClient: vi.fn(),
}));
import type { InfiniteData } from "@tanstack/react-query";
import type { GitListBranchesResult } from "@t3tools/contracts";
import {
gitBranchSearchInfiniteQueryOptions,
gitMutationKeys,
gitQueryKeys,
gitPreparePullRequestThreadMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
invalidateGitStatusQuery,
gitStatusQueryOptions,
invalidateGitQueries,
} from "./gitReactQuery";
const BRANCH_QUERY_RESULT: GitListBranchesResult = {
branches: [],
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 0,
};
const BRANCH_SEARCH_RESULT: InfiniteData<GitListBranchesResult, number> = {
pages: [BRANCH_QUERY_RESULT],
pageParams: [0],
};
describe("gitMutationKeys", () => {
it("scopes stacked action keys by cwd", () => {
expect(gitMutationKeys.runStackedAction("/repo/a")).not.toEqual(
@@ -49,3 +79,69 @@ describe("git mutation options", () => {
expect(options.mutationKey).toEqual(gitMutationKeys.preparePullRequestThread("/repo/a"));
});
});
describe("invalidateGitQueries", () => {
it("can invalidate a single cwd without blasting other git query scopes", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(gitQueryKeys.status("/repo/a"), { ok: "a" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/a",
query: "feature",
}).queryKey,
BRANCH_SEARCH_RESULT,
);
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/b",
query: "feature",
}).queryKey,
BRANCH_SEARCH_RESULT,
);
await invalidateGitQueries(queryClient, { cwd: "/repo/a" });
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/a",
query: "feature",
}).queryKey,
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/b",
query: "feature",
}).queryKey,
)?.isInvalidated,
).toBe(false);
});
});
describe("invalidateGitStatusQuery", () => {
it("invalidates only status for the selected cwd", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(gitQueryKeys.status("/repo/a"), { ok: "a" });
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
await invalidateGitStatusQuery(queryClient, "/repo/a");
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
});
});
+46 -9
View File
@@ -1,5 +1,10 @@
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
import {
infiniteQueryOptions,
mutationOptions,
queryOptions,
type QueryClient,
} from "@tanstack/react-query";
import { ensureNativeApi } from "../nativeApi";
import { getWsRpcClient } from "../wsRpcClient";
@@ -7,11 +12,14 @@ const GIT_STATUS_STALE_TIME_MS = 5_000;
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
const GIT_BRANCHES_PAGE_SIZE = 100;
export const gitQueryKeys = {
all: ["git"] as const,
status: (cwd: string | null) => ["git", "status", cwd] as const,
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
branchSearch: (cwd: string | null, query: string) =>
["git", "branches", cwd, "search", query] as const,
};
export const gitMutationKeys = {
@@ -23,10 +31,26 @@ export const gitMutationKeys = {
["git", "mutation", "prepare-pull-request-thread", cwd] as const,
};
export function invalidateGitQueries(queryClient: QueryClient) {
export function invalidateGitQueries(queryClient: QueryClient, input?: { cwd?: string | null }) {
const cwd = input?.cwd ?? null;
if (cwd !== null) {
return Promise.all([
queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(cwd) }),
queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) }),
]);
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function invalidateGitStatusQuery(queryClient: QueryClient, cwd: string | null) {
if (cwd === null) {
return Promise.resolve();
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(cwd) });
}
export function gitStatusQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.status(cwd),
@@ -43,15 +67,28 @@ export function gitStatusQueryOptions(cwd: string | null) {
});
}
export function gitBranchesQueryOptions(cwd: string | null) {
return queryOptions({
queryKey: gitQueryKeys.branches(cwd),
queryFn: async () => {
export function gitBranchSearchInfiniteQueryOptions(input: {
cwd: string | null;
query: string;
enabled?: boolean;
}) {
const normalizedQuery = input.query.trim();
return infiniteQueryOptions({
queryKey: gitQueryKeys.branchSearch(input.cwd, normalizedQuery),
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git branches are unavailable.");
return api.git.listBranches({ cwd });
if (!input.cwd) throw new Error("Git branches are unavailable.");
return api.git.listBranches({
cwd: input.cwd,
...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}),
cursor: pageParam,
limit: GIT_BRANCHES_PAGE_SIZE,
});
},
enabled: cwd !== null,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
enabled: input.cwd !== null && (input.enabled ?? true),
staleTime: GIT_BRANCHES_STALE_TIME_MS,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
+72 -6
View File
@@ -21,6 +21,7 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { readNativeApi } from "../nativeApi";
import {
getServerConfigUpdatedNotification,
type ServerConfigUpdateSource,
useServerConfig,
useServerConfigUpdatedSubscription,
@@ -153,6 +154,43 @@ function errorDetails(error: unknown): string {
}
}
function coalesceOrchestrationUiEvents(
events: ReadonlyArray<OrchestrationEvent>,
): OrchestrationEvent[] {
if (events.length < 2) {
return [...events];
}
const coalesced: OrchestrationEvent[] = [];
for (const event of events) {
const previous = coalesced.at(-1);
if (
previous?.type === "thread.message-sent" &&
event.type === "thread.message-sent" &&
previous.payload.threadId === event.payload.threadId &&
previous.payload.messageId === event.payload.messageId
) {
coalesced[coalesced.length - 1] = {
...event,
payload: {
...event.payload,
attachments: event.payload.attachments ?? previous.payload.attachments,
createdAt: previous.payload.createdAt,
text:
!event.payload.streaming && event.payload.text.length > 0
? event.payload.text
: previous.payload.text + event.payload.text,
},
};
continue;
}
coalesced.push(event);
}
return coalesced;
}
function EventRouter() {
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
@@ -169,7 +207,7 @@ function EventRouter() {
const pathname = useLocation({ select: (loc) => loc.pathname });
const pathnameRef = useRef(pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const handledConfigReplayRef = useRef(false);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
const disposedRef = useRef(false);
const bootstrapFromSnapshotRef = useRef<() => Promise<void>>(async () => undefined);
const serverConfig = useServerConfig();
@@ -206,15 +244,19 @@ function EventRouter() {
const handleServerConfigUpdated = useEffectEvent(
({
id,
payload,
source,
}: {
readonly id: number;
readonly payload: import("@t3tools/contracts").ServerConfigUpdatedPayload;
readonly source: ServerConfigUpdateSource;
}) => {
const isReplay = !handledConfigReplayRef.current;
handledConfigReplayRef.current = true;
if (isReplay || source !== "keybindingsUpdated") {
if (id <= seenServerConfigUpdateIdRef.current) {
return;
}
seenServerConfigUpdateIdRef.current = id;
if (source !== "keybindingsUpdated") {
return;
}
@@ -269,6 +311,8 @@ function EventRouter() {
disposedRef.current = false;
const recovery = createOrchestrationRecoveryCoordinator();
let needsProviderInvalidation = false;
const pendingDomainEvents: OrchestrationEvent[] = [];
let flushPendingDomainEventsScheduled = false;
const reconcileSnapshotDerivedState = () => {
const threads = useStore.getState().threads;
@@ -316,6 +360,7 @@ function EventRouter() {
}
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
const uiEvents = coalesceOrchestrationUiEvents(nextEvents);
const needsProjectUiSync = nextEvents.some(
(event) =>
event.type === "project.created" ||
@@ -328,7 +373,7 @@ function EventRouter() {
void queryInvalidationThrottler.maybeExecute();
}
applyOrchestrationEvents(nextEvents);
applyOrchestrationEvents(uiEvents);
if (needsProjectUiSync) {
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
@@ -357,6 +402,23 @@ function EventRouter() {
removeTerminalState(threadId);
}
};
const flushPendingDomainEvents = () => {
flushPendingDomainEventsScheduled = false;
if (disposed || pendingDomainEvents.length === 0) {
return;
}
const events = pendingDomainEvents.splice(0, pendingDomainEvents.length);
applyEventBatch(events);
};
const schedulePendingDomainEventFlush = () => {
if (flushPendingDomainEventsScheduled) {
return;
}
flushPendingDomainEventsScheduled = true;
queueMicrotask(flushPendingDomainEvents);
};
const recoverFromSequenceGap = async (): Promise<void> => {
if (!recovery.beginReplayRecovery("sequence-gap")) {
@@ -410,10 +472,12 @@ function EventRouter() {
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
applyEventBatch([event]);
pendingDomainEvents.push(event);
schedulePendingDomainEventFlush();
return;
}
if (action === "recover") {
flushPendingDomainEvents();
void recoverFromSequenceGap();
}
});
@@ -434,6 +498,8 @@ function EventRouter() {
disposed = true;
disposedRef.current = true;
needsProviderInvalidation = false;
flushPendingDomainEventsScheduled = false;
pendingDomainEvents.length = 0;
queryInvalidationThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
+2 -2
View File
@@ -222,7 +222,7 @@ function ChatThreadRouteView() {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView key={threadId} threadId={threadId} />
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelInlineSidebar
diffOpen={diffOpen}
@@ -237,7 +237,7 @@ function ChatThreadRouteView() {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView key={threadId} threadId={threadId} />
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
{shouldRenderDiffContent ? <LazyDiffPanel mode="sheet" /> : null}
+13 -1
View File
@@ -18,6 +18,7 @@ import { appAtomRegistry, resetAppAtomRegistryForTests } from "./atomRegistry";
export type ServerConfigUpdateSource = ServerConfigStreamEvent["type"];
export interface ServerConfigUpdatedNotification {
readonly id: number;
readonly payload: ServerConfigUpdatedPayload;
readonly source: ServerConfigUpdateSource;
}
@@ -71,6 +72,10 @@ export function getServerConfig(): ServerConfig | null {
return appAtomRegistry.get(serverConfigAtom);
}
export function getServerConfigUpdatedNotification(): ServerConfigUpdatedNotification | null {
return appAtomRegistry.get(serverConfigUpdatedAtom);
}
export function setServerConfigSnapshot(config: ServerConfig): void {
resolveServerConfig(config);
emitProvidersUpdated({ providers: config.providers });
@@ -194,8 +199,11 @@ export function startServerStateSync(client: ServerStateClient): () => void {
export function resetServerStateForTests() {
resetAppAtomRegistryForTests();
nextServerConfigUpdatedNotificationId = 1;
}
let nextServerConfigUpdatedNotificationId = 1;
function resolveServerConfig(config: ServerConfig): void {
appAtomRegistry.set(serverConfigAtom, config);
}
@@ -208,7 +216,11 @@ function emitServerConfigUpdated(
payload: ServerConfigUpdatedPayload,
source: ServerConfigUpdateSource,
): void {
appAtomRegistry.set(serverConfigUpdatedAtom, { payload, source });
appAtomRegistry.set(serverConfigUpdatedAtom, {
id: nextServerConfigUpdatedNotificationId++,
payload,
source,
});
}
function subscribeLatest<A>(
+73
View File
@@ -47,6 +47,9 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
}
function makeState(thread: Thread): AppState {
const threadIdsByProjectId: AppState["threadIdsByProjectId"] = {
[thread.projectId]: [thread.id],
};
return {
projects: [
{
@@ -61,6 +64,8 @@ function makeState(thread: Thread): AppState {
},
],
threads: [thread],
sidebarThreadsById: {},
threadIdsByProjectId,
bootstrapComplete: true,
};
}
@@ -271,6 +276,8 @@ describe("store read model sync", () => {
},
],
threads: [],
sidebarThreadsById: {},
threadIdsByProjectId: {},
bootstrapComplete: true,
};
const readModel: OrchestrationReadModel = {
@@ -361,6 +368,8 @@ describe("incremental orchestration updates", () => {
},
],
threads: [],
sidebarThreadsById: {},
threadIdsByProjectId: {},
bootstrapComplete: true,
};
@@ -386,6 +395,70 @@ describe("incremental orchestration updates", () => {
expect(next.projects[0]?.name).toBe("Project Recreated");
});
it("removes stale project index entries when thread.created recreates a thread under a new project", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const threadId = ThreadId.makeUnsafe("thread-1");
const thread = makeThread({
id: threadId,
projectId: originalProjectId,
});
const state: AppState = {
projects: [
{
id: originalProjectId,
name: "Project 1",
cwd: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
},
{
id: recreatedProjectId,
name: "Project 2",
cwd: "/tmp/project-2",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
},
],
threads: [thread],
sidebarThreadsById: {},
threadIdsByProjectId: {
[originalProjectId]: [threadId],
},
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.created", {
threadId,
projectId: recreatedProjectId,
title: "Recovered thread",
modelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.threads).toHaveLength(1);
expect(next.threads[0]?.projectId).toBe(recreatedProjectId);
expect(next.threadIdsByProjectId[originalProjectId]).toBeUndefined();
expect(next.threadIdsByProjectId[recreatedProjectId]).toEqual([threadId]);
});
it("updates only the affected thread for message events", () => {
const thread1 = makeThread({
id: ThreadId.makeUnsafe("thread-1"),
+246 -35
View File
@@ -2,6 +2,7 @@ import {
type OrchestrationEvent,
type OrchestrationMessage,
type OrchestrationProposedPlan,
type ProjectId,
type ProviderKind,
ThreadId,
type OrchestrationReadModel,
@@ -12,25 +13,36 @@ import {
} from "@t3tools/contracts";
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
import { create } from "zustand";
import { type ChatMessage, type Project, type Thread } from "./types";
import {
findLatestProposedPlan,
hasActionableProposedPlan,
derivePendingApprovals,
derivePendingUserInputs,
} from "./session-logic";
import { type ChatMessage, type Project, type SidebarThreadSummary, type Thread } from "./types";
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
projects: Project[];
threads: Thread[];
sidebarThreadsById: Record<string, SidebarThreadSummary>;
threadIdsByProjectId: Record<string, ThreadId[]>;
bootstrapComplete: boolean;
}
const initialState: AppState = {
projects: [],
threads: [],
sidebarThreadsById: {},
threadIdsByProjectId: {},
bootstrapComplete: false,
};
const MAX_THREAD_MESSAGES = 2_000;
const MAX_THREAD_CHECKPOINTS = 500;
const MAX_THREAD_PROPOSED_PLANS = 200;
const MAX_THREAD_ACTIVITIES = 500;
const EMPTY_THREAD_IDS: ThreadId[] = [];
// ── Pure helpers ──────────────────────────────────────────────────────
@@ -180,6 +192,127 @@ function mapProject(project: OrchestrationReadModel["projects"][number]): Projec
};
}
function getLatestUserMessageAt(
messages: ReadonlyArray<Thread["messages"][number]>,
): string | null {
let latestUserMessageAt: string | null = null;
for (const message of messages) {
if (message.role !== "user") {
continue;
}
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
latestUserMessageAt = message.createdAt;
}
}
return latestUserMessageAt;
}
function buildSidebarThreadSummary(thread: Thread): SidebarThreadSummary {
return {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
interactionMode: thread.interactionMode,
session: thread.session,
createdAt: thread.createdAt,
archivedAt: thread.archivedAt,
updatedAt: thread.updatedAt,
latestTurn: thread.latestTurn,
branch: thread.branch,
worktreePath: thread.worktreePath,
latestUserMessageAt: getLatestUserMessageAt(thread.messages),
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
hasActionableProposedPlan: hasActionableProposedPlan(
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
),
};
}
function sidebarThreadSummariesEqual(
left: SidebarThreadSummary | undefined,
right: SidebarThreadSummary,
): boolean {
return (
left !== undefined &&
left.id === right.id &&
left.projectId === right.projectId &&
left.title === right.title &&
left.interactionMode === right.interactionMode &&
left.session === right.session &&
left.createdAt === right.createdAt &&
left.archivedAt === right.archivedAt &&
left.updatedAt === right.updatedAt &&
left.latestTurn === right.latestTurn &&
left.branch === right.branch &&
left.worktreePath === right.worktreePath &&
left.latestUserMessageAt === right.latestUserMessageAt &&
left.hasPendingApprovals === right.hasPendingApprovals &&
left.hasPendingUserInput === right.hasPendingUserInput &&
left.hasActionableProposedPlan === right.hasActionableProposedPlan
);
}
function appendThreadIdByProjectId(
threadIdsByProjectId: Record<string, ThreadId[]>,
projectId: ProjectId,
threadId: ThreadId,
): Record<string, ThreadId[]> {
const existingThreadIds = threadIdsByProjectId[projectId] ?? EMPTY_THREAD_IDS;
if (existingThreadIds.includes(threadId)) {
return threadIdsByProjectId;
}
return {
...threadIdsByProjectId,
[projectId]: [...existingThreadIds, threadId],
};
}
function removeThreadIdByProjectId(
threadIdsByProjectId: Record<string, ThreadId[]>,
projectId: ProjectId,
threadId: ThreadId,
): Record<string, ThreadId[]> {
const existingThreadIds = threadIdsByProjectId[projectId] ?? EMPTY_THREAD_IDS;
if (!existingThreadIds.includes(threadId)) {
return threadIdsByProjectId;
}
const nextThreadIds = existingThreadIds.filter(
(existingThreadId) => existingThreadId !== threadId,
);
if (nextThreadIds.length === existingThreadIds.length) {
return threadIdsByProjectId;
}
if (nextThreadIds.length === 0) {
const nextThreadIdsByProjectId = { ...threadIdsByProjectId };
delete nextThreadIdsByProjectId[projectId];
return nextThreadIdsByProjectId;
}
return {
...threadIdsByProjectId,
[projectId]: nextThreadIds,
};
}
function buildThreadIdsByProjectId(threads: ReadonlyArray<Thread>): Record<string, ThreadId[]> {
const threadIdsByProjectId: Record<string, ThreadId[]> = {};
for (const thread of threads) {
const existingThreadIds = threadIdsByProjectId[thread.projectId] ?? EMPTY_THREAD_IDS;
threadIdsByProjectId[thread.projectId] = [...existingThreadIds, thread.id];
}
return threadIdsByProjectId;
}
function buildSidebarThreadsById(
threads: ReadonlyArray<Thread>,
): Record<string, SidebarThreadSummary> {
return Object.fromEntries(
threads.map((thread) => [thread.id, buildSidebarThreadSummary(thread)]),
);
}
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") {
return "error" as const;
@@ -398,6 +531,46 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
function updateThreadState(
state: AppState,
threadId: ThreadId,
updater: (thread: Thread) => Thread,
): AppState {
let updatedThread: Thread | null = null;
const threads = updateThread(state.threads, threadId, (thread) => {
const nextThread = updater(thread);
if (nextThread !== thread) {
updatedThread = nextThread;
}
return nextThread;
});
if (threads === state.threads || updatedThread === null) {
return state;
}
const nextSummary = buildSidebarThreadSummary(updatedThread);
const previousSummary = state.sidebarThreadsById[threadId];
const sidebarThreadsById = sidebarThreadSummariesEqual(previousSummary, nextSummary)
? state.sidebarThreadsById
: {
...state.sidebarThreadsById,
[threadId]: nextSummary,
};
if (sidebarThreadsById === state.sidebarThreadsById) {
return {
...state,
threads,
};
}
return {
...state,
threads,
sidebarThreadsById,
};
}
// ── Pure state transition functions ────────────────────────────────────
export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState {
@@ -405,10 +578,14 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
.filter((project) => project.deletedAt === null)
.map(mapProject);
const threads = readModel.threads.filter((thread) => thread.deletedAt === null).map(mapThread);
const sidebarThreadsById = buildSidebarThreadsById(threads);
const threadIdsByProjectId = buildThreadIdsByProjectId(threads);
return {
...state,
projects,
threads,
sidebarThreadsById,
threadIdsByProjectId,
bootstrapComplete: true,
};
}
@@ -489,34 +666,72 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
const threads = existing
? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread))
: [...state.threads, nextThread];
return { ...state, threads };
const nextSummary = buildSidebarThreadSummary(nextThread);
const previousSummary = state.sidebarThreadsById[nextThread.id];
const sidebarThreadsById = sidebarThreadSummariesEqual(previousSummary, nextSummary)
? state.sidebarThreadsById
: {
...state.sidebarThreadsById,
[nextThread.id]: nextSummary,
};
const nextThreadIdsByProjectId =
existing !== undefined && existing.projectId !== nextThread.projectId
? removeThreadIdByProjectId(state.threadIdsByProjectId, existing.projectId, existing.id)
: state.threadIdsByProjectId;
const threadIdsByProjectId = appendThreadIdByProjectId(
nextThreadIdsByProjectId,
nextThread.projectId,
nextThread.id,
);
return {
...state,
threads,
sidebarThreadsById,
threadIdsByProjectId,
};
}
case "thread.deleted": {
const threads = state.threads.filter((thread) => thread.id !== event.payload.threadId);
return threads.length === state.threads.length ? state : { ...state, threads };
if (threads.length === state.threads.length) {
return state;
}
const deletedThread = state.threads.find((thread) => thread.id === event.payload.threadId);
const sidebarThreadsById = { ...state.sidebarThreadsById };
delete sidebarThreadsById[event.payload.threadId];
const threadIdsByProjectId = deletedThread
? removeThreadIdByProjectId(
state.threadIdsByProjectId,
deletedThread.projectId,
deletedThread.id,
)
: state.threadIdsByProjectId;
return {
...state,
threads,
sidebarThreadsById,
threadIdsByProjectId,
};
}
case "thread.archived": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
archivedAt: event.payload.archivedAt,
updatedAt: event.payload.updatedAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.unarchived": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
archivedAt: null,
updatedAt: event.payload.updatedAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.meta-updated": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.modelSelection !== undefined
@@ -528,29 +743,26 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
: {}),
updatedAt: event.payload.updatedAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.runtime-mode-set": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
runtimeMode: event.payload.runtimeMode,
updatedAt: event.payload.updatedAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.interaction-mode-set": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
interactionMode: event.payload.interactionMode,
updatedAt: event.payload.updatedAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.turn-start-requested": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
...(event.payload.modelSelection !== undefined
? { modelSelection: normalizeModelSelection(event.payload.modelSelection) }
@@ -560,14 +772,13 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
pendingSourceProposedPlan: event.payload.sourceProposedPlan,
updatedAt: event.occurredAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.turn-interrupt-requested": {
if (event.payload.turnId === undefined) {
return state;
}
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const latestTurn = thread.latestTurn;
if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) {
return thread;
@@ -586,11 +797,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.message-sent": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const message = mapMessage({
id: event.payload.messageId,
role: event.payload.role,
@@ -678,11 +888,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.session-set": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
session: mapSession(event.payload.session),
error: event.payload.session.lastError ?? null,
@@ -710,11 +919,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
: thread.latestTurn,
updatedAt: event.occurredAt,
}));
return threads === state.threads ? state : { ...state, threads };
}
case "thread.session-stop-requested": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) =>
return updateThreadState(state, event.payload.threadId, (thread) =>
thread.session === null
? thread
: {
@@ -729,11 +937,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
},
);
return threads === state.threads ? state : { ...state, threads };
}
case "thread.proposed-plan-upserted": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const proposedPlan = mapProposedPlan(event.payload.proposedPlan);
const proposedPlans = [
...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id),
@@ -750,11 +957,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.turn-diff-completed": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const checkpoint = mapTurnDiffSummary({
turnId: event.payload.turnId,
checkpointTurnCount: event.payload.checkpointTurnCount,
@@ -800,11 +1006,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.reverted": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const turnDiffSummaries = thread.turnDiffSummaries
.filter(
(entry) =>
@@ -853,11 +1058,10 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.activity-appended": {
const threads = updateThread(state.threads, event.payload.threadId, (thread) => {
return updateThreadState(state, event.payload.threadId, (thread) => {
const activities = [
...thread.activities.filter((activity) => activity.id !== event.payload.activity.id),
{ ...event.payload.activity },
@@ -870,7 +1074,6 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
updatedAt: event.occurredAt,
};
});
return threads === state.threads ? state : { ...state, threads };
}
case "thread.approval-response-requested":
@@ -901,12 +1104,21 @@ export const selectThreadById =
(state: AppState): Thread | undefined =>
threadId ? state.threads.find((thread) => thread.id === threadId) : undefined;
export const selectSidebarThreadSummaryById =
(threadId: ThreadId | null | undefined) =>
(state: AppState): SidebarThreadSummary | undefined =>
threadId ? state.sidebarThreadsById[threadId] : undefined;
export const selectThreadIdsByProjectId =
(projectId: ProjectId | null | undefined) =>
(state: AppState): ThreadId[] =>
projectId ? (state.threadIdsByProjectId[projectId] ?? EMPTY_THREAD_IDS) : EMPTY_THREAD_IDS;
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
const threads = updateThread(state.threads, threadId, (t) => {
return updateThreadState(state, threadId, (t) => {
if (t.error === error) return t;
return { ...t, error };
});
return threads === state.threads ? state : { ...state, threads };
}
export function setThreadBranch(
@@ -915,7 +1127,7 @@ export function setThreadBranch(
branch: string | null,
worktreePath: string | null,
): AppState {
const threads = updateThread(state.threads, threadId, (t) => {
return updateThreadState(state, threadId, (t) => {
if (t.branch === branch && t.worktreePath === worktreePath) return t;
const cwdChanged = t.worktreePath !== worktreePath;
return {
@@ -925,7 +1137,6 @@ export function setThreadBranch(
...(cwdChanged ? { session: null } : {}),
};
});
return threads === state.threads ? state : { ...state, threads };
}
// ── Zustand store ────────────────────────────────────────────────────
+14 -2
View File
@@ -1,7 +1,12 @@
import { type ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { selectProjectById, selectThreadById, useStore } from "./store";
import { type Project, type Thread } from "./types";
import {
selectProjectById,
selectSidebarThreadSummaryById,
selectThreadById,
useStore,
} from "./store";
import { type Project, type SidebarThreadSummary, type Thread } from "./types";
export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined {
const selector = useMemo(() => selectProjectById(projectId), [projectId]);
@@ -12,3 +17,10 @@ export function useThreadById(threadId: ThreadId | null | undefined): Thread | u
const selector = useMemo(() => selectThreadById(threadId), [threadId]);
return useStore(selector);
}
export function useSidebarThreadSummaryById(
threadId: ThreadId | null | undefined,
): SidebarThreadSummary | undefined {
const selector = useMemo(() => selectSidebarThreadSummaryById(threadId), [threadId]);
return useStore(selector);
}
+18
View File
@@ -111,6 +111,24 @@ export interface Thread {
activities: OrchestrationThreadActivity[];
}
export interface SidebarThreadSummary {
id: ThreadId;
projectId: ProjectId;
title: string;
interactionMode: ProviderInteractionMode;
session: ThreadSession | null;
createdAt: string;
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
branch: string | null;
worktreePath: string | null;
latestUserMessageAt: string | null;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
hasActionableProposedPlan: boolean;
}
export interface ThreadSession {
provider: ProviderKind;
status: SessionPhase | "error" | "closed";
+46 -7
View File
@@ -4,6 +4,7 @@ import { Schema } from "effect";
import {
GitCreateWorktreeInput,
GitPreparePullRequestThreadInput,
GitRunStackedActionResult,
GitRunStackedActionInput,
GitResolvePullRequestResult,
} from "./git";
@@ -13,6 +14,7 @@ const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(
GitPreparePullRequestThreadInput,
);
const decodeRunStackedActionInput = Schema.decodeUnknownSync(GitRunStackedActionInput);
const decodeRunStackedActionResult = Schema.decodeUnknownSync(GitRunStackedActionResult);
const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);
describe("GitCreateWorktreeInput", () => {
@@ -60,18 +62,55 @@ describe("GitResolvePullRequestResult", () => {
});
describe("GitRunStackedActionInput", () => {
it("requires a client-provided actionId for progress correlation", () => {
it("accepts explicit stacked actions and requires a client-provided actionId", () => {
const parsed = decodeRunStackedActionInput({
actionId: "action-1",
cwd: "/repo",
action: "commit",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
action: "create_pr",
});
expect(parsed.actionId).toBe("action-1");
expect(parsed.action).toBe("commit");
expect(parsed.action).toBe("create_pr");
});
});
describe("GitRunStackedActionResult", () => {
it("decodes a server-authored completion toast", () => {
const parsed = decodeRunStackedActionResult({
action: "commit_push",
branch: {
status: "created",
name: "feature/server-owned-toast",
},
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: move toast state into git manager",
},
push: {
status: "pushed",
branch: "feature/server-owned-toast",
upstreamBranch: "origin/feature/server-owned-toast",
},
pr: {
status: "skipped_not_requested",
},
toast: {
title: "Pushed 89abcde to origin/feature/server-owned-toast",
description: "feat: move toast state into git manager",
cta: {
kind: "run_action",
label: "Create PR",
action: {
kind: "create_pr",
},
},
},
});
expect(parsed.toast.cta.kind).toBe("run_action");
if (parsed.toast.cta.kind === "run_action") {
expect(parsed.toast.cta.action.kind).toBe("create_pr");
}
});
});
+51 -3
View File
@@ -2,10 +2,17 @@ import { Schema } from "effect";
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
const GIT_LIST_BRANCHES_MAX_LIMIT = 200;
// Domain Types
export const GitStackedAction = Schema.Literals(["commit", "commit_push", "commit_push_pr"]);
export const GitStackedAction = Schema.Literals([
"commit",
"push",
"create_pr",
"commit_push",
"commit_push_pr",
]);
export type GitStackedAction = typeof GitStackedAction.Type;
export const GitActionProgressPhase = Schema.Literals(["branch", "commit", "push", "pr"]);
export type GitActionProgressPhase = typeof GitActionProgressPhase.Type;
@@ -21,7 +28,11 @@ export const GitActionProgressKind = Schema.Literals([
export type GitActionProgressKind = typeof GitActionProgressKind.Type;
export const GitActionProgressStream = Schema.Literals(["stdout", "stderr"]);
export type GitActionProgressStream = typeof GitActionProgressStream.Type;
const GitCommitStepStatus = Schema.Literals(["created", "skipped_no_changes"]);
const GitCommitStepStatus = Schema.Literals([
"created",
"skipped_no_changes",
"skipped_not_requested",
]);
const GitPushStepStatus = Schema.Literals([
"pushed",
"skipped_not_requested",
@@ -33,6 +44,32 @@ const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
const GitPullRequestReference = TrimmedNonEmptyStringSchema;
const GitPullRequestState = Schema.Literals(["open", "closed", "merged"]);
const GitPreparePullRequestThreadMode = Schema.Literals(["local", "worktree"]);
export const GitRunStackedActionToastRunAction = Schema.Struct({
kind: GitStackedAction,
});
export type GitRunStackedActionToastRunAction = typeof GitRunStackedActionToastRunAction.Type;
const GitRunStackedActionToastCta = Schema.Union([
Schema.Struct({
kind: Schema.Literal("none"),
}),
Schema.Struct({
kind: Schema.Literal("open_pr"),
label: TrimmedNonEmptyStringSchema,
url: Schema.String,
}),
Schema.Struct({
kind: Schema.Literal("run_action"),
label: TrimmedNonEmptyStringSchema,
action: GitRunStackedActionToastRunAction,
}),
]);
export type GitRunStackedActionToastCta = typeof GitRunStackedActionToastCta.Type;
const GitRunStackedActionToast = Schema.Struct({
title: TrimmedNonEmptyStringSchema,
description: Schema.optional(TrimmedNonEmptyStringSchema),
cta: GitRunStackedActionToastCta,
});
export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type;
export const GitBranch = Schema.Struct({
name: TrimmedNonEmptyStringSchema,
@@ -84,6 +121,11 @@ export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
export const GitListBranchesInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
query: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(256))),
cursor: Schema.optional(NonNegativeInt),
limit: Schema.optional(
PositiveInt.check(Schema.isLessThanOrEqualTo(GIT_LIST_BRANCHES_MAX_LIMIT)),
),
});
export type GitListBranchesInput = typeof GitListBranchesInput.Type;
@@ -144,7 +186,10 @@ const GitStatusPr = Schema.Struct({
});
export const GitStatusResult = Schema.Struct({
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
isRepo: Schema.Boolean,
hasOriginRemote: Schema.Boolean,
isDefaultBranch: Schema.Boolean,
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
hasWorkingTreeChanges: Schema.Boolean,
workingTree: Schema.Struct({
files: Schema.Array(
@@ -168,6 +213,8 @@ export const GitListBranchesResult = Schema.Struct({
branches: Schema.Array(GitBranch),
isRepo: Schema.Boolean,
hasOriginRemote: Schema.Boolean,
nextCursor: NonNegativeInt.pipe(Schema.NullOr),
totalCount: NonNegativeInt,
});
export type GitListBranchesResult = typeof GitListBranchesResult.Type;
@@ -213,6 +260,7 @@ export const GitRunStackedActionResult = Schema.Struct({
headBranch: Schema.optional(TrimmedNonEmptyStringSchema),
title: Schema.optional(TrimmedNonEmptyStringSchema),
}),
toast: GitRunStackedActionToast,
});
export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;
+60
View File
@@ -1,3 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
/**
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
* Strips quotes, collapses separators, limits to 64 chars.
@@ -59,3 +61,61 @@ export function resolveAutoFeatureBranchName(
return `${resolvedBase}-${suffix}`;
}
/**
* Strip the remote prefix from a remote ref such as `origin/feature/demo`.
*/
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
/**
* Hide `origin/*` remote refs when a matching local branch already exists.
*/
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
if (branch.remoteName !== "origin") {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
-2
View File
@@ -4,8 +4,6 @@
"type": "module",
"scripts": {
"prepare": "effect-language-service patch",
"claude-fast-mode-probe": "bun run claude-fast-mode-probe.ts",
"claude-haiku-thinking-probe": "bun run claude-haiku-thinking-probe.ts",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},