Compare commits

...
Author SHA1 Message Date
Cursor Agent aad2fb41da fix: only poll branch search when picker menu is open
Pass enabled: isBranchMenuOpen to gitBranchSearchInfiniteQueryOptions so
the infinite query (with its 60s refetchInterval) is only active while the
branch picker is open. The useEffect prefetch already ensures data is
available for the initial open.
2026-04-06 16:28:44 +00:00
Julius Marminge 4e80c83f12 rm 2026-04-06 09:13:40 -07:00
Julius Marminge 40614112af tsc 2026-04-06 09:12:29 -07:00
Julius Marminge 745d10df93 Create and checkout branches atomically
- Return the created branch from git createBranch
- Use one API call for branch creation and checkout in the selector
2026-04-06 09:07:00 -07:00
Julius Marminge e234ed097c Fix git status polling keys and pending snapshots
- Keep remote pollers keyed by the original cwd
- Initialize new cwd snapshots as pending in the web state
2026-04-05 19:16:57 -07:00
Julius Marminge 2c200cee78 Preserve local git status fields on remote refresh
- Keep working tree and branch metadata intact when applying remote updates
- Remove the unused enqueueRefreshStatus API
2026-04-05 18:52:05 -07:00
Julius Marminge 5efdbb0d4c Restore branch selector state after checkout failures
- Revert optimistic branch selection when checkout fails
- Co-authored-by: codex <[email protected]>
2026-04-05 18:41:48 -07:00
Julius Marminge acb9bf1054 Scope branch query invalidation to current cwd
- Invalidate only the active branch search query after branch actions
- Avoid broad git query refreshes
2026-04-05 18:33:01 -07:00
Julius Marmingeandcodex a49910639c Detach git status refresh after git actions
Co-authored-by: codex <[email protected]>
2026-04-05 18:02:52 -07:00
Julius Marminge 5326507ff5 Debounce git status refreshes on window focus
- Avoid duplicate refreshes when focus and visibility events fire together
- Add coverage for the 250ms debounce
2026-04-05 17:51:58 -07:00
Julius Marminge f5bec5e585 Use Scope.close for WS background scope
- Replace manual release callback with `Scope.close`
- Co-authored-by: codex <[email protected]>
2026-04-05 17:50:36 -07:00
Julius Marmingeandcodex 5cf6f7f3e4 Run git status refresh in server background scope
Co-authored-by: codex <[email protected]>
2026-04-05 17:46:12 -07:00
Julius Marmingeandcodex fc50e65e55 Fix remote-only git status fallback state
Co-authored-by: codex <[email protected]>
2026-04-05 16:26:27 -07:00
Julius Marmingeandcodex 6840b709ad Stop idle git remote pollers on disconnect
Co-authored-by: codex <[email protected]>
2026-04-05 16:17:06 -07:00
Julius Marmingeandcodex 564e94dccc Background git status refresh after successful mutations
Co-authored-by: codex <[email protected]>
2026-04-05 15:58:16 -07:00
Julius Marmingeandcodex f3bc116544 Fix git status browser test mocks
Co-authored-by: codex <[email protected]>
2026-04-05 14:39:12 -07:00
Julius Marmingeandcodex 0a3812afb3 Avoid phantom null git status atoms
Co-authored-by: codex <[email protected]>
2026-04-05 14:33:37 -07:00
Julius Marmingeandcodex 507822b1db Split local and remote git status streaming
Co-authored-by: codex <[email protected]>
2026-04-05 14:32:25 -07:00
Julius Marminge c7460b8604 Add explicit git status refresh RPC
- Refresh git status after pull and stacked actions
- Rehydrate status on window focus and menu open
- Wire refresh through server, web, and contracts
2026-04-05 14:10:52 -07:00
Julius Marminge 60b9b6c54f Remove git status refresh on menu open
- Rely on the existing watcher instead of resubscribing when the menu opens
- Drop the obsolete refresh helper and its test
2026-04-05 12:32:26 -07:00
Julius Marminge 8b9304ca7c Keep SidebarThreadRow hooks ordered before early return
- Compute git status inputs before the null guard
- Preserve hook order while rendering thread rows
2026-04-05 12:27:06 -07:00
Julius Marminge 366182e825 Use per-thread git status subscriptions
- Resolve PR status from each thread’s cwd in the sidebar
- Refactor git status state to shared per-cwd watches
- Update git status state tests
- Co-authored-by: codex <[email protected]>
2026-04-05 12:25:52 -07:00
Julius Marminge e8503a9f05 Share git status subscriptions across consumers
- Cache one live git-status stream per cwd
- Reset status state for tests and native API teardown
- Keep tracked cwd subscriptions stable across re-renders
2026-04-05 11:55:03 -07:00
Julius Marminge 0cd98e3856 Stabilize git status state and browser bootstrap
- prune stale cwd status entries
- make native API resets and test bootstrap async-safe
2026-04-05 11:20:02 -07:00
Julius Marminge 00d879b45f Stream git status updates over WebSocket
- Add server-side status broadcaster and cache invalidation
- Refresh git status after git actions and checkout
- Co-authored-by: codex <[email protected]>
2026-04-05 10:37:17 -07:00
38 changed files with 2303 additions and 382 deletions

No files matched your search

+2 -1
View File
@@ -949,11 +949,12 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* (yield* GitCore).checkoutBranch({
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
cwd: source,
branch: `${remoteName}/${featureBranch}`,
});
expect(checkoutResult.branch).toBe("upstream/feature");
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
+32 -9
View File
@@ -1177,9 +1177,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return branchLastCommit;
});
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
@@ -1312,6 +1310,17 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
};
});
const statusDetailsLocal: GitCoreShape["statusDetailsLocal"] = Effect.fn("statusDetailsLocal")(
function* (cwd) {
return yield* readStatusDetailsLocal(cwd);
},
);
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
return yield* readStatusDetailsLocal(cwd);
});
const status: GitCoreShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
@@ -2000,12 +2009,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return { branch: targetBranch };
});
const createBranch: GitCoreShape["createBranch"] = (input) =>
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
}).pipe(Effect.asVoid);
const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
function* (input) {
const [localInputExists, remoteExists] = yield* Effect.all(
@@ -2078,9 +2081,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
"branch",
"--show-current",
]).pipe(Effect.map((stdout) => stdout.trim() || null));
return { branch };
},
);
const createBranch: GitCoreShape["createBranch"] = Effect.fn("createBranch")(function* (input) {
yield* executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
if (input.checkout) {
yield* checkoutBranch({ cwd: input.cwd, branch: input.branch });
}
return { branch: input.branch };
});
const initRepo: GitCoreShape["initRepo"] = (input) =>
executeGit("GitCore.initRepo", input.cwd, ["init"], {
timeoutMs: 10_000,
@@ -2106,6 +2128,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
execute,
status,
statusDetails,
statusDetailsLocal,
prepareCommitContext,
commit,
pushCurrentBranch,
+105 -33
View File
@@ -8,9 +8,13 @@ import {
GitCommandError,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
@@ -695,26 +699,55 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
const readStatus = Effect.fn("readStatus")(function* (cwd: string) {
const details = yield* gitCore.statusDetails(cwd).pipe(
Effect.catchIf(isNotGitRepositoryError, () =>
Effect.succeed({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
} satisfies GitStatusDetails),
),
);
const nonRepositoryStatusDetails = {
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
} satisfies GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetailsLocal(cwd)
.pipe(
Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
);
const hostingProvider = details.isRepo
? yield* resolveHostingProvider(cwd, details.branch)
: null;
return {
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readLocalStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateLocalStatusResultCache = (cwd: string) =>
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
}
const pr =
details.isRepo && details.branch !== null
details.branch !== null
? yield* findLatestPr(cwd, {
branch: details.branch,
upstreamRef: details.upstreamRef,
@@ -725,29 +758,38 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
isRepo: details.isRepo,
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
pr,
};
} satisfies GitStatusRemoteResult;
});
const statusResultCache = yield* Cache.makeWith({
const remoteStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readStatus,
lookup: readRemoteStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateStatusResultCache = (cwd: string) =>
Cache.invalidate(statusResultCache, normalizeStatusCacheKey(cwd));
const invalidateRemoteStatusResultCache = (cwd: string) =>
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
cwd: string,
branch: string | null,
) {
const preferredRemoteName =
branch === null
? "origin"
: ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
const remoteUrl =
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
cwd: string,
remoteName: string | null,
@@ -1311,9 +1353,34 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
};
});
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd));
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
});
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
function* (input) {
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
},
);
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
});
const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
"invalidateLocalStatus",
)(function* (cwd) {
yield* invalidateLocalStatusResultCache(cwd);
});
const invalidateRemoteStatus: GitManagerShape["invalidateRemoteStatus"] = Effect.fn(
"invalidateRemoteStatus",
)(function* (cwd) {
yield* invalidateRemoteStatusResultCache(cwd);
});
const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
function* (cwd) {
yield* invalidateLocalStatusResultCache(cwd);
yield* invalidateRemoteStatusResultCache(cwd);
},
);
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
@@ -1488,7 +1555,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
branch: worktree.worktree.branch,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatusResultCache(input.cwd)));
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
});
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -1692,7 +1759,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
});
return yield* runAction().pipe(
Effect.ensuring(invalidateStatusResultCache(input.cwd)),
Effect.ensuring(invalidateStatus(input.cwd)),
Effect.tapError((error) =>
Effect.flatMap(Ref.get(currentPhase), (phase) =>
progress.emit({
@@ -1707,7 +1774,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
return {
localStatus,
remoteStatus,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
invalidateStatus,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
@@ -0,0 +1,276 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
import type {
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { describe } from "vitest";
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
const baseLocalStatus: GitStatusLocalResult = {
isRepo: true,
hostingProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/status-broadcast",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const baseStatus: GitStatusResult = {
...baseLocalStatus,
...baseRemoteStatus,
};
function makeTestLayer(state: {
currentLocalStatus: GitStatusLocalResult;
currentRemoteStatus: GitStatusRemoteResult | null;
localStatusCalls: number;
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
const gitManager: GitManagerShape = {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
};
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
}
describe("GitStatusBroadcasterLive", () => {
it.effect("reuses the cached git status across repeated reads", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(first, baseStatus);
assert.deepStrictEqual(second, baseStatus);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.localInvalidationCalls, 0);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
branch: "feature/updated-status",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 2,
};
const refreshed = yield* broadcaster.refreshStatus("/repo");
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshed, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 1);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("streams a local snapshot first and remote updates later", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
if (event._tag === "snapshot") {
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
}
if (event._tag === "remoteUpdated") {
return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkScoped);
const snapshot = yield* Deferred.await(snapshotDeferred);
yield* broadcaster.refreshStatus("/repo");
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
assert.deepStrictEqual(snapshot, {
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
} satisfies GitStatusStreamEvent);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies GitStatusStreamEvent);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const testLayer = GitStatusBroadcasterLive.pipe(
Layer.provide(
Layer.succeed(GitManager, {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () =>
Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
} satisfies GitManagerShape),
),
);
return Effect.gen(function* () {
const remoteInterrupted = yield* Deferred.make<void>();
const remoteStarted = yield* Deferred.make<void>();
remoteInterruptedDeferred = remoteInterrupted;
remoteStartedDeferred = remoteStarted;
const broadcaster = yield* GitStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const firstScope = yield* Scope.make();
const secondScope = yield* Scope.make();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
event._tag === "snapshot"
? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(firstScope));
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
event._tag === "snapshot"
? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(secondScope));
yield* Deferred.await(firstSnapshot);
yield* Deferred.await(secondSnapshot);
yield* Deferred.await(remoteStarted);
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(firstScope, Exit.void);
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
yield* Deferred.await(remoteInterrupted);
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
}).pipe(Effect.provide(testLayer));
});
});
@@ -0,0 +1,307 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitStatusInput,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly event: GitStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedGitStatus {
readonly local: CachedValue<GitStatusLocalResult> | null;
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
cwd: string,
local: GitStatusLocalResult,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<GitStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
});
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
cwd: string,
remote: GitStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<GitStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
});
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
});
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(normalizedCwd),
getOrLoadRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus = Effect.fn("refreshLocalStatus")(function* (cwd: string) {
yield* gitManager.invalidateLocalStatus(cwd);
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
yield* gitManager.invalidateRemoteStatus(cwd);
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(normalizedCwd),
refreshRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
},
);
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("git remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
yield* retainRemotePoller(normalizedCwd);
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return {
getStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
+12 -3
View File
@@ -7,10 +7,12 @@
* @module GitCore
*/
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
@@ -156,6 +158,11 @@ export interface GitCoreShape {
*/
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Read detailed working tree / branch status without refreshing remote tracking refs.
*/
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Build staged change context for commit generation.
*/
@@ -278,14 +285,16 @@ export interface GitCoreShape {
/**
* Create a local branch.
*/
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
/**
* Initialize a repository in the provided directory.
@@ -14,6 +14,8 @@ import {
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
@@ -41,6 +43,35 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Read local repository status without remote hosting enrichment.
*/
readonly localStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
/**
* Read remote tracking / PR status for a repository.
*/
readonly remoteStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
/**
* Clear any cached local status snapshot for a repository.
*/
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached remote status snapshot for a repository.
*/
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
@@ -0,0 +1,23 @@
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
GitStatusInput,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends ServiceMap.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
+376 -13
View File
@@ -22,7 +22,16 @@ import {
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, ManagedRuntime, Path, Stream } from "effect";
import {
Deferred,
Duration,
Effect,
FileSystem,
Layer,
ManagedRuntime,
Path,
Stream,
} from "effect";
import {
FetchHttpClient,
HttpBody,
@@ -44,6 +53,7 @@ import {
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
import { Open, type OpenShape } from "./open.ts";
import {
@@ -294,6 +304,10 @@ const buildAppUnderTest = (options?: {
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
const gitManagerLayer = Layer.mock(GitManager)({
...options?.layers?.gitManager,
});
const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
const appLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
@@ -333,11 +347,8 @@ const buildAppUnderTest = (options?: {
...options?.layers?.gitCore,
}),
),
Layer.provide(
Layer.mock(GitManager)({
...options?.layers?.gitManager,
}),
),
Layer.provide(gitManagerLayer),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
runForThread: () => Effect.succeed({ status: "no-script" as const }),
@@ -1260,6 +1271,25 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
invalidateStatus: () => Effect.void,
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
remoteStatus: () =>
Effect.succeed({
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
}),
status: () =>
Effect.succeed({
isRepo: true,
@@ -1373,8 +1403,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
worktree: { path: "/tmp/wt", branch: "feature/demo" },
}),
removeWorktree: () => Effect.void,
createBranch: () => Effect.void,
checkoutBranch: () => Effect.void,
createBranch: (input) => Effect.succeed({ branch: input.branch }),
checkoutBranch: (input) => Effect.succeed({ branch: input.branch }),
initRepo: () => Effect.void,
},
},
@@ -1382,16 +1412,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const wsUrl = yield* getWsServerUrl("/ws");
const status = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitStatus]({ cwd: "/tmp/repo" })),
);
assert.equal(status.branch, "main");
const pull = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
);
assert.equal(pull.status, "pulled");
const refreshedStatus = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRefreshStatus]({ cwd: "/tmp/repo" }),
),
);
assert.equal(refreshedStatus.isRepo, true);
const stackedEvents = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRunStackedAction]({
@@ -1494,11 +1526,62 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
cwd: "/tmp/repo",
detail: "upstream missing",
});
let invalidationCalls = 0;
let statusCalls = 0;
yield* buildAppUnderTest({
layers: {
gitCore: {
pullCurrentBranch: () => Effect.fail(gitError),
},
gitManager: {
invalidateLocalStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
remoteStatus: () =>
Effect.sync(() => {
statusCalls += 1;
return {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}),
status: () =>
Effect.sync(() => {
statusCalls += 1;
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}),
},
},
});
@@ -1510,9 +1593,289 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assertFailure(result, gitError);
assert.equal(invalidationCalls, 0);
assert.equal(statusCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc git.runStackedAction errors after refreshing git status", () =>
Effect.gen(function* () {
const gitError = new GitCommandError({
operation: "commit",
command: "git commit",
cwd: "/tmp/repo",
detail: "nothing to commit",
});
let invalidationCalls = 0;
let statusCalls = 0;
yield* buildAppUnderTest({
layers: {
gitManager: {
invalidateLocalStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
invalidationCalls += 1;
}),
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
remoteStatus: () =>
Effect.sync(() => {
statusCalls += 1;
return {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}),
status: () =>
Effect.sync(() => {
statusCalls += 1;
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}),
runStackedAction: () => Effect.fail(gitError),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRunStackedAction]({
actionId: "action-1",
cwd: "/tmp/repo",
action: "commit",
}).pipe(Stream.runCollect, Effect.result),
),
);
assertFailure(result, gitError);
assert.equal(invalidationCalls, 0);
assert.equal(statusCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("completes websocket rpc git.pull before background git status refresh finishes", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
layers: {
gitCore: {
pullCurrentBranch: () =>
Effect.succeed({
status: "pulled" as const,
branch: "main",
upstreamBranch: "origin/main",
}),
},
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
remoteStatus: () =>
Effect.sleep(Duration.seconds(2)).pipe(
Effect.as({
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
}),
),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const startedAt = Date.now();
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
);
const elapsedMs = Date.now() - startedAt;
assert.equal(result.status, "pulled");
assertTrue(elapsedMs < 1_000);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"completes websocket rpc git.runStackedAction before background git status refresh finishes",
() =>
Effect.gen(function* () {
yield* buildAppUnderTest({
layers: {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
remoteStatus: () =>
Effect.sleep(Duration.seconds(2)).pipe(
Effect.as({
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
}),
),
runStackedAction: () =>
Effect.succeed({
action: "commit" as const,
branch: { status: "skipped_not_requested" as const },
commit: {
status: "created" as const,
commitSha: "abc123",
subject: "feat: demo",
},
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,
},
},
},
}),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const startedAt = Date.now();
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRunStackedAction]({
actionId: "action-1",
cwd: "/tmp/repo",
action: "commit",
}).pipe(Stream.runCollect),
),
);
const elapsedMs = Date.now() - startedAt;
assertTrue(elapsedMs < 1_000);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"starts a background local git status refresh after a successful git.runStackedAction",
() =>
Effect.gen(function* () {
const localRefreshStarted = yield* Deferred.make<void>();
yield* buildAppUnderTest({
layers: {
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
localStatus: () =>
Deferred.succeed(localRefreshStarted, undefined).pipe(
Effect.ignore,
Effect.andThen(
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
),
),
remoteStatus: () =>
Effect.sleep(Duration.seconds(2)).pipe(
Effect.as({
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
}),
),
runStackedAction: () =>
Effect.succeed({
action: "commit" as const,
branch: { status: "skipped_not_requested" as const },
commit: {
status: "created" as const,
commitSha: "abc123",
subject: "feat: demo",
},
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,
},
},
},
}),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRunStackedAction]({
actionId: "action-1",
cwd: "/tmp/repo",
action: "commit",
}).pipe(Stream.runCollect),
),
);
yield* Deferred.await(localRefreshStarted);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc orchestration methods", () =>
Effect.gen(function* () {
const now = new Date().toISOString();
+10 -8
View File
@@ -30,6 +30,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster";
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { GitManagerLive } from "./git/Layers/GitManager";
@@ -161,15 +162,16 @@ const ProviderLayerLive = Layer.unwrap(
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const GitManagerLayerLive = GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
);
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(
GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
),
),
Layer.provideMerge(GitManagerLayerLive),
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
Layer.provideMerge(GitCoreLive),
);
+62 -21
View File
@@ -27,6 +27,7 @@ import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuer
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore";
import { GitManager } from "./git/Services/GitManager";
import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster";
import { Keybindings } from "./keybindings";
import { Open, resolveAvailableEditors } from "./open";
import { normalizeDispatchCommand } from "./orchestration/Normalizer";
@@ -56,6 +57,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const open = yield* Open;
const gitManager = yield* GitManager;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const terminalManager = yield* TerminalManager;
const providerRegistry = yield* ProviderRegistry;
const config = yield* ServerConfig;
@@ -65,7 +67,6 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const workspaceEntries = yield* WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const serverCommandId = (tag: string) =>
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
@@ -348,6 +349,11 @@ const WsRpcLayer = WsRpcGroup.toLayer(
};
});
const refreshGitStatus = (cwd: string) =>
gitStatusBroadcaster
.refreshStatus(cwd)
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
return WsRpcGroup.of({
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
observeRpcEffect(
@@ -559,14 +565,30 @@ const WsRpcLayer = WsRpcGroup.toLayer(
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.gitStatus]: (input) =>
observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), {
[WS_METHODS.subscribeGitStatus]: (input) =>
observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRefreshStatus]: (input) =>
observeRpcEffect(
WS_METHODS.gitRefreshStatus,
gitStatusBroadcaster.refreshStatus(input.cwd),
{
"rpc.aggregate": "git",
},
),
[WS_METHODS.gitPull]: (input) =>
observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitPull,
git.pullCurrentBranch(input.cwd).pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Effect.failCause(cause),
onSuccess: (result) =>
refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
}),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRunStackedAction]: (input) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
@@ -581,7 +603,10 @@ const WsRpcLayer = WsRpcGroup.toLayer(
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
onSuccess: () =>
refreshGitStatus(input.cwd).pipe(
Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
),
}),
),
),
@@ -594,7 +619,9 @@ const WsRpcLayer = WsRpcGroup.toLayer(
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager.preparePullRequestThread(input),
gitManager
.preparePullRequestThread(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
@@ -602,23 +629,37 @@ const WsRpcLayer = WsRpcGroup.toLayer(
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCreateWorktree,
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRemoveWorktree]: (input) =>
observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitRemoveWorktree,
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCreateBranch]: (input) =>
observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCreateBranch,
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCheckout]: (input) =>
observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitCheckout,
Effect.scoped(git.checkoutBranch(input)).pipe(
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitInit]: (input) =>
observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "rpc.aggregate": "git" }),
observeRpcEffect(
WS_METHODS.gitInit,
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
@@ -1,5 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -14,12 +14,8 @@ import {
useTransition,
} from "react";
import {
gitBranchSearchInfiniteQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
@@ -89,7 +85,7 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const branchStatusQuery = useGitStatus(branchCwd);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
@@ -188,7 +184,9 @@ export function BranchToolbarBranchSelector({
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.branches(branchCwd) })
.catch(() => undefined);
});
};
@@ -226,29 +224,26 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
const checkoutResult = await api.git.checkout({
cwd: selectionTarget.checkoutCwd,
branch: branch.name,
});
const nextBranchName = branch.isRemote
? (checkoutResult.branch ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: selectionTarget.checkoutCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
});
};
@@ -261,32 +256,24 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
const createBranchResult = await api.git.createBranch({
cwd: branchCwd,
branch: name,
checkout: true,
});
setOptimisticBranch(createBranchResult.branch);
onSetThreadBranch(createBranchResult.branch, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
type: "error",
title: "Failed to create branch.",
title: "Failed to create and checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
setOptimisticBranch(name);
onSetThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
+43 -28
View File
@@ -31,6 +31,8 @@ import {
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { __resetNativeApiForTests } from "../nativeApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
@@ -38,12 +40,19 @@ import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
vi.mock("../lib/gitStatusState", () => ({
useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useGitStatuses: () => new Map(),
refreshGitStatus: () => Promise.resolve(null),
resetGitStatusStateForTests: () => undefined,
}));
const THREAD_ID = "thread-browser-test" as ThreadId;
const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_ID = "project-1" as ProjectId;
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
interface TestFixture {
snapshot: OrchestrationReadModel;
@@ -93,9 +102,9 @@ const TEXT_VIEWPORT_MATRIX = [
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
const ATTACHMENT_VIEWPORT_MATRIX = [
DEFAULT_VIEWPORT,
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
{ ...DEFAULT_VIEWPORT, attachmentTolerancePx: 120 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 120 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 120 },
] as const satisfies readonly ViewportSpec[];
interface UserRowMeasurement {
@@ -224,6 +233,7 @@ function createSnapshotForTargetUser(options: {
name: `attachment-${attachmentIndex + 1}.png`,
mimeType: "image/png",
sizeBytes: 128,
previewUrl: `/attachments/attachment-${attachmentIndex + 1}`,
}))
: undefined;
@@ -397,6 +407,22 @@ async function waitForWsClient(): Promise<void> {
(request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents,
),
).toBe(true);
expect(
wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
).toBe(true);
expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe(
true,
);
},
{ timeout: 8_000, interval: 16 },
);
}
async function waitForAppBootstrap(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
expect(useStore.getState().bootstrapComplete).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
@@ -651,24 +677,6 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
return {
entries: [],
@@ -1044,10 +1052,17 @@ async function mountChatView(options: {
}),
);
const screen = await render(<RouterProvider router={router} />, {
container: host,
});
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{
container: host,
},
);
await waitForWsClient();
await waitForAppBootstrap();
await waitForLayout();
const cleanup = async () => {
@@ -1138,7 +1153,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
return [];
},
});
__resetNativeApiForTests();
await __resetNativeApiForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
@@ -1299,7 +1314,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
targetAttachmentCount: 3,
targetAttachmentCount: 2,
}),
});
@@ -1313,7 +1328,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{
role: "user",
text: userText,
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }],
},
{ timelineWidthPx: timelineWidthMeasuredPx },
);
+2 -2
View File
@@ -27,7 +27,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { useQuery } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -1399,7 +1399,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd));
const gitStatusQuery = useGitStatus(gitCwd);
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
+2 -2
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -189,7 +189,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitStatusQuery = useQuery(gitStatusQueryOptions(activeCwd ?? null));
const gitStatusQuery = useGitStatus(activeCwd ?? null);
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -10,7 +10,7 @@ const BRANCH_NAME = "feature/toast-scope";
const {
invalidateGitQueriesSpy,
invalidateGitStatusQuerySpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
@@ -19,7 +19,7 @@ const {
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
invalidateGitStatusQuerySpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
@@ -57,21 +57,6 @@ vi.mock("@tanstack/react-query", async () => {
};
}),
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: {
@@ -110,7 +95,6 @@ vi.mock("~/editorPreferences", () => ({
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitBranchesQueryOptions: vi.fn(() => ({ queryKey: ["git-branches"] })),
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
@@ -118,9 +102,25 @@ vi.mock("~/lib/gitReactQuery", () => ({
},
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/gitStatusState", () => ({
refreshGitStatus: refreshGitStatusSpy,
resetGitStatusStateForTests: () => undefined,
useGitStatus: vi.fn(() => ({
data: {
branch: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
pr: null,
},
error: null,
isPending: false,
})),
}));
vi.mock("~/lib/utils", async () => {
@@ -235,4 +235,42 @@ describe("GitActionsControl thread-scoped progress toast", () => {
host.remove();
}
});
it("debounces focus-driven git status refreshes", async () => {
vi.useFakeTimers();
const originalVisibilityState = Object.getOwnPropertyDescriptor(document, "visibilityState");
let visibilityState: DocumentVisibilityState = "hidden";
Object.defineProperty(document, "visibilityState", {
configurable: true,
get: () => visibilityState,
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<GitActionsControl gitCwd={GIT_CWD} activeThreadId={THREAD_A} />, {
container: host,
});
try {
window.dispatchEvent(new Event("focus"));
visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
expect(refreshGitStatusSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(249);
expect(refreshGitStatusSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
expect(refreshGitStatusSpy).toHaveBeenCalledWith(GIT_CWD);
} finally {
if (originalVisibilityState) {
Object.defineProperty(document, "visibilityState", originalVisibilityState);
}
await screen.unmount();
host.remove();
}
});
});
+41 -5
View File
@@ -5,7 +5,7 @@ import type {
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
@@ -45,9 +45,8 @@ import {
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitStatusQuery,
} from "~/lib/gitReactQuery";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
@@ -92,6 +91,8 @@ interface RunGitActionWithToastInput {
filePaths?: string[];
}
const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
@@ -275,7 +276,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: gitStatus = null, error: gitStatusError } = useGitStatus(gitCwd);
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
@@ -359,6 +360,39 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
};
}, [updateActiveProgressToast]);
useEffect(() => {
if (gitCwd === null) {
return;
}
let refreshTimeout: number | null = null;
const scheduleRefreshCurrentGitStatus = () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
void refreshGitStatus(gitCwd).catch(() => undefined);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
};
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
scheduleRefreshCurrentGitStatus();
}
};
window.addEventListener("focus", scheduleRefreshCurrentGitStatus);
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [gitCwd]);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
if (!api) {
@@ -801,7 +835,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitStatusQuery(queryClient, gitCwd);
if (open) {
void refreshGitStatus(gitCwd).catch(() => undefined);
}
}}
>
<MenuTrigger
@@ -19,10 +19,19 @@ import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { __resetNativeApiForTests } from "../nativeApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { useStore } from "../store";
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
vi.mock("../lib/gitStatusState", () => ({
useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useGitStatuses: () => new Map(),
refreshGitStatus: () => Promise.resolve(null),
resetGitStatusStateForTests: () => undefined,
}));
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
const PROJECT_ID = "project-1" as ProjectId;
const NOW_ISO = "2026-03-04T12:00:00.000Z";
@@ -170,20 +179,6 @@ function resolveWsRpc(tag: string): unknown {
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 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
return { entries: [], truncated: false };
}
@@ -258,6 +253,29 @@ async function waitForNoToast(title: string): Promise<void> {
);
}
async function waitForInitialWsSubscriptions(): Promise<void> {
await vi.waitFor(
() => {
expect(
rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
).toBe(true);
expect(
rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
}
async function waitForServerConfigSnapshot(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
},
{ timeout: 8_000, interval: 16 },
);
}
async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const host = document.createElement("div");
host.style.position = "fixed";
@@ -270,8 +288,15 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
const screen = await render(<RouterProvider router={router} />, { container: host });
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{ container: host },
);
await waitForComposerEditor();
await waitForInitialWsSubscriptions();
await waitForServerConfigSnapshot();
return {
cleanup: async () => {
@@ -322,7 +347,7 @@ describe("Keybindings update toast", () => {
return [];
},
});
__resetNativeApiForTests();
await __resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
useComposerDraftStore.setState({
+18 -53
View File
@@ -49,7 +49,6 @@ import {
ThreadId,
type GitStatusResult,
} from "@t3tools/contracts";
import { useQueries } from "@tanstack/react-query";
import { Link, useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
@@ -70,7 +69,7 @@ import {
threadJumpIndexFromCommand,
threadTraversalDirectionFromCommand,
} from "../keybindings";
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -245,8 +244,20 @@ function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
return null;
}
function resolveThreadPr(
threadBranch: string | null,
gitStatus: GitStatusResult | null,
): ThreadPr | null {
if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) {
return null;
}
return gitStatus.pr ?? null;
}
interface SidebarThreadRowProps {
threadId: ThreadId;
projectCwd: string | null;
orderedProjectThreadIds: readonly ThreadId[];
routeThreadId: ThreadId | null;
selectedThreadIds: ReadonlySet<ThreadId>;
@@ -277,7 +288,6 @@ interface SidebarThreadRowProps {
cancelRename: () => void;
attemptArchiveThread: (threadId: ThreadId) => Promise<void>;
openPrLink: (event: MouseEvent<HTMLElement>, prUrl: string) => void;
pr: ThreadPr | null;
}
function SidebarThreadRow(props: SidebarThreadRowProps) {
@@ -287,6 +297,8 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
(state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId).runningTerminalIds,
);
const gitCwd = thread?.worktreePath ?? props.projectCwd;
const gitStatus = useGitStatus(thread?.branch != null ? gitCwd : null);
if (!thread) {
return null;
@@ -303,7 +315,8 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
lastVisitedAt,
},
});
const prStatus = prStatusIndicator(props.pr);
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const prStatus = prStatusIndicator(pr);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = props.confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
@@ -762,54 +775,6 @@ export default function Sidebar() {
}),
[platform, routeTerminalOpen],
);
const threadGitTargets = useMemo(
() =>
sidebarThreads.map((thread) => ({
threadId: thread.id,
branch: thread.branch,
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
})),
[projectCwdById, sidebarThreads],
);
const threadGitStatusCwds = useMemo(
() => [
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
],
[threadGitTargets],
);
const threadGitStatusQueries = useQueries({
queries: threadGitStatusCwds.map((cwd) => ({
...gitStatusQueryOptions(cwd),
staleTime: 30_000,
refetchInterval: 60_000,
})),
});
const prByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
if (!cwd) continue;
const status = threadGitStatusQueries[index]?.data;
if (status) {
statusByCwd.set(cwd, status);
}
}
const map = new Map<ThreadId, ThreadPr>();
for (const target of threadGitTargets) {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
const openPrLink = useCallback((event: MouseEvent<HTMLElement>, prUrl: string) => {
event.preventDefault();
event.stopPropagation();
@@ -1718,6 +1683,7 @@ export default function Sidebar() {
<SidebarThreadRow
key={threadId}
threadId={threadId}
projectCwd={project.cwd}
orderedProjectThreadIds={orderedProjectThreadIds}
routeThreadId={routeThreadId}
selectedThreadIds={selectedThreadIds}
@@ -1741,7 +1707,6 @@ export default function Sidebar() {
cancelRename={cancelRename}
attemptArchiveThread={attemptArchiveThread}
openPrLink={openPrLink}
pr={prByThreadId.get(threadId) ?? null}
/>
))}
@@ -385,7 +385,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full object-cover"
className="block h-auto max-h-[220px] w-full object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
/>
@@ -30,16 +30,16 @@ function createBaseServerConfig(): ServerConfig {
}
describe("GeneralSettingsPanel observability", () => {
beforeEach(() => {
beforeEach(async () => {
resetServerStateForTests();
__resetNativeApiForTests();
await __resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
});
afterEach(() => {
afterEach(async () => {
resetServerStateForTests();
__resetNativeApiForTests();
await __resetNativeApiForTests();
document.body.innerHTML = "";
});
@@ -30,7 +30,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }],
}),
).toBe(346);
).toBe(234);
expect(
estimateTimelineMessageHeight({
@@ -38,7 +38,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }],
}),
).toBe(346);
).toBe(234);
});
it("adds a second attachment row for three or four user attachments", () => {
@@ -48,7 +48,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
}),
).toBe(574);
).toBe(350);
expect(
estimateTimelineMessageHeight({
@@ -56,7 +56,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
}),
).toBe(574);
).toBe(350);
});
it("does not cap long user message estimates", () => {
+3 -2
View File
@@ -11,8 +11,9 @@ const ASSISTANT_LINE_HEIGHT_PX = 22.75;
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.
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
// Full-app browser measurements land closer to a ~116px attachment row once
// the bubble shrinks to content width, so calibrate the estimate to that DOM.
const USER_ATTACHMENT_ROW_HEIGHT_PX = 116;
const USER_BUBBLE_WIDTH_RATIO = 0.8;
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
-29
View File
@@ -15,12 +15,9 @@ import type { GitListBranchesResult } from "@t3tools/contracts";
import {
gitBranchSearchInfiniteQueryOptions,
gitMutationKeys,
gitQueryKeys,
gitPreparePullRequestThreadMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
invalidateGitStatusQuery,
gitStatusQueryOptions,
invalidateGitQueries,
} from "./gitReactQuery";
@@ -84,7 +81,6 @@ 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",
@@ -92,7 +88,6 @@ describe("invalidateGitQueries", () => {
}).queryKey,
BRANCH_SEARCH_RESULT,
);
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/b",
@@ -103,9 +98,6 @@ describe("invalidateGitQueries", () => {
await invalidateGitQueries(queryClient, { cwd: "/repo/a" });
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -114,9 +106,6 @@ describe("invalidateGitQueries", () => {
}).queryKey,
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -127,21 +116,3 @@ describe("invalidateGitQueries", () => {
).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);
});
});
+29 -69
View File
@@ -12,15 +12,12 @@ import {
import { ensureNativeApi } from "../nativeApi";
import { getWsRpcClient } from "../wsRpcClient";
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,
@@ -38,37 +35,18 @@ export const gitMutationKeys = {
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.branches(cwd) });
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
export function invalidateGitStatusQuery(queryClient: QueryClient, cwd: string | null) {
function invalidateGitBranchQueries(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),
queryFn: async () => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git status is unavailable.");
return api.git.status({ cwd });
},
enabled: cwd !== null,
staleTime: GIT_STATUS_STALE_TIME_MS,
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
});
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) });
}
export function gitBranchSearchInfiniteQueryOptions(input: {
@@ -128,8 +106,8 @@ export function gitInitMutationOptions(input: { cwd: string | null; queryClient:
if (!input.cwd) throw new Error("Git init is unavailable.");
return api.git.init({ cwd: input.cwd });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -145,8 +123,8 @@ export function gitCheckoutMutationOptions(input: {
if (!input.cwd) throw new Error("Git checkout is unavailable.");
return api.git.checkout({ cwd: input.cwd, branch });
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -175,18 +153,18 @@ export function gitRunStackedActionMutationOptions(input: {
if (!input.cwd) throw new Error("Git action is unavailable.");
return getWsRpcClient().git.runStackedAction(
{
action,
actionId,
cwd: input.cwd,
action,
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
...(featureBranch ? { featureBranch: true } : {}),
...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
},
...(onProgress ? [{ onProgress }] : []),
);
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
@@ -199,31 +177,19 @@ export function gitPullMutationOptions(input: { cwd: string | null; queryClient:
if (!input.cwd) throw new Error("Git pull is unavailable.");
return api.git.pull({ cwd: input.cwd });
},
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({
cwd,
branch,
newBranch,
path,
}: {
cwd: string;
branch: string;
newBranch: string;
path?: string | null;
}) => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree creation is unavailable.");
return api.git.createWorktree({ cwd, branch, newBranch, path: path ?? null });
},
mutationKey: ["git", "mutation", "create-worktree"] as const,
onSettled: async () => {
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["createWorktree"]>[0],
) => ensureNativeApi().git.createWorktree(args),
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
@@ -231,13 +197,11 @@ export function gitCreateWorktreeMutationOptions(input: { queryClient: QueryClie
export function gitRemoveWorktreeMutationOptions(input: { queryClient: QueryClient }) {
return mutationOptions({
mutationFn: async ({ cwd, path, force }: { cwd: string; path: string; force?: boolean }) => {
const api = ensureNativeApi();
if (!cwd) throw new Error("Git worktree removal is unavailable.");
return api.git.removeWorktree({ cwd, path, force });
},
mutationKey: ["git", "mutation", "remove-worktree"] as const,
onSettled: async () => {
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["removeWorktree"]>[0],
) => ensureNativeApi().git.removeWorktree(args),
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
@@ -248,11 +212,8 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
queryClient: QueryClient;
}) {
return mutationOptions({
mutationFn: async ({
reference,
mode,
threadId,
}: {
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
mutationFn: async (args: {
reference: string;
mode: "local" | "worktree";
threadId?: ThreadId;
@@ -261,14 +222,13 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
return api.git.preparePullRequestThread({
cwd: input.cwd,
reference,
mode,
...(threadId ? { threadId } : {}),
reference: args.reference,
mode: args.mode,
...(args.threadId ? { threadId: args.threadId } : {}),
});
},
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
},
});
}
+112
View File
@@ -0,0 +1,112 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
getGitStatusSnapshot,
resetGitStatusStateForTests,
refreshGitStatus,
watchGitStatus,
} from "./gitStatusState";
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const gitClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
};
function emitGitStatus(event: GitStatusResult) {
for (const listener of gitStatusListeners) {
listener(event);
}
}
afterEach(() => {
gitStatusListeners.clear();
gitClient.onStatus.mockClear();
gitClient.refreshStatus.mockClear();
resetGitStatusStateForTests();
});
describe("gitStatusState", () => {
it("starts fresh cwd state in a pending state", () => {
expect(getGitStatusSnapshot("/fresh")).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
});
it("shares one live subscription per cwd and updates the per-cwd atom snapshot", () => {
const releaseA = watchGitStatus("/repo", gitClient);
const releaseB = watchGitStatus("/repo", gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(getGitStatusSnapshot("/repo")).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
emitGitStatus(BASE_STATUS);
expect(getGitStatusSnapshot("/repo")).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
releaseA();
expect(gitStatusListeners.size).toBe(1);
releaseB();
expect(gitStatusListeners.size).toBe(0);
});
it("refreshes git status through the unary RPC without restarting the stream", async () => {
const release = watchGitStatus("/repo", gitClient);
emitGitStatus(BASE_STATUS);
const refreshed = await refreshGitStatus("/repo", gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
expect(getGitStatusSnapshot("/repo")).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
});
+223
View File
@@ -0,0 +1,223 @@
import { useAtomValue } from "@effect/atom-react";
import { type GitManagerServiceError, type GitStatusResult } from "@t3tools/contracts";
import { Cause } from "effect";
import { Atom } from "effect/unstable/reactivity";
import { useEffect } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { getWsRpcClient, type WsRpcClient } from "../wsRpcClient";
export type GitStatusStreamError = GitManagerServiceError;
export interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitStatusStreamError | null;
readonly cause: Cause.Cause<GitStatusStreamError> | null;
readonly isPending: boolean;
}
type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
interface WatchedGitStatus {
refCount: number;
unsubscribe: () => void;
}
const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
...EMPTY_GIT_STATUS_STATE,
isPending: true,
});
const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
);
const NOOP: () => void = () => undefined;
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
const knownGitStatusCwds = new Set<string>();
const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
const gitStatusLastRefreshAtByCwd = new Map<string, number>();
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
let sharedGitStatusClient: GitStatusClient | null = null;
const gitStatusStateAtom = Atom.family((cwd: string) => {
knownGitStatusCwds.add(cwd);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${cwd}`),
);
});
export function getGitStatusSnapshot(cwd: string | null): GitStatusState {
if (cwd === null) {
return EMPTY_GIT_STATUS_STATE;
}
return appAtomRegistry.get(gitStatusStateAtom(cwd));
}
export function watchGitStatus(
cwd: string | null,
client: GitStatusClient = getWsRpcClient().git,
): () => void {
if (cwd === null) {
return NOOP;
}
ensureGitStatusClient(client);
const watched = watchedGitStatuses.get(cwd);
if (watched) {
watched.refCount += 1;
return () => unwatchGitStatus(cwd);
}
watchedGitStatuses.set(cwd, {
refCount: 1,
unsubscribe: subscribeToGitStatus(cwd),
});
return () => unwatchGitStatus(cwd);
}
export function refreshGitStatus(
cwd: string | null,
client: GitStatusClient = getWsRpcClient().git,
): Promise<GitStatusResult | null> {
if (cwd === null) {
return Promise.resolve(null);
}
ensureGitStatusClient(client);
const currentInFlight = gitStatusRefreshInFlight.get(cwd);
if (currentInFlight) {
return currentInFlight;
}
const lastRequestedAt = gitStatusLastRefreshAtByCwd.get(cwd) ?? 0;
if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getGitStatusSnapshot(cwd).data);
}
gitStatusLastRefreshAtByCwd.set(cwd, Date.now());
const refreshPromise = client.refreshStatus({ cwd }).finally(() => {
gitStatusRefreshInFlight.delete(cwd);
});
gitStatusRefreshInFlight.set(cwd, refreshPromise);
return refreshPromise;
}
export function resetGitStatusStateForTests(): void {
for (const watched of watchedGitStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
gitStatusRefreshInFlight.clear();
gitStatusLastRefreshAtByCwd.clear();
sharedGitStatusClient = null;
for (const cwd of knownGitStatusCwds) {
appAtomRegistry.set(gitStatusStateAtom(cwd), INITIAL_GIT_STATUS_STATE);
}
knownGitStatusCwds.clear();
}
export function useGitStatus(cwd: string | null): GitStatusState {
useEffect(() => watchGitStatus(cwd), [cwd]);
const state = useAtomValue(cwd !== null ? gitStatusStateAtom(cwd) : EMPTY_GIT_STATUS_ATOM);
return cwd === null ? EMPTY_GIT_STATUS_STATE : state;
}
function ensureGitStatusClient(client: GitStatusClient): void {
if (sharedGitStatusClient === client) {
return;
}
if (sharedGitStatusClient !== null) {
resetLiveGitStatusSubscriptions();
}
sharedGitStatusClient = client;
}
function resetLiveGitStatusSubscriptions(): void {
for (const watched of watchedGitStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
}
function unwatchGitStatus(cwd: string): void {
const watched = watchedGitStatuses.get(cwd);
if (!watched) {
return;
}
watched.refCount -= 1;
if (watched.refCount > 0) {
return;
}
watched.unsubscribe();
watchedGitStatuses.delete(cwd);
}
function subscribeToGitStatus(cwd: string): () => void {
const client = sharedGitStatusClient;
if (!client) {
return NOOP;
}
markGitStatusPending(cwd);
return client.onStatus(
{ cwd },
(status) => {
appAtomRegistry.set(gitStatusStateAtom(cwd), {
data: status,
error: null,
cause: null,
isPending: false,
});
},
{
onResubscribe: () => {
markGitStatusPending(cwd);
},
},
);
}
function markGitStatusPending(cwd: string): void {
const atom = gitStatusStateAtom(cwd);
const current = appAtomRegistry.get(atom);
const next =
current.data === null
? INITIAL_GIT_STATUS_STATE
: {
...current,
error: null,
cause: null,
isPending: true,
};
if (
current.data === next.data &&
current.error === next.error &&
current.cause === next.cause &&
current.isPending === next.isPending
) {
return;
}
appAtomRegistry.set(atom, next);
}
+2 -2
View File
@@ -25,7 +25,7 @@ export function ensureNativeApi(): NativeApi {
return api;
}
export function __resetNativeApiForTests() {
export async function __resetNativeApiForTests() {
cachedApi = undefined;
__resetWsNativeApiForTests();
await __resetWsNativeApiForTests();
}
+46 -1
View File
@@ -3,6 +3,7 @@ import {
DEFAULT_SERVER_SETTINGS,
type DesktopBridge,
EventId,
type GitStatusResult,
ProjectId,
type OrchestrationEvent,
type ServerConfig,
@@ -31,6 +32,7 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>();
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const rpcClientMock = {
dispose: vi.fn(),
@@ -54,7 +56,10 @@ const rpcClientMock = {
},
git: {
pull: vi.fn(),
status: vi.fn(),
refreshStatus: vi.fn(),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
runStackedAction: vi.fn(),
listBranches: vi.fn(),
createWorktree: vi.fn(),
@@ -168,12 +173,26 @@ const baseServerConfig: ServerConfig = {
settings: DEFAULT_SERVER_SETTINGS,
};
const baseGitStatus: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/streamed",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
showContextMenuFallbackMock.mockReset();
terminalEventListeners.clear();
orchestrationEventListeners.clear();
gitStatusListeners.clear();
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
});
@@ -243,6 +262,32 @@ describe("wsNativeApi", () => {
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
});
it("forwards git status stream events", async () => {
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
const onStatus = vi.fn();
api.git.onStatus({ cwd: "/repo" }, onStatus);
const gitStatus = baseGitStatus;
emitEvent(gitStatusListeners, gitStatus);
expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
expect(onStatus).toHaveBeenCalledWith(gitStatus);
});
it("forwards git status refreshes directly to the RPC client", async () => {
rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus);
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
await api.git.refreshStatus({ cwd: "/repo" });
expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
});
it("forwards orchestration stream subscription options to the RPC client", async () => {
const { createWsNativeApi } = await import("./wsNativeApi");
+8 -3
View File
@@ -1,6 +1,8 @@
import { type ContextMenuItem, type NativeApi } from "@t3tools/contracts";
import { resetGitStatusStateForTests } from "./lib/gitStatusState";
import { showContextMenuFallback } from "./contextMenuFallback";
import { __resetWsRpcAtomClientForTests } from "./rpc/client";
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
import { resetServerStateForTests } from "./rpc/serverState";
import { resetWsConnectionStateForTests } from "./rpc/wsConnectionState";
@@ -8,9 +10,11 @@ import { __resetWsRpcClientForTests, getWsRpcClient } from "./wsRpcClient";
let instance: { api: NativeApi } | null = null;
export function __resetWsNativeApiForTests() {
export async function __resetWsNativeApiForTests() {
instance = null;
__resetWsRpcClientForTests();
await __resetWsRpcAtomClientForTests();
await __resetWsRpcClientForTests();
resetGitStatusStateForTests();
resetRequestLatencyStateForTests();
resetServerStateForTests();
resetWsConnectionStateForTests();
@@ -65,7 +69,8 @@ export function createWsNativeApi(): NativeApi {
},
git: {
pull: rpcClient.git.pull,
status: rpcClient.git.status,
refreshStatus: rpcClient.git.refreshStatus,
onStatus: (input, callback, options) => rpcClient.git.onStatus(input, callback, options),
listBranches: rpcClient.git.listBranches,
createWorktree: rpcClient.git.createWorktree,
removeWorktree: rpcClient.git.removeWorktree,
+94
View File
@@ -0,0 +1,94 @@
import type {
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vitest";
import { createWsRpcClient } from "./wsRpcClient";
import { type WsTransport } from "./wsTransport";
const baseLocalStatus: GitStatusLocalResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
describe("wsRpcClient", () => {
it("reduces git status stream events into flat status snapshots", () => {
const subscribe = vi.fn(<TValue>(_connect: unknown, listener: (value: TValue) => void) => {
for (const event of [
{
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
},
{
_tag: "remoteUpdated",
remote: baseRemoteStatus,
},
{
_tag: "localUpdated",
local: {
...baseLocalStatus,
hasWorkingTreeChanges: true,
},
},
] satisfies GitStatusStreamEvent[]) {
listener(event as TValue);
}
return () => undefined;
});
const transport = {
dispose: vi.fn(async () => undefined),
reconnect: vi.fn(async () => undefined),
request: vi.fn(),
requestStream: vi.fn(),
subscribe,
} satisfies Pick<
WsTransport,
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
>;
const client = createWsRpcClient(transport as unknown as WsTransport);
const listener = vi.fn();
client.git.onStatus({ cwd: "/repo" }, listener);
expect(listener.mock.calls).toEqual([
[
{
...baseLocalStatus,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
},
],
[
{
...baseLocalStatus,
...baseRemoteStatus,
},
],
[
{
...baseLocalStatus,
...baseRemoteStatus,
hasWorkingTreeChanges: true,
},
],
]);
});
});
+22 -2
View File
@@ -2,11 +2,14 @@ import {
type GitActionProgressEvent,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusResult,
type GitStatusStreamEvent,
type NativeApi,
ORCHESTRATION_WS_METHODS,
type ServerSettingsPatch,
WS_METHODS,
} from "@t3tools/contracts";
import { applyGitStatusStreamEvent } from "@t3tools/shared/git";
import { Effect, Stream } from "effect";
import { type WsRpcProtocolClient } from "./rpc/protocol";
@@ -64,7 +67,12 @@ export interface WsRpcClient {
};
readonly git: {
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
readonly status: RpcUnaryMethod<typeof WS_METHODS.gitStatus>;
readonly refreshStatus: RpcUnaryMethod<typeof WS_METHODS.gitRefreshStatus>;
readonly onStatus: (
input: RpcInput<typeof WS_METHODS.subscribeGitStatus>,
listener: (status: GitStatusResult) => void,
options?: StreamSubscriptionOptions,
) => () => void;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
@@ -149,7 +157,19 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
},
git: {
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)),
refreshStatus: (input) =>
transport.request((client) => client[WS_METHODS.gitRefreshStatus](input)),
onStatus: (input, listener, options) => {
let current: GitStatusResult | null = null;
return transport.subscribe(
(client) => client[WS_METHODS.subscribeGitStatus](input),
(event: GitStatusStreamEvent) => {
current = applyGitStatusStreamEvent(current, event);
listener(current);
},
options,
);
},
runStackedAction: async (input, options) => {
let result: GitRunStackedActionResult | null = null;
+2 -1
View File
@@ -24,6 +24,7 @@ interface BrowserWsRpcHarnessOptions {
const STREAM_METHODS = new Set<string>([
WS_METHODS.gitRunStackedAction,
WS_METHODS.subscribeGitStatus,
WS_METHODS.subscribeOrchestrationDomainEvents,
WS_METHODS.subscribeTerminalEvents,
WS_METHODS.subscribeServerConfig,
@@ -108,7 +109,7 @@ export class BrowserWsRpcHarness {
async onMessage(rawData: string): Promise<void> {
const server = await this.serverReady;
if (!server) {
throw new Error("RPC test server is not connected");
return;
}
const messages = this.parser.decode(rawData);
for (const message of messages) {
+49 -1
View File
@@ -44,6 +44,14 @@ 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 GitHostingProviderKind = Schema.Literals(["github", "gitlab", "unknown"]);
export type GitHostingProviderKind = typeof GitHostingProviderKind.Type;
export const GitHostingProvider = Schema.Struct({
kind: GitHostingProviderKind,
name: TrimmedNonEmptyStringSchema,
baseUrl: Schema.String,
});
export type GitHostingProvider = typeof GitHostingProvider.Type;
export const GitRunStackedActionToastRunAction = Schema.Struct({
kind: GitStackedAction,
});
@@ -161,9 +169,15 @@ export type GitRemoveWorktreeInput = typeof GitRemoveWorktreeInput.Type;
export const GitCreateBranchInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
branch: TrimmedNonEmptyStringSchema,
checkout: Schema.optional(Schema.Boolean),
});
export type GitCreateBranchInput = typeof GitCreateBranchInput.Type;
export const GitCreateBranchResult = Schema.Struct({
branch: TrimmedNonEmptyStringSchema,
});
export type GitCreateBranchResult = typeof GitCreateBranchResult.Type;
export const GitCheckoutInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
branch: TrimmedNonEmptyStringSchema,
@@ -186,8 +200,9 @@ const GitStatusPr = Schema.Struct({
state: GitStatusPrState,
});
export const GitStatusResult = Schema.Struct({
const GitStatusLocalShape = {
isRepo: Schema.Boolean,
hostingProvider: Schema.optional(GitHostingProvider),
hasOriginRemote: Schema.Boolean,
isDefaultBranch: Schema.Boolean,
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
@@ -203,13 +218,41 @@ export const GitStatusResult = Schema.Struct({
insertions: NonNegativeInt,
deletions: NonNegativeInt,
}),
};
const GitStatusRemoteShape = {
hasUpstream: Schema.Boolean,
aheadCount: NonNegativeInt,
behindCount: NonNegativeInt,
pr: Schema.NullOr(GitStatusPr),
};
export const GitStatusLocalResult = Schema.Struct(GitStatusLocalShape);
export type GitStatusLocalResult = typeof GitStatusLocalResult.Type;
export const GitStatusRemoteResult = Schema.Struct(GitStatusRemoteShape);
export type GitStatusRemoteResult = typeof GitStatusRemoteResult.Type;
export const GitStatusResult = Schema.Struct({
...GitStatusLocalShape,
...GitStatusRemoteShape,
});
export type GitStatusResult = typeof GitStatusResult.Type;
export const GitStatusStreamEvent = Schema.Union([
Schema.TaggedStruct("snapshot", {
local: GitStatusLocalResult,
remote: Schema.NullOr(GitStatusRemoteResult),
}),
Schema.TaggedStruct("localUpdated", {
local: GitStatusLocalResult,
}),
Schema.TaggedStruct("remoteUpdated", {
remote: Schema.NullOr(GitStatusRemoteResult),
}),
]);
export type GitStatusStreamEvent = typeof GitStatusStreamEvent.Type;
export const GitListBranchesResult = Schema.Struct({
branches: Schema.Array(GitBranch),
isRepo: Schema.Boolean,
@@ -236,6 +279,11 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({
});
export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type;
export const GitCheckoutResult = Schema.Struct({
branch: Schema.NullOr(TrimmedNonEmptyStringSchema),
});
export type GitCheckoutResult = typeof GitCheckoutResult.Type;
export const GitRunStackedActionResult = Schema.Struct({
action: GitStackedAction,
branch: Schema.Struct({
+12 -3
View File
@@ -1,5 +1,6 @@
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
@@ -15,6 +16,7 @@ import type {
GitResolvePullRequestResult,
GitStatusInput,
GitStatusResult,
GitCreateBranchResult,
} from "./git";
import type {
ProjectSearchEntriesInput,
@@ -148,8 +150,8 @@ export interface NativeApi {
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<void>;
checkout: (input: GitCheckoutInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<GitCreateBranchResult>;
checkout: (input: GitCheckoutInput) => Promise<GitCheckoutResult>;
init: (input: GitInitInput) => Promise<void>;
resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;
preparePullRequestThread: (
@@ -157,7 +159,14 @@ export interface NativeApi {
) => Promise<GitPreparePullRequestThreadResult>;
// Stacked action API
pull: (input: GitPullInput) => Promise<GitPullResult>;
status: (input: GitStatusInput) => Promise<GitStatusResult>;
refreshStatus: (input: GitStatusInput) => Promise<GitStatusResult>;
onStatus: (
input: GitStatusInput,
callback: (status: GitStatusResult) => void,
options?: {
onResubscribe?: () => void;
},
) => () => void;
};
contextMenu: {
show: <T extends string>(
+18 -4
View File
@@ -6,8 +6,10 @@ import { OpenError, OpenInEditorInput } from "./editor";
import {
GitActionProgressEvent,
GitCheckoutInput,
GitCheckoutResult,
GitCommandError,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
@@ -24,6 +26,7 @@ import {
GitRunStackedActionInput,
GitStatusInput,
GitStatusResult,
GitStatusStreamEvent,
} from "./git";
import { KeybindingsConfigError } from "./keybindings";
import {
@@ -83,7 +86,7 @@ export const WS_METHODS = {
// Git methods
gitPull: "git.pull",
gitStatus: "git.status",
gitRefreshStatus: "git.refreshStatus",
gitRunStackedAction: "git.runStackedAction",
gitListBranches: "git.listBranches",
gitCreateWorktree: "git.createWorktree",
@@ -110,6 +113,7 @@ export const WS_METHODS = {
serverUpdateSettings: "server.updateSettings",
// Streaming subscriptions
subscribeGitStatus: "subscribeGitStatus",
subscribeOrchestrationDomainEvents: "subscribeOrchestrationDomainEvents",
subscribeTerminalEvents: "subscribeTerminalEvents",
subscribeServerConfig: "subscribeServerConfig",
@@ -162,10 +166,11 @@ export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
error: OpenError,
});
export const WsGitStatusRpc = Rpc.make(WS_METHODS.gitStatus, {
export const WsSubscribeGitStatusRpc = Rpc.make(WS_METHODS.subscribeGitStatus, {
payload: GitStatusInput,
success: GitStatusResult,
success: GitStatusStreamEvent,
error: GitManagerServiceError,
stream: true,
});
export const WsGitPullRpc = Rpc.make(WS_METHODS.gitPull, {
@@ -174,6 +179,12 @@ export const WsGitPullRpc = Rpc.make(WS_METHODS.gitPull, {
error: GitCommandError,
});
export const WsGitRefreshStatusRpc = Rpc.make(WS_METHODS.gitRefreshStatus, {
payload: GitStatusInput,
success: GitStatusResult,
error: GitManagerServiceError,
});
export const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, {
payload: GitRunStackedActionInput,
success: GitActionProgressEvent,
@@ -212,11 +223,13 @@ export const WsGitRemoveWorktreeRpc = Rpc.make(WS_METHODS.gitRemoveWorktree, {
export const WsGitCreateBranchRpc = Rpc.make(WS_METHODS.gitCreateBranch, {
payload: GitCreateBranchInput,
success: GitCreateBranchResult,
error: GitCommandError,
});
export const WsGitCheckoutRpc = Rpc.make(WS_METHODS.gitCheckout, {
payload: GitCheckoutInput,
success: GitCheckoutResult,
error: GitCommandError,
});
@@ -330,8 +343,9 @@ export const WsRpcGroup = RpcGroup.make(
WsProjectsSearchEntriesRpc,
WsProjectsWriteFileRpc,
WsShellOpenInEditorRpc,
WsGitStatusRpc,
WsSubscribeGitStatusRpc,
WsGitPullRpc,
WsGitRefreshStatusRpc,
WsGitRunStackedActionRpc,
WsGitResolvePullRequestRpc,
WsGitPreparePullRequestThreadRpc,
+67
View File
@@ -0,0 +1,67 @@
import type { GitStatusRemoteResult, GitStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { applyGitStatusStreamEvent } from "./git";
describe("applyGitStatusStreamEvent", () => {
it("treats a remote-only update as a repository when local state is missing", () => {
const remote: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 2,
behindCount: 1,
pr: null,
};
expect(applyGitStatusStreamEvent(null, { _tag: "remoteUpdated", remote })).toEqual({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 2,
behindCount: 1,
pr: null,
});
});
it("preserves local-only fields when applying a remote update", () => {
const current: GitStatusResult = {
isRepo: true,
hostingProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasWorkingTreeChanges: true,
workingTree: {
files: [{ path: "src/demo.ts", insertions: 1, deletions: 0 }],
insertions: 1,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const remote: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 2,
behindCount: 1,
pr: null,
};
expect(applyGitStatusStreamEvent(current, { _tag: "remoteUpdated", remote })).toEqual({
...current,
hasUpstream: true,
aheadCount: 2,
behindCount: 1,
pr: null,
});
});
});
+138 -1
View File
@@ -1,4 +1,11 @@
import type { GitBranch } from "@t3tools/contracts";
import type {
GitBranch,
GitHostingProvider,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
/**
* Sanitize an arbitrary string into a valid, lowercase git branch fragment.
@@ -119,3 +126,133 @@ export function dedupeRemoteBranchesWithLocalMatches(
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
function parseGitRemoteHost(remoteUrl: string): string | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.startsWith("git@")) {
const hostWithPath = trimmed.slice("git@".length);
const separatorIndex = hostWithPath.search(/[:/]/);
if (separatorIndex <= 0) {
return null;
}
return hostWithPath.slice(0, separatorIndex).toLowerCase();
}
try {
return new URL(trimmed).hostname.toLowerCase();
} catch {
return null;
}
}
function toBaseUrl(host: string): string {
return `https://${host}`;
}
function isGitHubHost(host: string): boolean {
return host === "github.com" || host.includes("github");
}
function isGitLabHost(host: string): boolean {
return host === "gitlab.com" || host.includes("gitlab");
}
export function detectGitHostingProviderFromRemoteUrl(
remoteUrl: string,
): GitHostingProvider | null {
const host = parseGitRemoteHost(remoteUrl);
if (!host) {
return null;
}
if (isGitHubHost(host)) {
return {
kind: "github",
name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
if (isGitLabHost(host)) {
return {
kind: "gitlab",
name: host === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",
baseUrl: toBaseUrl(host),
};
}
return {
kind: "unknown",
name: host,
baseUrl: toBaseUrl(host),
};
}
const EMPTY_GIT_STATUS_REMOTE: GitStatusRemoteResult = {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
};
export function mergeGitStatusParts(
local: GitStatusLocalResult,
remote: GitStatusRemoteResult | null,
): GitStatusResult {
return {
...local,
...(remote ?? EMPTY_GIT_STATUS_REMOTE),
};
}
function toRemoteStatusPart(status: GitStatusResult): GitStatusRemoteResult {
return {
hasUpstream: status.hasUpstream,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
pr: status.pr,
};
}
function toLocalStatusPart(status: GitStatusResult): GitStatusLocalResult {
return {
isRepo: status.isRepo,
...(status.hostingProvider ? { hostingProvider: status.hostingProvider } : {}),
hasOriginRemote: status.hasOriginRemote,
isDefaultBranch: status.isDefaultBranch,
branch: status.branch,
hasWorkingTreeChanges: status.hasWorkingTreeChanges,
workingTree: status.workingTree,
};
}
export function applyGitStatusStreamEvent(
current: GitStatusResult | null,
event: GitStatusStreamEvent,
): GitStatusResult {
switch (event._tag) {
case "snapshot":
return mergeGitStatusParts(event.local, event.remote);
case "localUpdated":
return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);
case "remoteUpdated":
if (current === null) {
return mergeGitStatusParts(
{
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
},
event.remote,
);
}
return mergeGitStatusParts(toLocalStatusPart(current), event.remote);
}
}