Compare commits

..
Author SHA1 Message Date
Cursor Agent 776d8b4943 fix: remove redundant metricModel reassignment and per-statement DB query metrics
- Remove duplicate assignment of metricModel in ProviderService.sendTurn
  (line 419 was identical to line 411, input is never mutated between them)
- Remove withMetrics wrapper from individual SQLite runStatement/runValues
  to eliminate per-query overhead (generator alloc, exit boxing, timestamps,
  metric attribute construction) on the hot path for sub-millisecond queries
2026-04-03 02:31:22 +00:00
Julius Marminge 8cc42335ed Defer provider metric attributes until routing resolves
- Allow withMetrics attributes to be computed lazily
- Record sendTurn metrics with the resolved provider
2026-04-02 19:19:19 -07:00
Julius Marminge 5fada58185 Improve effect tracing across orchestration and telemetry
- name previously untraced effects
- annotate editor launch spans with context
2026-04-02 18:21:00 -07:00
Julius Marminge ad971dbdd3 Track orchestration command outcomes in metrics
- Record success, failure, and interrupt outcomes from command dispatch
- Normalize invalid dates and group GPT models under a shared label
- Add coverage for failed dispatch metric accounting
2026-04-02 18:15:27 -07:00
Julius Marminge 3e9d5fcfc3 Inline RPC tracing helpers in websocket handlers
- Call `observeRpc*` directly for each WS method
- Remove the local `rpcEffect`/`rpcStream` aliases
2026-04-02 17:30:26 -07:00
Julius Marminge 988862989d Surface observability config in the settings UI
- expose logs folder and OTLP tracing state in server config
- add a Diagnostics section with an open-logs-folder action
- update tests and observability docs for the new config shape
2026-04-02 17:24:21 -07:00
Julius Marmingeandcodex 0ac582fabf Merge origin/main into t3code/effect-tracing-observability
Co-authored-by: codex <[email protected]>
2026-04-02 16:35:03 -07:00
Julius Marminge 067241843a Improve observability metrics and trace handling
- Record orchestration command ack latency and route provider metrics by resolved provider
- Capture RPC stream failures and keep trace sink writing past bad records
- Add circular attribute normalization coverage
2026-04-02 16:26:35 -07:00
Julius Marminge 1f4c8d1280 Merge remote-tracking branch 'origin/main' into t3code/effect-tracing-observability 2026-04-02 15:57:59 -07:00
Julius Marmingeandcodex 772ba77281 Merge origin/main into t3code/effect-tracing-observability
Resolve startup and git observability conflicts while preserving mainline behavior.

Co-authored-by: codex <[email protected]>
2026-04-02 13:16:41 -07:00
Julius Marminge aa65f06d4c Add observability tracing and metrics
- Add local trace file output and OTLP export hooks
- Instrument RPC, git, orchestration, provider, and DB paths
- Document observability configuration
2026-04-02 12:38:53 -07:00
123 changed files with 1039 additions and 8676 deletions

No files matched your search

+1 -34
View File
@@ -28,7 +28,6 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
@@ -77,7 +76,6 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
@@ -101,10 +99,8 @@ let aboutCommitHashCache: string | null | undefined;
let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
@@ -125,21 +121,6 @@ function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function readPersistedBackendObservabilitySettings(): {
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
} {
try {
if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
} catch (error) {
console.warn("[desktop] failed to read persisted backend observability settings", error);
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
}
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
@@ -1007,7 +988,6 @@ function scheduleBackendRestart(reason: string): void {
function startBackend(): void {
if (isQuitting || backendProcess) return;
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
const backendEntry = resolveBackendEntry();
if (!FS.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
@@ -1036,12 +1016,6 @@ function startBackend(): void {
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
...(backendObservabilitySettings.otlpMetricsUrl
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
: {}),
})}\n`,
);
bootstrapStream.end();
@@ -1068,26 +1042,21 @@ function startBackend(): void {
});
child.on("error", (error) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
if (wasExpected) {
return;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
);
if (isQuitting || wasExpected) return;
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
@@ -1104,7 +1073,6 @@ function stopBackend(): void {
if (!child) return;
if (child.exitCode === null && child.signalCode === null) {
expectedBackendExitChildren.add(child);
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
@@ -1125,7 +1093,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
if (!child) return;
const backendChild = child;
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
expectedBackendExitChildren.add(backendChild);
await new Promise<void>((resolve) => {
let settled = false;
+4 -5
View File
@@ -1,6 +1,5 @@
---
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.">
@@ -18,11 +17,11 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
<a class="download-card" data-asset="arm64.dmg" href="#">
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
<a class="download-card" data-asset="x64.dmg" href="#">
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
@@ -36,7 +35,7 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
<a class="download-card" data-asset="x64.exe" href="#">
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
@@ -50,7 +49,7 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<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 { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { RuntimeReceiptBusLive } 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,
RuntimeReceiptBusTest,
RuntimeReceiptBusLive,
);
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.streamEventsForTest, (receipt) =>
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
@@ -86,7 +86,6 @@ const collectEventsDuring = <A, E, R>(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
@@ -105,6 +104,7 @@ 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.live("replays typed runtime fixture events", () =>
it.effect("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
@@ -149,7 +149,7 @@ it.live("replays typed runtime fixture events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("replays file-changing fixture turn events", () =>
it.effect("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -188,7 +188,7 @@ it.live("replays file-changing fixture turn events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("runs multi-turn tool/approval flow", () =>
it.effect("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -242,7 +242,7 @@ it.live("runs multi-turn tool/approval flow", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("rolls back provider conversation state only", () =>
it.effect("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -80,7 +80,7 @@ function initRepoWithCommit(
});
}
function buildLargeText(lineCount = 5_000): string {
function buildLargeText(lineCount = 20_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("diff --git");
expect(diff).not.toContain("[truncated]");
expect(diff).toContain("+line 04999");
expect(diff).toContain("+line 19999");
}),
);
});
-76
View File
@@ -40,7 +40,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -103,7 +102,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(true),
authToken: Option.some("flag-token"),
@@ -169,8 +167,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
@@ -180,7 +176,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -207,8 +202,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
@@ -231,7 +224,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
const customCwd = path.join(baseDir, "nested", "project");
const resolved = yield* resolveServerConfig(
{
@@ -239,7 +231,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.some(customCwd),
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
noBrowser: Option.none(),
authToken: Option.none(),
@@ -258,7 +249,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
);
for (const directory of [
customCwd,
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
@@ -270,7 +260,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
expect(resolved.cwd).toBe(path.resolve(customCwd));
}),
);
@@ -297,7 +286,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.none(),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.none(),
authToken: Option.some("flag-token"),
@@ -344,68 +332,4 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
});
}),
);
it.effect("falls back to persisted observability settings when env vars are absent", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
`${JSON.stringify({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
})}\n`,
);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
NetService.layer,
),
),
);
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
authToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
});
+5 -46
View File
@@ -1,7 +1,6 @@
import { NetService } from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
@@ -13,7 +12,7 @@ import {
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -28,8 +27,6 @@ const BootstrapEnvelopeSchema = Schema.Struct({
authToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
@@ -140,7 +137,6 @@ interface CliServerFlags {
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
@@ -156,17 +152,6 @@ const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
return parsePersistedServerObservabilitySettings(raw);
});
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
@@ -226,14 +211,8 @@ export const resolveServerConfig = (
),
),
);
const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
);
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const noBrowser = resolveBooleanFlag(
@@ -299,27 +278,13 @@ export const resolveServerConfig = (
traceBatchWindowMs: env.traceBatchWindowMs,
traceMaxBytes: env.traceMaxBytes,
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
),
) ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
),
) ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpTracesUrl: env.otlpTracesUrl,
otlpMetricsUrl: env.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
mode,
port,
cwd,
cwd: process.cwd(),
baseDir,
...derivedPaths,
serverTracePath,
@@ -340,12 +305,6 @@ const commandFlags = {
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
Argument.withDescription(
"Working directory for provider sessions (defaults to the current directory).",
),
Argument.optional,
),
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
+1 -2
View File
@@ -949,12 +949,11 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
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;
+9 -32
View File
@@ -1177,7 +1177,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return branchLastCommit;
});
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
@@ -1310,17 +1312,6 @@ 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) => ({
@@ -2009,6 +2000,12 @@ 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(
@@ -2081,28 +2078,9 @@ 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,
@@ -2128,7 +2106,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
execute,
status,
statusDetails,
statusDetailsLocal,
prepareCommitContext,
commit,
pushCurrentBranch,
+2 -128
View File
@@ -6,12 +6,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import type {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
ModelSelection,
ThreadId,
} from "@t3tools/contracts";
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -26,11 +21,6 @@ import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
ProjectSetupScriptRunner,
type ProjectSetupScriptRunnerInput,
type ProjectSetupScriptRunnerShape,
} from "../../project/Services/ProjectSetupScriptRunner.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -603,7 +593,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe
function preparePullRequestThread(
manager: GitManagerShape,
input: GitPreparePullRequestThreadInput,
input: { cwd: string; reference: string; mode: "local" | "worktree" },
) {
return manager.preparePullRequestThread(input);
}
@@ -611,7 +601,6 @@ function preparePullRequestThread(
function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
setupScriptRunner?: ProjectSetupScriptRunnerShape;
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
@@ -629,12 +618,6 @@ function makeManager(input?: {
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
Layer.succeed(
ProjectSetupScriptRunner,
input?.setupScriptRunner ?? {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
gitCoreLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
@@ -645,8 +628,6 @@ function makeManager(input?: {
);
}
const asThreadId = (threadId: string) => threadId as ThreadId;
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(NodeServices.layer),
@@ -2195,59 +2176,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("launches setup only when creating a new PR worktree", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]);
fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n");
yield* runGit(repoDir, ["add", "setup.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]);
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]);
yield* runGit(repoDir, ["checkout", "main"]);
const setupCalls: ProjectSetupScriptRunnerInput[] = [];
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 177,
title: "Worktree setup PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/177",
baseRefName: "main",
headRefName: "feature/pr-worktree-setup",
state: "open",
},
},
setupScriptRunner: {
runForThread: (setupInput) =>
Effect.sync(() => {
setupCalls.push(setupInput);
return { status: "no-script" as const };
}),
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "177",
mode: "worktree",
threadId: asThreadId("thread-pr-setup"),
});
expect(result.worktreePath).not.toBeNull();
expect(setupCalls).toHaveLength(1);
expect(setupCalls[0]).toEqual({
threadId: "thread-pr-setup",
projectCwd: repoDir,
worktreePath: result.worktreePath as string,
});
}),
);
it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2432,7 +2360,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
const setupCalls: ProjectSetupScriptRunnerInput[] = [];
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
@@ -2444,27 +2371,18 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
state: "open",
},
},
setupScriptRunner: {
runForThread: (setupInput) =>
Effect.sync(() => {
setupCalls.push(setupInput);
return { status: "no-script" as const };
}),
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "78",
mode: "worktree",
threadId: asThreadId("thread-pr-existing-worktree"),
});
expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
fs.realpathSync.native(worktreePath),
);
expect(result.branch).toBe("feature/pr-existing-worktree");
expect(setupCalls).toHaveLength(0);
}),
);
@@ -2644,50 +2562,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("does not fail PR worktree prep when setup terminal startup fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]);
fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n");
yield* runGit(repoDir, ["add", "setup-failure.txt"]);
yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]);
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/184/head"]);
yield* runGit(repoDir, ["checkout", "main"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 184,
title: "Setup failure PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/184",
baseRefName: "main",
headRefName: "feature/pr-setup-failure",
state: "open",
},
},
setupScriptRunner: {
runForThread: () => Effect.fail(new Error("terminal start failed")),
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "184",
mode: "worktree",
threadId: asThreadId("thread-pr-setup-failure"),
});
expect(result.branch).toBe("feature/pr-setup-failure");
expect(result.worktreePath).not.toBeNull();
expect(fs.existsSync(result.worktreePath as string)).toBe(true);
}),
);
it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+32 -125
View File
@@ -8,13 +8,9 @@ import {
GitCommandError,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
@@ -30,7 +26,6 @@ import {
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
@@ -557,7 +552,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
@@ -699,55 +693,26 @@ 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 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 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 pr =
details.branch !== null
details.isRepo && details.branch !== null
? yield* findLatestPr(cwd, {
branch: details.branch,
upstreamRef: details.upstreamRef,
@@ -758,38 +723,29 @@ 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 remoteStatusResultCache = yield* Cache.makeWith({
const statusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readRemoteStatus,
lookup: readStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateRemoteStatusResultCache = (cwd: string) =>
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
const invalidateStatusResultCache = (cwd: string) =>
Cache.invalidate(statusResultCache, 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,
@@ -1353,34 +1309,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
};
});
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);
return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd));
});
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) {
@@ -1398,24 +1329,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn(
"preparePullRequestThread",
)(function* (input) {
const maybeRunSetupScript = (worktreePath: string) => {
if (!input.threadId) {
return Effect.void;
}
return projectSetupScriptRunner
.runForThread({
threadId: input.threadId,
projectCwd: input.cwd,
worktreePath,
})
.pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`,
).pipe(Effect.asVoid),
),
);
};
return yield* Effect.gen(function* () {
const normalizedReference = normalizePullRequestReference(input.reference);
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
@@ -1548,14 +1461,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
yield* maybeRunSetupScript(worktree.worktree.path);
return {
pullRequest,
branch: worktree.worktree.branch,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
}).pipe(Effect.ensuring(invalidateStatusResultCache(input.cwd)));
});
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -1759,7 +1671,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
});
return yield* runAction().pipe(
Effect.ensuring(invalidateStatus(input.cwd)),
Effect.ensuring(invalidateStatusResultCache(input.cwd)),
Effect.tapError((error) =>
Effect.flatMap(Ref.get(currentPhase), (phase) =>
progress.emit({
@@ -1774,12 +1686,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
return {
localStatus,
remoteStatus,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
invalidateStatus,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
@@ -1,276 +0,0 @@
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));
});
});
@@ -1,307 +0,0 @@
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;
}),
);
+3 -12
View File
@@ -7,12 +7,10 @@
* @module GitCore
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { Effect, Scope } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
@@ -158,11 +156,6 @@ 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.
*/
@@ -285,16 +278,14 @@ export interface GitCoreShape {
/**
* Create a local branch.
*/
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
/**
* Initialize a repository in the provided directory.
@@ -14,8 +14,6 @@ import {
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
@@ -43,35 +41,6 @@ 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.
*/
@@ -1,23 +0,0 @@
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") {}
+2 -75
View File
@@ -1,15 +1,6 @@
import Mime from "@effect/platform-node/Mime";
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 { Effect, FileSystem, Option, Path } from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import {
ATTACHMENTS_ROUTE_PREFIX,
@@ -18,74 +9,10 @@ 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,8 +4,6 @@ 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;
@@ -18,14 +16,9 @@ export const ObservabilityLive = Layer.unwrap(
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
);
const tracerLayer = Layer.unwrap(
const tracerLayer = Layer.effect(
Tracer.Tracer,
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
@@ -41,26 +34,13 @@ export const ObservabilityLive = Layer.unwrap(
},
});
const tracer = yield* makeLocalFileTracer({
return 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 { EffectTraceRecord } from "./TraceRecord.ts";
import type { TraceRecord } 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<EffectTraceRecord> =>
const readTraceRecords = (tracePath: string): Array<TraceRecord> =>
fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as EffectTraceRecord);
.map((line) => JSON.parse(line) as TraceRecord);
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 { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
import { spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
export interface LocalFileTracerOptions {
readonly filePath: string;
@@ -10,7 +10,6 @@ export interface LocalFileTracerOptions {
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly delegate?: Tracer.Tracer;
readonly sink?: TraceSink;
}
class LocalFileSpan implements Tracer.Span {
@@ -31,7 +30,7 @@ class LocalFileSpan implements Tracer.Span {
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
private readonly delegate: Tracer.Span,
private readonly push: (record: EffectTraceRecord) => void,
private readonly push: (record: ReturnType<typeof spanToTraceRecord>) => void,
) {
this.name = delegate.name;
this.spanId = delegate.spanId;
@@ -83,14 +82,12 @@ class LocalFileSpan implements Tracer.Span {
export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
options: LocalFileTracerOptions,
) {
const sink =
options.sink ??
(yield* makeTraceSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
batchWindowMs: options.batchWindowMs,
}));
const sink = yield* makeTraceSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
batchWindowMs: options.batchWindowMs,
});
const delegate =
options.delegate ??
+8
View File
@@ -70,6 +70,14 @@ export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total"
description: "Total terminal restart requests handled.",
});
export const dbQueriesTotal = Metric.counter("t3_db_queries_total", {
description: "Total sqlite queries executed by the server runtime.",
});
export const dbQueryDuration = Metric.timer("t3_db_query_duration", {
description: "Sqlite query execution duration.",
});
export const metricAttributes = (
attributes: Readonly<Record<string, unknown>>,
): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
@@ -1,13 +0,0 @@
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") {}
+15 -202
View File
@@ -1,37 +1,29 @@
import { Cause, Exit, Option, Tracer } from "effect";
import { compactTraceAttributes } from "./Attributes.ts";
import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
interface TraceRecordEvent {
export interface TraceRecord {
readonly type: "effect-span";
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<TraceRecordEvent>;
readonly links: ReadonlyArray<TraceRecordLink>;
}
export interface EffectTraceRecord extends BaseTraceRecord {
readonly type: "effect-span";
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 exit:
| {
readonly _tag: "Success";
@@ -46,29 +38,6 @@ export interface EffectTraceRecord extends BaseTraceRecord {
};
}
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;
@@ -84,7 +53,7 @@ interface SerializableSpan {
>;
}
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): TraceRecord["exit"] {
if (Exit.isSuccess(exit)) {
return { _tag: "Success" };
}
@@ -100,7 +69,7 @@ function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["
};
}
export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
export function spanToTraceRecord(span: SerializableSpan): TraceRecord {
const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
@@ -129,159 +98,3 @@ export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
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;
}
}
+1 -37
View File
@@ -75,19 +75,10 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace"],
});
const ideaLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLaunch, {
command: "idea",
args: ["/tmp/workspace"],
});
}),
);
it.effect("applies launch-style-specific navigation arguments", () =>
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
@@ -151,33 +142,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
const zedLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineOnly, {
command: "zed",
args: ["/tmp/workspace/AGENTS.md:48"],
});
const ideaLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineOnly, {
command: "idea",
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
});
const ideaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineAndColumn, {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
}),
);
+6 -42
View File
@@ -34,45 +34,10 @@ interface CommandAvailabilityOptions {
readonly env?: NodeJS.ProcessEnv;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function parseTargetPathAndPosition(target: string): {
path: string;
line: string | undefined;
column: string | undefined;
} | null {
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
if (!match?.[1] || !match[2]) {
return null;
}
return {
path: match[1],
line: match[2],
column: match[3],
};
}
function resolveCommandEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const parsedTarget = parseTargetPathAndPosition(target);
switch (editor.launchStyle) {
case "direct-path":
return [target];
case "goto":
return parsedTarget ? ["--goto", target] : [target];
case "line-column": {
if (!parsedTarget) {
return [target];
}
const { path, line, column } = parsedTarget;
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
}
}
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -248,10 +213,9 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
}
if (editorDef.command) {
return {
command: editorDef.command,
args: resolveCommandEditorArgs(editorDef, input.cwd),
};
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
@@ -96,9 +96,7 @@ function createProviderServiceHarness(
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -208,9 +208,7 @@ describe("ProviderCommandReactor", () => {
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -98,9 +98,7 @@ function createProviderServiceHarness() {
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
};
const setSession = (session: ProviderSession): void => {
@@ -1,13 +1,3 @@
/**
* 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 {
@@ -16,21 +6,13 @@ import {
type OrchestrationRuntimeReceipt,
} from "../Services/RuntimeReceiptBus.ts";
const makeRuntimeReceiptBus = Effect.succeed({
publish: () => Effect.void,
streamEventsForTest: Stream.empty,
} satisfies RuntimeReceiptBusShape);
const makeRuntimeReceiptBusTest = Effect.gen(function* () {
const makeRuntimeReceiptBus = Effect.gen(function* () {
const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();
return {
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
get streamEventsForTest() {
return Stream.fromPubSub(pubSub);
},
stream: Stream.fromPubSub(pubSub),
} satisfies RuntimeReceiptBusShape;
});
export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);
export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);
@@ -1,19 +1,3 @@
/**
* 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";
@@ -56,7 +40,7 @@ export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Typ
export interface RuntimeReceiptBusShape {
readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
readonly stream: Stream.Stream<OrchestrationRuntimeReceipt>;
}
export class RuntimeReceiptBus extends ServiceMap.Service<
@@ -150,7 +150,6 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
@@ -1,166 +0,0 @@
import { Effect, Layer, Stream } from "effect";
import { describe, expect, it, vi } from "vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
const emptySnapshot = (
scripts: OrchestrationReadModel["projects"][number]["scripts"],
): OrchestrationReadModel =>
({
snapshotSequence: 1,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: "project-1",
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: null,
scripts,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [],
providerSessions: [],
providerStatuses: [],
pendingApprovals: [],
latestTurnByThreadId: {},
}) as unknown as OrchestrationReadModel;
describe("ProjectSetupScriptRunner", () => {
it("returns no-script when no setup script exists", async () => {
const open = vi.fn();
const write = vi.fn();
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () => Effect.succeed(emptySnapshot([])),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectId: "project-1",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({ status: "no-script" });
expect(open).not.toHaveBeenCalled();
expect(write).not.toHaveBeenCalled();
});
it("opens the deterministic setup terminal with worktree env and writes the command", async () => {
const open = vi.fn(() =>
Effect.succeed({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-01-01T00:00:00.000Z",
}),
);
const write = vi.fn(() => Effect.void);
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () =>
Effect.succeed(
emptySnapshot([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectCwd: "/repo/project",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({
status: "started",
scriptId: "setup",
scriptName: "Setup",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
});
expect(open).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
},
});
expect(write).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
data: "bun install\r",
});
});
});
@@ -1,75 +0,0 @@
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
import { Effect, Layer } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import {
type ProjectSetupScriptRunnerShape,
ProjectSetupScriptRunner,
} from "../Services/ProjectSetupScriptRunner.ts";
const makeProjectSetupScriptRunner = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const terminalManager = yield* TerminalManager;
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const project =
(input.projectId
? readModel.projects.find((entry) => entry.id === input.projectId)
: null) ??
(input.projectCwd
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
: null) ??
null;
if (!project) {
return yield* Effect.fail(new Error("Project was not found for setup script execution."));
}
const script = setupProjectScript(project.scripts);
if (!script) {
return {
status: "no-script",
} as const;
}
const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
const cwd = input.worktreePath;
const env = projectScriptRuntimeEnv({
project: { cwd: project.workspaceRoot },
worktreePath: input.worktreePath,
});
yield* terminalManager.open({
threadId: input.threadId,
terminalId,
cwd,
worktreePath: input.worktreePath,
env,
});
yield* terminalManager.write({
threadId: input.threadId,
terminalId,
data: `${script.command}\r`,
});
return {
status: "started",
scriptId: script.id,
scriptName: script.name,
terminalId,
cwd,
} as const;
});
return {
runForThread,
} satisfies ProjectSetupScriptRunnerShape;
});
export const ProjectSetupScriptRunnerLive = Layer.effect(
ProjectSetupScriptRunner,
makeProjectSetupScriptRunner,
);
@@ -1,37 +0,0 @@
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProjectSetupScriptRunnerResultNoScript {
readonly status: "no-script";
}
export interface ProjectSetupScriptRunnerResultStarted {
readonly status: "started";
readonly scriptId: string;
readonly scriptName: string;
readonly terminalId: string;
readonly cwd: string;
}
export type ProjectSetupScriptRunnerResult =
| ProjectSetupScriptRunnerResultNoScript
| ProjectSetupScriptRunnerResultStarted;
export interface ProjectSetupScriptRunnerInput {
readonly threadId: string;
readonly projectId?: string;
readonly projectCwd?: string;
readonly worktreePath: string;
readonly preferredTerminalId?: string;
}
export interface ProjectSetupScriptRunnerShape {
readonly runForThread: (
input: ProjectSetupScriptRunnerInput,
) => Effect.Effect<ProjectSetupScriptRunnerResult, Error>;
}
export class ProjectSetupScriptRunner extends ServiceMap.Service<
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerShape
>()("t3/project/ProjectSetupScriptRunner") {}
@@ -3054,9 +3054,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
listSessions,
hasSession,
stopAll,
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
streamEvents: Stream.fromQueue(runtimeEventQueue),
} satisfies ClaudeAdapterShape;
});
@@ -1631,9 +1631,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
listSessions,
hasSession,
stopAll,
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
streamEvents: Stream.fromQueue(runtimeEventQueue),
} satisfies CodexAdapterShape;
});
@@ -32,7 +32,6 @@ import {
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { DEFAULT_CODEX_MODEL_CAPABILITIES } from "@t3tools/shared/model";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
@@ -160,8 +159,13 @@ 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 ??
DEFAULT_CODEX_MODEL_CAPABILITIES
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
}
);
}
@@ -335,12 +339,7 @@ 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,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
if (!codexSettings.enabled) {
return buildServerProvider({
@@ -112,49 +112,6 @@ 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, SynchronizedRef } from "effect";
import { Effect, Exit, Logger, Scope } from "effect";
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
@@ -40,11 +40,6 @@ 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 }));
}
@@ -198,56 +193,34 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
return undefined;
}
const stateRef = yield* SynchronizedRef.make<LoggerState>({
threadWriters: new Map(),
failedSegments: new Set(),
});
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.failedSegments.has(threadSegment)) {
return Effect.succeed([undefined, state] as const);
}
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
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;
}),
);
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
@@ -266,21 +239,10 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
});
const close = Effect.fn("close")(function* () {
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;
}),
);
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
return {
@@ -115,9 +115,7 @@ function makeMutableServerSettingsService(
yield* PubSub.publish(changes, next);
return next;
}),
get streamChanges() {
return Stream.fromPubSub(changes);
},
streamChanges: Stream.fromPubSub(changes),
} satisfies ServerSettingsShape;
});
}
@@ -220,41 +218,6 @@ 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,9 +191,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
readThread,
rollbackThread,
stopAll,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
streamEvents: 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, Schema, SchemaIssue, Stream } from "effect";
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
import {
increment,
@@ -156,6 +156,7 @@ 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> =>
@@ -193,8 +194,15 @@ 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, processRuntimeEvent).pipe(Effect.forkScoped),
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
@@ -408,7 +416,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
metricModel = input.modelSelection?.model;
yield* Effect.annotateCurrentSpan({
"provider.kind": routed.adapter.provider,
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
+1 -3
View File
@@ -1,5 +1,4 @@
import type {
ModelCapabilities,
ServerProvider,
ServerProviderAuth,
ServerProviderModel,
@@ -103,7 +102,6 @@ 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));
@@ -119,7 +117,7 @@ export function providerModelsFromSettings(
slug: normalized,
name: normalized,
isCustom: true,
capabilities: defaultCustomCapabilities,
capabilities: null,
});
}
File diff suppressed because it is too large. Load diff
+13 -24
View File
@@ -2,12 +2,7 @@ import { Effect, Layer } from "effect";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import { ServerConfig } from "./config";
import {
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
staticAndDevRouteLayer,
} from "./http";
import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http";
import { fixPath } from "./os-jank";
import { websocketRpcRouteLayer } from "./ws";
import { OpenLive } from "./open";
@@ -30,7 +25,6 @@ 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";
@@ -47,7 +41,6 @@ import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResol
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner";
import { ObservabilityLive } from "./observability/Layers/Observability";
const PtyAdapterLive = Layer.unwrap(
@@ -162,16 +155,14 @@ 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(GitManagerLayerLive),
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
Layer.provideMerge(
GitManagerLive.pipe(
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
),
),
Layer.provideMerge(GitCoreLive),
);
@@ -186,12 +177,15 @@ const WorkspaceLayerLive = Layer.mergeAll(
),
);
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
const RuntimeServicesLive = Layer.empty.pipe(
Layer.provideMerge(ServerRuntimeStartupLive),
Layer.provideMerge(ReactorLayerLive),
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(OrchestrationLayerLive),
Layer.provideMerge(ProviderLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
@@ -206,13 +200,8 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ServerLifecycleEventsLive),
);
const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
Layer.provideMerge(RuntimeDependenciesLive),
);
export const makeRoutesLayer = Layer.mergeAll(
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
-26
View File
@@ -171,24 +171,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims observability settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const next = yield* serverSettings.updateSettings({
observability: {
otlpTracesUrl: " http://localhost:4318/v1/traces ",
otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
},
});
assert.deepEqual(next.observability, {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("defaults blank binary paths to provider executables", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -215,10 +197,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const next = yield* serverSettings.updateSettings({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
@@ -230,10 +208,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
@@ -428,85 +428,6 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
Effect.gen(function* () {
const { manager, getEvents, baseDir } = yield* createManager();
const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
yield* makeDirectory(firstWorktreePath);
yield* makeDirectory(secondWorktreePath);
const startedSnapshot = yield* manager.open(
openInput({
cwd: firstWorktreePath,
worktreePath: firstWorktreePath,
}),
);
const restartedSnapshot = yield* manager.restart(
restartInput({
cwd: secondWorktreePath,
worktreePath: secondWorktreePath,
}),
);
assert.equal(startedSnapshot.worktreePath, firstWorktreePath);
assert.equal(restartedSnapshot.worktreePath, secondWorktreePath);
const events = yield* getEvents;
const startedEvent = events.find(
(event): event is Extract<TerminalEvent, { type: "started" }> => event.type === "started",
);
const restartedEvent = events.find(
(event): event is Extract<TerminalEvent, { type: "restarted" }> =>
event.type === "restarted",
);
assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath);
assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath);
}),
);
it.effect("preserves worktree metadata when reopening an exited session", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
const worktreePath = path.join(baseDir, "worktrees", "feature-a");
yield* makeDirectory(worktreePath);
yield* manager.open(
openInput({
cwd: worktreePath,
worktreePath,
}),
);
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")),
);
const reopenedSnapshot = yield* manager.open(
openInput({
cwd: worktreePath,
worktreePath,
}),
);
assert.equal(reopenedSnapshot.worktreePath, worktreePath);
const events = yield* getEvents;
const reopenedEvent = events
.toReversed()
.find(
(event): event is Extract<TerminalEvent, { type: "started" }> => event.type === "started",
);
assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath);
}),
);
it.effect("emits exited event and reopens with clean transcript after exit", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
@@ -80,7 +80,6 @@ interface TerminalStartInput {
threadId: string;
terminalId: string;
cwd: string;
worktreePath?: string | null;
cols: number;
rows: number;
env?: Record<string, string>;
@@ -90,7 +89,6 @@ interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
@@ -145,7 +143,6 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
worktreePath: session.worktreePath,
status: session.status,
pid: session.pid,
history: session.history,
@@ -1312,7 +1309,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
yield* modifyManagerState((state) => {
session.status = "starting";
session.cwd = input.cwd;
session.worktreePath = input.worktreePath ?? null;
session.cols = input.cols;
session.rows = input.rows;
session.exitCode = null;
@@ -1581,7 +1577,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history,
@@ -1615,7 +1610,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
cols,
rows,
...(input.env ? { env: input.env } : {}),
@@ -1635,7 +1629,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
if (liveSession.cwd !== input.cwd || runtimeEnvChanged) {
yield* stopProcess(liveSession);
liveSession.cwd = input.cwd;
liveSession.worktreePath = input.worktreePath ?? null;
liveSession.runtimeEnv = nextRuntimeEnv;
liveSession.history = "";
liveSession.pendingHistoryControlSequence = "";
@@ -1649,7 +1642,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
);
} else if (liveSession.status === "exited" || liveSession.status === "error") {
liveSession.runtimeEnv = nextRuntimeEnv;
liveSession.worktreePath = input.worktreePath ?? null;
liveSession.history = "";
liveSession.pendingHistoryControlSequence = "";
liveSession.pendingProcessEvents = [];
@@ -1669,7 +1661,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: liveSession.worktreePath,
cols: targetCols,
rows: targetRows,
...(input.env ? { env: input.env } : {}),
@@ -1760,7 +1751,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history: "",
@@ -1790,7 +1780,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session = existingSession.value;
yield* stopProcess(session);
session.cwd = input.cwd;
session.worktreePath = input.worktreePath ?? null;
session.runtimeEnv = normalizedRuntimeEnv(input.env);
}
@@ -1809,7 +1798,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
cols,
rows,
...(input.env ? { env: input.env } : {}),
@@ -37,7 +37,6 @@ export interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
+24 -327
View File
@@ -1,8 +1,5 @@
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import {
CommandId,
EventId,
type OrchestrationCommand,
type GitActionProgressEvent,
type GitManagerServiceError,
OrchestrationDispatchCommandError,
@@ -14,7 +11,6 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
ThreadId,
type TerminalEvent,
WS_METHODS,
WsRpcGroup,
@@ -27,7 +23,6 @@ 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";
@@ -46,7 +41,6 @@ import { TerminalManager } from "./terminal/Services/Manager";
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";
const WsRpcLayer = WsRpcGroup.toLayer(
Effect.gen(function* () {
@@ -57,7 +51,6 @@ 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;
@@ -66,264 +59,6 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const startup = yield* ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const serverCommandId = (tag: string) =>
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
const appendSetupScriptActivity = (input: {
readonly threadId: ThreadId;
readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
readonly summary: string;
readonly createdAt: string;
readonly payload: Record<string, unknown>;
readonly tone: "info" | "error";
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("setup-script-activity"),
threadId: input.threadId,
activity: {
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: input.tone,
kind: input.kind,
summary: input.summary,
payload: input.payload,
turnId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: cause instanceof Error ? cause.message : fallbackMessage,
cause,
});
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
const error = Cause.squash(cause);
return Schema.is(OrchestrationDispatchCommandError)(error)
? error
: new OrchestrationDispatchCommandError({
message:
error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
cause,
});
};
const dispatchBootstrapTurnStart = (
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
Effect.gen(function* () {
const bootstrap = command.bootstrap;
const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
let createdThread = false;
let targetProjectId = bootstrap?.createThread?.projectId;
let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
const cleanupCreatedThread = () =>
createdThread
? orchestrationEngine
.dispatch({
type: "thread.delete",
commandId: serverCommandId("bootstrap-thread-delete"),
threadId: command.threadId,
})
.pipe(Effect.ignoreCause({ log: true }))
: Effect.void;
const recordSetupScriptLaunchFailure = (input: {
readonly error: unknown;
readonly requestedAt: string;
readonly worktreePath: string;
}) => {
const detail =
input.error instanceof Error ? input.error.message : "Unknown setup failure.";
return appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.failed",
summary: "Setup script failed to start",
createdAt: input.requestedAt,
payload: {
detail,
worktreePath: input.worktreePath,
},
tone: "error",
}).pipe(
Effect.ignoreCause({ log: false }),
Effect.flatMap(() =>
Effect.logWarning("bootstrap turn start failed to launch setup script", {
threadId: command.threadId,
worktreePath: input.worktreePath,
detail,
}),
),
);
};
const recordSetupScriptStarted = (input: {
readonly requestedAt: string;
readonly worktreePath: string;
readonly scriptId: string;
readonly scriptName: string;
readonly terminalId: string;
}) => {
const payload = {
scriptId: input.scriptId,
scriptName: input.scriptName,
terminalId: input.terminalId,
worktreePath: input.worktreePath,
};
return Effect.all([
appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.requested",
summary: "Starting setup script",
createdAt: input.requestedAt,
payload,
tone: "info",
}),
appendSetupScriptActivity({
threadId: command.threadId,
kind: "setup-script.started",
summary: "Setup script started",
createdAt: new Date().toISOString(),
payload,
tone: "info",
}),
]).pipe(
Effect.asVoid,
Effect.catch((error) =>
Effect.logWarning(
"bootstrap turn start launched setup script but failed to record setup activity",
{
threadId: command.threadId,
worktreePath: input.worktreePath,
scriptId: input.scriptId,
terminalId: input.terminalId,
detail:
error instanceof Error
? error.message
: "Unknown setup activity dispatch failure.",
},
),
),
);
};
const runSetupProgram = () =>
bootstrap?.runSetupScript && targetWorktreePath
? (() => {
const worktreePath = targetWorktreePath;
const requestedAt = new Date().toISOString();
return projectSetupScriptRunner
.runForThread({
threadId: command.threadId,
...(targetProjectId ? { projectId: targetProjectId } : {}),
...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
worktreePath,
})
.pipe(
Effect.matchEffect({
onFailure: (error) =>
recordSetupScriptLaunchFailure({
error,
requestedAt,
worktreePath,
}),
onSuccess: (setupResult) => {
if (setupResult.status !== "started") {
return Effect.void;
}
return recordSetupScriptStarted({
requestedAt,
worktreePath,
scriptId: setupResult.scriptId,
scriptName: setupResult.scriptName,
terminalId: setupResult.terminalId,
});
},
}),
);
})()
: Effect.void;
const bootstrapProgram = Effect.gen(function* () {
if (bootstrap?.createThread) {
yield* orchestrationEngine.dispatch({
type: "thread.create",
commandId: serverCommandId("bootstrap-thread-create"),
threadId: command.threadId,
projectId: bootstrap.createThread.projectId,
title: bootstrap.createThread.title,
modelSelection: bootstrap.createThread.modelSelection,
runtimeMode: bootstrap.createThread.runtimeMode,
interactionMode: bootstrap.createThread.interactionMode,
branch: bootstrap.createThread.branch,
worktreePath: bootstrap.createThread.worktreePath,
createdAt: bootstrap.createThread.createdAt,
});
createdThread = true;
}
if (bootstrap?.prepareWorktree) {
const worktree = yield* git.createWorktree({
cwd: bootstrap.prepareWorktree.projectCwd,
branch: bootstrap.prepareWorktree.baseBranch,
newBranch: bootstrap.prepareWorktree.branch,
path: null,
});
targetWorktreePath = worktree.worktree.path;
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("bootstrap-thread-meta-update"),
threadId: command.threadId,
branch: worktree.worktree.branch,
worktreePath: targetWorktreePath,
});
}
yield* runSetupProgram();
return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
});
return yield* bootstrapProgram.pipe(
Effect.catchCause((cause) => {
const dispatchError = toBootstrapDispatchCommandCauseError(cause);
if (Cause.hasInterruptsOnly(cause)) {
return Effect.fail(dispatchError);
}
return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
}),
);
});
const dispatchNormalizedCommand = (
normalizedCommand: OrchestrationCommand,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
const dispatchEffect =
normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
? dispatchBootstrapTurnStart(normalizedCommand)
: orchestrationEngine
.dispatch(normalizedCommand)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
return startup
.enqueueCommand(dispatchEffect)
.pipe(
Effect.mapError((cause) =>
toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
),
);
};
const loadServerConfig = Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.loadConfigState;
@@ -349,11 +84,6 @@ 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(
@@ -374,7 +104,9 @@ const WsRpcLayer = WsRpcGroup.toLayer(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const result = yield* dispatchNormalizedCommand(normalizedCommand);
const result = yield* startup.enqueueCommand(
orchestrationEngine.dispatch(normalizedCommand),
);
if (normalizedCommand.type === "thread.archive") {
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
@@ -565,30 +297,14 @@ const WsRpcLayer = WsRpcGroup.toLayer(
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.subscribeGitStatus]: (input) =>
observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
[WS_METHODS.gitStatus]: (input) =>
observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(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).pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Effect.failCause(cause),
onSuccess: (result) =>
refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
}),
),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRunStackedAction]: (input) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
@@ -603,10 +319,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () =>
refreshGitStatus(input.cwd).pipe(
Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
}),
),
),
@@ -619,9 +332,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager
.preparePullRequestThread(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
gitManager.preparePullRequestThread(input),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
@@ -629,37 +340,23 @@ const WsRpcLayer = WsRpcGroup.toLayer(
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateWorktree,
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRemoveWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitRemoveWorktree,
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateBranch]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateBranch,
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCheckout]: (input) =>
observeRpcEffect(
WS_METHODS.gitCheckout,
Effect.scoped(git.checkoutBranch(input)).pipe(
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitInit]: (input) =>
observeRpcEffect(
WS_METHODS.gitInit,
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "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, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -14,8 +14,12 @@ import {
useTransition,
} from "react";
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import {
gitBranchSearchInfiniteQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
@@ -85,7 +89,7 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useGitStatus(branchCwd);
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
@@ -106,6 +110,7 @@ export function BranchToolbarBranchSelector({
gitBranchSearchInfiniteQueryOptions({
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
enabled: isBranchMenuOpen,
}),
);
const branches = useMemo(
@@ -183,9 +188,7 @@ export function BranchToolbarBranchSelector({
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.branches(branchCwd) })
.catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
@@ -223,26 +226,29 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
try {
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);
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} 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);
});
};
@@ -255,24 +261,32 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
try {
const createBranchResult = await api.git.createBranch({
cwd: branchCwd,
branch: name,
checkout: true,
});
setOptimisticBranch(createBranchResult.branch);
onSetThreadBranch(createBranchResult.branch, activeWorktreePath);
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;
}
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
type: "error",
title: "Failed to create and checkout branch.",
title: "Failed to create branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
setOptimisticBranch(name);
onSetThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
+54 -343
View File
@@ -31,28 +31,18 @@ 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";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
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='120'></svg>";
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='300'></svg>";
interface TestFixture {
snapshot: OrchestrationReadModel;
@@ -102,9 +92,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, attachmentTolerancePx: 120 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 120 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 120 },
DEFAULT_VIEWPORT,
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
interface UserRowMeasurement {
@@ -233,7 +223,6 @@ function createSnapshotForTargetUser(options: {
name: `attachment-${attachmentIndex + 1}.png`,
mimeType: "image/png",
sizeBytes: 128,
previewUrl: `/attachments/attachment-${attachmentIndex + 1}`,
}))
: undefined;
@@ -407,22 +396,6 @@ 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 },
);
@@ -677,6 +650,24 @@ 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: [],
@@ -691,12 +682,6 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
terminalId: typeof body.terminalId === "string" ? body.terminalId : "default",
cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project",
worktreePath:
typeof body.worktreePath === "string"
? body.worktreePath
: body.worktreePath === null
? null
: null,
status: "running",
pid: 123,
history: "",
@@ -874,7 +859,7 @@ async function expectComposerActionsContained(): Promise<void> {
}
async function waitForInteractionModeButton(
expectedLabel: "Build" | "Plan",
expectedLabel: "Chat" | "Plan",
): Promise<HTMLButtonElement> {
return waitForElement(
() =>
@@ -1052,17 +1037,10 @@ async function mountChatView(options: {
}),
);
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{
container: host,
},
);
const screen = await render(<RouterProvider router={router} />, {
container: host,
});
await waitForWsClient();
await waitForAppBootstrap();
await waitForLayout();
const cleanup = async () => {
@@ -1153,7 +1131,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
return [];
},
});
await __resetNativeApiForTests();
__resetNativeApiForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
@@ -1171,13 +1149,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
threads: [],
bootstrapComplete: false,
});
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
});
afterEach(() => {
@@ -1314,7 +1285,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
targetAttachmentCount: 2,
targetAttachmentCount: 3,
}),
});
@@ -1328,7 +1299,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{
role: "user",
text: userText,
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }],
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
},
{ timelineWidthPx: timelineWidthMeasuredPx },
);
@@ -1401,74 +1372,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-launch-context-target" as MessageId,
targetText: "launch context worktree override",
});
const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID);
if (targetThread) {
Object.assign(targetThread, {
branch: "feature/branch",
worktreePath: "/repo/worktrees/feature-branch",
});
}
useTerminalStateStore.setState({
terminalStateByThreadId: {
[THREAD_ID]: {
terminalOpen: true,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
},
},
terminalLaunchContextByThreadId: {
[THREAD_ID]: {
cwd: "/repo/project",
worktreePath: null,
},
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot,
});
try {
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
) as
| {
_tag: string;
cwd?: string;
worktreePath?: string | null;
env?: Record<string, string>;
}
| undefined;
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
cwd: "/repo/project",
worktreePath: null,
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
},
});
expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
@@ -1810,7 +1713,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("lets the server own setup after preparing a pull request worktree thread", async () => {
it("runs setup scripts after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
@@ -1915,188 +1818,45 @@ describe("ChatView timeline estimator parity (full app)", () => {
cwd: "/repo/project",
reference: "1359",
mode: "worktree",
threadId: THREAD_ID,
});
},
{ timeout: 8_000, interval: 16 },
);
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
),
).toBe(false);
} finally {
await mounted.cleanup();
}
});
it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
expect(sendButton.disabled).toBe(false);
sendButton.click();
await vi.waitFor(
() => {
const dispatchRequest = wsRequests.find(
(request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand,
) as
| {
_tag: string;
type?: string;
bootstrap?: {
createThread?: { projectId?: string };
prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string };
runSetupScript?: boolean;
};
}
| undefined;
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "thread.turn.start",
bootstrap: {
createThread: {
projectId: PROJECT_ID,
},
prepareWorktree: {
projectCwd: "/repo/project",
baseBranch: "main",
branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/),
},
runSetupScript: true,
const openRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: expect.any(String),
cwd: "/repo/worktrees/pr-1359",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
},
});
},
{ timeout: 8_000, interval: 16 },
);
expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe(
false,
);
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.terminalWrite &&
request.threadId === THREAD_ID &&
request.data === "bun install\r",
),
).toBe(false);
} finally {
await mounted.cleanup();
}
});
it("shows the send state once bootstrap dispatch is in flight", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
let resolveDispatch!: (value: { sequence: number }) => void;
const dispatchPromise = new Promise<{ sequence: number }>((resolve) => {
resolveDispatch = resolve;
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return dispatchPromise;
}
return undefined;
},
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
expect(sendButton.disabled).toBe(false);
sendButton.click();
await vi.waitFor(
() => {
expect(
wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand),
).toBe(true);
expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy();
expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull();
const writeRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
);
expect(writeRequest).toMatchObject({
_tag: WS_METHODS.terminalWrite,
threadId: expect.any(String),
data: "bun install\r",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 });
await mounted.cleanup();
}
});
@@ -2111,7 +1871,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const initialModeButton = await waitForInteractionModeButton("Build");
const initialModeButton = await waitForInteractionModeButton("Chat");
expect(initialModeButton.title).toContain("enter plan mode");
window.dispatchEvent(
@@ -2124,7 +1884,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
await waitForLayout();
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
@@ -2140,7 +1900,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Plan")).title).toContain(
"return to normal build mode",
"return to normal chat mode",
);
},
{ timeout: 8_000, interval: 16 },
@@ -2157,7 +1917,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
},
{ timeout: 8_000, interval: 16 },
);
@@ -2833,55 +2593,6 @@ 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,
+180 -180
View File
@@ -21,13 +21,12 @@ import {
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useGitStatus } from "~/lib/gitStatusState";
import { gitCreateWorktreeMutationOptions, gitStatusQueryOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -53,6 +52,7 @@ import {
deriveWorkLogEntries,
hasActionableProposedPlan,
hasToolActivityForTurn,
isSessionActivelyRunningTurn,
isLatestTurnSettled,
formatElapsed,
} from "../session-logic";
@@ -112,7 +112,10 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
} from "~/projectScripts";
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
@@ -197,7 +200,6 @@ 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`;
@@ -332,14 +334,12 @@ interface ChatViewProps {
threadId: ThreadId;
}
interface TerminalLaunchContext {
interface PendingPullRequestSetupRequest {
threadId: ThreadId;
cwd: string;
worktreePath: string | null;
worktreePath: string;
scriptId: string;
}
type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
@@ -410,7 +410,6 @@ function useLocalDispatchState(input: {
interface PersistentThreadTerminalDrawerProps {
threadId: ThreadId;
visible: boolean;
launchContext: PersistentTerminalLaunchContext | null;
focusRequestId: number;
splitShortcutLabel: string | undefined;
newShortcutLabel: string | undefined;
@@ -421,7 +420,6 @@ interface PersistentThreadTerminalDrawerProps {
function PersistentThreadTerminalDrawer({
threadId,
visible,
launchContext,
focusRequestId,
splitShortcutLabel,
newShortcutLabel,
@@ -443,32 +441,25 @@ function PersistentThreadTerminalDrawer({
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const effectiveWorktreePath = useMemo(() => {
if (launchContext !== null) {
return launchContext.worktreePath;
}
return worktreePath;
}, [launchContext, worktreePath]);
const cwd = useMemo(
() =>
launchContext?.cwd ??
(project
project
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
worktreePath,
})
: null),
[effectiveWorktreePath, launchContext?.cwd, project],
: null,
[project, worktreePath],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
worktreePath,
})
: {},
[effectiveWorktreePath, project],
[project, worktreePath],
);
const bumpFocusRequestId = useCallback(() => {
@@ -551,7 +542,6 @@ function PersistentThreadTerminalDrawer({
<ThreadTerminalDrawer
threadId={threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible={visible}
height={terminalState.terminalHeight}
@@ -577,6 +567,7 @@ function PersistentThreadTerminalDrawer({
export default function ChatView({ threadId }: ChatViewProps) {
const serverThread = useThreadById(threadId);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[threadId],
@@ -592,6 +583,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
select: (params) => parseDiffRouteSearch(params),
});
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const composerDraft = useComposerThreadDraft(threadId);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
@@ -682,9 +675,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
useState<PendingPullRequestSetupRequest | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -750,12 +742,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const storeNewTerminal = useTerminalStateStore((s) => s.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
const storeServerTerminalLaunchContext = useTerminalStateStore(
(s) => s.terminalLaunchContextByThreadId[threadId] ?? null,
);
const storeClearTerminalLaunchContext = useTerminalStateStore(
(s) => s.clearTerminalLaunchContext,
);
const threads = useStore((state) => state.threads);
const serverThreadIds = useMemo(() => threads.map((thread) => thread.id), [threads]);
const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId);
@@ -957,13 +943,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handlePreparedPullRequestThread = useCallback(
async (input: { branch: string; worktreePath: string | null }) => {
await openOrReuseProjectDraftThread({
const targetThreadId = await openOrReuseProjectDraftThread({
branch: input.branch,
worktreePath: input.worktreePath,
envMode: input.worktreePath ? "worktree" : "local",
});
const setupScript =
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
if (targetThreadId && input.worktreePath && setupScript) {
setPendingPullRequestSetupRequest({
threadId: targetThreadId,
worktreePath: input.worktreePath,
scriptId: setupScript.id,
});
} else {
setPendingPullRequestSetupRequest(null);
}
},
[openOrReuseProjectDraftThread],
[activeProject, openOrReuseProjectDraftThread],
);
useEffect(() => {
@@ -1124,7 +1121,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePendingUserInput: activePendingUserInput?.requestId ?? null,
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const isTurnRunning = isSessionActivelyRunningTurn(
activeLatestTurn,
activeThread?.session ?? null,
);
const isWorking = isTurnRunning || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
@@ -1141,7 +1142,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (activePendingProgress) {
return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`;
}
if (phase === "running") {
if (isTurnRunning) {
return "running";
}
if (showPlanFollowUpPrompt) {
@@ -1155,7 +1156,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
isConnecting,
isPreparingWorktree,
isSendBusy,
phase,
isTurnRunning,
prompt,
showPlanFollowUpPrompt,
]);
@@ -1399,7 +1400,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const gitStatusQuery = useGitStatus(gitCwd);
const gitStatusQuery = useQuery(gitStatusQueryOptions(gitCwd));
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
@@ -1476,7 +1477,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
type: "slash-command",
command: "default",
label: "/default",
description: "Switch this thread back to normal build mode",
description: "Switch this thread back to normal chat mode",
},
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
const query = composerTrigger.query.trim().toLowerCase();
@@ -1524,13 +1525,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
[selectedProvider, providerStatuses],
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
@@ -1601,18 +1595,17 @@ 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, nextError);
setStoreThreadError(targetThreadId, error);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[targetThreadId] ?? null) === nextError) {
if ((existing[targetThreadId] ?? null) === error) {
return existing;
}
return {
...existing,
[targetThreadId]: nextError,
[targetThreadId]: error,
};
});
},
@@ -1752,13 +1745,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${randomUUID()}`
: baseTerminalId;
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
setTerminalLaunchContext({
threadId: activeThreadId,
cwd: targetCwd,
worktreePath: targetWorktreePath,
});
setTerminalOpen(true);
if (shouldCreateNewTerminal) {
storeNewTerminal(activeThreadId, targetTerminalId);
@@ -1771,7 +1758,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
project: {
cwd: activeProject.cwd,
},
worktreePath: targetWorktreePath,
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
@@ -1779,7 +1766,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
env: runtimeEnv,
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
@@ -1788,7 +1774,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
env: runtimeEnv,
};
@@ -1822,6 +1807,44 @@ export default function ChatView({ threadId }: ChatViewProps) {
],
);
useEffect(() => {
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
return;
}
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
return;
}
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
return;
}
const setupScript =
activeProject.scripts.find(
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
) ?? null;
setPendingPullRequestSetupRequest(null);
if (!setupScript) {
return;
}
void runProjectScript(setupScript, {
cwd: pendingPullRequestSetupRequest.worktreePath,
worktreePath: pendingPullRequestSetupRequest.worktreePath,
rememberAsLastInvoked: false,
}).catch((error) => {
toastManager.add({
type: "error",
title: "Failed to run setup script.",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, [
activeProject,
activeThread,
activeThreadId,
pendingPullRequestSetupRequest,
runProjectScript,
]);
const persistProjectScripts = useCallback(
async (input: {
projectId: ProjectId;
@@ -2293,10 +2316,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
scheduleStickToBottom();
}, [messageCount, scheduleStickToBottom]);
useEffect(() => {
if (phase !== "running") return;
if (!isTurnRunning) return;
if (!shouldAutoScrollRef.current) return;
scheduleStickToBottom();
}, [phase, scheduleStickToBottom, timelineEntries]);
}, [isTurnRunning, scheduleStickToBottom, timelineEntries]);
useEffect(() => {
setExpandedWorkGroups({});
@@ -2515,82 +2538,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
: "local";
useEffect(() => {
if (!activeThreadId) {
setTerminalLaunchContext(null);
storeClearTerminalLaunchContext(threadId);
return;
}
setTerminalLaunchContext((current) => {
if (!current) return current;
if (current.threadId === activeThreadId) return current;
return null;
});
}, [activeThreadId, storeClearTerminalLaunchContext, threadId]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd) {
return;
}
setTerminalLaunchContext((current) => {
if (!current || current.threadId !== activeThreadId) {
return current;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === current.cwd &&
(activeThreadWorktreePath ?? null) === current.worktreePath
) {
storeClearTerminalLaunchContext(activeThreadId);
return null;
}
return current;
});
}, [activeProjectCwd, activeThreadId, activeThreadWorktreePath, storeClearTerminalLaunchContext]);
useEffect(() => {
if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) {
return;
}
const settledCwd = projectScriptCwd({
project: { cwd: activeProjectCwd },
worktreePath: activeThreadWorktreePath,
});
if (
settledCwd === storeServerTerminalLaunchContext.cwd &&
(activeThreadWorktreePath ?? null) === storeServerTerminalLaunchContext.worktreePath
) {
storeClearTerminalLaunchContext(activeThreadId);
}
}, [
activeProjectCwd,
activeThreadId,
activeThreadWorktreePath,
storeClearTerminalLaunchContext,
storeServerTerminalLaunchContext,
]);
useEffect(() => {
if (terminalState.terminalOpen) {
return;
}
if (activeThreadId) {
storeClearTerminalLaunchContext(activeThreadId);
}
setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current));
}, [activeThreadId, storeClearTerminalLaunchContext, terminalState.terminalOpen]);
useEffect(() => {
if (phase !== "running") return;
if (!isTurnRunning) return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [phase]);
}, [isTurnRunning]);
useEffect(() => {
if (!activeThreadId) return;
@@ -2810,7 +2765,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy || isConnecting) {
if (isTurnRunning || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -2843,7 +2798,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
setIsRevertingCheckpoint(false);
},
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, isTurnRunning, setThreadError],
);
const onSend = async (e?: { preventDefault: () => void }) => {
@@ -2996,8 +2951,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(0);
setComposerTrigger(null);
let createdServerThreadForLocalDraft = false;
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
branch: baseBranchForWorktree,
newBranch,
});
nextThreadBranch = result.worktree.branch;
nextThreadWorktreePath = result.worktree.path;
if (isServerThread) {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: threadIdForSend,
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
// Keep local thread state in sync immediately so terminal drawer opens
// with the worktree cwd/env instead of briefly using the project root.
setStoreThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path);
}
}
let firstComposerImageName: string | null = null;
if (composerImagesSnapshot.length > 0) {
const firstComposerImage = composerImagesSnapshot[0];
@@ -3025,6 +3008,48 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}),
};
if (isLocalDraftThread) {
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: threadIdForSend,
projectId: activeProject.id,
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
branch: nextThreadBranch,
worktreePath: nextThreadWorktreePath,
createdAt: activeThread.createdAt,
});
createdServerThreadForLocalDraft = true;
}
let setupScript: ProjectScript | null = null;
if (baseBranchForWorktree) {
setupScript = setupProjectScript(activeProject.scripts);
}
if (setupScript) {
let shouldRunSetupScript = false;
if (isServerThread) {
shouldRunSetupScript = true;
} else {
if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
}
if (shouldRunSetupScript) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
worktreePath: nextThreadWorktreePath,
rememberAsLastInvoked: false,
};
if (nextThreadWorktreePath) {
setupScriptOptions.cwd = nextThreadWorktreePath;
}
await runProjectScript(setupScript, setupScriptOptions);
}
}
// Auto-title from first message
if (isFirstMessage && isServerThread) {
await api.orchestration.dispatchCommand({
@@ -3045,37 +3070,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
const turnAttachments = await turnAttachmentsPromise;
const bootstrap =
isLocalDraftThread || baseBranchForWorktree
? {
...(isLocalDraftThread
? {
createThread: {
projectId: activeProject.id,
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
createdAt: activeThread.createdAt,
},
}
: {}),
...(baseBranchForWorktree
? {
prepareWorktree: {
projectCwd: activeProject.cwd,
baseBranch: baseBranchForWorktree,
branch: buildTemporaryWorktreeBranchName(),
},
runSetupScript: true,
}
: {}),
}
: undefined;
beginLocalDispatch({ preparingWorktree: false });
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
@@ -3090,11 +3086,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
titleSeed: title,
runtimeMode,
interactionMode,
...(bootstrap ? { bootstrap } : {}),
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
})().catch(async (err: unknown) => {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: threadIdForSend,
})
.catch(() => undefined);
}
if (
!turnStartSucceeded &&
promptRef.current.length === 0 &&
@@ -3156,14 +3160,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
})
.catch((err: unknown) => {
setThreadError(
setStoreThreadError(
activeThreadId,
err instanceof Error ? err.message : "Failed to submit approval decision.",
);
});
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
},
[activeThreadId, setThreadError],
[activeThreadId, setStoreThreadError],
);
const onRespondToUserInput = useCallback(
@@ -3184,14 +3188,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
})
.catch((err: unknown) => {
setThreadError(
setStoreThreadError(
activeThreadId,
err instanceof Error ? err.message : "Failed to submit user input.",
);
});
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
},
[activeThreadId, setThreadError],
[activeThreadId, setStoreThreadError],
);
const setActivePendingUserInputQuestionIndex = useCallback(
@@ -4005,7 +4009,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeWorkspaceRoot}
workspaceRoot={activeProject?.cwd ?? undefined}
/>
</div>
@@ -4029,7 +4033,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
<form
ref={composerFormRef}
onSubmit={onSend}
className="mx-auto w-full min-w-0 max-w-208"
className="mx-auto w-full min-w-0 max-w-[52rem]"
data-chat-composer-form="true"
>
<div
@@ -4284,13 +4288,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
onClick={toggleInteractionMode}
title={
interactionMode === "plan"
? "Plan mode — click to return to normal build mode"
? "Plan mode — click to return to normal chat mode"
: "Default mode — click to enter plan mode"
}
>
<BotIcon />
<span className="sr-only sm:not-sr-only">
{interactionMode === "plan" ? "Plan" : "Build"}
{interactionMode === "plan" ? "Plan" : "Chat"}
</span>
</Button>
@@ -4383,7 +4387,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
: null
}
isRunning={phase === "running"}
isRunning={isTurnRunning}
showPlanFollowUpPrompt={
pendingUserInputs.length === 0 && showPlanFollowUpPrompt
}
@@ -4419,7 +4423,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
<PullRequestThreadDialog
key={pullRequestDialogState.key}
open
threadId={activeThread.id}
cwd={activeProject?.cwd ?? null}
initialReference={pullRequestDialogState.initialReference}
onOpenChange={(open) => {
@@ -4439,7 +4442,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
workspaceRoot={activeProject?.cwd ?? undefined}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
@@ -4459,9 +4462,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
key={mountedThreadId}
threadId={mountedThreadId}
visible={mountedThreadId === activeThreadId && terminalState.terminalOpen}
launchContext={
mountedThreadId === activeThreadId ? (activeTerminalLaunchContext ?? null) : null
}
focusRequestId={mountedThreadId === activeThreadId ? terminalFocusRequestId : 0}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
+2 -2
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { useGitStatus } from "~/lib/gitStatusState";
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
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 = useGitStatus(activeCwd ?? null);
const gitStatusQuery = useQuery(gitStatusQueryOptions(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,
refreshGitStatusSpy,
invalidateGitStatusQuerySpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
@@ -19,7 +19,7 @@ const {
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
invalidateGitStatusQuerySpy: vi.fn(() => Promise.resolve()),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
@@ -57,6 +57,21 @@ 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: {
@@ -95,6 +110,7 @@ vi.mock("~/editorPreferences", () => ({
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitBranchesQueryOptions: vi.fn(() => ({ queryKey: ["git-branches"] })),
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
@@ -102,25 +118,9 @@ vi.mock("~/lib/gitReactQuery", () => ({
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
gitStatusQueryOptions: vi.fn(() => ({ queryKey: ["git-status"] })),
invalidateGitQueries: invalidateGitQueriesSpy,
}));
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,
})),
invalidateGitStatusQuery: invalidateGitStatusQuerySpy,
}));
vi.mock("~/lib/utils", async () => {
@@ -235,42 +235,4 @@ 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 -41
View File
@@ -5,7 +5,7 @@ import type {
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useIsMutating, useMutation, useQuery, 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,8 +45,9 @@ 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";
@@ -91,8 +92,6 @@ interface RunGitActionWithToastInput {
filePaths?: string[];
}
const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
@@ -276,7 +275,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useGitStatus(gitCwd);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
@@ -360,39 +359,6 @@ 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) {
@@ -835,9 +801,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) {
void refreshGitStatus(gitCwd).catch(() => undefined);
}
if (open) void invalidateGitStatusQuery(queryClient, gitCwd);
}}
>
<MenuTrigger
-101
View File
@@ -310,107 +310,6 @@ export const AntigravityIcon: Icon = (props) => (
</svg>
);
export const IntelliJIdeaIcon: Icon = (props) => {
const id = useId();
const gradientAId = `${id}-idea-a`;
const gradientBId = `${id}-idea-b`;
const gradientCId = `${id}-idea-c`;
const gradientDId = `${id}-idea-d`;
return (
<svg {...props} viewBox="0 0 70 70" fill="none">
<defs>
<linearGradient
id={gradientAId}
x1="0.7898"
y1="40.0893"
x2="33.3172"
y2="40.0893"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.2581" stopColor="#F97A12" />
<stop offset="0.4591" stopColor="#B07B58" />
<stop offset="0.7241" stopColor="#577BAE" />
<stop offset="0.9105" stopColor="#1E7CE5" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientBId}
x1="25.7674"
y1="24.88"
x2="79.424"
y2="54.57"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#F97A12" />
<stop offset="0.07179946" stopColor="#CB7A3E" />
<stop offset="0.1541" stopColor="#9E7B6A" />
<stop offset="0.242" stopColor="#757B91" />
<stop offset="0.3344" stopColor="#537BB1" />
<stop offset="0.4324" stopColor="#387CCC" />
<stop offset="0.5381" stopColor="#237CE0" />
<stop offset="0.6552" stopColor="#147CEF" />
<stop offset="0.7925" stopColor="#0B7CF7" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientCId}
x1="63.2277"
y1="42.9153"
x2="48.2903"
y2="-1.7191"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FE315D" />
<stop offset="0.07840246" stopColor="#CB417E" />
<stop offset="0.1601" stopColor="#9E4E9B" />
<stop offset="0.2474" stopColor="#755BB4" />
<stop offset="0.3392" stopColor="#5365CA" />
<stop offset="0.4365" stopColor="#386DDB" />
<stop offset="0.5414" stopColor="#2374E9" />
<stop offset="0.6576" stopColor="#1478F3" />
<stop offset="0.794" stopColor="#0B7BF8" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
<linearGradient
id={gradientDId}
x1="10.7204"
y1="16.473"
x2="55.5237"
y2="90.58"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FE315D" />
<stop offset="0.04023279" stopColor="#F63462" />
<stop offset="0.1037" stopColor="#DF3A71" />
<stop offset="0.1667" stopColor="#C24383" />
<stop offset="0.2912" stopColor="#AD4A91" />
<stop offset="0.5498" stopColor="#755BB4" />
<stop offset="0.9175" stopColor="#1D76ED" />
<stop offset="1" stopColor="#087CFA" />
</linearGradient>
</defs>
<polygon points="17.7,54.6 0.8,41.2 9.2,25.6 33.3,35" fill={`url(#${gradientAId})`} />
<path
d="M70 18.7 68.7 59.2 41.8 70 25.6 59.6 49.3 35 38.9 12.3 48.2 1.1Z"
fill={`url(#${gradientBId})`}
/>
<polygon points="70,18.7 48.7,43.9 38.9,12.3 48.2,1.1" fill={`url(#${gradientCId})`} />
<path
d="M33.7 58.1 5.6 68.3 10.1 52.5 16 33.1 0 27.7 10.1 0 32.1 2.7 53.7 27.4Z"
fill={`url(#${gradientDId})`}
/>
<rect x="13.7" y="13.5" width="43.2" height="43.2" fill="#000" />
<rect x="17.7" y="48.6" width="16.2" height="2.7" fill="#fff" />
<path d="M29.4 22.4v-3.3h-9v3.3h2.6v11.3h-2.6V37h9v-3.3h-2.5V22.4h2.5Z" fill="#fff" />
<path
d="M38 37.3c-1.4 0-2.6-.3-3.5-.8-.9-.5-1.7-1.2-2.3-1.9l2.5-2.8c.5.6 1 1 1.5 1.3.5.3 1.1.5 1.7.5.7 0 1.3-.2 1.8-.7.4-.5.6-1.2.6-2.3V19.1h4v11.7c0 1.1-.1 2-.4 2.8-.3.8-.7 1.4-1.3 2-.5.5-1.2 1-2 1.2-.8.3-1.6.5-2.6.5Z"
fill="#fff"
/>
</svg>
);
};
export const OpenCodeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clipPath="url(#opencode__clip0_1311_94969)">
@@ -1,7 +1,6 @@
import "../index.css";
import {
DEFAULT_SERVER_SETTINGS,
ORCHESTRATION_WS_METHODS,
type MessageId,
type OrchestrationReadModel,
@@ -19,19 +18,10 @@ 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";
@@ -73,7 +63,6 @@ function createBaseServerConfig(): ServerConfig {
otlpMetricsEnabled: false,
},
settings: {
...DEFAULT_SERVER_SETTINGS,
enableAssistantStreaming: false,
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
@@ -179,6 +168,20 @@ 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 };
}
@@ -253,29 +256,6 @@ 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";
@@ -288,15 +268,8 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{ container: host },
);
const screen = await render(<RouterProvider router={router} />, { container: host });
await waitForComposerEditor();
await waitForInitialWsSubscriptions();
await waitForServerConfigSnapshot();
return {
cleanup: async () => {
@@ -347,7 +320,7 @@ describe("Keybindings update toast", () => {
return [];
},
});
await __resetNativeApiForTests();
__resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
useComposerDraftStore.setState({
@@ -1,4 +1,4 @@
import type { GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts";
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,7 +24,6 @@ import { Spinner } from "./ui/spinner";
interface PullRequestThreadDialogProps {
open: boolean;
threadId: ThreadId;
cwd: string | null;
initialReference: string | null;
onOpenChange: (open: boolean) => void;
@@ -33,7 +32,6 @@ interface PullRequestThreadDialogProps {
export function PullRequestThreadDialog({
open,
threadId,
cwd,
initialReference,
onOpenChange,
@@ -132,7 +130,6 @@ export function PullRequestThreadDialog({
const result = await preparePullRequestThreadMutation.mutateAsync({
reference: parsedReference,
mode,
...(mode === "worktree" ? { threadId } : {}),
});
await onPrepared({
branch: result.branch,
@@ -150,7 +147,6 @@ export function PullRequestThreadDialog({
parsedReference,
preparePullRequestThreadMutation,
resolvedPullRequest,
threadId,
],
);
+53 -18
View File
@@ -49,6 +49,7 @@ 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,
@@ -69,7 +70,7 @@ import {
threadJumpIndexFromCommand,
threadTraversalDirectionFromCommand,
} from "../keybindings";
import { useGitStatus } from "../lib/gitStatusState";
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
@@ -244,20 +245,8 @@ 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>;
@@ -288,6 +277,7 @@ interface SidebarThreadRowProps {
cancelRename: () => void;
attemptArchiveThread: (threadId: ThreadId) => Promise<void>;
openPrLink: (event: MouseEvent<HTMLElement>, prUrl: string) => void;
pr: ThreadPr | null;
}
function SidebarThreadRow(props: SidebarThreadRowProps) {
@@ -297,8 +287,6 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
(state) =>
selectThreadTerminalState(state.terminalStateByThreadId, props.threadId).runningTerminalIds,
);
const gitCwd = thread?.worktreePath ?? props.projectCwd;
const gitStatus = useGitStatus(thread?.branch != null ? gitCwd : null);
if (!thread) {
return null;
@@ -315,8 +303,7 @@ function SidebarThreadRow(props: SidebarThreadRowProps) {
lastVisitedAt,
},
});
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const prStatus = prStatusIndicator(pr);
const prStatus = prStatusIndicator(props.pr);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = props.confirmingArchiveThreadId === thread.id && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
@@ -775,6 +762,54 @@ 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();
@@ -1683,7 +1718,6 @@ export default function Sidebar() {
<SidebarThreadRow
key={threadId}
threadId={threadId}
projectCwd={project.cwd}
orderedProjectThreadIds={orderedProjectThreadIds}
routeThreadId={routeThreadId}
selectedThreadIds={selectedThreadIds}
@@ -1707,6 +1741,7 @@ export default function Sidebar() {
cancelRename={cancelRename}
attemptArchiveThread={attemptArchiveThread}
openPrLink={openPrLink}
pr={prByThreadId.get(threadId) ?? null}
/>
))}
@@ -212,7 +212,6 @@ interface TerminalViewportProps {
terminalId: string;
terminalLabel: string;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
onSessionExited: () => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
@@ -227,7 +226,6 @@ function TerminalViewport({
terminalId,
terminalLabel,
cwd,
worktreePath,
runtimeEnv,
onSessionExited,
onAddTerminalContext,
@@ -599,7 +597,6 @@ function TerminalViewport({
threadId,
terminalId,
cwd,
...(worktreePath !== undefined ? { worktreePath } : {}),
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
@@ -723,7 +720,6 @@ function TerminalViewport({
interface ThreadTerminalDrawerProps {
threadId: ThreadId;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
visible?: boolean;
height: number;
@@ -775,7 +771,6 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
export default function ThreadTerminalDrawer({
threadId,
cwd,
worktreePath,
runtimeEnv,
visible = true,
height,
@@ -1102,7 +1097,6 @@ export default function ThreadTerminalDrawer({
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -1123,7 +1117,6 @@ export default function ThreadTerminalDrawer({
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -1,83 +0,0 @@
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);
});
});
@@ -1,544 +0,0 @@
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,7 +48,6 @@ import {
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
deriveDisplayedUserMessageState,
type ParsedTerminalContextEntry,
@@ -386,7 +385,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<img
src={image.previewUrl}
alt={image.name}
className="block h-auto max-h-[220px] w-full object-cover"
className="h-full max-h-[220px] w-full object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
/>
@@ -793,16 +792,6 @@ 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;
@@ -851,7 +840,6 @@ 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;
@@ -865,46 +853,19 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
<EntryIcon className="size-3" />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
<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>
<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>
</div>
{hasChangedFiles && !previewIsChangedFiles && (
+1 -14
View File
@@ -6,15 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
import {
AntigravityIcon,
CursorIcon,
Icon,
TraeIcon,
IntelliJIdeaIcon,
VisualStudioCode,
Zed,
} from "../Icons";
import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -55,11 +47,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
Icon: AntigravityIcon,
value: "antigravity",
},
{
label: "IntelliJ IDEA",
Icon: IntelliJIdeaIcon,
value: "idea",
},
{
label: isMacPlatform(platform)
? "Finder"
@@ -477,23 +477,6 @@ 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,36 +149,6 @@ 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(async () => {
beforeEach(() => {
resetServerStateForTests();
await __resetNativeApiForTests();
__resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
});
afterEach(async () => {
afterEach(() => {
resetServerStateForTests();
await __resetNativeApiForTests();
__resetNativeApiForTests();
document.body.innerHTML = "";
});
@@ -30,7 +30,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }],
}),
).toBe(234);
).toBe(346);
expect(
estimateTimelineMessageHeight({
@@ -38,7 +38,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }],
}),
).toBe(234);
).toBe(346);
});
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(350);
).toBe(574);
expect(
estimateTimelineMessageHeight({
@@ -56,7 +56,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
}),
).toBe(350);
).toBe(574);
});
it("does not cap long user message estimates", () => {
+2 -3
View File
@@ -11,9 +11,8 @@ const ASSISTANT_LINE_HEIGHT_PX = 22.75;
const ASSISTANT_BASE_HEIGHT_PX = 41;
const USER_BASE_HEIGHT_PX = 96;
const ATTACHMENTS_PER_ROW = 2;
// 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;
// Attachment thumbnails render with `max-h-[220px]` plus ~8px row gap.
const USER_ATTACHMENT_ROW_HEIGHT_PX = 228;
const USER_BUBBLE_WIDTH_RATIO = 0.8;
const USER_BUBBLE_HORIZONTAL_PADDING_PX = 32;
const ASSISTANT_MESSAGE_HORIZONTAL_PADDING_PX = 8;
+10 -13
View File
@@ -23,7 +23,6 @@ export type ThreadToastData = {
threadId?: ThreadId | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
hideCopyButton?: boolean;
};
const toastManager = Toast.createToastManager<ThreadToastData>();
@@ -309,15 +308,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 wrap-break-word font-medium"
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
{toast.type === "error" &&
typeof toast.description === "string" &&
!toast.data?.hideCopyButton && <CopyErrorButton text={toast.description} />}
{toast.type === "error" && typeof toast.description === "string" && (
<CopyErrorButton text={toast.description} />
)}
</div>
<Toast.Description
className="min-w-0 select-text wrap-break-word text-muted-foreground"
className="min-w-0 select-text break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
@@ -403,17 +402,15 @@ 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 wrap-break-word font-medium"
className="min-w-0 break-words font-medium"
data-slot="toast-title"
/>
{toast.type === "error" &&
typeof toast.description === "string" &&
!toast.data?.hideCopyButton && (
<CopyErrorButton text={toast.description} />
)}
{toast.type === "error" && typeof toast.description === "string" && (
<CopyErrorButton text={toast.description} />
)}
</div>
<Toast.Description
className="min-w-0 select-text wrap-break-word text-muted-foreground"
className="min-w-0 select-text break-words text-muted-foreground"
data-slot="toast-description"
/>
</div>
+29
View File
@@ -15,9 +15,12 @@ import type { GitListBranchesResult } from "@t3tools/contracts";
import {
gitBranchSearchInfiniteQueryOptions,
gitMutationKeys,
gitQueryKeys,
gitPreparePullRequestThreadMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
invalidateGitStatusQuery,
gitStatusQueryOptions,
invalidateGitQueries,
} from "./gitReactQuery";
@@ -81,6 +84,7 @@ 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",
@@ -88,6 +92,7 @@ describe("invalidateGitQueries", () => {
}).queryKey,
BRANCH_SEARCH_RESULT,
);
queryClient.setQueryData(gitQueryKeys.status("/repo/b"), { ok: "b" });
queryClient.setQueryData(
gitBranchSearchInfiniteQueryOptions({
cwd: "/repo/b",
@@ -98,6 +103,9 @@ describe("invalidateGitQueries", () => {
await invalidateGitQueries(queryClient, { cwd: "/repo/a" });
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/a").queryKey)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -106,6 +114,9 @@ describe("invalidateGitQueries", () => {
}).queryKey,
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(gitStatusQueryOptions("/repo/b").queryKey)?.isInvalidated,
).toBe(false);
expect(
queryClient.getQueryState(
gitBranchSearchInfiniteQueryOptions({
@@ -116,3 +127,21 @@ 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);
});
});
+65 -38
View File
@@ -1,8 +1,4 @@
import {
type GitActionProgressEvent,
type GitStackedAction,
type ThreadId,
} from "@t3tools/contracts";
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
import {
infiniteQueryOptions,
mutationOptions,
@@ -12,12 +8,15 @@ 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,
@@ -35,18 +34,37 @@ export const gitMutationKeys = {
export function invalidateGitQueries(queryClient: QueryClient, input?: { cwd?: string | null }) {
const cwd = input?.cwd ?? null;
if (cwd !== null) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) });
return Promise.all([
queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(cwd) }),
queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) }),
]);
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
}
function invalidateGitBranchQueries(queryClient: QueryClient, cwd: string | null) {
export function invalidateGitStatusQuery(queryClient: QueryClient, cwd: string | null) {
if (cwd === null) {
return Promise.resolve();
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(cwd) });
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,
});
}
export function gitBranchSearchInfiniteQueryOptions(input: {
@@ -106,8 +124,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 });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
@@ -123,8 +141,8 @@ export function gitCheckoutMutationOptions(input: {
if (!input.cwd) throw new Error("Git checkout is unavailable.");
return api.git.checkout({ cwd: input.cwd, branch });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
onSuccess: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
@@ -153,18 +171,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: true } : {}),
...(filePaths && filePaths.length > 0 ? { filePaths } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
},
...(onProgress ? [{ onProgress }] : []),
);
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
@@ -177,19 +195,31 @@ 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 });
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
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,
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["createWorktree"]>[0],
) => ensureNativeApi().git.createWorktree(args),
onSuccess: async () => {
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
@@ -197,11 +227,13 @@ 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,
mutationFn: (
args: Parameters<ReturnType<typeof ensureNativeApi>["git"]["removeWorktree"]>[0],
) => ensureNativeApi().git.removeWorktree(args),
onSuccess: async () => {
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
@@ -212,23 +244,18 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
queryClient: QueryClient;
}) {
return mutationOptions({
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
mutationFn: async (args: {
reference: string;
mode: "local" | "worktree";
threadId?: ThreadId;
}) => {
mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {
const api = ensureNativeApi();
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
return api.git.preparePullRequestThread({
cwd: input.cwd,
reference: args.reference,
mode: args.mode,
...(args.threadId ? { threadId: args.threadId } : {}),
reference,
mode,
});
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.cwd);
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
onSettled: async () => {
await invalidateGitQueries(input.queryClient);
},
});
}
-112
View File
@@ -1,112 +0,0 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
getGitStatusSnapshot,
resetGitStatusStateForTests,
refreshGitStatus,
watchGitStatus,
} from "./gitStatusState";
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const gitClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
};
function emitGitStatus(event: GitStatusResult) {
for (const listener of gitStatusListeners) {
listener(event);
}
}
afterEach(() => {
gitStatusListeners.clear();
gitClient.onStatus.mockClear();
gitClient.refreshStatus.mockClear();
resetGitStatusStateForTests();
});
describe("gitStatusState", () => {
it("starts fresh cwd state in a pending state", () => {
expect(getGitStatusSnapshot("/fresh")).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
});
it("shares one live subscription per cwd and updates the per-cwd atom snapshot", () => {
const releaseA = watchGitStatus("/repo", gitClient);
const releaseB = watchGitStatus("/repo", gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(getGitStatusSnapshot("/repo")).toEqual({
data: null,
error: null,
cause: null,
isPending: true,
});
emitGitStatus(BASE_STATUS);
expect(getGitStatusSnapshot("/repo")).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
releaseA();
expect(gitStatusListeners.size).toBe(1);
releaseB();
expect(gitStatusListeners.size).toBe(0);
});
it("refreshes git status through the unary RPC without restarting the stream", async () => {
const release = watchGitStatus("/repo", gitClient);
emitGitStatus(BASE_STATUS);
const refreshed = await refreshGitStatus("/repo", gitClient);
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
expect(getGitStatusSnapshot("/repo")).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
});
-223
View File
@@ -1,223 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { type GitManagerServiceError, type GitStatusResult } from "@t3tools/contracts";
import { Cause } from "effect";
import { Atom } from "effect/unstable/reactivity";
import { useEffect } from "react";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { getWsRpcClient, type WsRpcClient } from "../wsRpcClient";
export type GitStatusStreamError = GitManagerServiceError;
export interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitStatusStreamError | null;
readonly cause: Cause.Cause<GitStatusStreamError> | null;
readonly isPending: boolean;
}
type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
interface WatchedGitStatus {
refCount: number;
unsubscribe: () => void;
}
const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
...EMPTY_GIT_STATUS_STATE,
isPending: true,
});
const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
);
const NOOP: () => void = () => undefined;
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
const knownGitStatusCwds = new Set<string>();
const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
const gitStatusLastRefreshAtByCwd = new Map<string, number>();
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
let sharedGitStatusClient: GitStatusClient | null = null;
const gitStatusStateAtom = Atom.family((cwd: string) => {
knownGitStatusCwds.add(cwd);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${cwd}`),
);
});
export function getGitStatusSnapshot(cwd: string | null): GitStatusState {
if (cwd === null) {
return EMPTY_GIT_STATUS_STATE;
}
return appAtomRegistry.get(gitStatusStateAtom(cwd));
}
export function watchGitStatus(
cwd: string | null,
client: GitStatusClient = getWsRpcClient().git,
): () => void {
if (cwd === null) {
return NOOP;
}
ensureGitStatusClient(client);
const watched = watchedGitStatuses.get(cwd);
if (watched) {
watched.refCount += 1;
return () => unwatchGitStatus(cwd);
}
watchedGitStatuses.set(cwd, {
refCount: 1,
unsubscribe: subscribeToGitStatus(cwd),
});
return () => unwatchGitStatus(cwd);
}
export function refreshGitStatus(
cwd: string | null,
client: GitStatusClient = getWsRpcClient().git,
): Promise<GitStatusResult | null> {
if (cwd === null) {
return Promise.resolve(null);
}
ensureGitStatusClient(client);
const currentInFlight = gitStatusRefreshInFlight.get(cwd);
if (currentInFlight) {
return currentInFlight;
}
const lastRequestedAt = gitStatusLastRefreshAtByCwd.get(cwd) ?? 0;
if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getGitStatusSnapshot(cwd).data);
}
gitStatusLastRefreshAtByCwd.set(cwd, Date.now());
const refreshPromise = client.refreshStatus({ cwd }).finally(() => {
gitStatusRefreshInFlight.delete(cwd);
});
gitStatusRefreshInFlight.set(cwd, refreshPromise);
return refreshPromise;
}
export function resetGitStatusStateForTests(): void {
for (const watched of watchedGitStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
gitStatusRefreshInFlight.clear();
gitStatusLastRefreshAtByCwd.clear();
sharedGitStatusClient = null;
for (const cwd of knownGitStatusCwds) {
appAtomRegistry.set(gitStatusStateAtom(cwd), INITIAL_GIT_STATUS_STATE);
}
knownGitStatusCwds.clear();
}
export function useGitStatus(cwd: string | null): GitStatusState {
useEffect(() => watchGitStatus(cwd), [cwd]);
const state = useAtomValue(cwd !== null ? gitStatusStateAtom(cwd) : EMPTY_GIT_STATUS_ATOM);
return cwd === null ? EMPTY_GIT_STATUS_STATE : state;
}
function ensureGitStatusClient(client: GitStatusClient): void {
if (sharedGitStatusClient === client) {
return;
}
if (sharedGitStatusClient !== null) {
resetLiveGitStatusSubscriptions();
}
sharedGitStatusClient = client;
}
function resetLiveGitStatusSubscriptions(): void {
for (const watched of watchedGitStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
}
function unwatchGitStatus(cwd: string): void {
const watched = watchedGitStatuses.get(cwd);
if (!watched) {
return;
}
watched.refCount -= 1;
if (watched.refCount > 0) {
return;
}
watched.unsubscribe();
watchedGitStatuses.delete(cwd);
}
function subscribeToGitStatus(cwd: string): () => void {
const client = sharedGitStatusClient;
if (!client) {
return NOOP;
}
markGitStatusPending(cwd);
return client.onStatus(
{ cwd },
(status) => {
appAtomRegistry.set(gitStatusStateAtom(cwd), {
data: status,
error: null,
cause: null,
isPending: false,
});
},
{
onResubscribe: () => {
markGitStatusPending(cwd);
},
},
);
}
function markGitStatusPending(cwd: string): void {
const atom = gitStatusStateAtom(cwd);
const current = appAtomRegistry.get(atom);
const next =
current.data === null
? INITIAL_GIT_STATUS_STATE
: {
...current,
error: null,
cause: null,
isPending: true,
};
if (
current.data === next.data &&
current.error === next.error &&
current.cause === next.cause &&
current.isPending === next.isPending
) {
return;
}
appAtomRegistry.set(atom, next);
}
+2 -2
View File
@@ -25,7 +25,7 @@ export function ensureNativeApi(): NativeApi {
return api;
}
export async function __resetNativeApiForTests() {
export function __resetNativeApiForTests() {
cachedApi = undefined;
await __resetWsNativeApiForTests();
__resetWsNativeApiForTests();
}
-147
View File
@@ -1,147 +0,0 @@
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);
}
+4 -177
View File
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
createOrchestrationRecoveryCoordinator,
deriveReplayRetryDecision,
} from "./orchestrationRecovery";
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
describe("createOrchestrationRecoveryCoordinator", () => {
it("defers live events until bootstrap completes and then requests replay", () => {
@@ -62,13 +59,10 @@ describe("createOrchestrationRecoveryCoordinator", () => {
coordinator.classifyDomainEvent(7);
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
expect(coordinator.completeReplayRecovery()).toEqual({
replayMadeProgress: true,
shouldReplay: true,
});
expect(coordinator.completeReplayRecovery()).toBe(true);
});
it("retries replay when no progress was made but higher live sequences were observed", () => {
it("does not immediately replay again when replay returns no new events", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
@@ -76,10 +70,7 @@ describe("createOrchestrationRecoveryCoordinator", () => {
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
expect(coordinator.completeReplayRecovery()).toEqual({
replayMadeProgress: false,
shouldReplay: true,
});
expect(coordinator.completeReplayRecovery()).toBe(false);
expect(coordinator.getState()).toMatchObject({
latestSequence: 3,
highestObservedSequence: 5,
@@ -88,19 +79,6 @@ describe("createOrchestrationRecoveryCoordinator", () => {
});
});
it("does not request another replay when a replay made no progress and nothing newer was observed", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.beginReplayRecovery("sequence-gap");
expect(coordinator.completeReplayRecovery()).toEqual({
replayMadeProgress: false,
shouldReplay: false,
});
});
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
@@ -153,154 +131,3 @@ describe("createOrchestrationRecoveryCoordinator", () => {
});
});
});
describe("deriveReplayRetryDecision", () => {
it("retries immediately when replay made progress", () => {
expect(
deriveReplayRetryDecision({
previousTracker: {
attempts: 2,
latestSequence: 3,
highestObservedSequence: 5,
},
completion: {
replayMadeProgress: true,
shouldReplay: true,
},
recoveryState: {
latestSequence: 5,
highestObservedSequence: 5,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
}),
).toEqual({
shouldRetry: true,
delayMs: 0,
tracker: null,
});
});
it("caps no-progress retries for the same frontier", () => {
const first = deriveReplayRetryDecision({
previousTracker: null,
completion: {
replayMadeProgress: false,
shouldReplay: true,
},
recoveryState: {
latestSequence: 3,
highestObservedSequence: 5,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
});
const second = deriveReplayRetryDecision({
previousTracker: first.tracker,
completion: {
replayMadeProgress: false,
shouldReplay: true,
},
recoveryState: {
latestSequence: 3,
highestObservedSequence: 5,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
});
const third = deriveReplayRetryDecision({
previousTracker: second.tracker,
completion: {
replayMadeProgress: false,
shouldReplay: true,
},
recoveryState: {
latestSequence: 3,
highestObservedSequence: 5,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
});
const fourth = deriveReplayRetryDecision({
previousTracker: third.tracker,
completion: {
replayMadeProgress: false,
shouldReplay: true,
},
recoveryState: {
latestSequence: 3,
highestObservedSequence: 5,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
});
expect(first).toEqual({
shouldRetry: true,
delayMs: 100,
tracker: {
attempts: 1,
latestSequence: 3,
highestObservedSequence: 5,
},
});
expect(second).toEqual({
shouldRetry: true,
delayMs: 200,
tracker: {
attempts: 2,
latestSequence: 3,
highestObservedSequence: 5,
},
});
expect(third).toEqual({
shouldRetry: true,
delayMs: 400,
tracker: {
attempts: 3,
latestSequence: 3,
highestObservedSequence: 5,
},
});
expect(fourth).toEqual({
shouldRetry: false,
delayMs: 0,
tracker: null,
});
});
it("resets the retry budget when the replay frontier changes", () => {
const exhausted = {
attempts: 3,
latestSequence: 3,
highestObservedSequence: 5,
};
expect(
deriveReplayRetryDecision({
previousTracker: exhausted,
completion: {
replayMadeProgress: false,
shouldReplay: true,
},
recoveryState: {
latestSequence: 3,
highestObservedSequence: 6,
},
baseDelayMs: 100,
maxNoProgressRetries: 3,
}),
).toEqual({
shouldRetry: true,
delayMs: 100,
tracker: {
attempts: 1,
latestSequence: 3,
highestObservedSequence: 6,
},
});
});
});
+7 -77
View File
@@ -1,8 +1,4 @@
export type OrchestrationRecoveryReason =
| "bootstrap"
| "sequence-gap"
| "resubscribe"
| "replay-failed";
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
export interface OrchestrationRecoveryPhase {
kind: "snapshot" | "replay";
@@ -17,74 +13,8 @@ export interface OrchestrationRecoveryState {
inFlight: OrchestrationRecoveryPhase | null;
}
export interface ReplayRecoveryCompletion {
replayMadeProgress: boolean;
shouldReplay: boolean;
}
export interface ReplayRetryTracker {
attempts: number;
latestSequence: number;
highestObservedSequence: number;
}
export interface ReplayRetryDecision {
shouldRetry: boolean;
delayMs: number;
tracker: ReplayRetryTracker | null;
}
type SequencedEvent = Readonly<{ sequence: number }>;
export function deriveReplayRetryDecision(input: {
previousTracker: ReplayRetryTracker | null;
completion: ReplayRecoveryCompletion;
recoveryState: Pick<OrchestrationRecoveryState, "latestSequence" | "highestObservedSequence">;
baseDelayMs: number;
maxNoProgressRetries: number;
}): ReplayRetryDecision {
if (!input.completion.shouldReplay) {
return {
shouldRetry: false,
delayMs: 0,
tracker: null,
};
}
if (input.completion.replayMadeProgress) {
return {
shouldRetry: true,
delayMs: 0,
tracker: null,
};
}
const previousTracker = input.previousTracker;
const sameFrontier =
previousTracker !== null &&
previousTracker.latestSequence === input.recoveryState.latestSequence &&
previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence;
const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1;
if (attempts > input.maxNoProgressRetries) {
return {
shouldRetry: false,
delayMs: 0,
tracker: null,
};
}
return {
shouldRetry: true,
delayMs: input.baseDelayMs * 2 ** (attempts - 1),
tracker: {
attempts,
latestSequence: input.recoveryState.latestSequence,
highestObservedSequence: input.recoveryState.highestObservedSequence,
},
};
}
export function createOrchestrationRecoveryCoordinator() {
let state: OrchestrationRecoveryState = {
latestSequence: 0,
@@ -190,16 +120,16 @@ export function createOrchestrationRecoveryCoordinator() {
return true;
},
completeReplayRecovery(): ReplayRecoveryCompletion {
completeReplayRecovery(): boolean {
const replayMadeProgress =
replayStartSequence !== null && state.latestSequence > replayStartSequence;
replayStartSequence = null;
state.inFlight = null;
const replayResolution = resolveReplayNeedAfterRecovery();
return {
replayMadeProgress,
shouldReplay: replayResolution.shouldReplay,
};
if (!replayMadeProgress) {
state.pendingReplay = false;
return false;
}
return resolveReplayNeedAfterRecovery().shouldReplay;
},
failReplayRecovery(): void {
+3 -5
View File
@@ -1,15 +1,13 @@
import { describe, expect, it } from "vitest";
import {
projectScriptCwd,
projectScriptRuntimeEnv,
setupProjectScript,
} from "@t3tools/shared/projectScripts";
import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
} from "./projectScripts";
describe("projectScripts helpers", () => {
+36
View File
@@ -55,7 +55,43 @@ export function nextProjectScriptId(name: string, existingIds: Iterable<string>)
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
}
interface ProjectScriptRuntimeEnvInput {
project: {
cwd: string;
};
worktreePath?: string | null;
extraEnv?: Record<string, string>;
}
export function projectScriptCwd(input: {
project: {
cwd: string;
};
worktreePath?: string | null;
}): string {
return input.worktreePath ?? input.project.cwd;
}
export function projectScriptRuntimeEnv(
input: ProjectScriptRuntimeEnvInput,
): Record<string, string> {
const env: Record<string, string> = {
T3CODE_PROJECT_ROOT: input.project.cwd,
};
if (input.worktreePath) {
env.T3CODE_WORKTREE_PATH = input.worktreePath;
}
if (input.extraEnv) {
return { ...env, ...input.extraEnv };
}
return env;
}
export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
const regular = scripts.find((script) => !script.runOnWorktreeCreate);
return regular ?? scripts[0] ?? null;
}
export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
}
+2 -5
View File
@@ -5,7 +5,7 @@ import {
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { DEFAULT_CODEX_MODEL_CAPABILITIES, normalizeModelSlug } from "@t3tools/shared/model";
import { normalizeModelSlug } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -53,10 +53,7 @@ export function getProviderModelCapabilities(
provider: ProviderKind,
): ModelCapabilities {
const slug = normalizeModelSlug(model, provider);
const capabilities = models.find((candidate) => candidate.slug === slug)?.capabilities;
return (
capabilities ?? (provider === "codex" ? DEFAULT_CODEX_MODEL_CAPABILITIES : EMPTY_CAPABILITIES)
);
return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;
}
export function getDefaultServerModel(
+2 -2
View File
@@ -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", () => {
+1 -1
View File
@@ -22,7 +22,7 @@ export function parsePullRequestReference(input: string): string | null {
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
if (numberMatch?.[1]) {
return numberMatch[1];
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
}
return null;
+34 -78
View File
@@ -1,7 +1,7 @@
import {
OrchestrationEvent,
ThreadId,
type ServerLifecycleWelcomePayload,
type ThreadId,
} from "@t3tools/contracts";
import {
Outlet,
@@ -16,11 +16,6 @@ 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";
@@ -41,13 +36,13 @@ import {
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
import { deriveReplayRetryDecision } from "../orchestrationRecovery";
import { getWsRpcClient } from "~/wsRpcClient";
export const Route = createRootRouteWithContext<{
@@ -78,13 +73,9 @@ function RootRouteView() {
<AnchoredToastProvider>
<ServerStateBootstrap />
<EventRouter />
<WebSocketConnectionCoordinator />
<SlowRpcAckToastCoordinator />
<WebSocketConnectionSurface>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</WebSocketConnectionSurface>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</AnchoredToastProvider>
</ToastProvider>
);
@@ -198,9 +189,6 @@ function coalesceOrchestrationUiEvents(
return coalesced;
}
const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
function ServerStateBootstrap() {
useEffect(() => startServerStateSync(getWsRpcClient().server), []);
@@ -218,7 +206,6 @@ function EventRouter() {
const removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
const applyTerminalEvent = useTerminalStateStore((store) => store.applyTerminalEvent);
const queryClient = useQueryClient();
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
@@ -322,7 +309,6 @@ function EventRouter() {
let disposed = false;
disposedRef.current = false;
const recovery = createOrchestrationRecoveryCoordinator();
let replayRetryTracker: import("../orchestrationRecovery").ReplayRetryTracker | null = null;
let needsProviderInvalidation = false;
const pendingDomainEvents: OrchestrationEvent[] = [];
let flushPendingDomainEventsScheduled = false;
@@ -437,8 +423,8 @@ function EventRouter() {
queueMicrotask(flushPendingDomainEvents);
};
const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
if (!recovery.beginReplayRecovery(reason)) {
const recoverFromSequenceGap = async (): Promise<void> => {
if (!recovery.beginReplayRecovery("sequence-gap")) {
return;
}
@@ -449,42 +435,13 @@ function EventRouter() {
applyEventBatch(events);
}
} catch {
replayRetryTracker = null;
recovery.failReplayRecovery();
void fallbackToSnapshotRecovery();
return;
}
if (!disposed) {
const replayCompletion = recovery.completeReplayRecovery();
const retryDecision = deriveReplayRetryDecision({
previousTracker: replayRetryTracker,
completion: replayCompletion,
recoveryState: recovery.getState(),
baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
});
replayRetryTracker = retryDecision.tracker;
if (retryDecision.shouldRetry) {
if (retryDecision.delayMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, retryDecision.delayMs);
});
if (disposed) {
return;
}
}
void runReplayRecovery(reason);
} else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
console.warn(
"[orchestration-recovery]",
"Stopping replay recovery after no-progress retries.",
{
state: recovery.getState(),
},
);
}
if (!disposed && recovery.completeReplayRecovery()) {
void recoverFromSequenceGap();
}
};
@@ -514,7 +471,7 @@ function EventRouter() {
syncServerReadModel(snapshot);
reconcileSnapshotDerivedState();
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void runReplayRecovery("sequence-gap");
void recoverFromSequenceGap();
}
}
} catch {
@@ -531,35 +488,35 @@ 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 runReplayRecovery("sequence-gap");
}
},
{
onResubscribe: () => {
if (disposed) {
return;
}
flushPendingDomainEvents();
void runReplayRecovery("resubscribe");
},
},
);
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 unsubTerminalEvent = api.terminal.onEvent((event) => {
const thread = useStore.getState().threads.find((entry) => entry.id === event.threadId);
if (thread && thread.archivedAt !== null) {
return;
}
applyTerminalEvent(event);
useTerminalStateStore.getState().recordTerminalEvent(event);
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
if (hasRunningSubprocess === null) {
return;
}
useTerminalStateStore
.getState()
.setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
hasRunningSubprocess,
);
});
return () => {
disposed = true;
@@ -577,7 +534,6 @@ function EventRouter() {
queryClient,
removeTerminalState,
removeOrphanedTerminalStates,
applyTerminalEvent,
clearThreadUi,
setProjectExpanded,
syncProjects,
-48
View File
@@ -2,10 +2,6 @@ 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";
@@ -70,7 +66,6 @@ class MockWebSocket {
}
const originalWebSocket = globalThis.WebSocket;
const originalFetch = globalThis.fetch;
function getSocket(): MockWebSocket {
const socket = sockets.at(-1);
@@ -117,7 +112,6 @@ beforeEach(() => {
afterEach(() => {
__resetWsRpcAtomClientForTests();
globalThis.WebSocket = originalWebSocket;
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
@@ -234,46 +228,4 @@ 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 -11
View File
@@ -2,11 +2,6 @@ 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", {
@@ -21,22 +16,18 @@ function getRuntime() {
return sharedRuntime;
}
sharedRuntime = ManagedRuntime.make(Layer.mergeAll(WsRpcAtomClient.layer, ClientTracingLive));
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
return sharedRuntime;
}
export function runRpc<TSuccess, TError = never>(
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
): Promise<TSuccess> {
return configureClientTracing().then(() => {
const runtime = getRuntime();
return runtime.runPromise(WsRpcAtomClient.use(execute));
});
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
}
export async function __resetWsRpcAtomClientForTests() {
const runtime = sharedRuntime;
sharedRuntime = null;
await runtime?.dispose();
await __resetClientTracingForTests();
}
+5 -82
View File
@@ -1,22 +1,9 @@
import { WsRpcGroup } from "@t3tools/contracts";
import { Duration, Effect, Layer, Schedule } from "effect";
import { Effect, Layer } 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);
@@ -30,75 +17,11 @@ 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(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);
},
}),
),
Layer.provide(Socket.layerWebSocketConstructorGlobal),
);
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
return RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe(
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)),
);
}
@@ -1,65 +0,0 @@
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));
});
});
-133
View File
@@ -1,133 +0,0 @@
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);
}
-24
View File
@@ -1,24 +0,0 @@
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();
});
});
-23
View File
@@ -1,23 +0,0 @@
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);
}
-112
View File
@@ -1,112 +0,0 @@
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",
});
});
});
-219
View File
@@ -1,219 +0,0 @@
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",
};
}
+85 -94
View File
@@ -20,6 +20,7 @@ import {
findSidebarProposedPlan,
hasActionableProposedPlan,
hasToolActivityForTurn,
isSessionActivelyRunningTurn,
isLatestTurnSettled,
} from "./session-logic";
@@ -709,97 +710,6 @@ 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({
@@ -1163,15 +1073,30 @@ describe("isLatestTurnSettled", () => {
} as const;
it("returns false while the same turn is still active in a running session", () => {
expect(
isLatestTurnSettled(
{
...latestTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
),
).toBe(false);
});
it("returns true when the turn completed but the session status stayed stale-running", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
}),
).toBe(false);
).toBe(true);
});
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
it("returns false while a different turn is still running", () => {
expect(
isLatestTurnSettled(latestTurn, {
orchestrationStatus: "running",
@@ -1203,6 +1128,56 @@ describe("isLatestTurnSettled", () => {
});
});
describe("isSessionActivelyRunningTurn", () => {
const completedTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
startedAt: "2026-02-27T21:10:00.000Z",
completedAt: "2026-02-27T21:10:06.000Z",
} as const;
it("returns true when the current turn has not completed yet", () => {
expect(
isSessionActivelyRunningTurn(
{
...completedTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
),
).toBe(true);
});
it("returns false when the same turn already completed and only the session is stale", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
}),
).toBe(false);
});
it("returns true when a different turn is still active", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-2"),
}),
).toBe(true);
});
it("returns false when the session is not running", () => {
expect(
isSessionActivelyRunningTurn(completedTurn, {
orchestrationStatus: "ready",
activeTurnId: undefined,
}),
).toBe(false);
});
});
describe("deriveActiveWorkStartedAt", () => {
const latestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
@@ -1213,7 +1188,10 @@ describe("deriveActiveWorkStartedAt", () => {
it("prefers the in-flight turn start when the latest turn is not settled", () => {
expect(
deriveActiveWorkStartedAt(
latestTurn,
{
...latestTurn,
completedAt: null,
},
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
@@ -1223,6 +1201,19 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:10:00.000Z");
});
it("falls back to sendStartedAt when only the session status is stale-running", () => {
expect(
deriveActiveWorkStartedAt(
latestTurn,
{
orchestrationStatus: "running",
activeTurnId: TurnId.makeUnsafe("turn-1"),
},
"2026-02-27T21:11:00.000Z",
),
).toBe("2026-02-27T21:11:00.000Z");
});
it("falls back to sendStartedAt once the latest turn is settled", () => {
expect(
deriveActiveWorkStartedAt(
+30 -172
View File
@@ -38,7 +38,6 @@ export interface WorkLogEntry {
label: string;
detail?: string;
command?: string;
rawCommand?: string;
changedFiles?: ReadonlyArray<string>;
tone: "thinking" | "tool" | "info" | "error";
toolTitle?: string;
@@ -129,15 +128,30 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
export function isSessionActivelyRunningTurn(
latestTurn: LatestTurnTiming | null,
session: SessionActivityState | null,
): boolean {
if (!session || session.orchestrationStatus !== "running") return false;
if (!latestTurn) return true;
const activeTurnId = session.activeTurnId;
if (activeTurnId === undefined) {
return latestTurn.completedAt === null;
}
if (latestTurn.turnId !== activeTurnId) {
return true;
}
return latestTurn.completedAt === null;
}
export function isLatestTurnSettled(
latestTurn: LatestTurnTiming | null,
session: SessionActivityState | null,
): boolean {
if (!latestTurn?.startedAt) return false;
if (!latestTurn.completedAt) return false;
if (!session) return true;
if (session.orchestrationStatus === "running") return false;
return true;
return !isSessionActivelyRunningTurn(latestTurn, session);
}
export function deriveActiveWorkStartedAt(
@@ -490,7 +504,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const commandPreview = extractToolCommand(payload);
const command = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
const entry: DerivedWorkLogEntry = {
@@ -508,11 +522,8 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
entry.detail = detail;
}
}
if (commandPreview.command) {
entry.command = commandPreview.command;
}
if (commandPreview.rawCommand) {
entry.rawCommand = commandPreview.rawCommand;
if (command) {
entry.command = command;
}
if (changedFiles.length > 0) {
entry.changedFiles = changedFiles;
@@ -571,7 +582,6 @@ 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;
@@ -581,7 +591,6 @@ function mergeDerivedWorkLogEntries(
...next,
...(detail ? { detail } : {}),
...(command ? { command } : {}),
...(rawCommand ? { rawCommand } : {}),
...(changedFiles.length > 0 ? { changedFiles } : {}),
...(toolTitle ? { toolTitle } : {}),
...(itemType ? { itemType } : {}),
@@ -642,121 +651,7 @@ function asTrimmedString(value: unknown): string | null {
return trimmed.length > 0 ? trimmed : 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 {
function normalizeCommandValue(value: unknown): string | null {
const direct = asTrimmedString(value);
if (direct) {
return direct;
@@ -767,58 +662,21 @@ function formatCommandValue(value: unknown): string | null {
const parts = value
.map((entry) => asTrimmedString(entry))
.filter((entry): entry is string => entry !== null);
if (parts.length === 0) {
return null;
}
return parts.map((part) => formatCommandArrayPart(part)).join(" ");
return parts.length > 0 ? parts.join(" ") : 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;
} {
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
const data = asRecord(payload?.data);
const item = asRecord(data?.item);
const itemResult = asRecord(item?.result);
const itemInput = asRecord(item?.input);
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,
const candidates = [
normalizeCommandValue(item?.command),
normalizeCommandValue(itemInput?.command),
normalizeCommandValue(itemResult?.command),
normalizeCommandValue(data?.command),
];
for (const candidate of candidates) {
const command = normalizeCommandValue(candidate);
if (!command) {
continue;
}
return {
command,
rawCommand: toRawToolCommand(candidate, command),
};
}
return {
command: null,
rawCommand: null,
};
return candidates.find((candidate) => candidate !== null) ?? null;
}
function extractToolTitle(payload: Record<string, unknown> | null): string | null {
+2 -3
View File
@@ -19,7 +19,6 @@ import {
derivePendingApprovals,
derivePendingUserInputs,
} from "./session-logic";
import { sanitizeThreadErrorMessage } from "./rpc/transportError";
import { type ChatMessage, type Project, type SidebarThreadSummary, type Thread } from "./types";
// ── State ────────────────────────────────────────────────────────────
@@ -166,7 +165,7 @@ function mapThread(thread: OrchestrationThread): Thread {
session: thread.session ? mapSession(thread.session) : null,
messages: thread.messages.map(mapMessage),
proposedPlans: thread.proposedPlans.map(mapProposedPlan),
error: sanitizeThreadErrorMessage(thread.session?.lastError),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
archivedAt: thread.archivedAt,
updatedAt: thread.updatedAt,
@@ -895,7 +894,7 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
return updateThreadState(state, event.payload.threadId, (thread) => ({
...thread,
session: mapSession(event.payload.session),
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
error: event.payload.session.lastError ?? null,
latestTurn:
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
? buildLatestTurn({
-1
View File
@@ -7,7 +7,6 @@ const snapshot: TerminalSessionSnapshot = {
threadId: "thread-1",
terminalId: "default",
cwd: "/tmp",
worktreePath: null,
status: "running",
pid: 1234,
history: "",
-97
View File
@@ -39,7 +39,6 @@ function makeTerminalEvent(
threadId: THREAD_ID,
terminalId: "default",
cwd: "/tmp/workspace",
worktreePath: null,
status: "running",
pid: 123,
history: "",
@@ -57,7 +56,6 @@ describe("terminalStateStore actions", () => {
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
@@ -134,23 +132,6 @@ describe("terminalStateStore actions", () => {
]);
});
it("ensures unknown server terminals are registered, opened, and activated", () => {
const store = useTerminalStateStore.getState();
store.ensureTerminal(THREAD_ID, "setup-setup", { open: true, active: true });
const terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
expect(terminalState.terminalOpen).toBe(true);
expect(terminalState.terminalIds).toEqual(["default", "setup-setup"]);
expect(terminalState.activeTerminalId).toBe("setup-setup");
expect(terminalState.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default"] },
{ id: "group-setup-setup", terminalIds: ["setup-setup"] },
]);
});
it("allows unlimited groups while keeping each group capped at four terminals", () => {
const store = useTerminalStateStore.getState();
store.splitTerminal(THREAD_ID, "terminal-2");
@@ -238,84 +219,6 @@ describe("terminalStateStore actions", () => {
expect(entries.map((entry) => entry.event.type)).toEqual(["output", "activity"]);
});
it("applies started terminal events to terminal state, launch context, and event buffer", () => {
const store = useTerminalStateStore.getState();
store.applyTerminalEvent(
makeTerminalEvent("started", {
terminalId: "setup-bootstrap",
snapshot: {
threadId: THREAD_ID,
terminalId: "setup-bootstrap",
cwd: "/tmp/worktree",
worktreePath: "/tmp/worktree",
status: "running",
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-04-02T20:00:00.000Z",
},
}),
);
const terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
const entries = selectTerminalEventEntries(
useTerminalStateStore.getState().terminalEventEntriesByKey,
THREAD_ID,
"setup-bootstrap",
);
expect(terminalState.terminalOpen).toBe(true);
expect(terminalState.activeTerminalId).toBe("setup-bootstrap");
expect(terminalState.terminalIds).toEqual(["default", "setup-bootstrap"]);
expect(useTerminalStateStore.getState().terminalLaunchContextByThreadId[THREAD_ID]).toEqual({
cwd: "/tmp/worktree",
worktreePath: "/tmp/worktree",
});
expect(entries).toHaveLength(1);
expect(entries[0]?.event.type).toBe("started");
});
it("applies activity and exited terminal events to subprocess state while buffering events", () => {
const store = useTerminalStateStore.getState();
store.ensureTerminal(THREAD_ID, "terminal-2", { open: true, active: true });
store.applyTerminalEvent(
makeTerminalEvent("activity", {
terminalId: "terminal-2",
hasRunningSubprocess: true,
}),
);
expect(
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
.runningTerminalIds,
).toEqual(["terminal-2"]);
store.applyTerminalEvent(
makeTerminalEvent("exited", {
terminalId: "terminal-2",
exitCode: 0,
exitSignal: null,
}),
);
const terminalState = selectThreadTerminalState(
useTerminalStateStore.getState().terminalStateByThreadId,
THREAD_ID,
);
const entries = selectTerminalEventEntries(
useTerminalStateStore.getState().terminalEventEntriesByKey,
THREAD_ID,
"terminal-2",
);
expect(terminalState.runningTerminalIds).toEqual([]);
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
});
it("clears buffered terminal events when a thread terminal state is removed", () => {
const store = useTerminalStateStore.getState();
store.recordTerminalEvent(makeTerminalEvent("output"));
+22 -166
View File
@@ -5,11 +5,10 @@
* API constrained to store actions/selectors.
*/
import { ThreadId, type TerminalEvent } from "@t3tools/contracts";
import type { TerminalEvent, ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -27,11 +26,6 @@ interface ThreadTerminalState {
activeTerminalGroupId: string;
}
export interface ThreadTerminalLaunchContext {
cwd: string;
worktreePath: string | null;
}
export interface TerminalEventEntry {
id: number;
event: TerminalEvent;
@@ -251,40 +245,6 @@ function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[
}));
}
function appendTerminalEventEntry(
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>,
nextTerminalEventId: number,
event: TerminalEvent,
) {
const key = terminalEventBufferKey(ThreadId.makeUnsafe(event.threadId), event.terminalId);
const currentEntries = terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES;
const nextEntry: TerminalEventEntry = {
id: nextTerminalEventId,
event,
};
const nextEntries =
currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER
? [...currentEntries.slice(1), nextEntry]
: [...currentEntries, nextEntry];
return {
terminalEventEntriesByKey: {
...terminalEventEntriesByKey,
[key]: nextEntries,
},
nextTerminalEventId: nextTerminalEventId + 1,
};
}
function launchContextFromStartEvent(
event: Extract<TerminalEvent, { type: "started" | "restarted" }>,
): ThreadTerminalLaunchContext {
return {
cwd: event.snapshot.cwd,
worktreePath: event.snapshot.worktreePath,
};
}
function upsertTerminalIntoGroups(
state: ThreadTerminalState,
terminalId: string,
@@ -538,29 +498,20 @@ export function selectTerminalEventEntries(
interface TerminalStateStoreState {
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
terminalLaunchContextByThreadId: Record<ThreadId, ThreadTerminalLaunchContext>;
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>;
nextTerminalEventId: number;
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
setTerminalHeight: (threadId: ThreadId, height: number) => void;
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
newTerminal: (threadId: ThreadId, terminalId: string) => void;
ensureTerminal: (
threadId: ThreadId,
terminalId: string,
options?: { open?: boolean; active?: boolean },
) => void;
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
setTerminalLaunchContext: (threadId: ThreadId, context: ThreadTerminalLaunchContext) => void;
clearTerminalLaunchContext: (threadId: ThreadId) => void;
setTerminalActivity: (
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
) => void;
recordTerminalEvent: (event: TerminalEvent) => void;
applyTerminalEvent: (event: TerminalEvent) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
@@ -590,7 +541,6 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
return {
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
setTerminalOpen: (threadId, open) =>
@@ -601,104 +551,33 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
newTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
ensureTerminal: (threadId, terminalId, options) =>
updateTerminal(threadId, (state) => {
let nextState = state;
if (!state.terminalIds.includes(terminalId)) {
nextState = newThreadTerminal(nextState, terminalId);
}
if (options?.active === false) {
nextState = {
...nextState,
activeTerminalId: state.activeTerminalId,
activeTerminalGroupId: state.activeTerminalGroupId,
};
}
if (options?.active ?? true) {
nextState = setThreadActiveTerminal(nextState, terminalId);
}
if (options?.open) {
nextState = setThreadTerminalOpen(nextState, true);
}
return normalizeThreadTerminalState(nextState);
}),
setActiveTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
closeTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
setTerminalLaunchContext: (threadId, context) =>
set((state) => ({
terminalLaunchContextByThreadId: {
...state.terminalLaunchContextByThreadId,
[threadId]: context,
},
})),
clearTerminalLaunchContext: (threadId) =>
set((state) => {
if (!state.terminalLaunchContextByThreadId[threadId]) {
return state;
}
const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId;
return { terminalLaunchContextByThreadId: rest };
}),
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
updateTerminal(threadId, (state) =>
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
),
recordTerminalEvent: (event) =>
set((state) =>
appendTerminalEventEntry(
state.terminalEventEntriesByKey,
state.nextTerminalEventId,
event,
),
),
applyTerminalEvent: (event) =>
set((state) => {
const threadId = ThreadId.makeUnsafe(event.threadId);
let nextTerminalStateByThreadId = state.terminalStateByThreadId;
let nextTerminalLaunchContextByThreadId = state.terminalLaunchContextByThreadId;
if (event.type === "started" || event.type === "restarted") {
nextTerminalStateByThreadId = updateTerminalStateByThreadId(
nextTerminalStateByThreadId,
threadId,
(current) => {
let nextState = current;
if (!current.terminalIds.includes(event.terminalId)) {
nextState = newThreadTerminal(nextState, event.terminalId);
}
nextState = setThreadActiveTerminal(nextState, event.terminalId);
nextState = setThreadTerminalOpen(nextState, true);
return normalizeThreadTerminalState(nextState);
},
);
nextTerminalLaunchContextByThreadId = {
...nextTerminalLaunchContextByThreadId,
[threadId]: launchContextFromStartEvent(event),
};
}
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
if (hasRunningSubprocess !== null) {
nextTerminalStateByThreadId = updateTerminalStateByThreadId(
nextTerminalStateByThreadId,
threadId,
(current) =>
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
);
}
const nextEventState = appendTerminalEventEntry(
state.terminalEventEntriesByKey,
state.nextTerminalEventId,
const key = terminalEventBufferKey(event.threadId as ThreadId, event.terminalId);
const currentEntries =
state.terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES;
const nextEntry: TerminalEventEntry = {
id: state.nextTerminalEventId,
event,
);
};
const nextEntries =
currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER
? [...currentEntries.slice(1), nextEntry]
: [...currentEntries, nextEntry];
return {
terminalStateByThreadId: nextTerminalStateByThreadId,
terminalLaunchContextByThreadId: nextTerminalLaunchContextByThreadId,
...nextEventState,
terminalEventEntriesByKey: {
...state.terminalEventEntriesByKey,
[key]: nextEntries,
},
nextTerminalEventId: state.nextTerminalEventId + 1,
};
}),
clearTerminalState: (threadId) =>
@@ -708,9 +587,6 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
threadId,
() => createDefaultThreadTerminalState(),
);
const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined;
const { [threadId]: _removed, ...remainingLaunchContexts } =
state.terminalLaunchContextByThreadId;
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
let removedEventEntries = false;
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
@@ -721,21 +597,18 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
}
if (
nextTerminalStateByThreadId === state.terminalStateByThreadId &&
!hadLaunchContext &&
!removedEventEntries
) {
return state;
}
return {
terminalStateByThreadId: nextTerminalStateByThreadId,
terminalLaunchContextByThreadId: remainingLaunchContexts,
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
};
}),
removeTerminalState: (threadId) =>
set((state) => {
const hadTerminalState = state.terminalStateByThreadId[threadId] !== undefined;
const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined;
const hasThreadState = state.terminalStateByThreadId[threadId] !== undefined;
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
let removedEventEntries = false;
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
@@ -744,16 +617,13 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
removedEventEntries = true;
}
}
if (!hadTerminalState && !hadLaunchContext && !removedEventEntries) {
if (!hasThreadState && !removedEventEntries) {
return state;
}
const nextTerminalStateByThreadId = { ...state.terminalStateByThreadId };
delete nextTerminalStateByThreadId[threadId];
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId };
delete nextLaunchContexts[threadId];
const next = { ...state.terminalStateByThreadId };
delete next[threadId];
return {
terminalStateByThreadId: nextTerminalStateByThreadId,
terminalLaunchContextByThreadId: nextLaunchContexts,
terminalStateByThreadId: next,
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
};
}),
@@ -762,9 +632,6 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
(id) => !activeThreadIds.has(id as ThreadId),
);
const orphanedLaunchContextIds = Object.keys(
state.terminalLaunchContextByThreadId,
).filter((id) => !activeThreadIds.has(id as ThreadId));
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
let removedEventEntries = false;
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
@@ -774,24 +641,13 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
removedEventEntries = true;
}
}
if (
orphanedIds.length === 0 &&
orphanedLaunchContextIds.length === 0 &&
!removedEventEntries
) {
return state;
}
if (orphanedIds.length === 0 && !removedEventEntries) return state;
const next = { ...state.terminalStateByThreadId };
for (const id of orphanedIds) {
delete next[id as ThreadId];
}
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId };
for (const id of orphanedLaunchContextIds) {
delete nextLaunchContexts[id as ThreadId];
}
return {
terminalStateByThreadId: next,
terminalLaunchContextByThreadId: nextLaunchContexts,
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
};
}),
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more