Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4db64afccc | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d | ||
|
|
12347082ef | ||
|
|
740d7a3216 | ||
|
|
cd7980b457 | ||
|
|
f2cd53f232 | ||
|
|
04a1ae77e6 |
No files matched your search
@@ -1,5 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
|
||||
@@ -48,7 +48,7 @@ import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointRea
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
@@ -297,7 +297,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
RuntimeReceiptBusTest,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -376,7 +376,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
@@ -86,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
@@ -104,7 +105,6 @@ const runTurn = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
@@ -116,7 +116,7 @@ const runTurn = (input: {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
@@ -149,7 +149,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -188,7 +188,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -242,7 +242,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
|
||||
@@ -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") {}
|
||||
+75
-2
@@ -1,6 +1,15 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { Data, Effect, FileSystem, Layer, Option, Path } from "effect";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpClientResponse,
|
||||
HttpRouter,
|
||||
HttpServerResponse,
|
||||
HttpServerRequest,
|
||||
} from "effect/unstable/http";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
@@ -9,10 +18,74 @@ import {
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
|
||||
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
|
||||
readonly cause: unknown;
|
||||
readonly bodyJson: OtlpTracer.TraceData;
|
||||
}> {}
|
||||
|
||||
export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
OTLP_TRACES_PROXY_PATH,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const config = yield* ServerConfig;
|
||||
const otlpTracesUrl = config.otlpTracesUrl;
|
||||
const browserTraceCollector = yield* BrowserTraceCollector;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
|
||||
|
||||
yield* Effect.try({
|
||||
try: () => decodeOtlpTraceRecords(bodyJson),
|
||||
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
|
||||
}).pipe(
|
||||
Effect.flatMap((records) => browserTraceCollector.record(records)),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to decode browser OTLP traces", {
|
||||
cause,
|
||||
bodyJson,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (otlpTracesUrl === undefined) {
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}
|
||||
|
||||
return yield* httpClient
|
||||
.post(otlpTracesUrl, {
|
||||
body: HttpBody.jsonUnsafe(bodyJson),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.as(HttpServerResponse.empty({ status: 204 })),
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to export browser OTLP traces", {
|
||||
cause,
|
||||
otlpTracesUrl,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
HttpRouter.cors({
|
||||
allowedMethods: ["POST", "OPTIONS"],
|
||||
allowedHeaders: ["content-type"],
|
||||
maxAge: 600,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
|
||||
@@ -4,6 +4,8 @@ import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/obse
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerLoggerLive } from "../../serverLogger.ts";
|
||||
import { makeLocalFileTracer } from "../LocalFileTracer.ts";
|
||||
import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts";
|
||||
import { makeTraceSink } from "../TraceSink.ts";
|
||||
|
||||
const otlpSerializationLayer = OtlpSerialization.layerJson;
|
||||
|
||||
@@ -16,9 +18,14 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
|
||||
);
|
||||
|
||||
const tracerLayer = Layer.effect(
|
||||
Tracer.Tracer,
|
||||
const tracerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: config.serverTracePath,
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
});
|
||||
const delegate =
|
||||
config.otlpTracesUrl === undefined
|
||||
? undefined
|
||||
@@ -34,13 +41,26 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
},
|
||||
});
|
||||
|
||||
return yield* makeLocalFileTracer({
|
||||
const tracer = yield* makeLocalFileTracer({
|
||||
filePath: config.serverTracePath,
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
sink,
|
||||
...(delegate ? { delegate } : {}),
|
||||
});
|
||||
|
||||
return Layer.mergeAll(
|
||||
Layer.succeed(Tracer.Tracer, tracer),
|
||||
Layer.succeed(BrowserTraceCollector, {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
for (const record of records) {
|
||||
sink.push(record);
|
||||
}
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Layer.provideMerge(otlpSerializationLayer));
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Logger, References, Tracer } from "effect";
|
||||
|
||||
import type { TraceRecord } from "./TraceRecord.ts";
|
||||
import type { EffectTraceRecord } from "./TraceRecord.ts";
|
||||
import { makeLocalFileTracer } from "./LocalFileTracer.ts";
|
||||
|
||||
const makeTestLayer = (tracePath: string) =>
|
||||
@@ -23,13 +23,13 @@ const makeTestLayer = (tracePath: string) =>
|
||||
Layer.succeed(References.MinimumLogLevel, "Info"),
|
||||
);
|
||||
|
||||
const readTraceRecords = (tracePath: string): Array<TraceRecord> =>
|
||||
const readTraceRecords = (tracePath: string): Array<EffectTraceRecord> =>
|
||||
fs
|
||||
.readFileSync(tracePath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as TraceRecord);
|
||||
.map((line) => JSON.parse(line) as EffectTraceRecord);
|
||||
|
||||
describe("LocalFileTracer", () => {
|
||||
it.effect("writes nested spans to disk and captures log messages as span events", () =>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type * as Exit from "effect/Exit";
|
||||
import { Effect, Option, Tracer } from "effect";
|
||||
|
||||
import { spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import { makeTraceSink } from "./TraceSink.ts";
|
||||
import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
|
||||
|
||||
export interface LocalFileTracerOptions {
|
||||
readonly filePath: string;
|
||||
@@ -10,6 +10,7 @@ export interface LocalFileTracerOptions {
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly delegate?: Tracer.Tracer;
|
||||
readonly sink?: TraceSink;
|
||||
}
|
||||
|
||||
class LocalFileSpan implements Tracer.Span {
|
||||
@@ -30,7 +31,7 @@ class LocalFileSpan implements Tracer.Span {
|
||||
constructor(
|
||||
options: Parameters<Tracer.Tracer["span"]>[0],
|
||||
private readonly delegate: Tracer.Span,
|
||||
private readonly push: (record: ReturnType<typeof spanToTraceRecord>) => void,
|
||||
private readonly push: (record: EffectTraceRecord) => void,
|
||||
) {
|
||||
this.name = delegate.name;
|
||||
this.spanId = delegate.spanId;
|
||||
@@ -82,12 +83,14 @@ class LocalFileSpan implements Tracer.Span {
|
||||
export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
|
||||
options: LocalFileTracerOptions,
|
||||
) {
|
||||
const sink = yield* makeTraceSink({
|
||||
filePath: options.filePath,
|
||||
maxBytes: options.maxBytes,
|
||||
maxFiles: options.maxFiles,
|
||||
batchWindowMs: options.batchWindowMs,
|
||||
});
|
||||
const sink =
|
||||
options.sink ??
|
||||
(yield* makeTraceSink({
|
||||
filePath: options.filePath,
|
||||
maxBytes: options.maxBytes,
|
||||
maxFiles: options.maxFiles,
|
||||
batchWindowMs: options.batchWindowMs,
|
||||
}));
|
||||
|
||||
const delegate =
|
||||
options.delegate ??
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TraceRecord } from "../TraceRecord.ts";
|
||||
|
||||
export interface BrowserTraceCollectorShape {
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class BrowserTraceCollector extends ServiceMap.Service<
|
||||
BrowserTraceCollector,
|
||||
BrowserTraceCollectorShape
|
||||
>()("t3/observability/Services/BrowserTraceCollector") {}
|
||||
@@ -1,29 +1,37 @@
|
||||
import { Cause, Exit, Option, Tracer } from "effect";
|
||||
|
||||
import { compactTraceAttributes } from "./Attributes.ts";
|
||||
import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
export interface TraceRecord {
|
||||
readonly type: "effect-span";
|
||||
interface TraceRecordEvent {
|
||||
readonly name: string;
|
||||
readonly timeUnixNano: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface TraceRecordLink {
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface BaseTraceRecord {
|
||||
readonly name: string;
|
||||
readonly kind: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly parentSpanId?: string;
|
||||
readonly sampled: boolean;
|
||||
readonly kind: Tracer.SpanKind;
|
||||
readonly startTimeUnixNano: string;
|
||||
readonly endTimeUnixNano: string;
|
||||
readonly durationMs: number;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
readonly events: ReadonlyArray<{
|
||||
readonly name: string;
|
||||
readonly timeUnixNano: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
readonly links: ReadonlyArray<{
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
readonly events: ReadonlyArray<TraceRecordEvent>;
|
||||
readonly links: ReadonlyArray<TraceRecordLink>;
|
||||
}
|
||||
|
||||
export interface EffectTraceRecord extends BaseTraceRecord {
|
||||
readonly type: "effect-span";
|
||||
readonly exit:
|
||||
| {
|
||||
readonly _tag: "Success";
|
||||
@@ -38,6 +46,29 @@ export interface TraceRecord {
|
||||
};
|
||||
}
|
||||
|
||||
interface OtlpTraceRecord extends BaseTraceRecord {
|
||||
readonly type: "otlp-span";
|
||||
readonly resourceAttributes: Readonly<Record<string, unknown>>;
|
||||
readonly scope: Readonly<{
|
||||
readonly name?: string;
|
||||
readonly version?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
readonly status?:
|
||||
| {
|
||||
readonly code?: string;
|
||||
readonly message?: string;
|
||||
}
|
||||
| undefined;
|
||||
}
|
||||
|
||||
export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
|
||||
|
||||
type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
|
||||
type OtlpSpanEvent = OtlpSpan["events"][number];
|
||||
type OtlpSpanLink = OtlpSpan["links"][number];
|
||||
type OtlpSpanStatus = OtlpSpan["status"];
|
||||
|
||||
interface SerializableSpan {
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
@@ -53,7 +84,7 @@ interface SerializableSpan {
|
||||
>;
|
||||
}
|
||||
|
||||
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): TraceRecord["exit"] {
|
||||
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
|
||||
if (Exit.isSuccess(exit)) {
|
||||
return { _tag: "Success" };
|
||||
}
|
||||
@@ -69,7 +100,7 @@ function formatTraceExit(exit: Exit.Exit<unknown, unknown>): TraceRecord["exit"]
|
||||
};
|
||||
}
|
||||
|
||||
export function spanToTraceRecord(span: SerializableSpan): TraceRecord {
|
||||
export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
|
||||
const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
|
||||
const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
|
||||
|
||||
@@ -98,3 +129,159 @@ export function spanToTraceRecord(span: SerializableSpan): TraceRecord {
|
||||
exit: formatTraceExit(status.exit),
|
||||
};
|
||||
}
|
||||
|
||||
const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
|
||||
1: "internal",
|
||||
2: "server",
|
||||
3: "client",
|
||||
4: "producer",
|
||||
5: "consumer",
|
||||
};
|
||||
|
||||
export function decodeOtlpTraceRecords(
|
||||
payload: OtlpTracer.TraceData,
|
||||
): ReadonlyArray<OtlpTraceRecord> {
|
||||
const records: Array<OtlpTraceRecord> = [];
|
||||
|
||||
for (const resourceSpan of payload.resourceSpans) {
|
||||
const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
|
||||
|
||||
for (const scopeSpan of resourceSpan.scopeSpans) {
|
||||
for (const span of scopeSpan.spans) {
|
||||
records.push(
|
||||
otlpSpanToTraceRecord({
|
||||
resourceAttributes,
|
||||
scopeAttributes: decodeAttributes(
|
||||
"attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
|
||||
? scopeSpan.scope.attributes
|
||||
: [],
|
||||
),
|
||||
scopeName: scopeSpan.scope.name,
|
||||
scopeVersion:
|
||||
"version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
|
||||
? scopeSpan.scope.version
|
||||
: undefined,
|
||||
span,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
function otlpSpanToTraceRecord(input: {
|
||||
readonly resourceAttributes: Readonly<Record<string, unknown>>;
|
||||
readonly scopeAttributes: Readonly<Record<string, unknown>>;
|
||||
readonly scopeName: string | undefined;
|
||||
readonly scopeVersion: string | undefined;
|
||||
readonly span: OtlpSpan;
|
||||
}): OtlpTraceRecord {
|
||||
return {
|
||||
type: "otlp-span",
|
||||
name: input.span.name,
|
||||
traceId: input.span.traceId,
|
||||
spanId: input.span.spanId,
|
||||
...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
|
||||
sampled: true,
|
||||
kind: normalizeSpanKind(input.span.kind),
|
||||
startTimeUnixNano: input.span.startTimeUnixNano,
|
||||
endTimeUnixNano: input.span.endTimeUnixNano,
|
||||
durationMs:
|
||||
Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
|
||||
1_000_000,
|
||||
attributes: decodeAttributes(input.span.attributes),
|
||||
resourceAttributes: input.resourceAttributes,
|
||||
scope: {
|
||||
...(input.scopeName ? { name: input.scopeName } : {}),
|
||||
...(input.scopeVersion ? { version: input.scopeVersion } : {}),
|
||||
attributes: input.scopeAttributes,
|
||||
},
|
||||
events: decodeEvents(input.span.events),
|
||||
links: decodeLinks(input.span.links),
|
||||
status: decodeStatus(input.span.status),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
|
||||
const code = String(input.code);
|
||||
const message = input.message;
|
||||
|
||||
return {
|
||||
code,
|
||||
...(message ? { message } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
|
||||
return input.map((current) => ({
|
||||
name: current.name,
|
||||
timeUnixNano: current.timeUnixNano,
|
||||
attributes: decodeAttributes(current.attributes),
|
||||
}));
|
||||
}
|
||||
|
||||
function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
|
||||
return input.flatMap((current) => {
|
||||
const traceId = current.traceId;
|
||||
const spanId = current.spanId;
|
||||
return {
|
||||
traceId,
|
||||
spanId,
|
||||
attributes: decodeAttributes(current.attributes),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeAttributes(
|
||||
input: ReadonlyArray<OtlpResource.KeyValue>,
|
||||
): Readonly<Record<string, unknown>> {
|
||||
const entries: Record<string, unknown> = {};
|
||||
|
||||
for (const attribute of input) {
|
||||
entries[attribute.key] = decodeValue(attribute.value);
|
||||
}
|
||||
|
||||
return compactTraceAttributes(entries);
|
||||
}
|
||||
|
||||
function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
if ("stringValue" in input) {
|
||||
return input.stringValue;
|
||||
}
|
||||
if ("boolValue" in input) {
|
||||
return input.boolValue;
|
||||
}
|
||||
if ("intValue" in input) {
|
||||
return input.intValue;
|
||||
}
|
||||
if ("doubleValue" in input) {
|
||||
return input.doubleValue;
|
||||
}
|
||||
if ("bytesValue" in input) {
|
||||
return input.bytesValue;
|
||||
}
|
||||
if (input.arrayValue) {
|
||||
return input.arrayValue.values.map((entry) => decodeValue(entry));
|
||||
}
|
||||
if (input.kvlistValue) {
|
||||
return decodeAttributes(input.kvlistValue.values);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
|
||||
return SPAN_KIND_MAP[input] || "internal";
|
||||
}
|
||||
|
||||
function parseBigInt(input: string): bigint {
|
||||
try {
|
||||
return BigInt(input);
|
||||
} catch {
|
||||
return 0n;
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,9 @@ function createProviderServiceHarness(
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
|
||||
@@ -208,7 +208,9 @@ describe("ProviderCommandReactor", () => {
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
|
||||
@@ -98,7 +98,9 @@ function createProviderServiceHarness() {
|
||||
listSessions: () => Effect.succeed([...runtimeSessions]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const setSession = (session: ProviderSession): void => {
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/**
|
||||
* RuntimeReceiptBus layers.
|
||||
*
|
||||
* `RuntimeReceiptBusLive` is the production default and intentionally does not
|
||||
* retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory
|
||||
* PubSub-backed implementation used by integration tests that need to await
|
||||
* checkpoint-reactor milestones precisely.
|
||||
*
|
||||
* @module RuntimeReceiptBus
|
||||
*/
|
||||
import { Effect, Layer, PubSub, Stream } from "effect";
|
||||
|
||||
import {
|
||||
@@ -6,13 +16,21 @@ import {
|
||||
type OrchestrationRuntimeReceipt,
|
||||
} from "../Services/RuntimeReceiptBus.ts";
|
||||
|
||||
const makeRuntimeReceiptBus = Effect.gen(function* () {
|
||||
const makeRuntimeReceiptBus = Effect.succeed({
|
||||
publish: () => Effect.void,
|
||||
streamEventsForTest: Stream.empty,
|
||||
} satisfies RuntimeReceiptBusShape);
|
||||
|
||||
const makeRuntimeReceiptBusTest = Effect.gen(function* () {
|
||||
const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();
|
||||
|
||||
return {
|
||||
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
|
||||
stream: Stream.fromPubSub(pubSub),
|
||||
get streamEventsForTest() {
|
||||
return Stream.fromPubSub(pubSub);
|
||||
},
|
||||
} satisfies RuntimeReceiptBusShape;
|
||||
});
|
||||
|
||||
export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);
|
||||
export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);
|
||||
@@ -1,3 +1,19 @@
|
||||
/**
|
||||
* RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts.
|
||||
*
|
||||
* This service exists to expose short-lived orchestration milestones that are
|
||||
* useful in tests and harnesses but are not part of the production runtime
|
||||
* event model. `CheckpointReactor` publishes receipts such as baseline capture,
|
||||
* diff finalization, and turn-processing quiescence so integration tests can
|
||||
* wait for those exact points without inferring them indirectly from persisted
|
||||
* state.
|
||||
*
|
||||
* Production code should only call `publish`. Test code may subscribe via
|
||||
* `streamEventsForTest`, which is intentionally named to make the intended
|
||||
* usage explicit.
|
||||
*
|
||||
* @module RuntimeReceiptBus
|
||||
*/
|
||||
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
@@ -40,7 +56,7 @@ export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Typ
|
||||
|
||||
export interface RuntimeReceiptBusShape {
|
||||
readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;
|
||||
readonly stream: Stream.Stream<OrchestrationRuntimeReceipt>;
|
||||
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
|
||||
}
|
||||
|
||||
export class RuntimeReceiptBus extends ServiceMap.Service<
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export class TerminalProcessInspectionError extends Schema.TaggedErrorClass<TerminalProcessInspectionError>()(
|
||||
"TerminalProcessInspectionError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
terminalPid: Schema.Int,
|
||||
command: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.operation} failed for terminal pid ${this.terminalPid}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WebPortInspectionError extends Schema.TaggedErrorClass<WebPortInspectionError>()(
|
||||
"WebPortInspectionError",
|
||||
{
|
||||
port: Schema.Int,
|
||||
host: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Web port probe failed for ${this.host}:${this.port}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type TerminalInspectorError = TerminalProcessInspectionError | WebPortInspectionError;
|
||||
@@ -1,162 +0,0 @@
|
||||
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { TerminalProcessInspector } from "../Services/TerminalProcessInspector";
|
||||
import { TerminalProcessInspectorLive } from "./TerminalProcessInspector";
|
||||
|
||||
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
|
||||
|
||||
interface StartedProcess {
|
||||
readonly process: ListenerProcess;
|
||||
readonly port: number;
|
||||
}
|
||||
|
||||
const stopProcess = (child: ChildProcess) =>
|
||||
Effect.callback<void>((resume) => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
resume(Effect.void);
|
||||
return;
|
||||
}
|
||||
|
||||
child.kill("SIGTERM");
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000);
|
||||
|
||||
child.once("exit", () => {
|
||||
clearTimeout(timeout);
|
||||
resume(Effect.void);
|
||||
});
|
||||
});
|
||||
|
||||
const waitForPort = (child: ListenerProcess) =>
|
||||
Effect.callback<number, Error>((resume) => {
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
resume(Effect.fail(new Error("Timed out waiting for listener port")));
|
||||
}, 3_000);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("exit", onExit);
|
||||
};
|
||||
|
||||
const onStdout = (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
const match = stdout.match(/PORT:(\d+)/);
|
||||
if (!match?.[1]) return;
|
||||
const port = Number(match[1]);
|
||||
if (!Number.isInteger(port) || port <= 0) return;
|
||||
cleanup();
|
||||
resume(Effect.succeed(port));
|
||||
};
|
||||
|
||||
const onStderr = (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
};
|
||||
|
||||
const onExit = (code: number | null) => {
|
||||
cleanup();
|
||||
resume(
|
||||
Effect.fail(
|
||||
new Error(
|
||||
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.on("exit", onExit);
|
||||
|
||||
return Effect.sync(cleanup);
|
||||
});
|
||||
|
||||
const startListenerProcess = Effect.gen(function* () {
|
||||
const script = [
|
||||
"const { createServer } = require('node:http');",
|
||||
"const server = createServer((_req, res) => {",
|
||||
" res.statusCode = 200;",
|
||||
" res.end('ok');",
|
||||
"});",
|
||||
"server.listen(0, '127.0.0.1', () => {",
|
||||
" const address = server.address();",
|
||||
" if (typeof address !== 'object' || !address) process.exit(1);",
|
||||
" console.log(`PORT:${address.port}`);",
|
||||
"});",
|
||||
"const shutdown = () => server.close(() => process.exit(0));",
|
||||
"process.on('SIGTERM', shutdown);",
|
||||
"process.on('SIGINT', shutdown);",
|
||||
"setInterval(() => {}, 10_000);",
|
||||
].join("");
|
||||
|
||||
const process = spawn("node", ["-e", script], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const port = yield* waitForPort(process);
|
||||
return { process, port } satisfies StartedProcess;
|
||||
});
|
||||
|
||||
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const testLayer = TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer));
|
||||
|
||||
it.layer(testLayer)("TerminalProcessInspectorLive", (it) => {
|
||||
it.effect("detects listening ports when the terminal root pid is the listener", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startListenerProcess,
|
||||
({ process, port }) =>
|
||||
Effect.gen(function* () {
|
||||
const listenerPid = process.pid;
|
||||
if (!listenerPid) {
|
||||
return yield* Effect.fail(new Error("Listener process pid missing"));
|
||||
}
|
||||
|
||||
const inspector = yield* TerminalProcessInspector;
|
||||
const activity = yield* inspector.inspect(listenerPid);
|
||||
|
||||
assert.equal(activity.hasRunningSubprocess, true);
|
||||
assert.deepStrictEqual(activity.runningPorts.includes(port), true);
|
||||
}),
|
||||
({ process }) => stopProcess(process),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns idle activity when root process has no children and no listening ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
}),
|
||||
),
|
||||
(process) =>
|
||||
Effect.gen(function* () {
|
||||
const idlePid = process.pid;
|
||||
if (!idlePid) {
|
||||
return yield* Effect.fail(new Error("Idle process pid missing"));
|
||||
}
|
||||
|
||||
const inspector = yield* TerminalProcessInspector;
|
||||
const activity = yield* inspector.inspect(idlePid);
|
||||
|
||||
assert.equal(activity.hasRunningSubprocess, false);
|
||||
assert.deepStrictEqual(activity.runningPorts, []);
|
||||
}),
|
||||
stopProcess,
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,241 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { Effect, Layer, Option, PlatformError, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { TerminalProcessInspectionError } from "../Errors";
|
||||
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "../posix";
|
||||
import type { TerminalProcessInspectorShape } from "../Services/TerminalProcessInspector";
|
||||
import { TerminalProcessInspector } from "../Services/TerminalProcessInspector";
|
||||
import {
|
||||
type TerminalSubprocessActivity,
|
||||
type TerminalSubprocessChecker,
|
||||
type TerminalSubprocessInspector,
|
||||
} from "../types";
|
||||
import { checkWindowsListeningPorts, collectWindowsChildPids } from "../win32";
|
||||
|
||||
const DEFAULT_COMMAND_KILL_GRACE_MS = 1_000;
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface CollectOutputResult {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
interface RunInspectorCommandInput {
|
||||
readonly operation: string;
|
||||
readonly terminalPid: number;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs: number;
|
||||
readonly maxOutputBytes: number;
|
||||
}
|
||||
|
||||
function commandLabel(command: string, args: ReadonlyArray<string>): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn("process.collectOutput")(function* (
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<CollectOutputResult, PlatformError.PlatformError> {
|
||||
return yield* stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk) => {
|
||||
if (state.bytes >= maxOutputBytes) {
|
||||
return {
|
||||
...state,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const chunkBytes = Buffer.byteLength(chunk);
|
||||
const remainingBytes = maxOutputBytes - state.bytes;
|
||||
if (chunkBytes <= remainingBytes) {
|
||||
return {
|
||||
text: `${state.text}${chunk}`,
|
||||
bytes: state.bytes + chunkBytes,
|
||||
truncated: state.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
const truncatedChunk = Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8");
|
||||
return {
|
||||
text: `${state.text}${truncatedChunk}`,
|
||||
bytes: state.bytes + remainingBytes,
|
||||
truncated: true,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(({ text, truncated }) => ({ text, truncated })),
|
||||
);
|
||||
});
|
||||
|
||||
const makeTerminalProcessInspector = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const runInspectorCommand = Effect.fn("process.runInspectorCommand")(function* (
|
||||
input: RunInspectorCommandInput,
|
||||
) {
|
||||
const command = ChildProcess.make(input.command, [...input.args], {
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_COMMAND_KILL_GRACE_MS,
|
||||
});
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to spawn inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(child.stdout, input.maxOutputBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read stdout from inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
collectOutput(child.stderr, input.maxOutputBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read stderr from inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read inspector command exit code.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode,
|
||||
} satisfies InspectorCommandResult;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(input.timeoutMs),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Inspector command timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const inspect: TerminalProcessInspectorShape["inspect"] = Effect.fn("process.inspect")(
|
||||
function* (terminalPid) {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const childPids = yield* collectWindowsChildPids(terminalPid, runInspectorCommand);
|
||||
const processPidsForPortScan = [terminalPid, ...childPids];
|
||||
const runningPorts = yield* checkWindowsListeningPorts(processPidsForPortScan, {
|
||||
terminalPid,
|
||||
runCommand: runInspectorCommand,
|
||||
});
|
||||
return {
|
||||
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
const processFamilyPids = yield* collectPosixProcessFamilyPids(
|
||||
terminalPid,
|
||||
runInspectorCommand,
|
||||
);
|
||||
if (processFamilyPids.length === 0) {
|
||||
return {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
|
||||
const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, {
|
||||
terminalPid,
|
||||
runCommand: runInspectorCommand,
|
||||
});
|
||||
return {
|
||||
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
inspect,
|
||||
} satisfies TerminalProcessInspectorShape;
|
||||
});
|
||||
|
||||
export const subprocessCheckerToInspector = (
|
||||
subprocessChecker: TerminalSubprocessChecker,
|
||||
): TerminalSubprocessInspector =>
|
||||
Effect.fn("process.subprocessCheckerToInspector")(function* (terminalPid) {
|
||||
return {
|
||||
hasRunningSubprocess: yield* subprocessChecker(terminalPid),
|
||||
runningPorts: [],
|
||||
};
|
||||
});
|
||||
|
||||
export const TerminalProcessInspectorLive = Layer.effect(
|
||||
TerminalProcessInspector,
|
||||
makeTerminalProcessInspector,
|
||||
);
|
||||
@@ -1,113 +0,0 @@
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { WebPortInspector } from "../Services/WebPortInspector";
|
||||
import { WebPortInspectorLive } from "./WebPortInspector";
|
||||
|
||||
const closeServer = (server: Server) =>
|
||||
Effect.callback<void>((resume) => {
|
||||
server.close(() => {
|
||||
resume(Effect.void);
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
try {
|
||||
server.close();
|
||||
} catch {
|
||||
// Ignore cleanup failures in tests.
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const listenServer = (server: Server) =>
|
||||
Effect.callback<number, Error>((resume) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
resume(Effect.fail(error));
|
||||
return;
|
||||
}
|
||||
|
||||
const address = server.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
resume(Effect.fail(new Error("Server did not provide a valid listening address.")));
|
||||
return;
|
||||
}
|
||||
|
||||
resume(Effect.succeed(address.port));
|
||||
});
|
||||
|
||||
return closeServer(server);
|
||||
});
|
||||
|
||||
const startServer = (
|
||||
handler: (request: IncomingMessage, response: ServerResponse) => void,
|
||||
): Effect.Effect<{ server: Server; port: number }, Error> =>
|
||||
Effect.gen(function* () {
|
||||
const server = createServer(handler);
|
||||
const port = yield* listenServer(server);
|
||||
return { server, port };
|
||||
});
|
||||
|
||||
it.layer(WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)))(
|
||||
"WebPortInspectorLive",
|
||||
(it) => {
|
||||
it.effect("treats slow HTML responses as web ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
setTimeout(() => {
|
||||
response.statusCode = 200;
|
||||
response.setHeader("content-type", "text/html; charset=utf-8");
|
||||
response.end(
|
||||
"<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>",
|
||||
);
|
||||
}, 800);
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, true);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats HTML responses with large bodies as web ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
response.statusCode = 200;
|
||||
response.setHeader("content-type", "text/html; charset=utf-8");
|
||||
response.end(
|
||||
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
|
||||
);
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, true);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores HTTP 404 responses", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, false);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,186 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { WebPortInspectionError } from "../Errors";
|
||||
import type { WebPortInspectorShape } from "../Services/WebPortInspector";
|
||||
import { WebPortInspector } from "../Services/WebPortInspector";
|
||||
|
||||
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
|
||||
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
|
||||
|
||||
interface WebProbeResult {
|
||||
readonly status: number;
|
||||
readonly contentType: string;
|
||||
readonly body: string;
|
||||
readonly location: string;
|
||||
}
|
||||
|
||||
function normalizeHeaderValue(value: string | string[] | undefined): string {
|
||||
if (typeof value === "string") return value;
|
||||
if (Array.isArray(value)) return value[0] ?? "";
|
||||
return "";
|
||||
}
|
||||
|
||||
function isLikelyWebProbe(result: WebProbeResult | null): boolean {
|
||||
if (!result) return false;
|
||||
if (result.status === 404) return false;
|
||||
if (result.status >= 300 && result.status < 400 && result.location.length > 0) {
|
||||
return true;
|
||||
}
|
||||
const contentType = result.contentType.toLowerCase();
|
||||
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
|
||||
return true;
|
||||
}
|
||||
const body = result.body.toLowerCase();
|
||||
return body.includes("<!doctype") || body.includes("<html") || body.includes("<head");
|
||||
}
|
||||
|
||||
const collectBodyPreview = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, never> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
}),
|
||||
(state, chunk) => {
|
||||
if (state.bytes >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const chunkBytes = Buffer.byteLength(chunk);
|
||||
const remainingBytes = WEB_PORT_PROBE_MAX_BODY_BYTES - state.bytes;
|
||||
if (chunkBytes <= remainingBytes) {
|
||||
return {
|
||||
text: `${state.text}${chunk}`,
|
||||
bytes: state.bytes + chunkBytes,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
text: `${state.text}${Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8")}`,
|
||||
bytes: state.bytes + remainingBytes,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map((preview) => preview.text),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
|
||||
const makeWebPortInspector = Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
|
||||
const probeWebPortOnHost = Effect.fn("process.probeWebPortOnHost")(function* (
|
||||
port: number,
|
||||
host: string,
|
||||
): Effect.fn.Return<WebProbeResult | null, WebPortInspectionError> {
|
||||
const request = HttpClientRequest.get(`http://${host}:${port}/`).pipe(
|
||||
HttpClientRequest.setHeaders({
|
||||
accept: "text/html,application/xhtml+xml;q=1,*/*;q=0.1",
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* httpClient.execute(request).pipe(
|
||||
Effect.flatMap((response) =>
|
||||
Effect.gen(function* () {
|
||||
const status = response.status;
|
||||
const contentType = normalizeHeaderValue(response.headers["content-type"]);
|
||||
const location = normalizeHeaderValue(response.headers.location);
|
||||
|
||||
if (
|
||||
(status >= 300 && status < 400 && location.length > 0) ||
|
||||
contentType.toLowerCase().includes("text/html") ||
|
||||
contentType.toLowerCase().includes("application/xhtml+xml")
|
||||
) {
|
||||
return {
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: "",
|
||||
} satisfies WebProbeResult;
|
||||
}
|
||||
|
||||
const body = yield* collectBodyPreview(response.stream);
|
||||
return {
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body,
|
||||
} satisfies WebProbeResult;
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "HTTP probe timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"_tag" in cause &&
|
||||
cause._tag === "WebPortInspectionError"
|
||||
) {
|
||||
return cause as WebPortInspectionError;
|
||||
}
|
||||
return new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "Failed to execute HTTP probe request.",
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const inspect: WebPortInspectorShape["inspect"] = Effect.fn("process.inspectWebPort")(
|
||||
function* (port) {
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65_535) {
|
||||
return yield* new WebPortInspectionError({
|
||||
port,
|
||||
host: "127.0.0.1",
|
||||
detail: "Port must be an integer between 1 and 65535.",
|
||||
});
|
||||
}
|
||||
|
||||
const ipv4Result = yield* probeWebPortOnHost(port, "127.0.0.1").pipe(Effect.exit);
|
||||
if (ipv4Result._tag === "Success" && isLikelyWebProbe(ipv4Result.value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ipv6Result = yield* probeWebPortOnHost(port, "::1").pipe(Effect.exit);
|
||||
if (ipv6Result._tag === "Success" && isLikelyWebProbe(ipv6Result.value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ipv4Result._tag === "Success" || ipv6Result._tag === "Success") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ipv6Result._tag === "Failure") {
|
||||
return yield* Effect.failCause(ipv6Result.cause);
|
||||
}
|
||||
|
||||
return yield* Effect.failCause(ipv4Result.cause);
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
inspect,
|
||||
} satisfies WebPortInspectorShape;
|
||||
});
|
||||
|
||||
export const WebPortInspectorLive = Layer.effect(WebPortInspector, makeWebPortInspector);
|
||||
@@ -1,16 +0,0 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError } from "../Errors";
|
||||
import type { TerminalSubprocessActivity } from "../types";
|
||||
|
||||
export interface TerminalProcessInspectorShape {
|
||||
readonly inspect: (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export class TerminalProcessInspector extends ServiceMap.Service<
|
||||
TerminalProcessInspector,
|
||||
TerminalProcessInspectorShape
|
||||
>()("t3/process/Services/TerminalProcessInspector") {}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { WebPortInspectionError } from "../Errors";
|
||||
|
||||
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
|
||||
|
||||
export interface WebPortInspectorShape {
|
||||
readonly inspect: (port: number) => Effect.Effect<boolean, WebPortInspectionError>;
|
||||
}
|
||||
|
||||
export class WebPortInspector extends ServiceMap.Service<WebPortInspector, WebPortInspectorShape>()(
|
||||
"t3/process/Services/WebPortInspector",
|
||||
) {}
|
||||
@@ -1,145 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError } from "./Errors";
|
||||
import { MAX_PORT_NUMBER, portFromAddress } from "./utils";
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface PosixRunCommand {
|
||||
(
|
||||
input: Readonly<{
|
||||
operation: string;
|
||||
terminalPid: number;
|
||||
command: string;
|
||||
args: ReadonlyArray<string>;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}>,
|
||||
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export const collectPosixProcessFamilyPids = Effect.fn("process.collectPosixProcessFamilyPids")(
|
||||
function* (
|
||||
terminalPid: number,
|
||||
runCommand: PosixRunCommand,
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
const psResult = yield* runCommand({
|
||||
operation: "TerminalProcessInspector.collectPosixProcessFamilyPids",
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
args: ["-eo", "pid=,ppid="],
|
||||
timeoutMs: 1_000,
|
||||
maxOutputBytes: 262_144,
|
||||
});
|
||||
if (psResult.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const childrenByParentPid = new Map<number, number[]>();
|
||||
for (const line of psResult.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
const children = childrenByParentPid.get(ppid);
|
||||
if (children) {
|
||||
children.push(pid);
|
||||
} else {
|
||||
childrenByParentPid.set(ppid, [pid]);
|
||||
}
|
||||
}
|
||||
|
||||
const processFamily = new Set<number>([terminalPid]);
|
||||
const pendingParents = [terminalPid];
|
||||
while (pendingParents.length > 0) {
|
||||
const parentPid = pendingParents.shift();
|
||||
if (!parentPid) continue;
|
||||
const childPids = childrenByParentPid.get(parentPid);
|
||||
if (!childPids || childPids.length === 0) continue;
|
||||
for (const childPid of childPids) {
|
||||
if (processFamily.has(childPid)) continue;
|
||||
processFamily.add(childPid);
|
||||
pendingParents.push(childPid);
|
||||
}
|
||||
}
|
||||
|
||||
return [...processFamily];
|
||||
},
|
||||
);
|
||||
|
||||
export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPorts")(function* (
|
||||
processIds: number[],
|
||||
input: {
|
||||
terminalPid: number;
|
||||
runCommand: PosixRunCommand;
|
||||
},
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
if (processIds.length === 0) return [];
|
||||
|
||||
const ports = new Set<number>();
|
||||
const pidFilter = new Set(processIds);
|
||||
|
||||
const lsofResult = yield* input
|
||||
.runCommand({
|
||||
operation: "TerminalProcessInspector.checkPosixListeningPorts.lsof",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "lsof",
|
||||
args: ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 262_144,
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
|
||||
if (lsofResult._tag === "Success") {
|
||||
if (lsofResult.value.exitCode === 1) {
|
||||
return [];
|
||||
}
|
||||
if (lsofResult.value.exitCode === 0) {
|
||||
for (const line of lsofResult.value.stdout.split(/\r?\n/g)) {
|
||||
const match = line.match(/:(\d+)\s+\(LISTEN\)$/);
|
||||
if (!match?.[1]) continue;
|
||||
const port = Number(match[1]);
|
||||
if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return [...ports].toSorted((left, right) => left - right);
|
||||
}
|
||||
}
|
||||
|
||||
const ssResult = yield* input.runCommand({
|
||||
operation: "TerminalProcessInspector.checkPosixListeningPorts.ss",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "ss",
|
||||
args: ["-ltnp"],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 524_288,
|
||||
});
|
||||
if (ssResult.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const line of ssResult.stdout.split(/\r?\n/g)) {
|
||||
if (!line.includes("pid=")) continue;
|
||||
const localAddress = line.trim().split(/\s+/g)[3];
|
||||
if (!localAddress) continue;
|
||||
const port = portFromAddress(localAddress);
|
||||
if (port === null) continue;
|
||||
|
||||
const pidMatches = [...line.matchAll(/pid=(\d+)/g)];
|
||||
if (pidMatches.length === 0) continue;
|
||||
if (
|
||||
pidMatches.some((match) => {
|
||||
const pid = Number(match[1]);
|
||||
return Number.isInteger(pid) && pidFilter.has(pid);
|
||||
})
|
||||
) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return [...ports].toSorted((left, right) => left - right);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError, WebPortInspectionError } from "./Errors";
|
||||
|
||||
export type TerminalSubprocessChecker = (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<boolean, TerminalProcessInspectionError>;
|
||||
|
||||
export type TerminalWebPortInspector = (
|
||||
port: number,
|
||||
) => Effect.Effect<boolean, WebPortInspectionError>;
|
||||
|
||||
export interface TerminalSubprocessActivity {
|
||||
hasRunningSubprocess: boolean;
|
||||
runningPorts: number[];
|
||||
}
|
||||
|
||||
export type TerminalSubprocessInspector = (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
|
||||
@@ -1,52 +0,0 @@
|
||||
export const MAX_PORT_NUMBER = 65_535;
|
||||
|
||||
export function normalizeRunningPorts(ports: number[]): number[] {
|
||||
if (ports.length === 0) return [];
|
||||
return [...new Set(ports)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
export function parsePidList(stdout: string): number[] {
|
||||
const pids: number[] = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
const pid = Number(line.trim());
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
continue;
|
||||
}
|
||||
pids.push(pid);
|
||||
}
|
||||
return [...new Set(pids)];
|
||||
}
|
||||
|
||||
export function parsePortList(stdout: string): number[] {
|
||||
const ports: number[] = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
const port = Number(line.trim());
|
||||
if (!Number.isInteger(port)) {
|
||||
continue;
|
||||
}
|
||||
ports.push(port);
|
||||
}
|
||||
return normalizeRunningPorts(ports);
|
||||
}
|
||||
|
||||
export function portFromAddress(address: string): number | null {
|
||||
const match = address.match(/:(\d+)$/);
|
||||
if (!match?.[1]) return null;
|
||||
const port = Number(match[1]);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
|
||||
return null;
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
export function arePortListsEqual(left: number[], right: number[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
if (left[index] !== right[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError } from "./Errors";
|
||||
import { parsePidList, parsePortList } from "./utils";
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface WindowsRunCommand {
|
||||
(
|
||||
input: Readonly<{
|
||||
operation: string;
|
||||
terminalPid: number;
|
||||
command: string;
|
||||
args: ReadonlyArray<string>;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}>,
|
||||
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPids")(function* (
|
||||
terminalPid: number,
|
||||
runCommand: WindowsRunCommand,
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if (-not $children) { exit 0 }",
|
||||
"$children | Select-Object -ExpandProperty ProcessId",
|
||||
].join("; ");
|
||||
const result = yield* runCommand({
|
||||
operation: "TerminalProcessInspector.collectWindowsChildPids",
|
||||
terminalPid,
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 32_768,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePidList(result.stdout);
|
||||
});
|
||||
|
||||
export const checkWindowsListeningPorts = Effect.fn("process.checkWindowsListeningPorts")(
|
||||
function* (
|
||||
processIds: number[],
|
||||
input: {
|
||||
terminalPid: number;
|
||||
runCommand: WindowsRunCommand;
|
||||
},
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
if (processIds.length === 0) return [];
|
||||
|
||||
const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or ");
|
||||
const command = [
|
||||
"$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue",
|
||||
`$matching = $connections | Where-Object { ${processFilter} }`,
|
||||
"if (-not $matching) { exit 0 }",
|
||||
"$matching | Select-Object -ExpandProperty LocalPort -Unique",
|
||||
].join("; ");
|
||||
const result = yield* input.runCommand({
|
||||
operation: "TerminalProcessInspector.checkWindowsListeningPorts",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 65_536,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePortList(result.stdout);
|
||||
},
|
||||
);
|
||||
@@ -3054,7 +3054,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEventQueue);
|
||||
},
|
||||
} satisfies ClaudeAdapterShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1631,7 +1631,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEventQueue);
|
||||
},
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -112,6 +112,49 @@ describe("EventNdjsonLogger", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent first writes for the same segment", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = path.join(tempDir, "provider-canonical.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "canonical",
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.all(
|
||||
[
|
||||
logger.write({ id: "evt-concurrent-1" }, null),
|
||||
logger.write({ id: "evt-concurrent-2" }, null),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = path.join(tempDir, "_global.log");
|
||||
assert.equal(fs.existsSync(globalPath), true);
|
||||
const lines = fs
|
||||
.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => parseLogLine(line));
|
||||
|
||||
assert.equal(lines.length, 2);
|
||||
assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
|
||||
'{"id":"evt-concurrent-1"}',
|
||||
'{"id":"evt-concurrent-2"}',
|
||||
]);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rotates per-thread files when max size is exceeded", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||
|
||||
@@ -10,7 +10,7 @@ import path from "node:path";
|
||||
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { Effect, Exit, Logger, Scope } from "effect";
|
||||
import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect";
|
||||
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
|
||||
@@ -40,6 +40,11 @@ interface ThreadWriter {
|
||||
close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface LoggerState {
|
||||
readonly threadWriters: Map<string, ThreadWriter>;
|
||||
readonly failedSegments: Set<string>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
|
||||
}
|
||||
@@ -193,34 +198,56 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
const stateRef = yield* SynchronizedRef.make<LoggerState>({
|
||||
threadWriters: new Map(),
|
||||
failedSegments: new Set(),
|
||||
});
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
if (failedSegments.has(threadSegment)) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
if (state.failedSegments.has(threadSegment)) {
|
||||
return Effect.succeed([undefined, state] as const);
|
||||
}
|
||||
|
||||
const writer = yield* makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
const existing = state.threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return Effect.succeed([existing, state] as const);
|
||||
}
|
||||
|
||||
return makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
}).pipe(
|
||||
Effect.map((writer) => {
|
||||
if (!writer) {
|
||||
const nextFailedSegments = new Set(state.failedSegments);
|
||||
nextFailedSegments.add(threadSegment);
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
...state,
|
||||
failedSegments: nextFailedSegments,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
const nextThreadWriters = new Map(state.threadWriters);
|
||||
nextThreadWriters.set(threadSegment, writer);
|
||||
return [
|
||||
writer,
|
||||
{
|
||||
...state,
|
||||
threadWriters: nextThreadWriters,
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
if (!writer) {
|
||||
failedSegments.add(threadSegment);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
threadWriters.set(threadSegment, writer);
|
||||
return writer;
|
||||
});
|
||||
|
||||
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
|
||||
@@ -239,10 +266,21 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
|
||||
});
|
||||
|
||||
const close = Effect.fn("close")(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.gen(function* () {
|
||||
for (const writer of state.threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
threadWriters: new Map<string, ThreadWriter>(),
|
||||
failedSegments: new Set<string>(),
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -115,7 +115,9 @@ function makeMutableServerSettingsService(
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
}),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changes);
|
||||
},
|
||||
} satisfies ServerSettingsShape;
|
||||
});
|
||||
}
|
||||
@@ -218,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();
|
||||
|
||||
@@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
|
||||
import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect";
|
||||
|
||||
import {
|
||||
increment,
|
||||
@@ -156,7 +156,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
@@ -194,15 +193,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
eventType: event.type,
|
||||
}).pipe(Effect.andThen(publishRuntimeEvent(event)));
|
||||
|
||||
const worker = Effect.forever(
|
||||
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
|
||||
);
|
||||
yield* Effect.forkScoped(worker);
|
||||
|
||||
yield* Effect.forEach(adapters, (adapter) =>
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkScoped),
|
||||
Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+783
-14
@@ -1,6 +1,7 @@
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
@@ -21,8 +22,24 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
|
||||
import { Effect, FileSystem, Layer, Path, Stream } from "effect";
|
||||
import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
import {
|
||||
Deferred,
|
||||
Duration,
|
||||
Effect,
|
||||
FileSystem,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Path,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpRouter,
|
||||
HttpServer,
|
||||
} from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import { vi } from "vitest";
|
||||
|
||||
@@ -36,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 {
|
||||
@@ -56,6 +74,10 @@ import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./server
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
|
||||
import {
|
||||
BrowserTraceCollector,
|
||||
type BrowserTraceCollectorShape,
|
||||
} from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import {
|
||||
ProjectSetupScriptRunner,
|
||||
@@ -124,6 +146,113 @@ const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
ProjectFaviconResolverLive,
|
||||
);
|
||||
|
||||
const browserOtlpTracingLayer = Layer.mergeAll(
|
||||
FetchHttpClient.layer,
|
||||
OtlpSerialization.layerJson,
|
||||
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
|
||||
);
|
||||
|
||||
const makeBrowserOtlpPayload = (spanName: string) =>
|
||||
Effect.gen(function* () {
|
||||
const collector = yield* Effect.acquireRelease(
|
||||
Effect.promise(async () => {
|
||||
const NodeHttp = await import("node:http");
|
||||
|
||||
return await new Promise<{
|
||||
readonly close: () => Promise<void>;
|
||||
readonly firstRequest: Promise<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}>;
|
||||
readonly url: string;
|
||||
}>((resolve, reject) => {
|
||||
let resolveFirstRequest:
|
||||
| ((request: { readonly body: string; readonly contentType: string | null }) => void)
|
||||
| undefined;
|
||||
const firstRequest = new Promise<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}>((resolveRequest) => {
|
||||
resolveFirstRequest = resolveRequest;
|
||||
});
|
||||
|
||||
const server = NodeHttp.createServer((request, response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
request.on("end", () => {
|
||||
resolveFirstRequest?.({
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
contentType: request.headers["content-type"] ?? null,
|
||||
});
|
||||
resolveFirstRequest = undefined;
|
||||
response.statusCode = 204;
|
||||
response.end();
|
||||
});
|
||||
});
|
||||
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Expected TCP collector address"));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
url: `http://127.0.0.1:${address.port}/v1/traces`,
|
||||
firstRequest,
|
||||
close: () =>
|
||||
new Promise<void>((resolveClose, rejectClose) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
rejectClose(error);
|
||||
return;
|
||||
}
|
||||
resolveClose();
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}),
|
||||
({ close }) => Effect.promise(close),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OtlpTracer.layer({
|
||||
url: collector.url,
|
||||
exportInterval: "10 millis",
|
||||
resource: {
|
||||
serviceName: "t3-web",
|
||||
attributes: {
|
||||
"service.runtime": "t3-web",
|
||||
"service.mode": "browser",
|
||||
"service.version": "test",
|
||||
},
|
||||
},
|
||||
}).pipe(Layer.provide(browserOtlpTracingLayer)),
|
||||
);
|
||||
|
||||
try {
|
||||
yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName))));
|
||||
} finally {
|
||||
yield* Effect.promise(() => runtime.dispose());
|
||||
}
|
||||
|
||||
const request = yield* Effect.promise(() =>
|
||||
Promise.race([
|
||||
collector.firstRequest,
|
||||
new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000);
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
return JSON.parse(request.body) as OtlpTracer.TraceData;
|
||||
});
|
||||
|
||||
const buildAppUnderTest = (options?: {
|
||||
config?: Partial<ServerConfigShape>;
|
||||
layers?: {
|
||||
@@ -138,6 +267,7 @@ const buildAppUnderTest = (options?: {
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>;
|
||||
checkpointDiffQuery?: Partial<CheckpointDiffQueryShape>;
|
||||
browserTraceCollector?: Partial<BrowserTraceCollectorShape>;
|
||||
serverLifecycleEvents?: Partial<ServerLifecycleEventsShape>;
|
||||
serverRuntimeStartup?: Partial<ServerRuntimeStartupShape>;
|
||||
};
|
||||
@@ -174,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,
|
||||
@@ -213,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 }),
|
||||
@@ -263,6 +394,12 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.checkpointDiffQuery,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(BrowserTraceCollector)({
|
||||
record: () => Effect.void,
|
||||
...options?.layers?.browserTraceCollector,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerLifecycleEvents)({
|
||||
publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }),
|
||||
@@ -280,6 +417,7 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(workspaceAndProjectServicesLayer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(layerConfig),
|
||||
);
|
||||
|
||||
@@ -437,6 +575,285 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("proxies browser OTLP trace exports through the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const upstreamRequests: Array<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}> = [];
|
||||
const localTraceRecords: Array<unknown> = [];
|
||||
const payload = {
|
||||
resourceSpans: [
|
||||
{
|
||||
resource: {
|
||||
attributes: [
|
||||
{
|
||||
key: "service.name",
|
||||
value: { stringValue: "t3-web" },
|
||||
},
|
||||
],
|
||||
},
|
||||
scopeSpans: [
|
||||
{
|
||||
scope: {
|
||||
name: "effect",
|
||||
version: "4.0.0-beta.43",
|
||||
},
|
||||
spans: [
|
||||
{
|
||||
traceId: "11111111111111111111111111111111",
|
||||
spanId: "2222222222222222",
|
||||
parentSpanId: "3333333333333333",
|
||||
name: "RpcClient.server.getSettings",
|
||||
kind: 3,
|
||||
startTimeUnixNano: "1000000",
|
||||
endTimeUnixNano: "2000000",
|
||||
attributes: [
|
||||
{
|
||||
key: "rpc.method",
|
||||
value: { stringValue: "server.getSettings" },
|
||||
},
|
||||
],
|
||||
events: [
|
||||
{
|
||||
name: "http.request",
|
||||
timeUnixNano: "1500000",
|
||||
attributes: [
|
||||
{
|
||||
key: "http.status_code",
|
||||
value: { intValue: "200" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
links: [],
|
||||
status: {
|
||||
code: "STATUS_CODE_OK",
|
||||
},
|
||||
flags: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const collector = yield* Effect.acquireRelease(
|
||||
Effect.promise(async () => {
|
||||
const NodeHttp = await import("node:http");
|
||||
|
||||
return await new Promise<{
|
||||
readonly close: () => Promise<void>;
|
||||
readonly url: string;
|
||||
}>((resolve, reject) => {
|
||||
const server = NodeHttp.createServer((request, response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
request.on("end", () => {
|
||||
upstreamRequests.push({
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
contentType: request.headers["content-type"] ?? null,
|
||||
});
|
||||
response.statusCode = 204;
|
||||
response.end();
|
||||
});
|
||||
});
|
||||
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Expected TCP collector address"));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
url: `http://127.0.0.1:${address.port}/v1/traces`,
|
||||
close: () =>
|
||||
new Promise<void>((resolveClose, rejectClose) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
rejectClose(error);
|
||||
return;
|
||||
}
|
||||
resolveClose();
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}),
|
||||
({ close }) => Effect.promise(close),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
otlpTracesUrl: collector.url,
|
||||
},
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
localTraceRecords.push(...records);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
origin: "http://localhost:5733",
|
||||
},
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers["access-control-allow-origin"], "*");
|
||||
assert.deepEqual(localTraceRecords, [
|
||||
{
|
||||
type: "otlp-span",
|
||||
name: "RpcClient.server.getSettings",
|
||||
traceId: "11111111111111111111111111111111",
|
||||
spanId: "2222222222222222",
|
||||
parentSpanId: "3333333333333333",
|
||||
sampled: true,
|
||||
kind: "client",
|
||||
startTimeUnixNano: "1000000",
|
||||
endTimeUnixNano: "2000000",
|
||||
durationMs: 1,
|
||||
attributes: {
|
||||
"rpc.method": "server.getSettings",
|
||||
},
|
||||
resourceAttributes: {
|
||||
"service.name": "t3-web",
|
||||
},
|
||||
scope: {
|
||||
name: "effect",
|
||||
version: "4.0.0-beta.43",
|
||||
attributes: {},
|
||||
},
|
||||
events: [
|
||||
{
|
||||
name: "http.request",
|
||||
timeUnixNano: "1500000",
|
||||
attributes: {
|
||||
"http.status_code": "200",
|
||||
},
|
||||
},
|
||||
],
|
||||
links: [],
|
||||
status: {
|
||||
code: "STATUS_CODE_OK",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(upstreamRequests, [
|
||||
{
|
||||
body: JSON.stringify(payload),
|
||||
contentType: "application/json",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("responds to browser OTLP trace preflight requests with CORS headers", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/api/observability/v1/traces");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(url, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://localhost:5733",
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
||||
assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS");
|
||||
assert.equal(response.headers.get("access-control-allow-headers"), "content-type");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"stores browser OTLP trace exports locally when no upstream collector is configured",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const localTraceRecords: Array<unknown> = [];
|
||||
const payload = yield* makeBrowserOtlpPayload("client.test");
|
||||
const resourceSpan = payload.resourceSpans[0];
|
||||
const scopeSpan = resourceSpan?.scopeSpans[0];
|
||||
const span = scopeSpan?.spans[0];
|
||||
|
||||
assert.notEqual(resourceSpan, undefined);
|
||||
assert.notEqual(scopeSpan, undefined);
|
||||
assert.notEqual(span, undefined);
|
||||
if (!resourceSpan || !scopeSpan || !span) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
localTraceRecords.push(...records);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(localTraceRecords.length, 1);
|
||||
const record = localTraceRecords[0] as {
|
||||
readonly type: string;
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly kind: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
readonly events: ReadonlyArray<unknown>;
|
||||
readonly links: ReadonlyArray<unknown>;
|
||||
readonly scope: {
|
||||
readonly name?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
readonly resourceAttributes: Readonly<Record<string, unknown>>;
|
||||
readonly status?: {
|
||||
readonly code?: string;
|
||||
};
|
||||
};
|
||||
|
||||
assert.equal(record.type, "otlp-span");
|
||||
assert.equal(record.name, span.name);
|
||||
assert.equal(record.traceId, span.traceId);
|
||||
assert.equal(record.spanId, span.spanId);
|
||||
assert.equal(record.kind, "internal");
|
||||
assert.deepEqual(record.attributes, {});
|
||||
assert.deepEqual(record.events, []);
|
||||
assert.deepEqual(record.links, []);
|
||||
assert.equal(record.scope.name, scopeSpan.scope.name);
|
||||
assert.deepEqual(record.scope.attributes, {});
|
||||
assert.equal(record.resourceAttributes["service.name"], "t3-web");
|
||||
assert.equal(record.status?.code, String(span.status.code));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("returns 404 for missing attachment id lookups", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -854,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,
|
||||
@@ -967,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,
|
||||
},
|
||||
},
|
||||
@@ -976,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]({
|
||||
@@ -1088,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,
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1104,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();
|
||||
|
||||
+18
-16
@@ -2,7 +2,12 @@ import { Effect, Layer } from "effect";
|
||||
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "./config";
|
||||
import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http";
|
||||
import {
|
||||
attachmentsRouteLayer,
|
||||
otlpTracesProxyRouteLayer,
|
||||
projectFaviconRouteLayer,
|
||||
staticAndDevRouteLayer,
|
||||
} from "./http";
|
||||
import { fixPath } from "./os-jank";
|
||||
import { websocketRpcRouteLayer } from "./ws";
|
||||
import { OpenLive } from "./open";
|
||||
@@ -25,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";
|
||||
@@ -43,8 +49,6 @@ import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability";
|
||||
import { TerminalProcessInspectorLive } from "./process/Layers/TerminalProcessInspector";
|
||||
import { WebPortInspectorLive } from "./process/Layers/WebPortInspector";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -158,23 +162,20 @@ 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),
|
||||
);
|
||||
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(
|
||||
Layer.provideMerge(WebPortInspectorLive),
|
||||
Layer.provideMerge(TerminalProcessInspectorLive),
|
||||
Layer.provide(PtyAdapterLive),
|
||||
);
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
|
||||
|
||||
const WorkspaceLayerLive = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
@@ -211,6 +212,7 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
|
||||
|
||||
export const makeRoutesLayer = Layer.mergeAll(
|
||||
attachmentsRouteLayer,
|
||||
otlpTracesProxyRouteLayer,
|
||||
projectFaviconRouteLayer,
|
||||
staticAndDevRouteLayer,
|
||||
websocketRpcRouteLayer,
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type TerminalEvent,
|
||||
@@ -17,7 +15,6 @@ import {
|
||||
Exit,
|
||||
Fiber,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
PlatformError,
|
||||
Ref,
|
||||
@@ -27,10 +24,6 @@ import {
|
||||
import { TestClock } from "effect/testing";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { TerminalProcessInspectorLive } from "../../process/Layers/TerminalProcessInspector";
|
||||
import { WebPortInspectorLive } from "../../process/Layers/WebPortInspector";
|
||||
import { TerminalProcessInspector } from "../../process/Services/TerminalProcessInspector";
|
||||
import { WebPortInspector } from "../../process/Services/WebPortInspector";
|
||||
import type { TerminalManagerShape } from "../Services/Manager";
|
||||
import {
|
||||
type PtyAdapterShape,
|
||||
@@ -196,10 +189,6 @@ function multiTerminalHistoryLogPath(
|
||||
interface CreateManagerOptions {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
|
||||
subprocessInspector?: (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
|
||||
webPortInspector?: (port: number) => Effect.Effect<boolean>;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -220,7 +209,7 @@ const createManager = (
|
||||
): Effect.Effect<
|
||||
ManagerFixture,
|
||||
PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Scope.Scope | TerminalProcessInspector | WebPortInspector
|
||||
FileSystem.FileSystem | Scope.Scope
|
||||
> =>
|
||||
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -236,12 +225,6 @@ const createManager = (
|
||||
...(options.subprocessChecker !== undefined
|
||||
? { subprocessChecker: options.subprocessChecker }
|
||||
: {}),
|
||||
...(options.subprocessInspector !== undefined
|
||||
? { subprocessInspector: options.subprocessInspector }
|
||||
: {}),
|
||||
...(options.webPortInspector !== undefined
|
||||
? { webPortInspector: options.webPortInspector }
|
||||
: {}),
|
||||
...(options.subprocessPollIntervalMs !== undefined
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
@@ -269,16 +252,7 @@ const createManager = (
|
||||
}),
|
||||
);
|
||||
|
||||
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
it.layer(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)),
|
||||
TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer)),
|
||||
),
|
||||
{ excludeTestServices: true },
|
||||
)("TerminalManager", (it) => {
|
||||
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
|
||||
it.effect("spawns lazily and reuses running terminal per thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager();
|
||||
@@ -574,56 +548,29 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits subprocess activity events when child-process state or web ports change", () =>
|
||||
it.effect("emits subprocess activity events when child-process state changes", () =>
|
||||
Effect.gen(function* () {
|
||||
let activity = {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [] as number[],
|
||||
};
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager, getEvents } = yield* createManager(5, {
|
||||
subprocessInspector: () => Effect.succeed(activity),
|
||||
webPortInspector: (port) => Effect.succeed(port === 3000),
|
||||
subprocessChecker: () => Effect.succeed(hasRunningSubprocess),
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
|
||||
yield* manager.open(openInput());
|
||||
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
|
||||
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
|
||||
hasRunningSubprocess = true;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.join(",") === "3000",
|
||||
),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
|
||||
hasRunningSubprocess = false;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === false &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
@@ -28,19 +28,7 @@ import {
|
||||
terminalRestartsTotal,
|
||||
terminalSessionsTotal,
|
||||
} from "../../observability/Metrics";
|
||||
import { arePortListsEqual, normalizeRunningPorts } from "../../process/utils";
|
||||
import { TerminalProcessInspector } from "../../process/Services/TerminalProcessInspector";
|
||||
import {
|
||||
type TerminalSubprocessActivity,
|
||||
type TerminalSubprocessChecker,
|
||||
type TerminalSubprocessInspector,
|
||||
type TerminalWebPortInspector,
|
||||
} from "../../process/types";
|
||||
import { subprocessCheckerToInspector } from "../../process/Layers/TerminalProcessInspector";
|
||||
import {
|
||||
DEFAULT_WEB_PORT_PROBE_TTL_MS,
|
||||
WebPortInspector,
|
||||
} from "../../process/Services/WebPortInspector";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import {
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
@@ -66,6 +54,17 @@ const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
|
||||
type TerminalSubprocessChecker = (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<boolean, TerminalSubprocessCheckError>;
|
||||
|
||||
class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
readonly terminalPid: number;
|
||||
readonly command: "powershell" | "pgrep" | "ps";
|
||||
}> {}
|
||||
|
||||
class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -108,7 +107,6 @@ interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runningSubprocessPorts: number[];
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
@@ -301,6 +299,108 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function checkWindowsSubprocessActivity(
|
||||
terminalPid: number,
|
||||
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
].join("; ");
|
||||
return Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to check Windows terminal subprocess activity.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "powershell",
|
||||
}),
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
}
|
||||
|
||||
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
const runPgrep = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with pgrep.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "pgrep",
|
||||
}),
|
||||
});
|
||||
|
||||
const runPs = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with ps.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
}),
|
||||
});
|
||||
|
||||
const pgrepResult = yield* Effect.exit(runPgrep);
|
||||
if (pgrepResult._tag === "Success") {
|
||||
if (pgrepResult.value.code === 0) {
|
||||
return pgrepResult.value.stdout.trim().length > 0;
|
||||
}
|
||||
if (pgrepResult.value.code === 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const psResult = yield* Effect.exit(runPs);
|
||||
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
if (ppid === terminalPid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return yield* checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return yield* checkPosixSubprocessActivity(terminalPid);
|
||||
});
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
if (history.length === 0) return history;
|
||||
const hasTrailingNewline = history.endsWith("\n");
|
||||
@@ -547,9 +647,6 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessInspector?: TerminalSubprocessInspector;
|
||||
webPortInspector?: TerminalWebPortInspector;
|
||||
webPortProbeCacheTtlMs?: number;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -573,19 +670,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
const logsDir = options.logsDir;
|
||||
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
const shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
const subprocessInspector =
|
||||
options.subprocessInspector ??
|
||||
(options.subprocessChecker
|
||||
? subprocessCheckerToInspector(options.subprocessChecker)
|
||||
: (yield* TerminalProcessInspector).inspect);
|
||||
const webPortInspector = options.webPortInspector ?? (yield* WebPortInspector).inspect;
|
||||
const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
|
||||
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
const subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
const maxRetainedInactiveSessions =
|
||||
options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
|
||||
const webPortProbeCache = new Map<number, { isWeb: boolean; checkedAt: number }>();
|
||||
|
||||
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
|
||||
|
||||
@@ -605,44 +695,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
}
|
||||
});
|
||||
|
||||
const inspectWebPortCached = (port: number) =>
|
||||
Effect.gen(function* () {
|
||||
const now = Date.now();
|
||||
const cached = webPortProbeCache.get(port);
|
||||
if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) {
|
||||
return cached.isWeb;
|
||||
}
|
||||
|
||||
const isWeb = yield* webPortInspector(port).pipe(Effect.catch(() => Effect.succeed(false)));
|
||||
webPortProbeCache.set(port, {
|
||||
isWeb,
|
||||
checkedAt: Date.now(),
|
||||
});
|
||||
return isWeb;
|
||||
});
|
||||
|
||||
const detectWebPorts = (runningPorts: number[]) =>
|
||||
Effect.gen(function* () {
|
||||
if (runningPorts.length === 0) {
|
||||
return [] as number[];
|
||||
}
|
||||
|
||||
const checks = yield* Effect.forEach(
|
||||
runningPorts,
|
||||
(port) =>
|
||||
Effect.map(inspectWebPortCached(port), (isWeb) => ({
|
||||
port,
|
||||
isWeb,
|
||||
})),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return checks
|
||||
.filter((entry) => entry.isWeb)
|
||||
.map((entry) => entry.port)
|
||||
.toSorted((left, right) => left - right);
|
||||
});
|
||||
|
||||
const historyPath = (threadId: string, terminalId: string) => {
|
||||
const threadPart = toSafeThreadId(threadId);
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
@@ -1106,7 +1158,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
@@ -1174,7 +1225,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
@@ -1268,7 +1318,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.exitCode = null;
|
||||
session.exitSignal = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
@@ -1342,7 +1391,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.unsubscribeData = null;
|
||||
session.unsubscribeExit = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
@@ -1413,7 +1461,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session: TerminalSessionState & { pid: number },
|
||||
) {
|
||||
const terminalPid = session.pid;
|
||||
const activity = yield* subprocessInspector(terminalPid).pipe(
|
||||
const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to check terminal subprocess activity", {
|
||||
@@ -1421,21 +1469,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
terminalId: session.terminalId,
|
||||
terminalPid,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}).pipe(Effect.as(Option.none<TerminalSubprocessActivity>())),
|
||||
}).pipe(Effect.as(Option.none<boolean>())),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(activity)) {
|
||||
if (Option.isNone(hasRunningSubprocess)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasRunningSubprocess = activity.value.hasRunningSubprocess === true;
|
||||
const runningPorts = hasRunningSubprocess
|
||||
? normalizeRunningPorts(
|
||||
yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)),
|
||||
)
|
||||
: [];
|
||||
|
||||
const event = yield* modifyManagerState((state) => {
|
||||
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
|
||||
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
|
||||
@@ -1444,14 +1485,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
Option.isNone(liveSession) ||
|
||||
liveSession.value.status !== "running" ||
|
||||
liveSession.value.pid !== terminalPid ||
|
||||
(liveSession.value.hasRunningSubprocess === hasRunningSubprocess &&
|
||||
arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts))
|
||||
liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value
|
||||
) {
|
||||
return [Option.none(), state] as const;
|
||||
}
|
||||
|
||||
liveSession.value.hasRunningSubprocess = hasRunningSubprocess;
|
||||
liveSession.value.runningSubprocessPorts = runningPorts;
|
||||
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
|
||||
liveSession.value.updatedAt = new Date().toISOString();
|
||||
|
||||
return [
|
||||
@@ -1460,8 +1499,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess,
|
||||
runningPorts,
|
||||
hasRunningSubprocess: hasRunningSubprocess.value,
|
||||
}),
|
||||
state,
|
||||
] as const;
|
||||
@@ -1560,7 +1598,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
|
||||
@@ -1740,7 +1777,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
const createdSession = session;
|
||||
|
||||
@@ -51,7 +51,6 @@ export interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runningSubprocessPorts: number[];
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
|
||||
+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 },
|
||||
);
|
||||
@@ -1406,7 +1421,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
@@ -2097,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(
|
||||
@@ -2110,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();
|
||||
@@ -2126,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 },
|
||||
@@ -2143,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 },
|
||||
);
|
||||
@@ -2819,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";
|
||||
@@ -197,6 +197,7 @@ import {
|
||||
useServerConfig,
|
||||
useServerKeybindings,
|
||||
} from "~/rpc/serverState";
|
||||
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
|
||||
|
||||
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
@@ -558,8 +559,6 @@ function PersistentThreadTerminalDrawer({
|
||||
activeTerminalId={terminalState.activeTerminalId}
|
||||
terminalGroups={terminalState.terminalGroups}
|
||||
activeTerminalGroupId={terminalState.activeTerminalGroupId}
|
||||
runningTerminalIds={terminalState.runningTerminalIds}
|
||||
runningTerminalPorts={terminalState.runningTerminalPorts}
|
||||
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
|
||||
onSplitTerminal={splitTerminal}
|
||||
onNewTerminal={createNewTerminal}
|
||||
@@ -1400,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(
|
||||
@@ -1477,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();
|
||||
@@ -1527,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
|
||||
@@ -1601,17 +1601,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setThreadError = useCallback(
|
||||
(targetThreadId: ThreadId | null, error: string | null) => {
|
||||
if (!targetThreadId) return;
|
||||
const nextError = sanitizeThreadErrorMessage(error);
|
||||
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
|
||||
setStoreThreadError(targetThreadId, error);
|
||||
setStoreThreadError(targetThreadId, nextError);
|
||||
return;
|
||||
}
|
||||
setLocalDraftErrorsByThreadId((existing) => {
|
||||
if ((existing[targetThreadId] ?? null) === error) {
|
||||
if ((existing[targetThreadId] ?? null) === nextError) {
|
||||
return existing;
|
||||
}
|
||||
return {
|
||||
...existing,
|
||||
[targetThreadId]: error,
|
||||
[targetThreadId]: nextError,
|
||||
};
|
||||
});
|
||||
},
|
||||
@@ -3155,14 +3156,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
setStoreThreadError(
|
||||
setThreadError(
|
||||
activeThreadId,
|
||||
err instanceof Error ? err.message : "Failed to submit approval decision.",
|
||||
);
|
||||
});
|
||||
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
},
|
||||
[activeThreadId, setStoreThreadError],
|
||||
[activeThreadId, setThreadError],
|
||||
);
|
||||
|
||||
const onRespondToUserInput = useCallback(
|
||||
@@ -3183,14 +3184,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
setStoreThreadError(
|
||||
setThreadError(
|
||||
activeThreadId,
|
||||
err instanceof Error ? err.message : "Failed to submit user input.",
|
||||
);
|
||||
});
|
||||
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
},
|
||||
[activeThreadId, setStoreThreadError],
|
||||
[activeThreadId, setThreadError],
|
||||
);
|
||||
|
||||
const setActivePendingUserInputQuestionIndex = useCallback(
|
||||
@@ -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({
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
GlobeIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
@@ -50,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,
|
||||
@@ -71,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";
|
||||
@@ -151,10 +149,9 @@ type SidebarProjectSnapshot = Project & {
|
||||
expanded: boolean;
|
||||
};
|
||||
interface TerminalStatusIndicator {
|
||||
label: string;
|
||||
label: "Terminal process running";
|
||||
colorClass: string;
|
||||
pulse: boolean;
|
||||
primaryWebPort: number | null;
|
||||
}
|
||||
|
||||
interface PrStatusIndicator {
|
||||
@@ -204,39 +201,16 @@ function ThreadStatusLabel({
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(rawPorts: number[] | undefined): number[] {
|
||||
if (!rawPorts) return [];
|
||||
return [...new Set(rawPorts)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function terminalStatusFromTerminalState(
|
||||
function terminalStatusFromRunningIds(
|
||||
runningTerminalIds: string[],
|
||||
runningTerminalPorts: Record<string, number[]>,
|
||||
): TerminalStatusIndicator | null {
|
||||
if (runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const runningPorts = normalizeRunningPorts(
|
||||
runningTerminalIds.flatMap((terminalId) => runningTerminalPorts[terminalId] ?? []),
|
||||
);
|
||||
const primaryWebPort = runningPorts[0] ?? null;
|
||||
|
||||
return {
|
||||
label:
|
||||
primaryWebPort === null
|
||||
? "Terminal process running"
|
||||
: runningPorts.length === 1
|
||||
? `Open web server: http://localhost:${primaryWebPort}`
|
||||
: `Open web server: http://localhost:${primaryWebPort} (detected web ports: ${runningPorts.join(", ")})`,
|
||||
colorClass:
|
||||
primaryWebPort === null
|
||||
? "text-teal-600 dark:text-teal-300/90"
|
||||
: "text-sky-600 dark:text-sky-300/90",
|
||||
label: "Terminal process running",
|
||||
colorClass: "text-teal-600 dark:text-teal-300/90",
|
||||
pulse: true,
|
||||
primaryWebPort,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -270,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>;
|
||||
@@ -301,17 +287,18 @@ interface SidebarThreadRowProps {
|
||||
commitRename: (threadId: ThreadId, newTitle: string, originalTitle: string) => Promise<void>;
|
||||
cancelRename: () => void;
|
||||
attemptArchiveThread: (threadId: ThreadId) => Promise<void>;
|
||||
openWebPort: (event: MouseEvent<HTMLElement>, port: number) => void;
|
||||
openPrLink: (event: MouseEvent<HTMLElement>, prUrl: string) => void;
|
||||
pr: ThreadPr | null;
|
||||
}
|
||||
|
||||
function SidebarThreadRow(props: SidebarThreadRowProps) {
|
||||
const thread = useSidebarThreadSummaryById(props.threadId);
|
||||
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[props.threadId]);
|
||||
const terminalState = useTerminalStateStore((state) =>
|
||||
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId),
|
||||
const runningTerminalIds = useTerminalStateStore(
|
||||
(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;
|
||||
@@ -328,11 +315,9 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
|
||||
lastVisitedAt,
|
||||
},
|
||||
});
|
||||
const prStatus = prStatusIndicator(props.pr);
|
||||
const terminalStatus = terminalStatusFromTerminalState(
|
||||
terminalState.runningTerminalIds,
|
||||
terminalState.runningTerminalPorts,
|
||||
);
|
||||
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
|
||||
? "pointer-events-none opacity-0"
|
||||
@@ -449,29 +434,16 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus &&
|
||||
(terminalStatus.primaryWebPort === null ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center rounded-sm ${terminalStatus.colorClass} outline-hidden transition-colors hover:bg-accent hover:text-sky-700 focus-visible:ring-1 focus-visible:ring-ring dark:hover:text-sky-200`}
|
||||
onClick={(event) => {
|
||||
props.openWebPort(event, terminalStatus.primaryWebPort!);
|
||||
}}
|
||||
>
|
||||
<GlobeIcon className="size-3" />
|
||||
</button>
|
||||
))}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</span>
|
||||
)}
|
||||
<div className="flex min-w-12 justify-end">
|
||||
{isConfirmingArchive ? (
|
||||
<button
|
||||
@@ -803,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();
|
||||
@@ -873,18 +797,6 @@ export default function Sidebar() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const openWebPort = useCallback((event: MouseEvent<HTMLElement>, port: number) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const attemptArchiveThread = useCallback(
|
||||
async (threadId: ThreadId) => {
|
||||
try {
|
||||
@@ -1771,6 +1683,7 @@ export default function Sidebar() {
|
||||
<SidebarThreadRow
|
||||
key={threadId}
|
||||
threadId={threadId}
|
||||
projectCwd={project.cwd}
|
||||
orderedProjectThreadIds={orderedProjectThreadIds}
|
||||
routeThreadId={routeThreadId}
|
||||
selectedThreadIds={selectedThreadIds}
|
||||
@@ -1793,9 +1706,7 @@ export default function Sidebar() {
|
||||
commitRename={commitRename}
|
||||
cancelRename={cancelRename}
|
||||
attemptArchiveThread={attemptArchiveThread}
|
||||
openWebPort={openWebPort}
|
||||
openPrLink={openPrLink}
|
||||
pr={prByThreadId.get(threadId) ?? null}
|
||||
/>
|
||||
))}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Globe, Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
|
||||
import {
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { Terminal, type ITheme } from "@xterm/xterm";
|
||||
import {
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
@@ -75,42 +74,6 @@ export function selectPendingTerminalEventEntries(
|
||||
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
|
||||
}
|
||||
|
||||
interface TerminalRuntimeStatus {
|
||||
label: string;
|
||||
primaryWebPort: number | null;
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(rawPorts: number[] | undefined): number[] {
|
||||
if (!rawPorts) return [];
|
||||
return [...new Set(rawPorts)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function terminalRuntimeStatus(
|
||||
terminalId: string,
|
||||
runningTerminalIds: Set<string>,
|
||||
runningTerminalPorts: Record<string, number[]>,
|
||||
): TerminalRuntimeStatus | null {
|
||||
if (!runningTerminalIds.has(terminalId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const runningPorts = normalizeRunningPorts(runningTerminalPorts[terminalId]);
|
||||
const primaryWebPort = runningPorts[0] ?? null;
|
||||
const label =
|
||||
runningPorts.length === 0
|
||||
? "Terminal process running"
|
||||
: runningPorts.length === 1
|
||||
? `Open web server: http://localhost:${primaryWebPort}`
|
||||
: `Open web server: http://localhost:${primaryWebPort} (detected web ports: ${runningPorts.join(", ")})`;
|
||||
|
||||
return {
|
||||
label,
|
||||
primaryWebPort,
|
||||
};
|
||||
}
|
||||
|
||||
function terminalThemeFromApp(): ITheme {
|
||||
const isDark = document.documentElement.classList.contains("dark");
|
||||
const bodyStyles = getComputedStyle(document.body);
|
||||
@@ -768,8 +731,6 @@ interface ThreadTerminalDrawerProps {
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
runningTerminalIds: string[];
|
||||
runningTerminalPorts: Record<string, number[]>;
|
||||
focusRequestId: number;
|
||||
onSplitTerminal: () => void;
|
||||
onNewTerminal: () => void;
|
||||
@@ -822,8 +783,6 @@ export default function ThreadTerminalDrawer({
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
runningTerminalIds,
|
||||
runningTerminalPorts,
|
||||
focusRequestId,
|
||||
onSplitTerminal,
|
||||
onNewTerminal,
|
||||
@@ -947,10 +906,6 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const runningTerminalIdSet = useMemo(
|
||||
() => new Set(runningTerminalIds.map((terminalId) => terminalId.trim())),
|
||||
[runningTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedSplitLimit
|
||||
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
|
||||
: splitShortcutLabel
|
||||
@@ -1072,14 +1027,6 @@ export default function ThreadTerminalDrawer({
|
||||
};
|
||||
}, [syncHeight]);
|
||||
|
||||
const openWebPort = useCallback((event: ReactMouseEvent<HTMLButtonElement>, port: number) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
void api.shell.openExternal(`http://localhost:${port}`).catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
||||
@@ -1252,11 +1199,6 @@ export default function ThreadTerminalDrawer({
|
||||
>
|
||||
{terminalGroup.terminalIds.map((terminalId) => {
|
||||
const isActive = terminalId === resolvedActiveTerminalId;
|
||||
const runtimeStatus = terminalRuntimeStatus(
|
||||
terminalId,
|
||||
runningTerminalIdSet,
|
||||
runningTerminalPorts,
|
||||
);
|
||||
const closeTerminalLabel = `Close ${
|
||||
terminalLabelById.get(terminalId) ?? "terminal"
|
||||
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
|
||||
@@ -1282,29 +1224,6 @@ export default function ThreadTerminalDrawer({
|
||||
{terminalLabelById.get(terminalId) ?? "Terminal"}
|
||||
</span>
|
||||
</button>
|
||||
{runtimeStatus &&
|
||||
(runtimeStatus.primaryWebPort === null ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={runtimeStatus.label}
|
||||
title={runtimeStatus.label}
|
||||
className="inline-flex items-center justify-center text-teal-600 dark:text-teal-300/90"
|
||||
>
|
||||
<TerminalSquare className="size-2.5 animate-pulse" />
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center justify-center rounded p-0.5 text-sky-600 transition-colors hover:bg-accent hover:text-sky-700 dark:text-sky-300/90 dark:hover:text-sky-200"
|
||||
onClick={(event) =>
|
||||
openWebPort(event, runtimeStatus.primaryWebPort!)
|
||||
}
|
||||
aria-label={runtimeStatus.label}
|
||||
title={runtimeStatus.label}
|
||||
>
|
||||
<Globe className="size-2.5 shrink-0" />
|
||||
</button>
|
||||
))}
|
||||
{normalizedTerminalIds.length > 1 && (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { WsConnectionStatus } from "../rpc/wsConnectionState";
|
||||
import { shouldAutoReconnect } from "./WebSocketConnectionSurface";
|
||||
|
||||
function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionStatus {
|
||||
return {
|
||||
attemptCount: 0,
|
||||
closeCode: null,
|
||||
closeReason: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
hasConnected: false,
|
||||
lastError: null,
|
||||
lastErrorAt: null,
|
||||
nextRetryAt: null,
|
||||
online: true,
|
||||
phase: "idle",
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectMaxAttempts: 8,
|
||||
reconnectPhase: "idle",
|
||||
socketUrl: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("WebSocketConnectionSurface.logic", () => {
|
||||
it("forces reconnect on online when the app was offline", () => {
|
||||
expect(
|
||||
shouldAutoReconnect(
|
||||
makeStatus({
|
||||
disconnectedAt: "2026-04-03T20:00:00.000Z",
|
||||
online: false,
|
||||
phase: "disconnected",
|
||||
}),
|
||||
"online",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("forces reconnect on focus only for previously connected disconnected states", () => {
|
||||
expect(
|
||||
shouldAutoReconnect(
|
||||
makeStatus({
|
||||
hasConnected: true,
|
||||
online: true,
|
||||
phase: "disconnected",
|
||||
reconnectAttemptCount: 3,
|
||||
reconnectPhase: "waiting",
|
||||
}),
|
||||
"focus",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
shouldAutoReconnect(
|
||||
makeStatus({
|
||||
hasConnected: false,
|
||||
online: true,
|
||||
phase: "disconnected",
|
||||
reconnectAttemptCount: 1,
|
||||
reconnectPhase: "waiting",
|
||||
}),
|
||||
"focus",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("forces reconnect on focus for exhausted reconnect loops", () => {
|
||||
expect(
|
||||
shouldAutoReconnect(
|
||||
makeStatus({
|
||||
hasConnected: true,
|
||||
online: true,
|
||||
phase: "disconnected",
|
||||
reconnectAttemptCount: 8,
|
||||
reconnectPhase: "exhausted",
|
||||
}),
|
||||
"focus",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,544 @@
|
||||
import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
|
||||
import { useServerConfig } from "../rpc/serverState";
|
||||
import {
|
||||
exhaustWsReconnectIfStillWaiting,
|
||||
getWsConnectionStatus,
|
||||
getWsConnectionUiState,
|
||||
setBrowserOnlineStatus,
|
||||
type WsConnectionStatus,
|
||||
type WsConnectionUiState,
|
||||
useWsConnectionStatus,
|
||||
WS_RECONNECT_MAX_ATTEMPTS,
|
||||
} from "../rpc/wsConnectionState";
|
||||
import { Button } from "./ui/button";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { getWsRpcClient } from "~/wsRpcClient";
|
||||
|
||||
const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
|
||||
type WsAutoReconnectTrigger = "focus" | "online";
|
||||
|
||||
const connectionTimeFormatter = new Intl.DateTimeFormat(undefined, {
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
month: "short",
|
||||
second: "2-digit",
|
||||
});
|
||||
|
||||
function formatConnectionMoment(isoDate: string | null): string | null {
|
||||
if (!isoDate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return connectionTimeFormatter.format(new Date(isoDate));
|
||||
}
|
||||
|
||||
function formatRetryCountdown(nextRetryAt: string, nowMs: number): string {
|
||||
const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs);
|
||||
return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`;
|
||||
}
|
||||
|
||||
function describeOfflineToast(): string {
|
||||
return "WebSocket disconnected. Waiting for network.";
|
||||
}
|
||||
|
||||
function formatReconnectAttemptLabel(status: WsConnectionStatus): string {
|
||||
const reconnectAttempt = Math.max(
|
||||
1,
|
||||
Math.min(status.reconnectAttemptCount, WS_RECONNECT_MAX_ATTEMPTS),
|
||||
);
|
||||
return `Attempt ${reconnectAttempt}/${status.reconnectMaxAttempts}`;
|
||||
}
|
||||
|
||||
function describeExhaustedToast(): string {
|
||||
return "Retries exhausted trying to reconnect";
|
||||
}
|
||||
|
||||
function buildReconnectTitle(status: WsConnectionStatus): string {
|
||||
if (status.nextRetryAt === null) {
|
||||
return "Disconnected from T3 Server";
|
||||
}
|
||||
|
||||
return "Disconnected from T3 Server";
|
||||
}
|
||||
|
||||
function describeRecoveredToast(
|
||||
previousDisconnectedAt: string | null,
|
||||
connectedAt: string | null,
|
||||
): string {
|
||||
const reconnectedAtLabel = formatConnectionMoment(connectedAt);
|
||||
const disconnectedAtLabel = formatConnectionMoment(previousDisconnectedAt);
|
||||
|
||||
if (disconnectedAtLabel && reconnectedAtLabel) {
|
||||
return `Disconnected at ${disconnectedAtLabel} and reconnected at ${reconnectedAtLabel}.`;
|
||||
}
|
||||
|
||||
if (reconnectedAtLabel) {
|
||||
return `Connection restored at ${reconnectedAtLabel}.`;
|
||||
}
|
||||
|
||||
return "Connection restored.";
|
||||
}
|
||||
|
||||
function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): ReactNode {
|
||||
const count = requests.length;
|
||||
const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000);
|
||||
|
||||
return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
|
||||
}
|
||||
|
||||
export function shouldAutoReconnect(
|
||||
status: WsConnectionStatus,
|
||||
trigger: WsAutoReconnectTrigger,
|
||||
): boolean {
|
||||
const uiState = getWsConnectionUiState(status);
|
||||
|
||||
if (trigger === "online") {
|
||||
return (
|
||||
uiState === "offline" ||
|
||||
uiState === "reconnecting" ||
|
||||
uiState === "error" ||
|
||||
status.reconnectPhase === "exhausted"
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
status.online &&
|
||||
status.hasConnected &&
|
||||
(uiState === "reconnecting" || status.reconnectPhase === "exhausted")
|
||||
);
|
||||
}
|
||||
|
||||
function buildBlockingCopy(
|
||||
uiState: WsConnectionUiState,
|
||||
status: WsConnectionStatus,
|
||||
): {
|
||||
readonly description: string;
|
||||
readonly eyebrow: string;
|
||||
readonly title: string;
|
||||
} {
|
||||
if (uiState === "connecting") {
|
||||
return {
|
||||
description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`,
|
||||
eyebrow: "Starting Session",
|
||||
title: `Connecting to ${APP_DISPLAY_NAME}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (uiState === "offline") {
|
||||
return {
|
||||
description:
|
||||
"Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.",
|
||||
eyebrow: "Offline",
|
||||
title: "WebSocket connection unavailable",
|
||||
};
|
||||
}
|
||||
|
||||
if (status.lastError?.trim()) {
|
||||
return {
|
||||
description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`,
|
||||
eyebrow: "Connection Error",
|
||||
title: "Cannot reach the T3 server",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
description:
|
||||
"The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.",
|
||||
eyebrow: "Connection Error",
|
||||
title: "Cannot reach the T3 server",
|
||||
};
|
||||
}
|
||||
|
||||
function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string {
|
||||
const details = [
|
||||
`state: ${uiState}`,
|
||||
`online: ${status.online ? "yes" : "no"}`,
|
||||
`attempts: ${status.attemptCount}`,
|
||||
];
|
||||
|
||||
if (status.socketUrl) {
|
||||
details.push(`socket: ${status.socketUrl}`);
|
||||
}
|
||||
if (status.connectedAt) {
|
||||
details.push(`connectedAt: ${status.connectedAt}`);
|
||||
}
|
||||
if (status.disconnectedAt) {
|
||||
details.push(`disconnectedAt: ${status.disconnectedAt}`);
|
||||
}
|
||||
if (status.lastErrorAt) {
|
||||
details.push(`lastErrorAt: ${status.lastErrorAt}`);
|
||||
}
|
||||
if (status.lastError) {
|
||||
details.push(`lastError: ${status.lastError}`);
|
||||
}
|
||||
if (status.closeCode !== null) {
|
||||
details.push(`closeCode: ${status.closeCode}`);
|
||||
}
|
||||
if (status.closeReason) {
|
||||
details.push(`closeReason: ${status.closeReason}`);
|
||||
}
|
||||
|
||||
return details.join("\n");
|
||||
}
|
||||
|
||||
function WebSocketBlockingState({
|
||||
status,
|
||||
uiState,
|
||||
}: {
|
||||
readonly status: WsConnectionStatus;
|
||||
readonly uiState: WsConnectionUiState;
|
||||
}) {
|
||||
const copy = buildBlockingCopy(uiState, status);
|
||||
const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt);
|
||||
const Icon =
|
||||
uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle;
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-90">
|
||||
<div className="absolute inset-x-0 top-0 h-56 bg-[radial-gradient(48rem_18rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-xl rounded-[1.75rem] border border-border/80 bg-card/92 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{copy.eyebrow}
|
||||
</p>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{copy.title}</h1>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-border/70 bg-background/80 p-3 text-foreground shadow-sm">
|
||||
<Icon className={uiState === "connecting" ? "size-5 animate-spin" : "size-5"} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">{copy.description}</p>
|
||||
|
||||
<div className="mt-5 grid gap-3 rounded-2xl border border-border/70 bg-background/60 p-4 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
|
||||
Connection
|
||||
</p>
|
||||
<p className="mt-1 font-medium text-foreground">
|
||||
{uiState === "connecting"
|
||||
? "Opening WebSocket"
|
||||
: uiState === "offline"
|
||||
? "Waiting for network"
|
||||
: "Retrying server connection"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
|
||||
Latest Event
|
||||
</p>
|
||||
<p className="mt-1 font-medium text-foreground">{disconnectedAt ?? "Pending"}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 flex flex-wrap gap-2">
|
||||
<Button size="sm" onClick={() => window.location.reload()}>
|
||||
<RotateCw />
|
||||
Reload app
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
|
||||
<summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
|
||||
<span className="group-open:hidden">Show connection details</span>
|
||||
<span className="hidden group-open:inline">Hide connection details</span>
|
||||
</summary>
|
||||
<pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
|
||||
{buildConnectionDetails(status, uiState)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WebSocketConnectionCoordinator() {
|
||||
const status = useWsConnectionStatus();
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
const lastForcedReconnectAtRef = useRef(0);
|
||||
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
|
||||
const toastResetTimerRef = useRef<number | null>(null);
|
||||
const previousUiStateRef = useRef<WsConnectionUiState>(getWsConnectionUiState(status));
|
||||
const previousDisconnectedAtRef = useRef<string | null>(status.disconnectedAt);
|
||||
|
||||
const runReconnect = useEffectEvent((showFailureToast: boolean) => {
|
||||
if (toastResetTimerRef.current !== null) {
|
||||
window.clearTimeout(toastResetTimerRef.current);
|
||||
toastResetTimerRef.current = null;
|
||||
}
|
||||
lastForcedReconnectAtRef.current = Date.now();
|
||||
void getWsRpcClient()
|
||||
.reconnect()
|
||||
.catch((error) => {
|
||||
if (!showFailureToast) {
|
||||
console.warn("Automatic WebSocket reconnect failed", { error });
|
||||
return;
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Reconnect failed",
|
||||
description: error instanceof Error ? error.message : "Unable to restart the WebSocket.",
|
||||
data: {
|
||||
dismissAfterVisibleMs: 8_000,
|
||||
hideCopyButton: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
const syncBrowserOnlineStatus = useEffectEvent(() => {
|
||||
setBrowserOnlineStatus(navigator.onLine !== false);
|
||||
});
|
||||
const triggerManualReconnect = useEffectEvent(() => {
|
||||
runReconnect(true);
|
||||
});
|
||||
const triggerAutoReconnect = useEffectEvent((trigger: WsAutoReconnectTrigger) => {
|
||||
const currentStatus =
|
||||
trigger === "online" ? setBrowserOnlineStatus(true) : getWsConnectionStatus();
|
||||
|
||||
if (!shouldAutoReconnect(currentStatus, trigger)) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() - lastForcedReconnectAtRef.current < FORCED_WS_RECONNECT_DEBOUNCE_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
runReconnect(false);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => {
|
||||
triggerAutoReconnect("online");
|
||||
};
|
||||
const handleFocus = () => {
|
||||
triggerAutoReconnect("focus");
|
||||
};
|
||||
|
||||
syncBrowserOnlineStatus();
|
||||
window.addEventListener("online", handleOnline);
|
||||
window.addEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.addEventListener("focus", handleFocus);
|
||||
return () => {
|
||||
window.removeEventListener("online", handleOnline);
|
||||
window.removeEventListener("offline", syncBrowserOnlineStatus);
|
||||
window.removeEventListener("focus", handleFocus);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setNowMs(Date.now());
|
||||
const intervalId = window.setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, 1_000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [status.nextRetryAt, status.reconnectPhase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
status.reconnectPhase !== "waiting" ||
|
||||
status.nextRetryAt === null ||
|
||||
!status.online ||
|
||||
!status.hasConnected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextRetryAt = status.nextRetryAt;
|
||||
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
exhaustWsReconnectIfStillWaiting(nextRetryAt);
|
||||
}, timeoutMs);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
};
|
||||
}, [
|
||||
status.hasConnected,
|
||||
status.nextRetryAt,
|
||||
status.online,
|
||||
status.reconnectAttemptCount,
|
||||
status.reconnectPhase,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const uiState = getWsConnectionUiState(status);
|
||||
const previousUiState = previousUiStateRef.current;
|
||||
const previousDisconnectedAt = previousDisconnectedAtRef.current;
|
||||
const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting";
|
||||
const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null;
|
||||
const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted";
|
||||
|
||||
if (
|
||||
toastResetTimerRef.current !== null &&
|
||||
(shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast)
|
||||
) {
|
||||
window.clearTimeout(toastResetTimerRef.current);
|
||||
toastResetTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) {
|
||||
const toastPayload = shouldShowOfflineToast
|
||||
? {
|
||||
description: describeOfflineToast(),
|
||||
timeout: 0,
|
||||
title: "Offline",
|
||||
type: "warning" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}
|
||||
: shouldShowExhaustedToast
|
||||
? {
|
||||
actionProps: {
|
||||
children: "Retry",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
description: describeExhaustedToast(),
|
||||
timeout: 0,
|
||||
title: "Disconnected from T3 Server",
|
||||
type: "error" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}
|
||||
: {
|
||||
actionProps: {
|
||||
children: "Retry now",
|
||||
onClick: triggerManualReconnect,
|
||||
},
|
||||
description:
|
||||
status.nextRetryAt === null
|
||||
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
|
||||
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
|
||||
timeout: 0,
|
||||
title: buildReconnectTitle(status),
|
||||
type: "loading" as const,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (toastIdRef.current) {
|
||||
toastManager.update(toastIdRef.current, toastPayload);
|
||||
} else {
|
||||
toastIdRef.current = toastManager.add(toastPayload);
|
||||
}
|
||||
} else if (toastIdRef.current) {
|
||||
toastManager.close(toastIdRef.current);
|
||||
toastIdRef.current = null;
|
||||
}
|
||||
|
||||
if (
|
||||
uiState === "connected" &&
|
||||
(previousUiState === "offline" || previousUiState === "reconnecting") &&
|
||||
previousDisconnectedAt !== null
|
||||
) {
|
||||
const successToast = {
|
||||
description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
|
||||
title: "Reconnected to T3 Server",
|
||||
type: "success" as const,
|
||||
timeout: 0,
|
||||
data: {
|
||||
dismissAfterVisibleMs: 8_000,
|
||||
hideCopyButton: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (toastIdRef.current) {
|
||||
toastManager.update(toastIdRef.current, successToast);
|
||||
} else {
|
||||
toastIdRef.current = toastManager.add(successToast);
|
||||
}
|
||||
|
||||
toastResetTimerRef.current = window.setTimeout(() => {
|
||||
toastIdRef.current = null;
|
||||
toastResetTimerRef.current = null;
|
||||
}, 8_250);
|
||||
}
|
||||
|
||||
previousUiStateRef.current = uiState;
|
||||
previousDisconnectedAtRef.current = status.disconnectedAt;
|
||||
}, [nowMs, status]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (toastResetTimerRef.current !== null) {
|
||||
window.clearTimeout(toastResetTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function SlowRpcAckToastCoordinator() {
|
||||
const slowRequests = useSlowRpcAckRequests();
|
||||
const status = useWsConnectionStatus();
|
||||
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (getWsConnectionUiState(status) !== "connected") {
|
||||
if (toastIdRef.current) {
|
||||
toastManager.close(toastIdRef.current);
|
||||
toastIdRef.current = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (slowRequests.length === 0) {
|
||||
if (toastIdRef.current) {
|
||||
toastManager.close(toastIdRef.current);
|
||||
toastIdRef.current = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextToast = {
|
||||
description: describeSlowRpcAckToast(slowRequests),
|
||||
timeout: 0,
|
||||
title: "Some requests are slow",
|
||||
type: "warning" as const,
|
||||
};
|
||||
|
||||
if (toastIdRef.current) {
|
||||
toastManager.update(toastIdRef.current, nextToast);
|
||||
} else {
|
||||
toastIdRef.current = toastManager.add(nextToast);
|
||||
}
|
||||
}, [slowRequests, status]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) {
|
||||
const serverConfig = useServerConfig();
|
||||
const status = useWsConnectionStatus();
|
||||
|
||||
if (serverConfig === null) {
|
||||
const uiState = getWsConnectionUiState(status);
|
||||
return (
|
||||
<WebSocketBlockingState
|
||||
status={status}
|
||||
uiState={uiState === "connected" ? "connecting" : uiState}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -23,6 +23,7 @@ export type ThreadToastData = {
|
||||
threadId?: ThreadId | null;
|
||||
tooltipStyle?: boolean;
|
||||
dismissAfterVisibleMs?: number;
|
||||
hideCopyButton?: boolean;
|
||||
};
|
||||
|
||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
||||
@@ -308,15 +309,15 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
className="min-w-0 wrap-break-word font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
{toast.type === "error" &&
|
||||
typeof toast.description === "string" &&
|
||||
!toast.data?.hideCopyButton && <CopyErrorButton text={toast.description} />}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 select-text wrap-break-word text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
@@ -402,15 +403,17 @@ function AnchoredToasts() {
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
className="min-w-0 wrap-break-word font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
{toast.type === "error" &&
|
||||
typeof toast.description === "string" &&
|
||||
!toast.data?.hideCopyButton && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 select-text wrap-break-word text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect";
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { resolveServerUrl } from "../lib/utils";
|
||||
import { APP_VERSION } from "~/branding";
|
||||
|
||||
const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
|
||||
const CLIENT_TRACING_RESOURCE = {
|
||||
serviceName: "t3-web",
|
||||
attributes: {
|
||||
"service.runtime": "t3-web",
|
||||
"service.mode": isElectron ? "electron" : "browser",
|
||||
"service.version": APP_VERSION,
|
||||
},
|
||||
} as const;
|
||||
|
||||
const delegateRuntimeLayer = Layer.mergeAll(
|
||||
FetchHttpClient.layer,
|
||||
OtlpSerialization.layerJson,
|
||||
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
|
||||
);
|
||||
|
||||
let activeDelegate: Tracer.Tracer | null = null;
|
||||
let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
|
||||
let activeScope: Scope.Closeable | null = null;
|
||||
let activeConfigKey: string | null = null;
|
||||
let configurationGeneration = 0;
|
||||
let pendingConfiguration = Promise.resolve();
|
||||
|
||||
export interface ClientTracingConfig {
|
||||
readonly exportIntervalMs?: number;
|
||||
}
|
||||
|
||||
export const ClientTracingLive = Layer.succeed(
|
||||
Tracer.Tracer,
|
||||
Tracer.make({
|
||||
span(options) {
|
||||
return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
|
||||
if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
|
||||
return pendingConfiguration;
|
||||
}
|
||||
pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
|
||||
return pendingConfiguration;
|
||||
}
|
||||
|
||||
async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
|
||||
const otlpTracesUrl = resolveServerUrl({
|
||||
protocol: window.location.protocol === "https:" ? "https" : "http",
|
||||
pathname: "/api/observability/v1/traces",
|
||||
});
|
||||
const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
|
||||
const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
|
||||
|
||||
if (activeConfigKey === nextConfigKey && activeDelegate !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
activeConfigKey = nextConfigKey;
|
||||
const generation = ++configurationGeneration;
|
||||
|
||||
const previousRuntime = activeRuntime;
|
||||
const previousScope = activeScope;
|
||||
|
||||
activeDelegate = null;
|
||||
activeRuntime = null;
|
||||
activeScope = null;
|
||||
|
||||
await disposeTracerRuntime(previousRuntime, previousScope);
|
||||
|
||||
const runtime = ManagedRuntime.make(delegateRuntimeLayer);
|
||||
const scope = runtime.runSync(Scope.make());
|
||||
|
||||
try {
|
||||
const delegate = await runtime.runPromise(
|
||||
Scope.provide(scope)(
|
||||
OtlpTracer.make({
|
||||
url: otlpTracesUrl,
|
||||
exportInterval: `${exportIntervalMs} millis`,
|
||||
resource: CLIENT_TRACING_RESOURCE,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (generation !== configurationGeneration) {
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
return;
|
||||
}
|
||||
|
||||
activeDelegate = delegate;
|
||||
activeRuntime = runtime;
|
||||
activeScope = scope;
|
||||
} catch (error) {
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
|
||||
if (generation === configurationGeneration) {
|
||||
console.warn("Failed to configure client tracing exporter", {
|
||||
error: formatError(error),
|
||||
otlpTracesUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function disposeTracerRuntime(
|
||||
runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
|
||||
scope: Scope.Closeable | null,
|
||||
): Promise<void> {
|
||||
if (runtime === null || scope === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runtime
|
||||
.runPromise(Scope.close(scope, Exit.void))
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
runtime.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
function formatError(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export async function __resetClientTracingForTests() {
|
||||
configurationGeneration++;
|
||||
activeConfigKey = null;
|
||||
activeDelegate = null;
|
||||
pendingConfiguration = Promise.resolve();
|
||||
|
||||
const runtime = activeRuntime;
|
||||
const scope = activeScope;
|
||||
activeRuntime = null;
|
||||
activeScope = null;
|
||||
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
|
||||
export type OrchestrationRecoveryReason =
|
||||
| "bootstrap"
|
||||
| "sequence-gap"
|
||||
| "resubscribe"
|
||||
| "replay-failed";
|
||||
|
||||
export interface OrchestrationRecoveryPhase {
|
||||
kind: "snapshot" | "replay";
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("parsePullRequestReference", () => {
|
||||
});
|
||||
|
||||
it("accepts #number references", () => {
|
||||
expect(parsePullRequestReference("#42")).toBe("#42");
|
||||
expect(parsePullRequestReference("#42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with raw numbers", () => {
|
||||
@@ -22,7 +22,7 @@ describe("parsePullRequestReference", () => {
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with #number references", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
|
||||
if (numberMatch?.[1]) {
|
||||
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
|
||||
return numberMatch[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -16,6 +16,11 @@ import { Throttler } from "@tanstack/react-pacer";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import {
|
||||
SlowRpcAckToastCoordinator,
|
||||
WebSocketConnectionCoordinator,
|
||||
WebSocketConnectionSurface,
|
||||
} from "../components/WebSocketConnectionSurface";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
@@ -73,9 +78,13 @@ function RootRouteView() {
|
||||
<AnchoredToastProvider>
|
||||
<ServerStateBootstrap />
|
||||
<EventRouter />
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
<WebSocketConnectionCoordinator />
|
||||
<SlowRpcAckToastCoordinator />
|
||||
<WebSocketConnectionSurface>
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
</WebSocketConnectionSurface>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
@@ -428,8 +437,8 @@ function EventRouter() {
|
||||
queueMicrotask(flushPendingDomainEvents);
|
||||
};
|
||||
|
||||
const recoverFromSequenceGap = async (): Promise<void> => {
|
||||
if (!recovery.beginReplayRecovery("sequence-gap")) {
|
||||
const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
|
||||
if (!recovery.beginReplayRecovery(reason)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -466,7 +475,7 @@ function EventRouter() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
void recoverFromSequenceGap();
|
||||
void runReplayRecovery(reason);
|
||||
} else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
|
||||
console.warn(
|
||||
"[orchestration-recovery]",
|
||||
@@ -505,7 +514,7 @@ function EventRouter() {
|
||||
syncServerReadModel(snapshot);
|
||||
reconcileSnapshotDerivedState();
|
||||
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
|
||||
void recoverFromSequenceGap();
|
||||
void runReplayRecovery("sequence-gap");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -522,18 +531,29 @@ function EventRouter() {
|
||||
const fallbackToSnapshotRecovery = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("replay-failed");
|
||||
};
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
pendingDomainEvents.push(event);
|
||||
schedulePendingDomainEventFlush();
|
||||
return;
|
||||
}
|
||||
if (action === "recover") {
|
||||
flushPendingDomainEvents();
|
||||
void recoverFromSequenceGap();
|
||||
}
|
||||
});
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent(
|
||||
(event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
pendingDomainEvents.push(event);
|
||||
schedulePendingDomainEventFlush();
|
||||
return;
|
||||
}
|
||||
if (action === "recover") {
|
||||
flushPendingDomainEvents();
|
||||
void runReplayRecovery("sequence-gap");
|
||||
}
|
||||
},
|
||||
{
|
||||
onResubscribe: () => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
flushPendingDomainEvents();
|
||||
void runReplayRecovery("resubscribe");
|
||||
},
|
||||
},
|
||||
);
|
||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
||||
const thread = useStore.getState().threads.find((entry) => entry.id === event.threadId);
|
||||
if (thread && thread.archivedAt !== null) {
|
||||
|
||||
@@ -2,6 +2,10 @@ import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
configureClientTracing,
|
||||
__resetClientTracingForTests,
|
||||
} from "../observability/clientTracing";
|
||||
import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
@@ -66,6 +70,7 @@ class MockWebSocket {
|
||||
}
|
||||
|
||||
const originalWebSocket = globalThis.WebSocket;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
function getSocket(): MockWebSocket {
|
||||
const socket = sockets.at(-1);
|
||||
@@ -112,6 +117,7 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
__resetWsRpcAtomClientForTests();
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -228,4 +234,46 @@ describe("WsRpcAtomClient", () => {
|
||||
release();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("attaches distributed trace ids when client OTLP tracing is enabled", async () => {
|
||||
await configureClientTracing({
|
||||
exportIntervalMs: 10,
|
||||
});
|
||||
|
||||
const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as {
|
||||
id: string;
|
||||
spanId?: string;
|
||||
tag: string;
|
||||
traceId?: string;
|
||||
};
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
||||
expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,11 @@ import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
import { AtomRpc } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
__resetClientTracingForTests,
|
||||
ClientTracingLive,
|
||||
configureClientTracing,
|
||||
} from "../observability/clientTracing";
|
||||
import { createWsRpcProtocolLayer } from "./protocol";
|
||||
|
||||
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
||||
@@ -16,18 +21,22 @@ function getRuntime() {
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
|
||||
sharedRuntime = ManagedRuntime.make(Layer.mergeAll(WsRpcAtomClient.layer, ClientTracingLive));
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
export function runRpc<TSuccess, TError = never>(
|
||||
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
|
||||
return configureClientTracing().then(() => {
|
||||
const runtime = getRuntime();
|
||||
return runtime.runPromise(WsRpcAtomClient.use(execute));
|
||||
});
|
||||
}
|
||||
|
||||
export async function __resetWsRpcAtomClientForTests() {
|
||||
const runtime = sharedRuntime;
|
||||
sharedRuntime = null;
|
||||
await runtime?.dispose();
|
||||
await __resetClientTracingForTests();
|
||||
}
|
||||
@@ -1,9 +1,22 @@
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
|
||||
import { resolveServerUrl } from "../lib/utils";
|
||||
import {
|
||||
acknowledgeRpcRequest,
|
||||
clearAllTrackedRpcRequests,
|
||||
trackRpcRequestSent,
|
||||
} from "./requestLatencyState";
|
||||
import {
|
||||
getWsReconnectDelayMsForRetry,
|
||||
recordWsConnectionAttempt,
|
||||
recordWsConnectionClosed,
|
||||
recordWsConnectionErrored,
|
||||
recordWsConnectionOpened,
|
||||
WS_RECONNECT_MAX_RETRIES,
|
||||
} from "./wsConnectionState";
|
||||
|
||||
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
|
||||
|
||||
@@ -17,11 +30,75 @@ export function createWsRpcProtocolLayer(url?: string) {
|
||||
protocol: window.location.protocol === "https:" ? "wss" : "ws",
|
||||
pathname: "/ws",
|
||||
});
|
||||
const trackingWebSocketConstructorLayer = Layer.succeed(
|
||||
Socket.WebSocketConstructor,
|
||||
(socketUrl, protocols) => {
|
||||
recordWsConnectionAttempt(socketUrl);
|
||||
const socket = new globalThis.WebSocket(socketUrl, protocols);
|
||||
|
||||
socket.addEventListener(
|
||||
"open",
|
||||
() => {
|
||||
recordWsConnectionOpened();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"error",
|
||||
() => {
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"close",
|
||||
(event) => {
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionClosed({
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
});
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
|
||||
Layer.provide(Socket.layerWebSocketConstructorGlobal),
|
||||
Layer.provide(trackingWebSocketConstructorLayer),
|
||||
);
|
||||
const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) =>
|
||||
Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
|
||||
);
|
||||
const protocolLayer = Layer.effect(
|
||||
RpcClient.Protocol,
|
||||
Effect.map(
|
||||
RpcClient.makeProtocolSocket({
|
||||
retryPolicy,
|
||||
retryTransientErrors: true,
|
||||
}),
|
||||
(protocol) => ({
|
||||
...protocol,
|
||||
run: (writeResponse) =>
|
||||
protocol.run((response) => {
|
||||
if (response._tag === "Chunk" || response._tag === "Exit") {
|
||||
acknowledgeRpcRequest(response.requestId);
|
||||
} else if (response._tag === "ClientProtocolError" || response._tag === "Defect") {
|
||||
clearAllTrackedRpcRequests();
|
||||
}
|
||||
return writeResponse(response);
|
||||
}),
|
||||
send: (request, transferables) => {
|
||||
if (request._tag === "Request") {
|
||||
trackRpcRequestSent(request.id, request.tag);
|
||||
}
|
||||
return protocol.send(request, transferables);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe(
|
||||
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)),
|
||||
);
|
||||
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
acknowledgeRpcRequest,
|
||||
getSlowRpcAckRequests,
|
||||
resetRequestLatencyStateForTests,
|
||||
trackRpcRequestSent,
|
||||
SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
MAX_TRACKED_RPC_ACK_REQUESTS,
|
||||
} from "./requestLatencyState";
|
||||
|
||||
describe("requestLatencyState", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
resetRequestLatencyStateForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("marks unary requests as slow when the ack threshold is exceeded", () => {
|
||||
trackRpcRequestSent("1", "server.getConfig");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS - 1);
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(getSlowRpcAckRequests()).toMatchObject([
|
||||
{
|
||||
requestId: "1",
|
||||
tag: "server.getConfig",
|
||||
thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears the slow request once the server acknowledges it", () => {
|
||||
trackRpcRequestSent("1", "git.status");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
expect(getSlowRpcAckRequests()).toHaveLength(1);
|
||||
|
||||
acknowledgeRpcRequest("1");
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores long-lived subscribe requests", () => {
|
||||
trackRpcRequestSent("1", "subscribeServerConfig");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS * 2);
|
||||
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it("evicts the oldest pending requests once the tracker reaches capacity", () => {
|
||||
for (let index = 0; index < MAX_TRACKED_RPC_ACK_REQUESTS + 1; index += 1) {
|
||||
trackRpcRequestSent(String(index), "server.getConfig");
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
|
||||
const slowRequests = getSlowRpcAckRequests();
|
||||
expect(slowRequests).toHaveLength(MAX_TRACKED_RPC_ACK_REQUESTS);
|
||||
expect(slowRequests[0]?.requestId).toBe("1");
|
||||
expect(slowRequests.at(-1)?.requestId).toBe(String(MAX_TRACKED_RPC_ACK_REQUESTS));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atomRegistry";
|
||||
|
||||
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;
|
||||
readonly startedAt: string;
|
||||
readonly startedAtMs: number;
|
||||
readonly tag: string;
|
||||
readonly thresholdMs: number;
|
||||
}
|
||||
|
||||
interface PendingRpcAckRequest {
|
||||
readonly request: SlowRpcAckRequest;
|
||||
readonly timeoutId: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const pendingRpcAckRequests = new Map<string, PendingRpcAckRequest>();
|
||||
|
||||
const slowRpcAckRequestsAtom = Atom.make<ReadonlyArray<SlowRpcAckRequest>>([]).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("slow-rpc-ack-requests"),
|
||||
);
|
||||
|
||||
function setSlowRpcAckRequests(requests: ReadonlyArray<SlowRpcAckRequest>) {
|
||||
appAtomRegistry.set(slowRpcAckRequestsAtom, [...requests]);
|
||||
}
|
||||
|
||||
function getSlowRpcAckRequestsValue(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return appAtomRegistry.get(slowRpcAckRequestsAtom);
|
||||
}
|
||||
|
||||
function shouldTrackRpcAck(tag: string): boolean {
|
||||
return !tag.startsWith("subscribe");
|
||||
}
|
||||
|
||||
export function getSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return getSlowRpcAckRequestsValue();
|
||||
}
|
||||
|
||||
export function trackRpcRequestSent(requestId: string, tag: string): void {
|
||||
if (!shouldTrackRpcAck(tag)) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTrackedRpcRequest(requestId);
|
||||
evictOldestPendingRpcRequestIfNeeded();
|
||||
|
||||
const startedAtMs = Date.now();
|
||||
const request: SlowRpcAckRequest = {
|
||||
requestId,
|
||||
startedAt: new Date(startedAtMs).toISOString(),
|
||||
startedAtMs,
|
||||
tag,
|
||||
thresholdMs: slowRpcAckThresholdMs,
|
||||
};
|
||||
const timeoutId = setTimeout(() => {
|
||||
pendingRpcAckRequests.delete(requestId);
|
||||
appendSlowRpcAckRequest(request);
|
||||
}, slowRpcAckThresholdMs);
|
||||
|
||||
pendingRpcAckRequests.set(requestId, {
|
||||
request,
|
||||
timeoutId,
|
||||
});
|
||||
}
|
||||
|
||||
export function acknowledgeRpcRequest(requestId: string): void {
|
||||
clearTrackedRpcRequest(requestId);
|
||||
const slowRequests = getSlowRpcAckRequestsValue();
|
||||
if (!slowRequests.some((request) => request.requestId === requestId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSlowRpcAckRequests(slowRequests.filter((request) => request.requestId !== requestId));
|
||||
}
|
||||
|
||||
export function clearAllTrackedRpcRequests(): void {
|
||||
for (const pending of pendingRpcAckRequests.values()) {
|
||||
clearTimeout(pending.timeoutId);
|
||||
}
|
||||
pendingRpcAckRequests.clear();
|
||||
setSlowRpcAckRequests([]);
|
||||
}
|
||||
|
||||
function clearTrackedRpcRequest(requestId: string): void {
|
||||
const pending = pendingRpcAckRequests.get(requestId);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeoutId);
|
||||
pendingRpcAckRequests.delete(requestId);
|
||||
}
|
||||
|
||||
function appendSlowRpcAckRequest(request: SlowRpcAckRequest): void {
|
||||
const requests = [...getSlowRpcAckRequestsValue(), request];
|
||||
if (requests.length <= MAX_TRACKED_RPC_ACK_REQUESTS) {
|
||||
setSlowRpcAckRequests(requests);
|
||||
return;
|
||||
}
|
||||
|
||||
setSlowRpcAckRequests(requests.slice(-MAX_TRACKED_RPC_ACK_REQUESTS));
|
||||
}
|
||||
|
||||
function evictOldestPendingRpcRequestIfNeeded(): void {
|
||||
while (pendingRpcAckRequests.size >= MAX_TRACKED_RPC_ACK_REQUESTS) {
|
||||
const oldestRequestId = pendingRpcAckRequests.keys().next().value;
|
||||
if (oldestRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTrackedRpcRequest(oldestRequestId);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isTransportConnectionErrorMessage, sanitizeThreadErrorMessage } from "./transportError";
|
||||
|
||||
describe("transportError", () => {
|
||||
it("detects websocket transport failures", () => {
|
||||
expect(isTransportConnectionErrorMessage("SocketCloseError: 1006")).toBe(true);
|
||||
expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isTransportConnectionErrorMessage("SocketOpenError: Timeout")).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves non-transport thread errors", () => {
|
||||
expect(sanitizeThreadErrorMessage("Turn failed")).toBe("Turn failed");
|
||||
expect(sanitizeThreadErrorMessage("Select a base branch before sending.")).toBe(
|
||||
"Select a base branch before sending.",
|
||||
);
|
||||
});
|
||||
|
||||
it("drops transport failures from thread surfaces", () => {
|
||||
expect(sanitizeThreadErrorMessage("SocketCloseError: 1006")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const TRANSPORT_ERROR_PATTERNS = [
|
||||
/\bSocketCloseError\b/i,
|
||||
/\bSocketOpenError\b/i,
|
||||
/Unable to connect to the T3 server WebSocket\./i,
|
||||
/\bping timeout\b/i,
|
||||
] as const;
|
||||
|
||||
export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean {
|
||||
if (typeof message !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedMessage = message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage));
|
||||
}
|
||||
|
||||
export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null {
|
||||
return isTransportConnectionErrorMessage(message) ? null : (message ?? null);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
exhaustWsReconnectIfStillWaiting,
|
||||
getWsConnectionStatus,
|
||||
getWsReconnectDelayMsForRetry,
|
||||
getWsConnectionUiState,
|
||||
recordWsConnectionAttempt,
|
||||
recordWsConnectionClosed,
|
||||
recordWsConnectionErrored,
|
||||
recordWsConnectionOpened,
|
||||
resetWsConnectionStateForTests,
|
||||
setBrowserOnlineStatus,
|
||||
WS_RECONNECT_MAX_ATTEMPTS,
|
||||
} from "./wsConnectionState";
|
||||
|
||||
describe("wsConnectionState", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-04-03T20:30:00.000Z"));
|
||||
resetWsConnectionStateForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("treats a disconnected browser as offline once the websocket drops", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionOpened();
|
||||
recordWsConnectionClosed({ code: 1006, reason: "offline" });
|
||||
setBrowserOnlineStatus(false);
|
||||
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("offline");
|
||||
});
|
||||
|
||||
it("stays in the initial connecting state until the first disconnect", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
attemptCount: 1,
|
||||
hasConnected: false,
|
||||
phase: "connecting",
|
||||
});
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("connecting");
|
||||
});
|
||||
|
||||
it("schedules the next retry after a failed websocket attempt", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
|
||||
const firstRetryDelayMs = getWsReconnectDelayMsForRetry(0);
|
||||
if (firstRetryDelayMs === null) {
|
||||
throw new Error("Expected an initial retry delay.");
|
||||
}
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: new Date(Date.now() + firstRetryDelayMs).toISOString(),
|
||||
reconnectAttemptCount: 1,
|
||||
reconnectPhase: "waiting",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks the reconnect cycle as exhausted after the final attempt fails", () => {
|
||||
for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS; attempt += 1) {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
}
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "exhausted",
|
||||
});
|
||||
});
|
||||
|
||||
it("can exhaust a stalled final retry window when no new attempt starts", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionOpened();
|
||||
|
||||
for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS - 1; attempt += 1) {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
}
|
||||
|
||||
const finalRetryDelayMs = getWsReconnectDelayMsForRetry(WS_RECONNECT_MAX_ATTEMPTS - 2);
|
||||
if (finalRetryDelayMs === null) {
|
||||
throw new Error("Expected a final retry delay.");
|
||||
}
|
||||
|
||||
const statusBeforeExhaust = getWsConnectionStatus();
|
||||
expect(statusBeforeExhaust).toMatchObject({
|
||||
nextRetryAt: new Date(Date.now() + finalRetryDelayMs).toISOString(),
|
||||
reconnectAttemptCount: 7,
|
||||
reconnectPhase: "waiting",
|
||||
});
|
||||
|
||||
const nextRetryAt = statusBeforeExhaust.nextRetryAt;
|
||||
if (!nextRetryAt) {
|
||||
throw new Error("Expected a scheduled retry.");
|
||||
}
|
||||
|
||||
vi.setSystemTime(new Date(Date.now() + finalRetryDelayMs + 1_000));
|
||||
exhaustWsReconnectIfStillWaiting(nextRetryAt);
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "exhausted",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atomRegistry";
|
||||
|
||||
export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting";
|
||||
export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting";
|
||||
|
||||
export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000;
|
||||
export const WS_RECONNECT_BACKOFF_FACTOR = 2;
|
||||
export const WS_RECONNECT_MAX_DELAY_MS = 64_000;
|
||||
export const WS_RECONNECT_MAX_RETRIES = 7;
|
||||
export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1;
|
||||
|
||||
export interface WsConnectionStatus {
|
||||
readonly attemptCount: number;
|
||||
readonly closeCode: number | null;
|
||||
readonly closeReason: string | null;
|
||||
readonly connectedAt: string | null;
|
||||
readonly disconnectedAt: string | null;
|
||||
readonly hasConnected: boolean;
|
||||
readonly lastError: string | null;
|
||||
readonly lastErrorAt: string | null;
|
||||
readonly nextRetryAt: string | null;
|
||||
readonly online: boolean;
|
||||
readonly phase: "idle" | "connecting" | "connected" | "disconnected";
|
||||
readonly reconnectAttemptCount: number;
|
||||
readonly reconnectMaxAttempts: number;
|
||||
readonly reconnectPhase: WsReconnectPhase;
|
||||
readonly socketUrl: string | null;
|
||||
}
|
||||
|
||||
const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
|
||||
attemptCount: 0,
|
||||
closeCode: null,
|
||||
closeReason: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
hasConnected: false,
|
||||
lastError: null,
|
||||
lastErrorAt: null,
|
||||
nextRetryAt: null,
|
||||
online: typeof navigator === "undefined" ? true : navigator.onLine !== false,
|
||||
phase: "idle",
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "idle",
|
||||
socketUrl: null,
|
||||
});
|
||||
|
||||
export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("ws-connection-status"),
|
||||
);
|
||||
|
||||
function isoNow() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function updateWsConnectionStatus(
|
||||
updater: (current: WsConnectionStatus) => WsConnectionStatus,
|
||||
): WsConnectionStatus {
|
||||
const nextStatus = updater(getWsConnectionStatus());
|
||||
appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
|
||||
return nextStatus;
|
||||
}
|
||||
|
||||
export function getWsConnectionStatus(): WsConnectionStatus {
|
||||
return appAtomRegistry.get(wsConnectionStatusAtom);
|
||||
}
|
||||
|
||||
export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState {
|
||||
if (status.phase === "connected") {
|
||||
return "connected";
|
||||
}
|
||||
|
||||
if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) {
|
||||
return "offline";
|
||||
}
|
||||
|
||||
if (!status.hasConnected) {
|
||||
return status.phase === "disconnected" ? "error" : "connecting";
|
||||
}
|
||||
|
||||
return "reconnecting";
|
||||
}
|
||||
|
||||
export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
attemptCount: current.attemptCount + 1,
|
||||
nextRetryAt: null,
|
||||
phase: "connecting",
|
||||
reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
|
||||
reconnectPhase: "attempting",
|
||||
socketUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
export function recordWsConnectionOpened(): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
closeCode: null,
|
||||
closeReason: null,
|
||||
connectedAt: isoNow(),
|
||||
disconnectedAt: null,
|
||||
hasConnected: true,
|
||||
nextRetryAt: null,
|
||||
phase: "connected",
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectPhase: "idle",
|
||||
}));
|
||||
}
|
||||
|
||||
export function recordWsConnectionErrored(message?: string | null): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) =>
|
||||
applyDisconnectState(current, {
|
||||
lastError: message?.trim() ? message : current.lastError,
|
||||
lastErrorAt: isoNow(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function recordWsConnectionClosed(details?: {
|
||||
readonly code?: number;
|
||||
readonly reason?: string;
|
||||
}): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) =>
|
||||
applyDisconnectState(current, {
|
||||
closeCode: details?.code ?? current.closeCode,
|
||||
closeReason: details?.reason?.trim() ? details.reason : current.closeReason,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
online,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resetWsReconnectBackoff(): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectPhase: "idle",
|
||||
}));
|
||||
}
|
||||
|
||||
export function exhaustWsReconnectIfStillWaiting(expectedNextRetryAt: string): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => {
|
||||
if (
|
||||
current.reconnectPhase !== "waiting" ||
|
||||
current.nextRetryAt !== expectedNextRetryAt ||
|
||||
!current.online ||
|
||||
!current.hasConnected
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: current.reconnectMaxAttempts,
|
||||
reconnectPhase: "exhausted",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function resetWsConnectionStateForTests(): void {
|
||||
appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
|
||||
}
|
||||
|
||||
export function useWsConnectionStatus(): WsConnectionStatus {
|
||||
return useAtomValue(wsConnectionStatusAtom);
|
||||
}
|
||||
|
||||
export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
|
||||
if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.min(
|
||||
Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
|
||||
WS_RECONNECT_MAX_DELAY_MS,
|
||||
);
|
||||
}
|
||||
|
||||
function applyDisconnectState(
|
||||
current: WsConnectionStatus,
|
||||
updates: Partial<
|
||||
Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
|
||||
>,
|
||||
): WsConnectionStatus {
|
||||
const disconnectedAt = current.disconnectedAt ?? isoNow();
|
||||
const nextRetryDelayMs =
|
||||
current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
|
||||
? null
|
||||
: getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
|
||||
|
||||
return {
|
||||
...current,
|
||||
...updates,
|
||||
disconnectedAt,
|
||||
nextRetryAt:
|
||||
nextRetryDelayMs === null
|
||||
? current.nextRetryAt
|
||||
: new Date(Date.now() + nextRetryDelayMs).toISOString(),
|
||||
phase: "disconnected",
|
||||
reconnectPhase:
|
||||
current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
|
||||
? current.reconnectPhase
|
||||
: nextRetryDelayMs === null
|
||||
? "exhausted"
|
||||
: "waiting",
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
} from "./session-logic";
|
||||
import { sanitizeThreadErrorMessage } from "./rpc/transportError";
|
||||
import { type ChatMessage, type Project, type SidebarThreadSummary, type Thread } from "./types";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
@@ -165,7 +166,7 @@ function mapThread(thread: OrchestrationThread): Thread {
|
||||
session: thread.session ? mapSession(thread.session) : null,
|
||||
messages: thread.messages.map(mapMessage),
|
||||
proposedPlans: thread.proposedPlans.map(mapProposedPlan),
|
||||
error: thread.session?.lastError ?? null,
|
||||
error: sanitizeThreadErrorMessage(thread.session?.lastError),
|
||||
createdAt: thread.createdAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
@@ -894,7 +895,7 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
|
||||
return updateThreadState(state, event.payload.threadId, (thread) => ({
|
||||
...thread,
|
||||
session: mapSession(event.payload.session),
|
||||
error: event.payload.session.lastError ?? null,
|
||||
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
|
||||
latestTurn:
|
||||
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
|
||||
? buildLatestTurn({
|
||||
|
||||
@@ -30,25 +30,22 @@ describe("terminalRunningSubprocessFromEvent", () => {
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [3000],
|
||||
});
|
||||
const idle = terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "activity",
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
});
|
||||
|
||||
expect(active).toBe(true);
|
||||
expect(idle).toBe(false);
|
||||
});
|
||||
|
||||
it("clears running state when a terminal session starts/restarts/exits/errors", () => {
|
||||
it("clears running state when a terminal session starts/restarts/exits", () => {
|
||||
const events: TerminalEvent[] = [
|
||||
{ ...eventBase(), type: "started", snapshot },
|
||||
{ ...eventBase(), type: "restarted", snapshot },
|
||||
{ ...eventBase(), type: "exited", exitCode: 0, exitSignal: null },
|
||||
{ ...eventBase(), type: "error", message: "oops" },
|
||||
];
|
||||
|
||||
for (const event of events) {
|
||||
@@ -64,5 +61,12 @@ describe("terminalRunningSubprocessFromEvent", () => {
|
||||
data: "hello",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
terminalRunningSubprocessFromEvent({
|
||||
...eventBase(),
|
||||
type: "error",
|
||||
message: "oops",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ export function terminalRunningSubprocessFromEvent(event: TerminalEvent): boolea
|
||||
case "started":
|
||||
case "restarted":
|
||||
case "exited":
|
||||
case "error":
|
||||
return false;
|
||||
default:
|
||||
return null;
|
||||
|
||||
@@ -23,13 +23,7 @@ function makeTerminalEvent(
|
||||
case "output":
|
||||
return { ...base, type, data: "hello\n", ...overrides } as TerminalEvent;
|
||||
case "activity":
|
||||
return {
|
||||
...base,
|
||||
type,
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [],
|
||||
...overrides,
|
||||
} as TerminalEvent;
|
||||
return { ...base, type, hasRunningSubprocess: true, ...overrides } as TerminalEvent;
|
||||
case "error":
|
||||
return { ...base, type, message: "boom", ...overrides } as TerminalEvent;
|
||||
case "cleared":
|
||||
@@ -79,7 +73,6 @@ describe("terminalStateStore actions", () => {
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
@@ -188,21 +181,17 @@ describe("terminalStateStore actions", () => {
|
||||
it("tracks and clears terminal subprocess activity", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", true, [5173, 3000, 5173]);
|
||||
let terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
|
||||
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
|
||||
expect(
|
||||
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
|
||||
.runningTerminalIds,
|
||||
).toEqual(["terminal-2"]);
|
||||
|
||||
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
|
||||
terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
expect(terminalState.runningTerminalIds).toEqual([]);
|
||||
expect(terminalState.runningTerminalPorts).toEqual({});
|
||||
expect(
|
||||
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
|
||||
.runningTerminalIds,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("resets to default and clears persisted entry when closing the last terminal", () => {
|
||||
@@ -298,15 +287,12 @@ describe("terminalStateStore actions", () => {
|
||||
makeTerminalEvent("activity", {
|
||||
terminalId: "terminal-2",
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [5173, 3000],
|
||||
}),
|
||||
);
|
||||
let terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
expect(terminalState.runningTerminalIds).toEqual(["terminal-2"]);
|
||||
expect(terminalState.runningTerminalPorts).toEqual({ "terminal-2": [3000, 5173] });
|
||||
expect(
|
||||
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
|
||||
.runningTerminalIds,
|
||||
).toEqual(["terminal-2"]);
|
||||
|
||||
store.applyTerminalEvent(
|
||||
makeTerminalEvent("exited", {
|
||||
@@ -316,7 +302,7 @@ describe("terminalStateStore actions", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
terminalState = selectThreadTerminalState(
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
@@ -327,7 +313,6 @@ describe("terminalStateStore actions", () => {
|
||||
);
|
||||
|
||||
expect(terminalState.runningTerminalIds).toEqual([]);
|
||||
expect(terminalState.runningTerminalPorts).toEqual({});
|
||||
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ interface ThreadTerminalState {
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
runningTerminalPorts: Record<string, number[]>;
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
@@ -62,30 +61,6 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeRunningPorts(ports: readonly number[] | undefined): number[] {
|
||||
if (!ports || ports.length === 0) return [];
|
||||
return [...new Set(ports)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalPorts(
|
||||
runningTerminalPorts: Record<string, number[]> | undefined,
|
||||
terminalIds: string[],
|
||||
): Record<string, number[]> {
|
||||
if (!runningTerminalPorts) return {};
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const normalizedEntries: Array<[string, number[]]> = [];
|
||||
for (const [rawTerminalId, ports] of Object.entries(runningTerminalPorts)) {
|
||||
const terminalId = rawTerminalId.trim();
|
||||
if (terminalId.length === 0 || !validTerminalIdSet.has(terminalId)) {
|
||||
continue;
|
||||
}
|
||||
normalizedEntries.push([terminalId, normalizeRunningPorts(ports)]);
|
||||
}
|
||||
return Object.fromEntries(normalizedEntries);
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
@@ -161,7 +136,7 @@ function normalizeTerminalGroups(
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
function arraysEqual<T>(a: readonly T[], b: readonly T[]): boolean {
|
||||
function arraysEqual(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
if (a[index] !== b[index]) return false;
|
||||
@@ -181,22 +156,6 @@ function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalG
|
||||
return true;
|
||||
}
|
||||
|
||||
function runningTerminalPortsEqual(
|
||||
left: Record<string, number[]>,
|
||||
right: Record<string, number[]>,
|
||||
): boolean {
|
||||
const leftEntries = Object.entries(left);
|
||||
const rightEntries = Object.entries(right);
|
||||
if (leftEntries.length !== rightEntries.length) return false;
|
||||
for (const [terminalId, leftPorts] of leftEntries) {
|
||||
const rightPorts = right[terminalId];
|
||||
if (!rightPorts || !arraysEqual(leftPorts, rightPorts)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
|
||||
return (
|
||||
left.terminalOpen === right.terminalOpen &&
|
||||
@@ -205,7 +164,6 @@ function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTermin
|
||||
left.activeTerminalGroupId === right.activeTerminalGroupId &&
|
||||
arraysEqual(left.terminalIds, right.terminalIds) &&
|
||||
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
|
||||
runningTerminalPortsEqual(left.runningTerminalPorts, right.runningTerminalPorts) &&
|
||||
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
|
||||
);
|
||||
}
|
||||
@@ -215,7 +173,6 @@ const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -231,7 +188,6 @@ function createDefaultThreadTerminalState(): ThreadTerminalState {
|
||||
...DEFAULT_THREAD_TERMINAL_STATE,
|
||||
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
|
||||
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
|
||||
runningTerminalPorts: { ...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalPorts },
|
||||
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
|
||||
};
|
||||
}
|
||||
@@ -244,10 +200,6 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
|
||||
const terminalIds = normalizeTerminalIds(state.terminalIds);
|
||||
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
|
||||
const runningTerminalPorts = normalizeRunningTerminalPorts(
|
||||
state.runningTerminalPorts,
|
||||
nextTerminalIds,
|
||||
);
|
||||
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
|
||||
? state.activeTerminalId
|
||||
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
@@ -268,7 +220,6 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina
|
||||
: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: nextTerminalIds,
|
||||
runningTerminalIds,
|
||||
runningTerminalPorts,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId:
|
||||
@@ -504,9 +455,6 @@ function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): Th
|
||||
terminalHeight: normalized.terminalHeight,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
runningTerminalPorts: Object.fromEntries(
|
||||
Object.entries(normalized.runningTerminalPorts).filter(([key]) => key !== terminalId),
|
||||
),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId: nextActiveTerminalGroupId,
|
||||
@@ -517,35 +465,22 @@ function setThreadTerminalActivity(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
runningPorts: readonly number[] = [],
|
||||
): ThreadTerminalState {
|
||||
const normalized = normalizeThreadTerminalState(state);
|
||||
if (!normalized.terminalIds.includes(terminalId)) {
|
||||
return normalized;
|
||||
}
|
||||
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
|
||||
const nextRunningPorts = normalizeRunningPorts(runningPorts);
|
||||
const currentRunningPorts = normalized.runningTerminalPorts[terminalId] ?? [];
|
||||
if (
|
||||
hasRunningSubprocess === alreadyRunning &&
|
||||
arraysEqual(currentRunningPorts, nextRunningPorts)
|
||||
) {
|
||||
if (hasRunningSubprocess === alreadyRunning) {
|
||||
return normalized;
|
||||
}
|
||||
const runningTerminalIds = new Set(normalized.runningTerminalIds);
|
||||
const runningTerminalPorts = { ...normalized.runningTerminalPorts };
|
||||
if (hasRunningSubprocess) {
|
||||
runningTerminalIds.add(terminalId);
|
||||
runningTerminalPorts[terminalId] = nextRunningPorts;
|
||||
} else {
|
||||
runningTerminalIds.delete(terminalId);
|
||||
delete runningTerminalPorts[terminalId];
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
runningTerminalIds: [...runningTerminalIds],
|
||||
runningTerminalPorts,
|
||||
};
|
||||
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
|
||||
}
|
||||
|
||||
export function selectThreadTerminalState(
|
||||
@@ -623,7 +558,6 @@ interface TerminalStateStoreState {
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
runningPorts?: readonly number[],
|
||||
) => void;
|
||||
recordTerminalEvent: (event: TerminalEvent) => void;
|
||||
applyTerminalEvent: (event: TerminalEvent) => void;
|
||||
@@ -707,9 +641,9 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId;
|
||||
return { terminalLaunchContextByThreadId: rest };
|
||||
}),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess, runningPorts) =>
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess, runningPorts),
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
recordTerminalEvent: (event) =>
|
||||
set((state) =>
|
||||
@@ -751,12 +685,7 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
nextTerminalStateByThreadId,
|
||||
threadId,
|
||||
(current) =>
|
||||
setThreadTerminalActivity(
|
||||
current,
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
event.type === "activity" ? event.runningPorts : [],
|
||||
),
|
||||
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,46 @@ 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");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
const onDomainEvent = vi.fn();
|
||||
const onResubscribe = vi.fn();
|
||||
|
||||
api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe });
|
||||
|
||||
expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, {
|
||||
onResubscribe,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends orchestration dispatch commands as the direct RPC payload", async () => {
|
||||
rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
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";
|
||||
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();
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
@@ -61,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,
|
||||
@@ -98,7 +107,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
rpcClient.orchestration
|
||||
.replayEvents({ fromSequenceExclusive })
|
||||
.then((events) => [...events]),
|
||||
onDomainEvent: (callback) => rpcClient.orchestration.onDomainEvent(callback),
|
||||
onDomainEvent: (callback, options) =>
|
||||
rpcClient.orchestration.onDomainEvent(callback, options),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
+53
-10
@@ -2,20 +2,28 @@ 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";
|
||||
import { resetWsReconnectBackoff } from "./rpc/wsConnectionState";
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
type RpcTag = keyof WsRpcProtocolClient & string;
|
||||
type RpcMethod<TTag extends RpcTag> = WsRpcProtocolClient[TTag];
|
||||
type RpcInput<TTag extends RpcTag> = Parameters<RpcMethod<TTag>>[0];
|
||||
|
||||
interface StreamSubscriptionOptions {
|
||||
readonly onResubscribe?: () => void;
|
||||
}
|
||||
|
||||
type RpcUnaryMethod<TTag extends RpcTag> =
|
||||
RpcMethod<TTag> extends (input: any, options?: any) => Effect.Effect<infer TSuccess, any, any>
|
||||
? (input: RpcInput<TTag>) => Promise<TSuccess>
|
||||
@@ -28,7 +36,7 @@ type RpcUnaryNoArgMethod<TTag extends RpcTag> =
|
||||
|
||||
type RpcStreamMethod<TTag extends RpcTag> =
|
||||
RpcMethod<TTag> extends (input: any, options?: any) => Stream.Stream<infer TEvent, any, any>
|
||||
? (listener: (event: TEvent) => void) => () => void
|
||||
? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void
|
||||
: never;
|
||||
|
||||
interface GitRunStackedActionOptions {
|
||||
@@ -37,6 +45,7 @@ interface GitRunStackedActionOptions {
|
||||
|
||||
export interface WsRpcClient {
|
||||
readonly dispose: () => Promise<void>;
|
||||
readonly reconnect: () => Promise<void>;
|
||||
readonly terminal: {
|
||||
readonly open: RpcUnaryMethod<typeof WS_METHODS.terminalOpen>;
|
||||
readonly write: RpcUnaryMethod<typeof WS_METHODS.terminalWrite>;
|
||||
@@ -58,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,
|
||||
@@ -113,6 +127,10 @@ export async function __resetWsRpcClientForTests() {
|
||||
export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
return {
|
||||
dispose: () => transport.dispose(),
|
||||
reconnect: async () => {
|
||||
resetWsReconnectBackoff();
|
||||
await transport.reconnect();
|
||||
},
|
||||
terminal: {
|
||||
open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)),
|
||||
write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)),
|
||||
@@ -120,8 +138,12 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)),
|
||||
restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)),
|
||||
close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)),
|
||||
onEvent: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeTerminalEvents]({}), listener),
|
||||
onEvent: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: (input) =>
|
||||
@@ -135,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;
|
||||
|
||||
@@ -179,10 +213,18 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),
|
||||
updateSettings: (patch) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })),
|
||||
subscribeConfig: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeServerConfig]({}), listener),
|
||||
subscribeLifecycle: (listener) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeServerLifecycle]({}), listener),
|
||||
subscribeConfig: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerConfig]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
subscribeLifecycle: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: () =>
|
||||
@@ -197,10 +239,11 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient {
|
||||
transport
|
||||
.request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input))
|
||||
.then((events) => [...events]),
|
||||
onDomainEvent: (listener) =>
|
||||
onDomainEvent: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
listener,
|
||||
options,
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
__resetClientTracingForTests,
|
||||
configureClientTracing,
|
||||
} from "./observability/clientTracing";
|
||||
import {
|
||||
getSlowRpcAckRequests,
|
||||
resetRequestLatencyStateForTests,
|
||||
setSlowRpcAckThresholdMsForTests,
|
||||
} from "./rpc/requestLatencyState";
|
||||
import {
|
||||
getWsConnectionStatus,
|
||||
getWsConnectionUiState,
|
||||
resetWsConnectionStateForTests,
|
||||
} from "./rpc/wsConnectionState";
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
@@ -53,6 +67,10 @@ class MockWebSocket {
|
||||
this.emit("message", { data, type: "message" });
|
||||
}
|
||||
|
||||
error() {
|
||||
this.emit("error", { type: "error" });
|
||||
}
|
||||
|
||||
private emit(type: WsEventType, event?: WsEvent) {
|
||||
const listeners = this.listeners.get(type);
|
||||
if (!listeners) return;
|
||||
@@ -63,6 +81,7 @@ class MockWebSocket {
|
||||
}
|
||||
|
||||
const originalWebSocket = globalThis.WebSocket;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
function getSocket(): MockWebSocket {
|
||||
const socket = sockets.at(-1);
|
||||
@@ -88,7 +107,10 @@ async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void>
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useRealTimers();
|
||||
sockets.length = 0;
|
||||
resetRequestLatencyStateForTests();
|
||||
resetWsConnectionStateForTests();
|
||||
|
||||
Object.defineProperty(globalThis, "window", {
|
||||
configurable: true,
|
||||
@@ -102,12 +124,20 @@ beforeEach(() => {
|
||||
desktopBridge: undefined,
|
||||
},
|
||||
});
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
configurable: true,
|
||||
value: { onLine: true },
|
||||
});
|
||||
|
||||
globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach(async () => {
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
globalThis.fetch = originalFetch;
|
||||
resetRequestLatencyStateForTests();
|
||||
resetWsConnectionStateForTests();
|
||||
await __resetClientTracingForTests();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -141,6 +171,186 @@ describe("WsTransport", () => {
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("tracks initial connection failures for the app error state", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
attemptCount: 1,
|
||||
phase: "connecting",
|
||||
socketUrl: "ws://localhost:3020/ws",
|
||||
});
|
||||
|
||||
socket.error();
|
||||
socket.close(1006, "server unavailable");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
closeCode: 1006,
|
||||
closeReason: "server unavailable",
|
||||
hasConnected: false,
|
||||
lastError: "Unable to connect to the T3 server WebSocket.",
|
||||
phase: "disconnected",
|
||||
});
|
||||
});
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("error");
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("surfaces reconnecting state after a live socket disconnects", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
hasConnected: true,
|
||||
phase: "connected",
|
||||
});
|
||||
});
|
||||
|
||||
socket.close(1013, "try again later");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
closeReason: "try again later",
|
||||
hasConnected: true,
|
||||
});
|
||||
});
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("reconnecting");
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("reconnects the websocket session without disposing the transport", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
hasConnected: true,
|
||||
phase: "connected",
|
||||
});
|
||||
});
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(2);
|
||||
});
|
||||
|
||||
const secondSocket = getSocket();
|
||||
expect(secondSocket).not.toBe(firstSocket);
|
||||
expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED);
|
||||
|
||||
const requestPromise = transport.request((client) =>
|
||||
client[WS_METHODS.serverUpsertKeybinding]({
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
}),
|
||||
);
|
||||
|
||||
secondSocket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(secondSocket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(secondSocket.sent[0] ?? "{}") as { id: string };
|
||||
secondSocket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
});
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
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) =>
|
||||
client[WS_METHODS.serverUpsertKeybinding]({
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
|
||||
await waitFor(() => {
|
||||
expect(getSlowRpcAckRequests()).toMatchObject([
|
||||
{
|
||||
requestId: requestMessage.id,
|
||||
tag: WS_METHODS.serverUpsertKeybinding,
|
||||
},
|
||||
]);
|
||||
}, 1_000);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: {
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual({
|
||||
keybindings: [],
|
||||
issues: [],
|
||||
});
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
|
||||
await transport.dispose();
|
||||
}, 5_000);
|
||||
|
||||
it("sends unary RPC requests and resolves successful exits", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
|
||||
@@ -250,10 +460,12 @@ describe("WsTransport", () => {
|
||||
it("re-subscribes stream listeners after the stream exits", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const listener = vi.fn();
|
||||
const onResubscribe = vi.fn();
|
||||
|
||||
const unsubscribe = transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
|
||||
listener,
|
||||
{ onResubscribe },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
@@ -301,6 +513,7 @@ describe("WsTransport", () => {
|
||||
.find((message) => message._tag === "Request" && message.id !== firstRequest.id);
|
||||
expect(nextRequest).toBeDefined();
|
||||
});
|
||||
expect(onResubscribe).toHaveBeenCalledOnce();
|
||||
|
||||
const secondRequest = socket.sent
|
||||
.map((message) => JSON.parse(message) as { _tag?: string; id?: string; tag?: string })
|
||||
@@ -339,6 +552,52 @@ describe("WsTransport", () => {
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("does not fire onResubscribe when the first stream attempt exits before any value", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const listener = vi.fn();
|
||||
const onResubscribe = vi.fn();
|
||||
|
||||
const unsubscribe = transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerLifecycle]({}),
|
||||
listener,
|
||||
{ onResubscribe },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstRequest = JSON.parse(socket.sent[0] ?? "{}") as { id: string };
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: firstRequest.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const nextRequest = socket.sent
|
||||
.map((message) => JSON.parse(message) as { _tag?: string; id?: string })
|
||||
.find((message) => message._tag === "Request" && message.id !== firstRequest.id);
|
||||
expect(nextRequest).toBeDefined();
|
||||
});
|
||||
expect(onResubscribe).not.toHaveBeenCalled();
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
|
||||
unsubscribe();
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("streams finite request events without re-subscribing", async () => {
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const listener = vi.fn();
|
||||
@@ -422,11 +681,21 @@ describe("WsTransport", () => {
|
||||
};
|
||||
const transport = {
|
||||
disposed: false,
|
||||
clientScope: {} as never,
|
||||
runtime,
|
||||
session: {
|
||||
clientScope: {} as never,
|
||||
runtime,
|
||||
},
|
||||
closeSession: (
|
||||
WsTransport.prototype as unknown as {
|
||||
closeSession: (session: {
|
||||
clientScope: unknown;
|
||||
runtime: { dispose: () => Promise<void>; runPromise: () => Promise<void> };
|
||||
}) => Promise<void>;
|
||||
}
|
||||
).closeSession,
|
||||
} as unknown as WsTransport;
|
||||
|
||||
WsTransport.prototype.dispose.call(transport);
|
||||
void WsTransport.prototype.dispose.call(transport);
|
||||
|
||||
expect(runtime.runPromise).toHaveBeenCalledTimes(1);
|
||||
expect(runtime.dispose).not.toHaveBeenCalled();
|
||||
@@ -440,4 +709,46 @@ describe("WsTransport", () => {
|
||||
|
||||
expect(callOrder).toEqual(["close:start", "close:done", "runtime:dispose"]);
|
||||
});
|
||||
|
||||
it("propagates OTLP trace ids for ws transport requests when client tracing is enabled", async () => {
|
||||
await configureClientTracing({
|
||||
exportIntervalMs: 10,
|
||||
});
|
||||
|
||||
const transport = new WsTransport("ws://localhost:3020");
|
||||
const requestPromise = transport.request((client) => client[WS_METHODS.serverGetSettings]({}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as {
|
||||
id: string;
|
||||
spanId?: string;
|
||||
traceId?: string;
|
||||
};
|
||||
expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS);
|
||||
await transport.dispose();
|
||||
});
|
||||
});
|
||||
+176
-42
@@ -1,14 +1,26 @@
|
||||
import { Duration, Effect, Exit, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
import {
|
||||
Cause,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { RpcClient } from "effect/unstable/rpc";
|
||||
|
||||
import { ClientTracingLive, configureClientTracing } from "./observability/clientTracing";
|
||||
import {
|
||||
createWsRpcProtocolLayer,
|
||||
makeWsRpcProtocolClient,
|
||||
type WsRpcProtocolClient,
|
||||
} from "./rpc/protocol";
|
||||
import { RpcClient } from "effect/unstable/rpc";
|
||||
|
||||
interface SubscribeOptions {
|
||||
readonly retryDelay?: Duration.Input;
|
||||
readonly onResubscribe?: () => void;
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
@@ -16,6 +28,13 @@ interface RequestOptions {
|
||||
}
|
||||
|
||||
const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250);
|
||||
const NOOP: () => void = () => undefined;
|
||||
|
||||
interface TransportSession {
|
||||
readonly clientPromise: Promise<WsRpcProtocolClient>;
|
||||
readonly clientScope: Scope.Closeable;
|
||||
readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
}
|
||||
|
||||
function formatErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
@@ -25,17 +44,16 @@ function formatErrorMessage(error: unknown): string {
|
||||
}
|
||||
|
||||
export class WsTransport {
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcProtocolClient>;
|
||||
private readonly tracingReady: Promise<void>;
|
||||
private readonly url: string | undefined;
|
||||
private disposed = false;
|
||||
private reconnectChain: Promise<void> = Promise.resolve();
|
||||
private session: TransportSession;
|
||||
|
||||
constructor(url?: string) {
|
||||
this.runtime = ManagedRuntime.make(createWsRpcProtocolLayer(url));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(
|
||||
Scope.provide(this.clientScope)(makeWsRpcProtocolClient),
|
||||
);
|
||||
this.url = url;
|
||||
this.tracingReady = configureClientTracing();
|
||||
this.session = this.createSession();
|
||||
}
|
||||
|
||||
async request<TSuccess>(
|
||||
@@ -46,8 +64,10 @@ export class WsTransport {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
await this.tracingReady;
|
||||
const session = this.session;
|
||||
const client = await session.clientPromise;
|
||||
return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
async requestStream<TValue>(
|
||||
@@ -58,8 +78,10 @@ export class WsTransport {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
await this.runtime.runPromise(
|
||||
await this.tracingReady;
|
||||
const session = this.session;
|
||||
const client = await session.clientPromise;
|
||||
await session.runtime.runPromise(
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
try {
|
||||
@@ -82,15 +104,132 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const retryDelayMs = options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
let hasReceivedValue = false;
|
||||
const retryDelayMs = Duration.toMillis(
|
||||
Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS),
|
||||
);
|
||||
let cancelCurrentStream: () => void = NOOP;
|
||||
|
||||
void (async () => {
|
||||
for (;;) {
|
||||
if (!active || this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (hasReceivedValue) {
|
||||
try {
|
||||
options?.onResubscribe?.();
|
||||
} catch {
|
||||
// Swallow reconnect hook errors so the stream can recover.
|
||||
}
|
||||
}
|
||||
|
||||
const session = this.session;
|
||||
const runningStream = this.runStreamOnSession(
|
||||
session,
|
||||
connect,
|
||||
listener,
|
||||
() => active,
|
||||
() => {
|
||||
hasReceivedValue = true;
|
||||
},
|
||||
);
|
||||
cancelCurrentStream = runningStream.cancel;
|
||||
await runningStream.completed;
|
||||
cancelCurrentStream = NOOP;
|
||||
} catch (error) {
|
||||
cancelCurrentStream = NOOP;
|
||||
if (!active || this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.warn("WebSocket RPC subscription disconnected", {
|
||||
error: formatErrorMessage(error),
|
||||
});
|
||||
await sleep(retryDelayMs);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancelCurrentStream();
|
||||
};
|
||||
}
|
||||
|
||||
async reconnect() {
|
||||
if (this.disposed) {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const reconnectOperation = this.reconnectChain.then(async () => {
|
||||
if (this.disposed) {
|
||||
throw new Error("Transport disposed");
|
||||
}
|
||||
|
||||
const previousSession = this.session;
|
||||
this.session = this.createSession();
|
||||
await this.closeSession(previousSession);
|
||||
});
|
||||
|
||||
this.reconnectChain = reconnectOperation.catch(() => undefined);
|
||||
await reconnectOperation;
|
||||
}
|
||||
|
||||
async dispose() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.closeSession(this.session);
|
||||
}
|
||||
|
||||
private closeSession(session: TransportSession) {
|
||||
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
|
||||
session.runtime.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
private createSession(): TransportSession {
|
||||
const runtime = ManagedRuntime.make(
|
||||
Layer.mergeAll(createWsRpcProtocolLayer(this.url), ClientTracingLive),
|
||||
);
|
||||
const clientScope = runtime.runSync(Scope.make());
|
||||
return {
|
||||
runtime,
|
||||
clientScope,
|
||||
clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
|
||||
};
|
||||
}
|
||||
|
||||
private runStreamOnSession<TValue>(
|
||||
session: TransportSession,
|
||||
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
isActive: () => boolean,
|
||||
markValueReceived: () => void,
|
||||
): {
|
||||
readonly cancel: () => void;
|
||||
readonly completed: Promise<void>;
|
||||
} {
|
||||
let resolveCompleted!: () => void;
|
||||
let rejectCompleted!: (error: unknown) => void;
|
||||
const completed = new Promise<void>((resolve, reject) => {
|
||||
resolveCompleted = resolve;
|
||||
rejectCompleted = reject;
|
||||
});
|
||||
const cancel = session.runtime.runCallback(
|
||||
Effect.promise(() => this.tracingReady).pipe(
|
||||
Effect.flatMap(() => Effect.promise(() => session.clientPromise)),
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
markValueReceived();
|
||||
try {
|
||||
listener(value);
|
||||
} catch {
|
||||
@@ -99,33 +238,28 @@ export class WsTransport {
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) => {
|
||||
if (!active || this.disposed) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.sync(() => {
|
||||
console.warn("WebSocket RPC subscription disconnected", {
|
||||
error: formatErrorMessage(error),
|
||||
});
|
||||
}).pipe(Effect.andThen(Effect.sleep(retryDelayMs)));
|
||||
}),
|
||||
Effect.forever,
|
||||
),
|
||||
{
|
||||
onExit: (exit) => {
|
||||
if (Exit.isSuccess(exit)) {
|
||||
resolveCompleted();
|
||||
return;
|
||||
}
|
||||
|
||||
rejectCompleted(Cause.squash(exit.cause));
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancel();
|
||||
return {
|
||||
cancel,
|
||||
completed,
|
||||
};
|
||||
}
|
||||
|
||||
async dispose() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)).finally(() => {
|
||||
this.runtime.dispose();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user