Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4db64afccc | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d |
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}),
|
||||
);
|
||||
@@ -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") {}
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
spawnAndCollect,
|
||||
type CommandResult,
|
||||
} from "../providerSnapshot";
|
||||
import { DEFAULT_CODEX_MODEL_CAPABILITIES } from "@t3tools/shared/model";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider";
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
@@ -159,13 +160,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
|
||||
const slug = model?.trim();
|
||||
return (
|
||||
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
|
||||
DEFAULT_CODEX_MODEL_CAPABILITIES
|
||||
);
|
||||
}
|
||||
|
||||
@@ -339,7 +335,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
|
||||
const models = providerModelsFromSettings(
|
||||
BUILT_IN_MODELS,
|
||||
PROVIDER,
|
||||
codexSettings.customModels,
|
||||
DEFAULT_CODEX_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
|
||||
@@ -220,6 +220,41 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("adds standard codex capabilities to custom codex models", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
codex: {
|
||||
customModels: ["custom-codex-model"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* checkCodexProviderStatus().pipe(
|
||||
Effect.provide(serverSettingsLayer),
|
||||
);
|
||||
const customModel = status.models.find((model) => model.slug === "custom-codex-model");
|
||||
|
||||
assert.ok(customModel);
|
||||
assert.strictEqual(customModel.isCustom, true);
|
||||
assert.deepStrictEqual(
|
||||
customModel.capabilities?.reasoningEffortLevels.map((level) => level.value),
|
||||
["xhigh", "high", "medium", "low"],
|
||||
);
|
||||
assert.strictEqual(customModel.capabilities?.supportsFastMode, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
@@ -102,6 +103,7 @@ export function providerModelsFromSettings(
|
||||
builtInModels: ReadonlyArray<ServerProviderModel>,
|
||||
provider: ServerProvider["provider"],
|
||||
customModels: ReadonlyArray<string>,
|
||||
defaultCustomCapabilities: ModelCapabilities | null = null,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const resolvedBuiltInModels = [...builtInModels];
|
||||
const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
|
||||
@@ -117,7 +119,7 @@ export function providerModelsFromSettings(
|
||||
slug: normalized,
|
||||
name: normalized,
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
capabilities: defaultCustomCapabilities,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+376
-13
@@ -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();
|
||||
|
||||
@@ -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
@@ -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();
|
||||
|
||||
@@ -110,7 +106,6 @@ export function BranchToolbarBranchSelector({
|
||||
gitBranchSearchInfiniteQueryOptions({
|
||||
cwd: branchCwd,
|
||||
query: deferredTrimmedBranchQuery,
|
||||
enabled: isBranchMenuOpen,
|
||||
}),
|
||||
);
|
||||
const branches = useMemo(
|
||||
@@ -188,7 +183,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 +223,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 +255,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("");
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -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: [],
|
||||
@@ -866,7 +874,7 @@ async function expectComposerActionsContained(): Promise<void> {
|
||||
}
|
||||
|
||||
async function waitForInteractionModeButton(
|
||||
expectedLabel: "Chat" | "Plan",
|
||||
expectedLabel: "Build" | "Plan",
|
||||
): Promise<HTMLButtonElement> {
|
||||
return waitForElement(
|
||||
() =>
|
||||
@@ -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 },
|
||||
);
|
||||
@@ -2096,7 +2111,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const initialModeButton = await waitForInteractionModeButton("Chat");
|
||||
const initialModeButton = await waitForInteractionModeButton("Build");
|
||||
expect(initialModeButton.title).toContain("enter plan mode");
|
||||
|
||||
window.dispatchEvent(
|
||||
@@ -2109,7 +2124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
await waitForLayout();
|
||||
|
||||
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
|
||||
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
@@ -2125,7 +2140,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
expect((await waitForInteractionModeButton("Plan")).title).toContain(
|
||||
"return to normal chat mode",
|
||||
"return to normal build mode",
|
||||
);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
@@ -2142,7 +2157,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
|
||||
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
@@ -2818,6 +2833,55 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the active worktree path when saving a proposed plan to the workspace", async () => {
|
||||
const snapshot = createSnapshotWithLongProposedPlan();
|
||||
const threads = snapshot.threads.slice();
|
||||
const targetThreadIndex = threads.findIndex((thread) => thread.id === THREAD_ID);
|
||||
const targetThread = targetThreadIndex >= 0 ? threads[targetThreadIndex] : undefined;
|
||||
if (targetThread) {
|
||||
threads[targetThreadIndex] = {
|
||||
...targetThread,
|
||||
worktreePath: "/repo/worktrees/plan-thread",
|
||||
};
|
||||
}
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
threads,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const planActionsButton = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Plan actions"]'),
|
||||
"Unable to find proposed plan actions button.",
|
||||
);
|
||||
planActionsButton.click();
|
||||
|
||||
const saveToWorkspaceItem = await waitForElement(
|
||||
() =>
|
||||
(Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find(
|
||||
(item) => item.textContent?.trim() === "Save to workspace",
|
||||
) ?? null) as HTMLElement | null,
|
||||
'Unable to find "Save to workspace" menu item.',
|
||||
);
|
||||
saveToWorkspaceItem.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(
|
||||
"Enter a path relative to /repo/worktrees/plan-thread.",
|
||||
);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps pending-question footer actions inside the composer after a real resize", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: WIDE_FOOTER_VIEWPORT,
|
||||
|
||||
@@ -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(
|
||||
@@ -1476,7 +1476,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type: "slash-command",
|
||||
command: "default",
|
||||
label: "/default",
|
||||
description: "Switch this thread back to normal chat mode",
|
||||
description: "Switch this thread back to normal build mode",
|
||||
},
|
||||
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
@@ -1526,6 +1526,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
|
||||
const activeTerminalLaunchContext =
|
||||
terminalLaunchContext?.threadId === activeThreadId
|
||||
? terminalLaunchContext
|
||||
@@ -4004,7 +4005,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
timestampFormat={timestampFormat}
|
||||
workspaceRoot={activeProject?.cwd ?? undefined}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -4028,7 +4029,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<form
|
||||
ref={composerFormRef}
|
||||
onSubmit={onSend}
|
||||
className="mx-auto w-full min-w-0 max-w-[52rem]"
|
||||
className="mx-auto w-full min-w-0 max-w-208"
|
||||
data-chat-composer-form="true"
|
||||
>
|
||||
<div
|
||||
@@ -4283,13 +4284,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onClick={toggleInteractionMode}
|
||||
title={
|
||||
interactionMode === "plan"
|
||||
? "Plan mode — click to return to normal chat mode"
|
||||
? "Plan mode — click to return to normal build mode"
|
||||
: "Default mode — click to enter plan mode"
|
||||
}
|
||||
>
|
||||
<BotIcon />
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{interactionMode === "plan" ? "Plan" : "Chat"}
|
||||
{interactionMode === "plan" ? "Plan" : "Build"}
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
@@ -4438,7 +4439,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activePlan={activePlan}
|
||||
activeProposedPlan={sidebarProposedPlan}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
workspaceRoot={activeProject?.cwd ?? undefined}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
timestampFormat={timestampFormat}
|
||||
onClose={() => {
|
||||
setPlanSidebarOpen(false);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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({
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
))}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
type MessagesTimelineRow,
|
||||
} from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
deriveDisplayedUserMessageState,
|
||||
type ParsedTerminalContextEntry,
|
||||
@@ -385,7 +386,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}
|
||||
/>
|
||||
@@ -792,6 +793,16 @@ function workEntryPreview(
|
||||
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
|
||||
}
|
||||
|
||||
function workEntryRawCommand(
|
||||
workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
|
||||
): string | null {
|
||||
const rawCommand = workEntry.rawCommand?.trim();
|
||||
if (!rawCommand || !workEntry.command) {
|
||||
return null;
|
||||
}
|
||||
return rawCommand === workEntry.command.trim() ? null : rawCommand;
|
||||
}
|
||||
|
||||
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
|
||||
if (workEntry.requestKind === "command") return TerminalIcon;
|
||||
if (workEntry.requestKind === "file-read") return EyeIcon;
|
||||
@@ -840,6 +851,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
const EntryIcon = workEntryIcon(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const preview = workEntryPreview(workEntry);
|
||||
const rawCommand = workEntryRawCommand(workEntry);
|
||||
const displayText = preview ? `${heading} - ${preview}` : heading;
|
||||
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
|
||||
const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
|
||||
@@ -853,19 +865,46 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<EntryIcon className="size-3" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-[11px] leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
title={displayText}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
|
||||
</p>
|
||||
<div className="max-w-full">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-[11px] leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
title={rawCommand ? undefined : displayText}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview &&
|
||||
(rawCommand ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
closeDelay={0}
|
||||
delay={75}
|
||||
render={
|
||||
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
|
||||
{" "}
|
||||
- {preview}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span className="text-muted-foreground/55"> - {preview}</span>
|
||||
))}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{hasChangedFiles && !previewIsChangedFiles && (
|
||||
|
||||
@@ -477,6 +477,23 @@ describe("TraitsPicker (Codex)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows default effort options for custom codex models without capabilities", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
model: "custom-codex-model",
|
||||
options: { reasoningEffort: "low" },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Extra High");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("Low");
|
||||
});
|
||||
});
|
||||
|
||||
it("persists sticky codex model options when traits change", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
|
||||
@@ -149,6 +149,36 @@ describe("getComposerProviderState", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses standard codex defaults for custom codex models without capabilities", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "custom-codex-model",
|
||||
models: [
|
||||
...CODEX_MODELS,
|
||||
{
|
||||
slug: "custom-codex-model",
|
||||
name: "custom-codex-model",
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "low",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves codex fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export function ensureNativeApi(): NativeApi {
|
||||
return api;
|
||||
}
|
||||
|
||||
export function __resetNativeApiForTests() {
|
||||
export async function __resetNativeApiForTests() {
|
||||
cachedApi = undefined;
|
||||
__resetWsNativeApiForTests();
|
||||
await __resetWsNativeApiForTests();
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { DEFAULT_CODEX_MODEL_CAPABILITIES, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
@@ -53,7 +53,10 @@ export function getProviderModelCapabilities(
|
||||
provider: ProviderKind,
|
||||
): ModelCapabilities {
|
||||
const slug = normalizeModelSlug(model, provider);
|
||||
return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;
|
||||
const capabilities = models.find((candidate) => candidate.slug === slug)?.capabilities;
|
||||
return (
|
||||
capabilities ?? (provider === "codex" ? DEFAULT_CODEX_MODEL_CAPABILITIES : EMPTY_CAPABILITIES)
|
||||
);
|
||||
}
|
||||
|
||||
export function getDefaultServerModel(
|
||||
|
||||
@@ -3,8 +3,9 @@ import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atomRegistry";
|
||||
|
||||
export const SLOW_RPC_ACK_THRESHOLD_MS = 2_500;
|
||||
export const SLOW_RPC_ACK_THRESHOLD_MS = 15_000;
|
||||
export const MAX_TRACKED_RPC_ACK_REQUESTS = 256;
|
||||
let slowRpcAckThresholdMs = SLOW_RPC_ACK_THRESHOLD_MS;
|
||||
|
||||
export interface SlowRpcAckRequest {
|
||||
readonly requestId: string;
|
||||
@@ -56,12 +57,12 @@ export function trackRpcRequestSent(requestId: string, tag: string): void {
|
||||
startedAt: new Date(startedAtMs).toISOString(),
|
||||
startedAtMs,
|
||||
tag,
|
||||
thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
thresholdMs: slowRpcAckThresholdMs,
|
||||
};
|
||||
const timeoutId = setTimeout(() => {
|
||||
pendingRpcAckRequests.delete(requestId);
|
||||
appendSlowRpcAckRequest(request);
|
||||
}, SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
}, slowRpcAckThresholdMs);
|
||||
|
||||
pendingRpcAckRequests.set(requestId, {
|
||||
request,
|
||||
@@ -119,9 +120,14 @@ function evictOldestPendingRpcRequestIfNeeded(): void {
|
||||
}
|
||||
|
||||
export function resetRequestLatencyStateForTests(): void {
|
||||
slowRpcAckThresholdMs = SLOW_RPC_ACK_THRESHOLD_MS;
|
||||
clearAllTrackedRpcRequests();
|
||||
}
|
||||
|
||||
export function setSlowRpcAckThresholdMsForTests(thresholdMs: number): void {
|
||||
slowRpcAckThresholdMs = thresholdMs;
|
||||
}
|
||||
|
||||
export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return useAtomValue(slowRpcAckRequestsAtom);
|
||||
}
|
||||
@@ -709,6 +709,97 @@ describe("deriveWorkLogEntries", () => {
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers for displayed command text", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool-windows-wrapper",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
item: {
|
||||
command: "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
expect(entry?.rawCommand).toBe(
|
||||
"\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
|
||||
);
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers from argv-style command payloads", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool-windows-wrapper-argv",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
item: {
|
||||
command: ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n foo ."],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe("rg -n foo .");
|
||||
expect(entry?.rawCommand).toBe(
|
||||
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."',
|
||||
);
|
||||
});
|
||||
|
||||
it("extracts command text from command detail when structured command metadata is missing", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool-windows-detail-fallback",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
detail:
|
||||
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command \'rg -n -F "new Date()" .\' <exited with exit code 0>',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe('rg -n -F "new Date()" .');
|
||||
expect(entry?.rawCommand).toBe(
|
||||
`"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not unwrap shell commands when no wrapper flag is present", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "command-tool-shell-script",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
data: {
|
||||
item: {
|
||||
command: "bash script.sh",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entry?.command).toBe("bash script.sh");
|
||||
expect(entry?.rawCommand).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps compact Codex tool metadata used for icons and labels", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
|
||||
+169
-12
@@ -38,6 +38,7 @@ export interface WorkLogEntry {
|
||||
label: string;
|
||||
detail?: string;
|
||||
command?: string;
|
||||
rawCommand?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
@@ -489,7 +490,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const command = extractToolCommand(payload);
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
@@ -507,8 +508,11 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
entry.detail = detail;
|
||||
}
|
||||
}
|
||||
if (command) {
|
||||
entry.command = command;
|
||||
if (commandPreview.command) {
|
||||
entry.command = commandPreview.command;
|
||||
}
|
||||
if (commandPreview.rawCommand) {
|
||||
entry.rawCommand = commandPreview.rawCommand;
|
||||
}
|
||||
if (changedFiles.length > 0) {
|
||||
entry.changedFiles = changedFiles;
|
||||
@@ -567,6 +571,7 @@ function mergeDerivedWorkLogEntries(
|
||||
const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
|
||||
const detail = next.detail ?? previous.detail;
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
@@ -576,6 +581,7 @@ function mergeDerivedWorkLogEntries(
|
||||
...next,
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
@@ -636,7 +642,121 @@ function asTrimmedString(value: unknown): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | null {
|
||||
function trimMatchingOuterQuotes(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (
|
||||
(trimmed.startsWith("'") && trimmed.endsWith("'")) ||
|
||||
(trimmed.startsWith('"') && trimmed.endsWith('"'))
|
||||
) {
|
||||
const unquoted = trimmed.slice(1, -1).trim();
|
||||
return unquoted.length > 0 ? unquoted : trimmed;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function executableBasename(value: string): string | null {
|
||||
const trimmed = trimMatchingOuterQuotes(value);
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const normalized = trimmed.replace(/\\/g, "/");
|
||||
const segments = normalized.split("/");
|
||||
const last = segments.at(-1)?.trim() ?? "";
|
||||
return last.length > 0 ? last.toLowerCase() : null;
|
||||
}
|
||||
|
||||
function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
|
||||
const quote = trimmed.charAt(0);
|
||||
const closeIndex = trimmed.indexOf(quote, 1);
|
||||
if (closeIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
executable: trimmed.slice(0, closeIndex + 1),
|
||||
rest: trimmed.slice(closeIndex + 1).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
const firstWhitespace = trimmed.search(/\s/);
|
||||
if (firstWhitespace < 0) {
|
||||
return {
|
||||
executable: trimmed,
|
||||
rest: "",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
executable: trimmed.slice(0, firstWhitespace),
|
||||
rest: trimmed.slice(firstWhitespace).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
const SHELL_WRAPPER_SPECS = [
|
||||
{
|
||||
executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
|
||||
wrapperFlagPattern: /(?:^|\s)-command\s+/i,
|
||||
},
|
||||
{
|
||||
executables: ["cmd", "cmd.exe"],
|
||||
wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
|
||||
},
|
||||
{
|
||||
executables: ["bash", "sh", "zsh"],
|
||||
wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
|
||||
},
|
||||
] as const;
|
||||
|
||||
function findShellWrapperSpec(shell: string) {
|
||||
return SHELL_WRAPPER_SPECS.find((spec) =>
|
||||
(spec.executables as ReadonlyArray<string>).includes(shell),
|
||||
);
|
||||
}
|
||||
|
||||
function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
|
||||
const match = wrapperFlagPattern.exec(value);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const command = value.slice(match.index + match[0].length).trim();
|
||||
if (command.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const unwrapped = trimMatchingOuterQuotes(command);
|
||||
return unwrapped.length > 0 ? unwrapped : null;
|
||||
}
|
||||
|
||||
function unwrapKnownShellCommandWrapper(value: string): string {
|
||||
const split = splitExecutableAndRest(value);
|
||||
if (!split || split.rest.length === 0) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const shell = executableBasename(split.executable);
|
||||
if (!shell) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const spec = findShellWrapperSpec(shell);
|
||||
if (!spec) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
|
||||
}
|
||||
|
||||
function formatCommandArrayPart(value: string): string {
|
||||
return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
|
||||
}
|
||||
|
||||
function formatCommandValue(value: unknown): string | null {
|
||||
const direct = asTrimmedString(value);
|
||||
if (direct) {
|
||||
return direct;
|
||||
@@ -647,21 +767,58 @@ function normalizeCommandValue(value: unknown): string | null {
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
return parts.length > 0 ? parts.join(" ") : null;
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return parts.map((part) => formatCommandArrayPart(part)).join(" ");
|
||||
}
|
||||
|
||||
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
|
||||
function normalizeCommandValue(value: unknown): string | null {
|
||||
const formatted = formatCommandValue(value);
|
||||
return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
|
||||
}
|
||||
|
||||
function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
|
||||
const formatted = formatCommandValue(value);
|
||||
if (!formatted || normalizedCommand === null) {
|
||||
return null;
|
||||
}
|
||||
return formatted === normalizedCommand ? null : formatted;
|
||||
}
|
||||
|
||||
function extractToolCommand(payload: Record<string, unknown> | null): {
|
||||
command: string | null;
|
||||
rawCommand: string | null;
|
||||
} {
|
||||
const data = asRecord(payload?.data);
|
||||
const item = asRecord(data?.item);
|
||||
const itemResult = asRecord(item?.result);
|
||||
const itemInput = asRecord(item?.input);
|
||||
const candidates = [
|
||||
normalizeCommandValue(item?.command),
|
||||
normalizeCommandValue(itemInput?.command),
|
||||
normalizeCommandValue(itemResult?.command),
|
||||
normalizeCommandValue(data?.command),
|
||||
const itemType = asTrimmedString(payload?.itemType);
|
||||
const detail = asTrimmedString(payload?.detail);
|
||||
const candidates: unknown[] = [
|
||||
item?.command,
|
||||
itemInput?.command,
|
||||
itemResult?.command,
|
||||
data?.command,
|
||||
itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
|
||||
];
|
||||
return candidates.find((candidate) => candidate !== null) ?? null;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const command = normalizeCommandValue(candidate);
|
||||
if (!command) {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
command,
|
||||
rawCommand: toRawToolCommand(candidate, command),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: null,
|
||||
rawCommand: null,
|
||||
};
|
||||
}
|
||||
|
||||
function extractToolTitle(payload: Record<string, unknown> | null): string | null {
|
||||
|
||||
@@ -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");
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -5,7 +5,11 @@ import {
|
||||
__resetClientTracingForTests,
|
||||
configureClientTracing,
|
||||
} from "./observability/clientTracing";
|
||||
import { getSlowRpcAckRequests, resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
|
||||
import {
|
||||
getSlowRpcAckRequests,
|
||||
resetRequestLatencyStateForTests,
|
||||
setSlowRpcAckThresholdMsForTests,
|
||||
} from "./rpc/requestLatencyState";
|
||||
import {
|
||||
getWsConnectionStatus,
|
||||
getWsConnectionUiState,
|
||||
@@ -292,6 +296,8 @@ describe("WsTransport", () => {
|
||||
});
|
||||
|
||||
it("marks unary requests as slow until the first server ack arrives", async () => {
|
||||
const slowAckThresholdMs = 25;
|
||||
setSlowRpcAckThresholdMsForTests(slowAckThresholdMs);
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
const requestPromise = transport.request((client) =>
|
||||
@@ -320,7 +326,7 @@ describe("WsTransport", () => {
|
||||
tag: WS_METHODS.serverUpsertKeybinding,
|
||||
},
|
||||
]);
|
||||
}, 5_000);
|
||||
}, 1_000);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
@@ -343,7 +349,7 @@ describe("WsTransport", () => {
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
|
||||
await transport.dispose();
|
||||
}, 10_000);
|
||||
}, 5_000);
|
||||
|
||||
it("sends unary RPC requests and resolves successful exits", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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>(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,19 @@ export interface SelectableModelOption {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
// ── Effort helpers ────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given effort value. */
|
||||
|
||||
Reference in new issue
Block a user