Compare commits

..
Author SHA1 Message Date
Ben Davis 4db64afccc Use Codex defaults for custom model capabilities
- Apply standard Codex capabilities to custom Codex models
- Keep provider and composer UI behavior consistent for custom models
- Add coverage for custom Codex model defaults
2026-04-06 14:24:05 -07:00
sonderandJulius Marminge c6f57a1064 Rename "Chat" to "Build" in interaction mode toggle (#1769)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-06 17:29:58 +00:00
legs 340dbbb36e fix(web): unwrap windows shell command wrappers (#1719) 2026-04-06 17:19:27 +00:00
Julius Marmingeandcodex 53a552e80d Stream git status updates over WebSocket (#1763)
Co-authored-by: codex <[email protected]>
2026-04-06 09:26:29 -07:00
Julius Marminge cf2c628bc0 Use active worktree path for workspace saves (#1762) 2026-04-05 11:22:24 -07:00
Julius Marminge e0874b651d Raise slow RPC ack warning threshold to 15s (#1760) 2026-04-05 16:53:53 +00:00
Danila Yudin 12347082ef [codex] Fix marketing download fallback links (#1747) 2026-04-04 23:25:43 -07:00
Julius Marmingeandcodex 740d7a3216 Use lazy stream accessors for provider runtime events (#1746)
Co-authored-by: codex <[email protected]>
2026-04-04 23:22:55 -07:00
Danila Yudin cd7980b457 [codex] Canonicalize PR number references (#1749) 2026-04-04 19:56:26 -07:00
f2cd53f232 Add WebSocket disconnect recovery and slow RPC toast UX (#1730)
Co-authored-by: Hwanseo Choi <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-04 17:12:49 -07:00
Julius Marmingeandcodex 04a1ae77e6 Proxy browser OTLP traces through the server (#1739)
Co-authored-by: codex <[email protected]>
2026-04-04 13:01:51 -07:00
Julius Marminge 6de4b47ecb Return replay retry state from orchestration recovery (#1728) 2026-04-03 22:05:33 -07:00
27c2b145f8 feat(cli): allow optional positional cwd argument (#1727)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-03 19:49:10 -07:00
8515f02770 Move worktree bootstrap to the server and persist terminal launch context (#1518)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-03 19:49:01 -07:00
Julius Marmingeandcodex e9ed849b53 Persist server OTLP tracing settings across restarts (#1705)
Co-authored-by: codex <[email protected]>
2026-04-02 20:33:30 -07:00
Julius Marmingeandcodex e8f5b4ad5b [codex] Revert stale send spinner fix (#1704)
Co-authored-by: codex <[email protected]>
2026-04-02 20:19:58 -07:00
Julius Marmingeandcodex 752f96e9ae Add server observability tracing and metrics (#1697)
Co-authored-by: codex <[email protected]>
2026-04-03 02:30:51 +00:00
c1yde3 1b272fd709 feat: support IntelliJ IDEA open-in launch (#1673) 2026-04-02 23:57:09 +00:00
Julius Marminge 9013c07f6d Clean up terminal state when threads are archived (#1702) 2026-04-02 16:26:18 -07:00
Vakhtang Vakhtangishvili 085340588a Fix scroll to bottom button flickering near bottom of the chat (#1692) 2026-04-02 23:04:47 +00:00
Harry 48481aa923 Fix stale send spinner after completed turns (#1700) 2026-04-02 22:59:27 +00:00
Julius Marminge da107f315c Fix websocket closing and reopening connections too eagerly (#1701) 2026-04-02 15:56:53 -07:00
IshanandJulius Marminge d2822a8883 fix: use explicit refspec for push in worktrees with slashed branch names (#1684)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 15:29:30 -07:00
Svilen Petrov ae3ea3980d Clicking logo now navigates to threads (#1617) 2026-04-02 21:45:34 +00:00
915a0548c0 Paginate git branch listing and search results (#1691)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 12:38:19 -07:00
Julius Marminge 5ce5472bc3 Scope git action progress toasts to the originating thread (#1675) 2026-04-02 11:39:27 -07:00
Julius Marminge 9ea443d73a Split PR creation into granular progress stages (#1694) 2026-04-02 11:24:24 -07:00
60f7ae86bb Add copy-to-clipboard action for proposed plan card (#1620)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-04-02 00:47:47 -07:00
Julius Marmingeandcodex 867cf4cf09 fix: stabilize messages timeline virtualization (#1664)
Co-authored-by: codex <[email protected]>
2026-04-02 00:10:34 -07:00
Julius MarmingeandCursor Agent ae6f9715c6 Normalize sidebar thread state for faster updates (#1668)
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 23:56:40 +00:00
Julius Marminge b92c78f552 Scope git query invalidation by cwd (#1670) 2026-04-01 23:52:28 +00:00
801dfe5b41 [codex] fix git remote parsing, PR resolution, and sidebar PR state (#1619)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-01 16:13:19 -07:00
169 changed files with 16292 additions and 2507 deletions

No files matched your search

+2
View File
@@ -45,6 +45,8 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+34 -1
View File
@@ -28,6 +28,7 @@ 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";
@@ -76,6 +77,7 @@ 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";
@@ -99,8 +101,10 @@ 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,
@@ -121,6 +125,21 @@ 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;
@@ -988,6 +1007,7 @@ 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}`);
@@ -1016,6 +1036,12 @@ function startBackend(): void {
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
...(backendObservabilitySettings.otlpMetricsUrl
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
: {}),
})}\n`,
);
bootstrapStream.end();
@@ -1042,21 +1068,26 @@ 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) return;
if (isQuitting || wasExpected) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
@@ -1073,6 +1104,7 @@ 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) {
@@ -1093,6 +1125,7 @@ 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;
+5 -4
View File
@@ -1,5 +1,6 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href="#">
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href="#">
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href="#">
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
@@ -48,7 +48,7 @@ import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointRea
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
@@ -297,7 +297,7 @@ export const makeOrchestrationIntegrationHarness = (
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusLive,
RuntimeReceiptBusTest,
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
@@ -376,7 +376,7 @@ export const makeOrchestrationIntegrationHarness = (
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
@@ -86,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
@@ -104,7 +105,6 @@ const runTurn = (input: {
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
@@ -116,7 +116,7 @@ const runTurn = (input: {
);
});
it.effect("replays typed runtime fixture events", () =>
it.live("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
@@ -149,7 +149,7 @@ it.effect("replays typed runtime fixture events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("replays file-changing fixture turn events", () =>
it.live("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -188,7 +188,7 @@ it.effect("replays file-changing fixture turn events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("runs multi-turn tool/approval flow", () =>
it.live("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -242,7 +242,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("rolls back provider conversation state only", () =>
it.live("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -80,7 +80,7 @@ function initRepoWithCommit(
});
}
function buildLargeText(lineCount = 20_000): string {
function buildLargeText(lineCount = 5_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 19999");
expect(diff).toContain("+line 04999");
}),
);
});
+93
View File
@@ -9,6 +9,18 @@ import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
} as const;
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
@@ -28,6 +40,7 @@ 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(),
@@ -62,6 +75,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Warn",
...defaultObservabilityConfig,
mode: "desktop",
port: 4001,
cwd: process.cwd(),
@@ -89,6 +103,7 @@ 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"),
@@ -123,6 +138,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Debug",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
@@ -153,6 +169,8 @@ 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"));
@@ -162,6 +180,7 @@ 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(),
@@ -187,6 +206,9 @@ 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(),
@@ -209,6 +231,7 @@ 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(
{
@@ -216,6 +239,7 @@ 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(),
@@ -234,6 +258,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
);
for (const directory of [
customCwd,
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
@@ -241,9 +266,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
resolved.attachmentsDir,
resolved.worktreesDir,
path.dirname(resolved.serverLogPath),
path.dirname(resolved.serverTracePath),
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
expect(resolved.cwd).toBe(path.resolve(customCwd));
}),
);
@@ -270,6 +297,7 @@ 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"),
@@ -300,6 +328,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved).toEqual({
logLevel: "Debug",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
@@ -315,4 +344,68 @@ 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,
});
}),
);
});
+80 -4
View File
@@ -1,6 +1,7 @@
import { NetService } from "@t3tools/shared/Net";
import { Config, Effect, LogLevel, Option, Schema } from "effect";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
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 {
DEFAULT_PORT,
@@ -12,7 +13,7 @@ import {
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { resolveBaseDir } from "./os-jank";
import { expandHomePath, resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -27,6 +28,8 @@ 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(
@@ -81,6 +84,27 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -116,6 +140,7 @@ 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>;
@@ -131,12 +156,25 @@ 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>,
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const env = yield* EnvServerConfig;
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -188,8 +226,16 @@ 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(
flags.noBrowser,
Option.getOrElse(
@@ -248,11 +294,35 @@ export const resolveServerConfig = (
const config: ServerConfigShape = {
logLevel,
traceMinLevel: env.traceMinLevel,
traceTimingEnabled: env.traceTimingEnabled,
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,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
mode,
port,
cwd: process.cwd(),
cwd,
baseDir,
...derivedPaths,
serverTracePath,
host,
staticDir,
devUrl,
@@ -270,6 +340,12 @@ 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,
+20
View File
@@ -25,6 +25,7 @@ export interface ServerDerivedPaths {
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly serverTracePath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
@@ -36,6 +37,15 @@ export interface ServerDerivedPaths {
*/
export interface ServerConfigShape extends ServerDerivedPaths {
readonly logLevel: LogLevel.LogLevel;
readonly traceMinLevel: LogLevel.LogLevel;
readonly traceTimingEnabled: boolean;
readonly traceBatchWindowMs: number;
readonly traceMaxBytes: number;
readonly traceMaxFiles: number;
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
readonly otlpExportIntervalMs: number;
readonly otlpServiceName: string;
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
@@ -68,6 +78,7 @@ export const deriveServerPaths = Effect.fn(function* (
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
serverTracePath: join(logsDir, "server.trace.ndjson"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
@@ -117,6 +128,15 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
return {
logLevel: "Error",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
cwd,
baseDir,
...derivedPaths,
+73 -1
View File
@@ -386,6 +386,36 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("paginates branch results and returns paging metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });
const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });
expect(firstPage.totalCount).toBe(4);
expect(firstPage.nextCursor).toBe(2);
expect(firstPage.branches.map((branch) => branch.name)).toEqual([
initialBranch,
"feature-a",
]);
const secondPage = yield* (yield* GitCore).listBranches({
cwd: tmp,
cursor: firstPage.nextCursor ?? 0,
limit: 2,
});
expect(secondPage.totalCount).toBe(4);
expect(secondPage.nextCursor).toBeNull();
expect(secondPage.branches.map((branch) => branch.name)).toEqual([
"feature-b",
"feature-c",
]);
}),
);
it.effect("parses separate branch names when column.ui is always enabled", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -531,6 +561,41 @@ it.layer(TestLayer)("git integration", (it) => {
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
it.effect(
"filters branch queries before pagination and dedupes origin refs with local matches",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
const result = yield* (yield* GitCore).listBranches({
cwd: tmp,
query: "feature/",
limit: 10,
});
expect(result.totalCount).toBe(2);
expect(result.nextCursor).toBeNull();
expect(result.branches.map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
}),
);
});
// ── checkoutGitBranch ──
@@ -737,6 +802,9 @@ it.layer(TestLayer)("git integration", (it) => {
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
@@ -800,6 +868,9 @@ it.layer(TestLayer)("git integration", (it) => {
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
@@ -878,11 +949,12 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* (yield* GitCore).checkoutBranch({
const checkoutResult = yield* (yield* GitCore).checkoutBranch({
cwd: source,
branch: `${remoteName}/${featureBranch}`,
});
expect(checkoutResult.branch).toBe("upstream/feature");
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
+194 -27
View File
@@ -18,7 +18,10 @@ import {
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { compactTraceAttributes } from "../../observability/Attributes.ts";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
import {
GitCore,
type ExecuteGitProgress,
@@ -49,6 +52,7 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
type TraceTailState = {
processedChars: number;
@@ -183,6 +187,40 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
};
}
function filterBranchesForListQuery(
branches: ReadonlyArray<GitBranch>,
query?: string,
): ReadonlyArray<GitBranch> {
if (!query) {
return branches;
}
const normalizedQuery = query.toLowerCase();
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
}
function paginateBranches(input: {
branches: ReadonlyArray<GitBranch>;
cursor?: number | undefined;
limit?: number | undefined;
}): {
branches: ReadonlyArray<GitBranch>;
nextCursor: number | null;
totalCount: number;
} {
const cursor = input.cursor ?? 0;
const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
const totalCount = input.branches.length;
const branches = input.branches.slice(cursor, cursor + limit);
const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null;
return {
branches,
nextCursor,
totalCount,
};
}
function sanitizeRemoteName(value: string): string {
const sanitized = value
.trim()
@@ -336,6 +374,18 @@ interface Trace2Monitor {
readonly flush: Effect.Effect<void, never>;
}
const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
Effect.currentSpan.pipe(
Effect.tap((span) =>
Effect.sync(() => {
span.event(name, nowUnixNano(), compactTraceAttributes(attributes));
}),
),
Effect.catch(() => Effect.void),
);
function trace2ChildKey(record: Record<string, unknown>): string | null {
const childId = record.child_id;
if (typeof childId === "number" || typeof childId === "string") {
@@ -408,6 +458,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_start") {
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
yield* addCurrentSpanEvent("git.hook.started", {
hookName,
});
if (progress.onHookStarted) {
yield* progress.onHookStarted(hookName);
}
@@ -416,12 +469,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_exit") {
hookStartByChildKey.delete(childKey);
const code = traceRecord.success.code;
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null;
yield* addCurrentSpanEvent("git.hook.finished", {
hookName: started?.hookName ?? hookName,
exitCode,
durationMs,
});
if (progress.onHookFinished) {
const code = traceRecord.success.code;
yield* progress.onHookFinished({
hookName: started?.hookName ?? hookName,
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
exitCode,
durationMs,
});
}
}
@@ -573,13 +633,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const path = yield* Path.Path;
const { worktreesDir } = yield* ServerConfig;
let execute: GitCoreShape["execute"];
let executeRaw: GitCoreShape["execute"];
if (options?.executeOverride) {
execute = options.executeOverride;
executeRaw = options.executeOverride;
} else {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
execute = Effect.fnUntraced(function* (input) {
executeRaw = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
@@ -680,6 +740,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
const execute: GitCoreShape["execute"] = (input) =>
executeRaw(input).pipe(
withMetrics({
counter: gitCommandsTotal,
timer: gitCommandDuration,
attributes: {
operation: input.operation,
},
}),
Effect.withSpan(input.operation, {
kind: "client",
attributes: {
"git.operation": input.operation,
"git.cwd": input.cwd,
"git.args_count": input.args.length,
},
}),
);
const executeGit = (
operation: string,
cwd: string,
@@ -1098,18 +1177,53 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return branchLastCommit;
});
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
],
{ concurrency: "unbounded" },
const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
{
allowNonZeroExit: true,
},
);
if (statusResult.code !== 0) {
const stderr = statusResult.stderr.trim();
return yield* createGitCommandError(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
stderr || "git status failed",
);
}
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
"diff",
"--cached",
"--numstat",
]),
executeGit(
"GitCore.statusDetails.defaultRef",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
allowNonZeroExit: true,
},
),
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
],
{ concurrency: "unbounded" },
);
const statusStdout = statusResult.stdout;
const defaultBranch =
defaultRefResult.code === 0
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
@@ -1176,6 +1290,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
files.sort((a, b) => a.path.localeCompare(b.path));
return {
isRepo: true,
hasOriginRemote,
isDefaultBranch:
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master"))),
branch,
upstreamRef,
hasWorkingTreeChanges,
@@ -1190,9 +1310,23 @@ 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) => ({
isRepo: details.isRepo,
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
@@ -1341,7 +1475,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
"push",
"-u",
publishRemoteName,
branch,
`HEAD:refs/heads/${branch}`,
]);
return {
status: "pushed" as const,
@@ -1571,7 +1705,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false, hasOriginRemote: false };
return {
branches: [],
isRepo: false,
hasOriginRemote: false,
nextCursor: null,
totalCount: 0,
};
}
return yield* createGitCommandError(
"GitCore.listBranches",
@@ -1735,9 +1875,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
})
: [];
const branches = [...localBranches, ...remoteBranches];
const branches = paginateBranches({
branches: filterBranchesForListQuery(
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
input.query,
),
cursor: input.cursor,
limit: input.limit,
});
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
return {
branches: [...branches.branches],
isRepo: true,
hasOriginRemote: remoteNames.includes("origin"),
nextCursor: branches.nextCursor,
totalCount: branches.totalCount,
};
});
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
@@ -1856,12 +2009,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return { branch: targetBranch };
});
const createBranch: GitCoreShape["createBranch"] = (input) =>
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
}).pipe(Effect.asVoid);
const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
function* (input) {
const [localInputExists, remoteExists] = yield* Effect.all(
@@ -1934,9 +2081,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
"branch",
"--show-current",
]).pipe(Effect.map((stdout) => stdout.trim() || null));
return { branch };
},
);
const createBranch: GitCoreShape["createBranch"] = Effect.fn("createBranch")(function* (input) {
yield* executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
if (input.checkout) {
yield* checkoutBranch({ cwd: input.cwd, branch: input.branch });
}
return { branch: input.branch };
});
const initRepo: GitCoreShape["initRepo"] = (input) =>
executeGit("GitCore.initRepo", input.cwd, ["init"], {
timeoutMs: 10_000,
@@ -1962,6 +2128,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
execute,
status,
statusDetails,
statusDetailsLocal,
prepareCommitContext,
commit,
pushCurrentBranch,
+168 -3
View File
@@ -6,7 +6,12 @@ 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, ModelSelection } from "@t3tools/contracts";
import type {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
ModelSelection,
ThreadId,
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -21,6 +26,11 @@ 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[];
@@ -593,7 +603,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe
function preparePullRequestThread(
manager: GitManagerShape,
input: { cwd: string; reference: string; mode: "local" | "worktree" },
input: GitPreparePullRequestThreadInput,
) {
return manager.preparePullRequestThread(input);
}
@@ -601,6 +611,7 @@ function preparePullRequestThread(
function makeManager(input?: {
ghScenario?: FakeGhScenario;
textGeneration?: Partial<FakeGitTextGeneration>;
setupScriptRunner?: ProjectSetupScriptRunnerShape;
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
@@ -618,6 +629,12 @@ 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));
@@ -628,6 +645,8 @@ 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),
@@ -660,6 +679,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
@@ -672,6 +694,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status returns an explicit non-repo result for non-git directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
const { manager } = yield* makeManager();
const status = yield* manager.status({ cwd });
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
pr: null,
});
}),
);
it.effect("status briefly caches repeated lookups for the same cwd", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2147,6 +2195,59 @@ 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-");
@@ -2331,6 +2432,7 @@ 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: {
@@ -2342,18 +2444,27 @@ 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);
}),
);
@@ -2533,6 +2644,50 @@ 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-");
@@ -2739,7 +2894,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
label: "Preparing PR...",
}),
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Generating PR content...",
}),
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
}),
]);
}),
+148 -28
View File
@@ -5,11 +5,16 @@ import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } f
import {
GitActionProgressEvent,
GitActionProgressPhase,
GitCommandError,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
sanitizeFeatureBranchName,
@@ -22,9 +27,10 @@ import {
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
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";
@@ -37,6 +43,11 @@ const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
function isNotGitRepositoryError(error: GitCommandError): boolean {
return error.message.toLowerCase().includes("not a git repository");
}
interface OpenPrInfo {
number: number;
@@ -546,6 +557,7 @@ 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 = (
@@ -687,8 +699,52 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
const readStatus = Effect.fn("readStatus")(function* (cwd: string) {
const details = yield* gitCore.statusDetails(cwd);
const nonRepositoryStatusDetails = {
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
} satisfies GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetailsLocal(cwd)
.pipe(
Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
);
const hostingProvider = details.isRepo
? yield* resolveHostingProvider(cwd, details.branch)
: null;
return {
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readLocalStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateLocalStatusResultCache = (cwd: string) =>
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
}
const pr =
details.branch !== null
@@ -702,26 +758,38 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
pr,
};
} satisfies GitStatusRemoteResult;
});
const statusResultCache = yield* Cache.makeWith({
const remoteStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readStatus,
lookup: readRemoteStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateStatusResultCache = (cwd: string) =>
Cache.invalidate(statusResultCache, normalizeStatusCacheKey(cwd));
const invalidateRemoteStatusResultCache = (cwd: string) =>
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
const readConfigValueNullable = (cwd: string, key: string) =>
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
cwd: string,
branch: string | null,
) {
const preferredRemoteName =
branch === null
? "origin"
: ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
const remoteUrl =
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
cwd: string,
remoteName: string | null,
@@ -908,12 +976,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return parsed[0] ?? null;
});
const isDefaultBranch = Effect.fn("isDefaultBranch")(function* (cwd: string, branch: string) {
const branches = yield* gitCore.listBranches({ cwd });
const currentBranch = branches.branches.find((candidate) => candidate.name === branch);
return currentBranch?.isDefault ?? (branch === "main" || branch === "master");
});
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
cwd: string,
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
@@ -935,11 +997,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
upstreamRef: finalStatus.upstreamRef,
hasUpstream: finalStatus.hasUpstream,
};
currentBranchIsDefault = yield* isDefaultBranch(cwd, finalStatus.branch).pipe(
Effect.catch(() =>
Effect.succeed(finalStatus.branch === "main" || finalStatus.branch === "master"),
),
);
currentBranchIsDefault = finalStatus.isDefaultBranch;
}
}
@@ -1200,6 +1258,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
modelSelection: ModelSelection,
cwd: string,
fallbackBranch: string | null,
emit: GitActionProgressEmitter,
) {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
@@ -1234,6 +1293,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Generating PR content...",
});
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
const generated = yield* textGeneration.generatePrContent({
@@ -1254,6 +1318,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause),
),
);
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
});
yield* gitHubCli
.createPullRequest({
cwd,
@@ -1284,9 +1353,34 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
};
});
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd));
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
});
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
function* (input) {
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
},
);
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
});
const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
"invalidateLocalStatus",
)(function* (cwd) {
yield* invalidateLocalStatusResultCache(cwd);
});
const invalidateRemoteStatus: GitManagerShape["invalidateRemoteStatus"] = Effect.fn(
"invalidateRemoteStatus",
)(function* (cwd) {
yield* invalidateRemoteStatusResultCache(cwd);
});
const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
function* (cwd) {
yield* invalidateLocalStatusResultCache(cwd);
yield* invalidateRemoteStatusResultCache(cwd);
},
);
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
@@ -1304,6 +1398,24 @@ 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);
@@ -1436,13 +1548,14 @@ 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(invalidateStatusResultCache(input.cwd)));
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
});
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -1612,11 +1725,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
.emit({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
label: "Preparing PR...",
})
.pipe(
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
Effect.flatMap(() => runPrStep(modelSelection, input.cwd, currentBranch)),
Effect.flatMap(() =>
runPrStep(modelSelection, input.cwd, currentBranch, progress.emit),
),
)
: { status: "skipped_not_requested" as const };
@@ -1644,7 +1759,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
});
return yield* runAction().pipe(
Effect.ensuring(invalidateStatusResultCache(input.cwd)),
Effect.ensuring(invalidateStatus(input.cwd)),
Effect.tapError((error) =>
Effect.flatMap(Ref.get(currentPhase), (phase) =>
progress.emit({
@@ -1659,7 +1774,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
return {
localStatus,
remoteStatus,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
invalidateStatus,
resolvePullRequest,
preparePullRequestThread,
runStackedAction,
@@ -0,0 +1,276 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
import type {
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { describe } from "vitest";
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
const baseLocalStatus: GitStatusLocalResult = {
isRepo: true,
hostingProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/status-broadcast",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: GitStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const baseStatus: GitStatusResult = {
...baseLocalStatus,
...baseRemoteStatus,
};
function makeTestLayer(state: {
currentLocalStatus: GitStatusLocalResult;
currentRemoteStatus: GitStatusRemoteResult | null;
localStatusCalls: number;
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
const gitManager: GitManagerShape = {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
};
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
}
describe("GitStatusBroadcasterLive", () => {
it.effect("reuses the cached git status across repeated reads", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(first, baseStatus);
assert.deepStrictEqual(second, baseStatus);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.localInvalidationCalls, 0);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
branch: "feature/updated-status",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 2,
};
const refreshed = yield* broadcaster.refreshStatus("/repo");
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshed, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 1);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("streams a local snapshot first and remote updates later", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
if (event._tag === "snapshot") {
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
}
if (event._tag === "remoteUpdated") {
return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkScoped);
const snapshot = yield* Deferred.await(snapshotDeferred);
yield* broadcaster.refreshStatus("/repo");
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
assert.deepStrictEqual(snapshot, {
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
} satisfies GitStatusStreamEvent);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies GitStatusStreamEvent);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const testLayer = GitStatusBroadcasterLive.pipe(
Layer.provide(
Layer.succeed(GitManager, {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () =>
Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
} satisfies GitManagerShape),
),
);
return Effect.gen(function* () {
const remoteInterrupted = yield* Deferred.make<void>();
const remoteStarted = yield* Deferred.make<void>();
remoteInterruptedDeferred = remoteInterrupted;
remoteStartedDeferred = remoteStarted;
const broadcaster = yield* GitStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const firstScope = yield* Scope.make();
const secondScope = yield* Scope.make();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
event._tag === "snapshot"
? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(firstScope));
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
event._tag === "snapshot"
? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(secondScope));
yield* Deferred.await(firstSnapshot);
yield* Deferred.await(secondSnapshot);
yield* Deferred.await(remoteStarted);
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(firstScope, Exit.void);
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
yield* Deferred.await(remoteInterrupted);
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
}).pipe(Effect.provide(testLayer));
});
});
@@ -0,0 +1,307 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitStatusInput,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly event: GitStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedGitStatus {
readonly local: CachedValue<GitStatusLocalResult> | null;
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
cwd: string,
local: GitStatusLocalResult,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<GitStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
});
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
cwd: string,
remote: GitStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<GitStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
});
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
});
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(normalizedCwd),
getOrLoadRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus = Effect.fn("refreshLocalStatus")(function* (cwd: string) {
yield* gitManager.invalidateLocalStatus(cwd);
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
yield* gitManager.invalidateRemoteStatus(cwd);
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(normalizedCwd),
refreshRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
},
);
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("git remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
yield* retainRemotePoller(normalizedCwd);
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return {
getStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
+12 -3
View File
@@ -7,10 +7,12 @@
* @module GitCore
*/
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
@@ -156,6 +158,11 @@ export interface GitCoreShape {
*/
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Read detailed working tree / branch status without refreshing remote tracking refs.
*/
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Build staged change context for commit generation.
*/
@@ -278,14 +285,16 @@ export interface GitCoreShape {
/**
* Create a local branch.
*/
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
/**
* Initialize a repository in the provided directory.
@@ -14,6 +14,8 @@ import {
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
@@ -41,6 +43,35 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Read local repository status without remote hosting enrichment.
*/
readonly localStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
/**
* Read remote tracking / PR status for a repository.
*/
readonly remoteStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
/**
* Clear any cached local status snapshot for a repository.
*/
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached remote status snapshot for a repository.
*/
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
@@ -0,0 +1,23 @@
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
GitStatusInput,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends ServiceMap.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
+75 -2
View File
@@ -1,6 +1,15 @@
import Mime from "@effect/platform-node/Mime";
import { Effect, FileSystem, Option, Path } from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { Data, Effect, FileSystem, Layer, Option, Path } from "effect";
import { cast } from "effect/Function";
import {
HttpBody,
HttpClient,
HttpClientResponse,
HttpRouter,
HttpServerResponse,
HttpServerRequest,
} from "effect/unstable/http";
import { OtlpTracer } from "effect/unstable/observability";
import {
ATTACHMENTS_ROUTE_PREFIX,
@@ -9,10 +18,74 @@ import {
} from "./attachmentPaths";
import { resolveAttachmentPathById } from "./attachmentStore";
import { ServerConfig } from "./config";
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
readonly cause: unknown;
readonly bodyJson: OtlpTracer.TraceData;
}> {}
export const otlpTracesProxyRouteLayer = HttpRouter.add(
"POST",
OTLP_TRACES_PROXY_PATH,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const config = yield* ServerConfig;
const otlpTracesUrl = config.otlpTracesUrl;
const browserTraceCollector = yield* BrowserTraceCollector;
const httpClient = yield* HttpClient.HttpClient;
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
yield* Effect.try({
try: () => decodeOtlpTraceRecords(bodyJson),
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
}).pipe(
Effect.flatMap((records) => browserTraceCollector.record(records)),
Effect.catch((cause) =>
Effect.logWarning("Failed to decode browser OTLP traces", {
cause,
bodyJson,
}),
),
);
if (otlpTracesUrl === undefined) {
return HttpServerResponse.empty({ status: 204 });
}
return yield* httpClient
.post(otlpTracesUrl, {
body: HttpBody.jsonUnsafe(bodyJson),
})
.pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.as(HttpServerResponse.empty({ status: 204 })),
Effect.tapError((cause) =>
Effect.logWarning("Failed to export browser OTLP traces", {
cause,
otlpTracesUrl,
}),
),
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
),
);
}),
).pipe(
Layer.provide(
HttpRouter.cors({
allowedMethods: ["POST", "OPTIONS"],
allowedHeaders: ["content-type"],
maxAge: 600,
}),
),
);
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
@@ -0,0 +1,46 @@
import { assert, describe, it } from "@effect/vitest";
import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts";
describe("Attributes", () => {
it("normalizes circular arrays, maps, and sets without recursing forever", () => {
const array: Array<unknown> = ["alpha"];
array.push(array);
const map = new Map<string, unknown>();
map.set("self", map);
const set = new Set<unknown>();
set.add(set);
assert.deepStrictEqual(
compactTraceAttributes({
array,
map,
set,
}),
{
array: ["alpha", "[Circular]"],
map: { self: "[Circular]" },
set: ["[Circular]"],
},
);
});
it("normalizes invalid dates without throwing", () => {
assert.deepStrictEqual(
compactTraceAttributes({
invalidDate: new Date("not-a-real-date"),
}),
{
invalidDate: "Invalid Date",
},
);
});
it("groups GPT-family models under a shared metric label", () => {
assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude");
});
});
+128
View File
@@ -0,0 +1,128 @@
import { Cause, Exit } from "effect";
export type MetricAttributeValue = string;
export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
export type TraceAttributes = Readonly<Record<string, unknown>>;
export type ObservabilityOutcome = "success" | "failure" | "interrupt";
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function markSeen(value: object, seen: WeakSet<object>): boolean {
if (seen.has(value)) {
return true;
}
seen.add(value);
return false;
}
function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
if (
value === null ||
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
return value ?? null;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
...(value.stack ? { stack: value.stack } : {}),
};
}
if (Array.isArray(value)) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return value.map((entry) => normalizeJsonValue(entry, seen));
}
if (value instanceof Map) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Array.from(value.entries(), ([key, entryValue]) => [
String(key),
normalizeJsonValue(entryValue, seen),
]),
);
}
if (value instanceof Set) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
}
if (!isPlainObject(value)) {
return String(value);
}
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
);
}
export function compactTraceAttributes(
attributes: Readonly<Record<string, unknown>>,
): TraceAttributes {
return Object.fromEntries(
Object.entries(attributes)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, normalizeJsonValue(value)]),
);
}
export function compactMetricAttributes(
attributes: Readonly<Record<string, unknown>>,
): MetricAttributes {
return Object.fromEntries(
Object.entries(attributes).flatMap(([key, value]) => {
if (value === undefined || value === null) {
return [];
}
if (typeof value === "string") {
return [[key, value]];
}
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
return [[key, String(value)]];
}
return [];
}),
);
}
export function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {
if (Exit.isSuccess(exit)) {
return "success";
}
return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure";
}
export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {
const normalized = model?.trim().toLowerCase();
if (!normalized) {
return undefined;
}
if (normalized.includes("gpt")) {
return "gpt";
}
if (normalized.includes("claude")) {
return "claude";
}
if (normalized.includes("gemini")) {
return "gemini";
}
return "other";
}
@@ -0,0 +1,84 @@
import { Effect, Layer, References, Tracer } from "effect";
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
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;
export const ObservabilityLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
);
const tracerLayer = Layer.unwrap(
Effect.gen(function* () {
const sink = yield* makeTraceSink({
filePath: config.serverTracePath,
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
});
const delegate =
config.otlpTracesUrl === undefined
? undefined
: yield* OtlpTracer.make({
url: config.otlpTracesUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
});
const tracer = yield* makeLocalFileTracer({
filePath: config.serverTracePath,
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
sink,
...(delegate ? { delegate } : {}),
});
return Layer.mergeAll(
Layer.succeed(Tracer.Tracer, tracer),
Layer.succeed(BrowserTraceCollector, {
record: (records) =>
Effect.sync(() => {
for (const record of records) {
sink.push(record);
}
}),
}),
);
}),
).pipe(Layer.provideMerge(otlpSerializationLayer));
const metricsLayer =
config.otlpMetricsUrl === undefined
? Layer.empty
: OtlpMetrics.layer({
url: config.otlpMetricsUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
}).pipe(Layer.provideMerge(otlpSerializationLayer));
return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);
}),
);
@@ -0,0 +1,117 @@
import fs from "node:fs";
import os from "node:os";
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 { makeLocalFileTracer } from "./LocalFileTracer.ts";
const makeTestLayer = (tracePath: string) =>
Layer.mergeAll(
Layer.effect(
Tracer.Tracer,
makeLocalFileTracer({
filePath: tracePath,
maxBytes: 1024 * 1024,
maxFiles: 2,
batchWindowMs: 10_000,
}),
),
Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
);
const readTraceRecords = (tracePath: string): Array<EffectTraceRecord> =>
fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as EffectTraceRecord);
describe("LocalFileTracer", () => {
it.effect("writes nested spans to disk and captures log messages as span events", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.gen(function* () {
const program = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.parent": true,
});
yield* Effect.logInfo("parent event");
yield* Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.child": true,
});
yield* Effect.logInfo("child event");
}).pipe(Effect.withSpan("child-span"));
}).pipe(Effect.withSpan("parent-span"));
yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
}),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 2);
const parent = records.find((record) => record.name === "parent-span");
const child = records.find((record) => record.name === "child-span");
assert.notEqual(parent, undefined);
assert.notEqual(child, undefined);
if (!parent || !child) {
return;
}
assert.equal(child.parentSpanId, parent.spanId);
assert.equal(parent.attributes["demo.parent"], true);
assert.equal(child.attributes["demo.child"], true);
assert.equal(
parent.events.some((event) => event.name === "parent event"),
true,
);
assert.equal(
child.events.some((event) => event.name === "child event"),
true,
);
assert.equal(
child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
true,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("serializes interrupted spans with an interrupted exit status", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.exit(
Effect.interrupt.pipe(
Effect.withSpan("interrupt-span"),
Effect.provide(makeTestLayer(tracePath)),
),
),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 1);
assert.equal(records[0]?.name, "interrupt-span");
assert.equal(records[0]?.exit._tag, "Interrupted");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
});
@@ -0,0 +1,107 @@
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";
export interface LocalFileTracerOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly delegate?: Tracer.Tracer;
readonly sink?: TraceSink;
}
class LocalFileSpan implements Tracer.Span {
readonly _tag = "Span";
readonly name: string;
readonly spanId: string;
readonly traceId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly annotations: Tracer.Span["annotations"];
readonly links: Array<Tracer.SpanLink>;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
status: Tracer.SpanStatus;
attributes: Map<string, unknown>;
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
private readonly delegate: Tracer.Span,
private readonly push: (record: EffectTraceRecord) => void,
) {
this.name = delegate.name;
this.spanId = delegate.spanId;
this.traceId = delegate.traceId;
this.parent = options.parent;
this.annotations = options.annotations;
this.links = [...options.links];
this.sampled = delegate.sampled;
this.kind = delegate.kind;
this.status = {
_tag: "Started",
startTime: options.startTime,
};
this.attributes = new Map();
this.events = [];
}
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
this.status = {
_tag: "Ended",
startTime: this.status.startTime,
endTime,
exit,
};
this.delegate.end(endTime, exit);
if (this.sampled) {
this.push(spanToTraceRecord(this));
}
}
attribute(key: string, value: unknown): void {
this.attributes.set(key, value);
this.delegate.attribute(key, value);
}
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
const nextAttributes = attributes ?? {};
this.events.push([name, startTime, nextAttributes]);
this.delegate.event(name, startTime, nextAttributes);
}
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
this.links.push(...links);
this.delegate.addLinks(links);
}
}
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 delegate =
options.delegate ??
Tracer.make({
span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
});
return Tracer.make({
span(spanOptions) {
return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
},
...(delegate.context ? { context: delegate.context } : {}),
});
});
@@ -0,0 +1,111 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("withMetrics", () => {
it.effect("supports pipe-style usage", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_pipe_total");
const timer = Metric.timer("with_metrics_pipe_duration");
const result = yield* Effect.succeed("ok").pipe(
withMetrics({
counter,
timer,
attributes: {
operation: "pipe",
},
}),
);
assert.equal(result, "ok");
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_total", {
operation: "pipe",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", {
operation: "pipe",
}),
true,
);
}),
);
it.effect("supports direct invocation", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_direct_total");
yield* withMetrics(Effect.fail("boom"), {
counter,
attributes: {
operation: "direct",
},
}).pipe(Effect.exit);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_direct_total", {
operation: "direct",
outcome: "failure",
}),
true,
);
}),
);
it.effect("evaluates attributes lazily after the wrapped effect runs", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = "unknown";
yield* Effect.sync(() => {
provider = "codex";
}).pipe(
withMetrics({
counter,
timer,
attributes: () => ({
provider,
operation: "lazy",
}),
}),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: "codex",
operation: "lazy",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: "codex",
operation: "lazy",
}),
true,
);
}),
);
});
+160
View File
@@ -0,0 +1,160 @@
import { Duration, Effect, Exit, Metric } from "effect";
import { dual } from "effect/Function";
import {
compactMetricAttributes,
normalizeModelMetricLabel,
outcomeFromExit,
} from "./Attributes.ts";
export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
description: "Total RPC requests handled by the websocket RPC server.",
});
export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
description: "RPC request handling duration.",
});
export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
description: "Total orchestration commands dispatched.",
});
export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
description: "Orchestration command dispatch duration.",
});
export const orchestrationCommandAckDuration = Metric.timer(
"t3_orchestration_command_ack_duration",
{
description:
"Time from orchestration command dispatch to the first committed domain event emitted for that command.",
},
);
export const orchestrationEventsProcessedTotal = Metric.counter(
"t3_orchestration_events_processed_total",
{
description: "Total orchestration intent events processed by runtime reactors.",
},
);
export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
description: "Total provider session lifecycle operations.",
});
export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
description: "Total provider turn lifecycle operations.",
});
export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
description: "Provider turn request duration.",
});
export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
description: "Total canonical provider runtime events processed.",
});
export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
description: "Total git commands executed by the server runtime.",
});
export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
description: "Git command execution duration.",
});
export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
description: "Total terminal sessions started.",
});
export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
description: "Total terminal restart requests handled.",
});
export const metricAttributes = (
attributes: Readonly<Record<string, unknown>>,
): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
export const increment = (
metric: Metric.Metric<number, unknown>,
attributes: Readonly<Record<string, unknown>>,
amount = 1,
) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
export interface WithMetricsOptions {
readonly counter?: Metric.Metric<number, unknown>;
readonly timer?: Metric.Metric<Duration.Duration, unknown>;
readonly attributes?:
| Readonly<Record<string, unknown>>
| (() => Readonly<Record<string, unknown>>);
readonly outcomeAttributes?: (
outcome: ReturnType<typeof outcomeFromExit>,
) => Readonly<Record<string, unknown>>;
}
const withMetricsImpl = <A, E, R>(
effect: Effect.Effect<A, E, R>,
options: WithMetricsOptions,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
const baseAttributes =
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
if (options.timer) {
yield* Metric.update(
Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
duration,
);
}
if (options.counter) {
const outcome = outcomeFromExit(exit);
yield* Metric.update(
Metric.withAttributes(
options.counter,
metricAttributes({
...baseAttributes,
outcome,
...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
}),
),
1,
);
}
if (Exit.isSuccess(exit)) {
return exit.value;
}
return yield* Effect.failCause(exit.cause);
});
export const withMetrics: {
<A, E, R>(
options: WithMetricsOptions,
): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
<A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
} = dual(2, withMetricsImpl);
export const providerMetricAttributes = (
provider: string,
extra?: Readonly<Record<string, unknown>>,
) =>
compactMetricAttributes({
provider,
...extra,
});
export const providerTurnMetricAttributes = (input: {
readonly provider: string;
readonly model: string | null | undefined;
readonly extra?: Readonly<Record<string, unknown>>;
}) => {
const modelFamily = normalizeModelMetricLabel(input.model);
return compactMetricAttributes({
provider: input.provider,
...(modelFamily ? { modelFamily } : {}),
...input.extra,
});
};
@@ -0,0 +1,161 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Exit, Metric, Stream } from "effect";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./RpcInstrumentation.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("RpcInstrumentation", () => {
it.effect("records success metrics for unary RPC handlers", () =>
Effect.gen(function* () {
yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.success.span"));
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.success",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.success",
}),
true,
);
}),
);
it.effect("records failure outcomes for unary RPC handlers", () =>
Effect.gen(function* () {
yield* Effect.exit(
observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.failure.span")),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.failure",
}),
true,
);
}),
);
it.effect("records subscription activation metrics for stream RPC handlers", () =>
Effect.gen(function* () {
const events = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream",
Effect.succeed(Stream.make("a", "b")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.span")),
);
assert.deepStrictEqual(Array.from(events), ["a", "b"]);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream",
}),
true,
);
}),
);
it.effect("records failure outcomes for direct stream RPC handlers during consumption", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.stream.failure",
Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.failure",
}),
true,
);
}),
);
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream.effect.failure",
Effect.succeed(Stream.fail("boom")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.effect.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.effect.failure",
}),
true,
);
}),
);
});
@@ -0,0 +1,89 @@
import { Duration, Effect, Exit, Metric, Stream } from "effect";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
const annotateRpcSpan = (
method: string,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<void, never, never> =>
Effect.annotateCurrentSpan({
"rpc.method": method,
...traceAttributes,
});
const recordRpcStreamMetrics = <E>(
method: string,
startedAt: number,
exit: Exit.Exit<unknown, E>,
): Effect.Effect<void, never, never> =>
Effect.gen(function* () {
yield* Metric.update(
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
Duration.millis(Math.max(0, Date.now() - startedAt)),
);
yield* Metric.update(
Metric.withAttributes(
rpcRequestsTotal,
metricAttributes({
method,
outcome: outcomeFromExit(exit),
}),
),
1,
);
});
export const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
return yield* effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
attributes: {
method,
},
}),
);
});
export const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
}),
);
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
if (Exit.isFailure(exit)) {
yield* recordRpcStreamMetrics(method, startedAt, exit);
return yield* Effect.failCause(exit.cause);
}
return exit.value.pipe(
Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
);
}),
);
@@ -0,0 +1,13 @@
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { TraceRecord } from "../TraceRecord.ts";
export interface BrowserTraceCollectorShape {
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
}
export class BrowserTraceCollector extends ServiceMap.Service<
BrowserTraceCollector,
BrowserTraceCollectorShape
>()("t3/observability/Services/BrowserTraceCollector") {}
@@ -0,0 +1,287 @@
import { Cause, Exit, Option, Tracer } from "effect";
import { compactTraceAttributes } from "./Attributes.ts";
import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
interface TraceRecordEvent {
readonly name: string;
readonly timeUnixNano: string;
readonly attributes: Readonly<Record<string, unknown>>;
}
interface TraceRecordLink {
readonly traceId: string;
readonly spanId: string;
readonly attributes: Readonly<Record<string, unknown>>;
}
interface BaseTraceRecord {
readonly name: string;
readonly kind: string;
readonly traceId: string;
readonly spanId: string;
readonly parentSpanId?: string;
readonly sampled: boolean;
readonly 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 exit:
| {
readonly _tag: "Success";
}
| {
readonly _tag: "Interrupted";
readonly cause: string;
}
| {
readonly _tag: "Failure";
readonly cause: string;
};
}
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;
readonly spanId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly status: Tracer.SpanStatus;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
readonly attributes: ReadonlyMap<string, unknown>;
readonly links: ReadonlyArray<Tracer.SpanLink>;
readonly events: ReadonlyArray<
readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
>;
}
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
if (Exit.isSuccess(exit)) {
return { _tag: "Success" };
}
if (Cause.hasInterruptsOnly(exit.cause)) {
return {
_tag: "Interrupted",
cause: Cause.pretty(exit.cause),
};
}
return {
_tag: "Failure",
cause: Cause.pretty(exit.cause),
};
}
export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
return {
type: "effect-span",
name: span.name,
traceId: span.traceId,
spanId: span.spanId,
...(parentSpanId ? { parentSpanId } : {}),
sampled: span.sampled,
kind: span.kind,
startTimeUnixNano: String(status.startTime),
endTimeUnixNano: String(status.endTime),
durationMs: Number(status.endTime - status.startTime) / 1_000_000,
attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
events: span.events.map(([name, startTime, attributes]) => ({
name,
timeUnixNano: String(startTime),
attributes: compactTraceAttributes(attributes),
})),
links: span.links.map((link) => ({
traceId: link.span.traceId,
spanId: link.span.spanId,
attributes: compactTraceAttributes(link.attributes),
})),
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;
}
}
@@ -0,0 +1,152 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
const makeRecord = (name: string, suffix = ""): TraceRecord => ({
type: "effect-span",
name,
traceId: `trace-${name}-${suffix}`,
spanId: `span-${name}-${suffix}`,
sampled: true,
kind: "internal",
startTimeUnixNano: "1",
endTimeUnixNano: "2",
durationMs: 1,
attributes: {
payload: suffix,
},
events: [],
links: [],
exit: {
_tag: "Success",
},
});
describe("TraceSink", () => {
it.effect("flushes buffered records on close", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
sink.push(makeRecord("alpha"));
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.name, "alpha");
assert.equal(lines[1]?.name, "beta");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("rotates the trace file when the configured max size is exceeded", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 180,
maxFiles: 2,
batchWindowMs: 10_000,
});
for (let index = 0; index < 8; index += 1) {
sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
yield* sink.flush;
}
yield* sink.close();
const matchingFiles = fs
.readdirSync(tempDir)
.filter(
(entry) =>
entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."),
)
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.1"),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.3"),
false,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("drops only the invalid record when serialization fails", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const circular: Array<unknown> = [];
circular.push(circular);
sink.push(makeRecord("alpha"));
sink.push({
...makeRecord("invalid"),
attributes: {
circular,
},
} as TraceRecord);
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.deepStrictEqual(
lines.map((line) => line.name),
["alpha", "beta"],
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
});
@@ -0,0 +1,68 @@
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
const FLUSH_BUFFER_THRESHOLD = 32;
export interface TraceSinkOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
}
export interface TraceSink {
readonly filePath: string;
push: (record: TraceRecord) => void;
flush: Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
const sink = new RotatingFileSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
});
let buffer: Array<string> = [];
const flushUnsafe = () => {
if (buffer.length === 0) {
return;
}
const chunk = buffer.join("");
buffer = [];
try {
sink.write(chunk);
} catch {
buffer.unshift(chunk);
}
};
const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
yield* Effect.forkScoped(
Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
);
return {
filePath: options.filePath,
push(record) {
try {
buffer.push(`${JSON.stringify(record)}\n`);
if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
flushUnsafe();
}
} catch {
return;
}
},
flush,
close: () => flush,
} satisfies TraceSink;
});
+37 -1
View File
@@ -75,10 +75,19 @@ 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("uses --goto when editor supports line/column suffixes", () =>
it.effect("applies launch-style-specific navigation arguments", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
@@ -142,6 +151,33 @@ 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"],
});
}),
);
+48 -7
View File
@@ -34,10 +34,45 @@ interface CommandAvailabilityOptions {
readonly env?: NodeJS.ProcessEnv;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
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 fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -198,19 +233,25 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
yield* Effect.annotateCurrentSpan({
"open.editor": input.editor,
"open.cwd": input.cwd,
"open.platform": platform,
});
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
return {
command: editorDef.command,
args: resolveCommandEditorArgs(editorDef, input.cwd),
};
}
if (editorDef.id !== "file-manager") {
@@ -96,7 +96,9 @@ function createProviderServiceHarness(
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -119,7 +119,7 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
threadId: ThreadId,
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -153,7 +153,7 @@ const make = Effect.gen(function* () {
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
// a git repository.
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
@@ -188,7 +188,7 @@ const make = Effect.gen(function* () {
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
// it against the previous turn, then dispatches the domain events to update
// the orchestration read model.
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly thread: {
@@ -321,70 +321,70 @@ const make = Effect.gen(function* () {
});
// Captures a real git checkpoint when a turn completes via a runtime event.
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
});
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
},
);
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
// is detected via a domain event. This replaces the placeholder with a real
@@ -394,7 +394,7 @@ const make = Effect.gen(function* () {
// events from the Codex runtime. This handler fires when the corresponding
// domain event arrives, allowing the reactor to capture the actual filesystem
// state into a git ref and dispatch a replacement checkpoint.
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
) {
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
@@ -448,57 +448,59 @@ const make = Effect.gen(function* () {
});
});
const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
});
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
},
);
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
"ensurePreTurnBaselineFromDomainTurnStart",
)(function* (
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
@@ -557,7 +559,7 @@ const make = Effect.gen(function* () {
});
});
const handleRevertRequested = Effect.fnUntraced(function* (
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
) {
const now = new Date().toISOString();
@@ -685,7 +687,7 @@ const make = Effect.gen(function* () {
);
});
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
@@ -724,7 +726,9 @@ const make = Effect.gen(function* () {
}
});
const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
) {
if (event.type === "turn.started") {
yield* ensurePreTurnBaselineFromTurnStart(event);
return;
@@ -8,7 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -62,6 +62,17 @@ function now() {
return new Date().toISOString();
}
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
@@ -408,6 +419,95 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("records command ack duration using the first committed event type", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
projectId: asProjectId("project-ack"),
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
threadId: ThreadId.makeUnsafe("thread-ack"),
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
);
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
commandType: "thread.create",
aggregateKind: "thread",
ackEventType: "thread.created",
}),
).toBe(true);
await system.dispose();
});
it("records failed command dispatches as metric failures", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await expect(
system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
threadId: ThreadId.makeUnsafe("thread-missing-project"),
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
),
).rejects.toThrow("does not exist");
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
commandType: "thread.create",
aggregateKind: "thread",
outcome: "failure",
}),
).toBe(true);
await system.dispose();
});
it("stores completed checkpoint summaries even when no files changed", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -5,9 +5,28 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
import {
Cause,
Deferred,
Duration,
Effect,
Exit,
Layer,
Metric,
Option,
PubSub,
Queue,
Schema,
Stream,
} from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
metricAttributes,
orchestrationCommandAckDuration,
orchestrationCommandsTotal,
orchestrationCommandDuration,
} from "../../observability/Metrics.ts";
import { toPersistenceSqlError } from "../../persistence/Errors.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
@@ -28,6 +47,7 @@ import {
interface CommandEnvelope {
command: OrchestrationCommand;
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
startedAtMs: number;
}
function commandToAggregateRef(command: OrchestrationCommand): {
@@ -64,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
const dispatchStartSequence = readModel.snapshotSequence;
const processingStartedAtMs = Date.now();
const aggregateRef = commandToAggregateRef(envelope.command);
const baseMetricAttributes = {
commandType: envelope.command.type,
aggregateKind: aggregateRef.aggregateKind,
} as const;
const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
const persistedEvents = yield* Stream.runCollect(
eventStore.readFromSequence(dispatchStartSequence),
@@ -83,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () {
}
});
return Effect.gen(function* () {
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
yield* Deferred.succeed(envelope.result, {
sequence: existingReceipt.value.resultSequence,
});
return;
}
yield* Deferred.fail(
envelope.result,
new OrchestrationCommandPreviouslyRejectedError({
return Effect.exit(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"orchestration.command_id": envelope.command.commandId,
"orchestration.command_type": envelope.command.type,
"orchestration.aggregate_kind": aggregateRef.aggregateKind,
"orchestration.aggregate_id": aggregateRef.aggregateId,
});
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
return {
sequence: existingReceipt.value.resultSequence,
};
}
return yield* new OrchestrationCommandPreviouslyRejectedError({
commandId: envelope.command.commandId,
detail: existingReceipt.value.error ?? "Previously rejected.",
}),
);
return;
}
});
}
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
),
);
readModel = committedCommand.nextReadModel;
for (const event of committedCommand.committedEvents) {
yield* PubSub.publish(eventPubSub, event);
}
yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
}).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
const aggregateRef = commandToAggregateRef(envelope.command);
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
readModel = committedCommand.nextReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandAckDuration,
metricAttributes({
...baseMetricAttributes,
ackEventType: event.type,
}),
),
Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)),
);
}
}
return { sequence: committedCommand.lastSequence };
}).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
).pipe(
Effect.flatMap((exit) =>
Effect.gen(function* () {
const outcome = Exit.isSuccess(exit)
? "success"
: Cause.hasInterruptsOnly(exit.cause)
? "interrupt"
: "failure";
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandDuration,
metricAttributes(baseMetricAttributes),
),
Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandsTotal,
metricAttributes({
...baseMetricAttributes,
outcome,
}),
),
1,
);
if (Exit.isSuccess(exit)) {
yield* Deferred.succeed(envelope.result, exit.value);
return;
}
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
}
yield* Deferred.fail(envelope.result, error);
}),
),
@@ -214,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result });
yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() });
return yield* Deferred.await(result);
});
@@ -208,7 +208,9 @@ describe("ProviderCommandReactor", () => {
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -16,6 +16,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
@@ -212,12 +213,12 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
const ensureSessionForThread = Effect.fnUntraced(function* (
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
threadId: ThreadId,
createdAt: string,
options?: {
@@ -357,7 +358,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fnUntraced(function* (input: {
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -409,7 +410,9 @@ const make = Effect.gen(function* () {
});
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
"maybeGenerateAndRenameWorktreeBranchForFirstTurn",
)(function* (input: {
readonly threadId: ThreadId;
readonly branch: string | null;
readonly worktreePath: string | null;
@@ -461,50 +464,52 @@ const make = Effect.gen(function* () {
);
});
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")(
function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
});
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const processTurnStartRequested = Effect.fnUntraced(function* (
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
},
);
const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
) {
const key = turnStartKeyForEvent(event);
@@ -583,7 +588,7 @@ const make = Effect.gen(function* () {
);
});
const processTurnInterruptRequested = Effect.fnUntraced(function* (
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -606,7 +611,7 @@ const make = Effect.gen(function* () {
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
});
const processApprovalResponseRequested = Effect.fnUntraced(function* (
const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -653,50 +658,52 @@ const make = Effect.gen(function* () {
);
});
const processUserInputResponseRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")(
function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
});
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
},
);
const processSessionStopRequested = Effect.fnUntraced(function* (
const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -727,6 +734,14 @@ const make = Effect.gen(function* () {
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
) {
yield* Effect.annotateCurrentSpan({
"orchestration.event_type": event.type,
"orchestration.thread_id": event.payload.threadId,
...(event.commandId ? { "orchestration.command_id": event.commandId } : {}),
});
yield* increment(orchestrationEventsProcessedTotal, {
eventType: event.type,
});
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
@@ -98,7 +98,9 @@ function createProviderServiceHarness() {
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const setSession = (session: ProviderSession): void => {
@@ -524,7 +524,7 @@ const make = Effect.fn("make")(function* () {
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
});
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
@@ -796,9 +796,9 @@ const make = Effect.fn("make")(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForPendingTurnStart",
)(function* (threadId: ThreadId) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
@@ -818,16 +818,17 @@ const make = Effect.fn("make")(function* () {
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")(
function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
},
);
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForAcceptedTurnStart",
)(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {
if (eventTurnId === undefined) {
return null;
}
@@ -840,34 +841,36 @@ const make = Effect.fn("make")(function* () {
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")(
function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
},
);
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
@@ -1,3 +1,13 @@
/**
* RuntimeReceiptBus layers.
*
* `RuntimeReceiptBusLive` is the production default and intentionally does not
* retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory
* PubSub-backed implementation used by integration tests that need to await
* checkpoint-reactor milestones precisely.
*
* @module RuntimeReceiptBus
*/
import { Effect, Layer, PubSub, Stream } from "effect";
import {
@@ -6,13 +16,21 @@ import {
type OrchestrationRuntimeReceipt,
} from "../Services/RuntimeReceiptBus.ts";
const makeRuntimeReceiptBus = Effect.gen(function* () {
const makeRuntimeReceiptBus = Effect.succeed({
publish: () => Effect.void,
streamEventsForTest: Stream.empty,
} satisfies RuntimeReceiptBusShape);
const makeRuntimeReceiptBusTest = Effect.gen(function* () {
const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();
return {
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
stream: Stream.fromPubSub(pubSub),
get streamEventsForTest() {
return Stream.fromPubSub(pubSub);
},
} satisfies RuntimeReceiptBusShape;
});
export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);
export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);
@@ -1,3 +1,19 @@
/**
* RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts.
*
* This service exists to expose short-lived orchestration milestones that are
* useful in tests and harnesses but are not part of the production runtime
* event model. `CheckpointReactor` publishes receipts such as baseline capture,
* diff finalization, and turn-processing quiescence so integration tests can
* wait for those exact points without inferring them indirectly from persisted
* state.
*
* Production code should only call `publish`. Test code may subscribe via
* `streamEventsForTest`, which is intentionally named to make the intended
* usage explicit.
*
* @module RuntimeReceiptBus
*/
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
@@ -40,7 +56,7 @@ export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Typ
export interface RuntimeReceiptBusShape {
readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;
readonly stream: Stream.Stream<OrchestrationRuntimeReceipt>;
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
}
export class RuntimeReceiptBus extends ServiceMap.Service<
+11 -1
View File
@@ -6,6 +6,7 @@ import { ServerConfig } from "../../config.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
readonly spanAttributes?: Record<string, unknown>;
};
type Loader = {
@@ -41,7 +42,16 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
return Layer.provideMerge(
setup,
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
"db.name": path.basename(dbPath),
"service.name": "t3-server",
},
}),
);
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
@@ -0,0 +1,166 @@
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",
});
});
});
@@ -0,0 +1,75 @@
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,
);
@@ -0,0 +1,37 @@
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,7 +3054,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies ClaudeAdapterShape;
});
@@ -1631,7 +1631,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
listSessions,
hasSession,
stopAll,
streamEvents: Stream.fromQueue(runtimeEventQueue),
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies CodexAdapterShape;
});
@@ -32,6 +32,7 @@ import {
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { DEFAULT_CODEX_MODEL_CAPABILITIES } from "@t3tools/shared/model";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
@@ -159,13 +160,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
}
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
DEFAULT_CODEX_MODEL_CAPABILITIES
);
}
@@ -339,7 +335,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
if (!codexSettings.enabled) {
return buildServerProvider({
@@ -112,6 +112,49 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("serializes concurrent first writes for the same segment", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
const basePath = path.join(tempDir, "provider-canonical.ndjson");
try {
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "canonical",
batchWindowMs: 0,
});
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
yield* Effect.all(
[
logger.write({ id: "evt-concurrent-1" }, null),
logger.write({ id: "evt-concurrent-2" }, null),
],
{ concurrency: "unbounded" },
);
yield* logger.close();
const globalPath = path.join(tempDir, "_global.log");
assert.equal(fs.existsSync(globalPath), true);
const lines = fs
.readFileSync(globalPath, "utf8")
.trim()
.split("\n")
.map((line) => parseLogLine(line));
assert.equal(lines.length, 2);
assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
'{"id":"evt-concurrent-1"}',
'{"id":"evt-concurrent-2"}',
]);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("rotates per-thread files when max size is exceeded", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
@@ -10,7 +10,7 @@ import path from "node:path";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect, Exit, Logger, Scope } from "effect";
import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect";
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
@@ -40,6 +40,11 @@ interface ThreadWriter {
close: () => Effect.Effect<void>;
}
interface LoggerState {
readonly threadWriters: Map<string, ThreadWriter>;
readonly failedSegments: Set<string>;
}
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
}
@@ -193,34 +198,56 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
return undefined;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const stateRef = yield* SynchronizedRef.make<LoggerState>({
threadWriters: new Map(),
failedSegments: new Set(),
});
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.failedSegments.has(threadSegment)) {
return Effect.succeed([undefined, state] as const);
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
const existing = state.threadWriters.get(threadSegment);
if (existing) {
return Effect.succeed([existing, state] as const);
}
return makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
}).pipe(
Effect.map((writer) => {
if (!writer) {
const nextFailedSegments = new Set(state.failedSegments);
nextFailedSegments.add(threadSegment);
return [
undefined,
{
...state,
failedSegments: nextFailedSegments,
},
] as const;
}
const nextThreadWriters = new Map(state.threadWriters);
nextThreadWriters.set(threadSegment, writer);
return [
writer,
{
...state,
threadWriters: nextThreadWriters,
},
] as const;
}),
);
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
@@ -239,10 +266,21 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function
});
const close = Effect.fn("close")(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.gen(function* () {
for (const writer of state.threadWriters.values()) {
yield* writer.close();
}
return [
undefined,
{
threadWriters: new Map<string, ThreadWriter>(),
failedSegments: new Set<string>(),
},
] as const;
}),
);
});
return {
@@ -115,7 +115,9 @@ function makeMutableServerSettingsService(
yield* PubSub.publish(changes, next);
return next;
}),
streamChanges: Stream.fromPubSub(changes),
get streamChanges() {
return Stream.fromPubSub(changes);
},
} satisfies ServerSettingsShape;
});
}
@@ -218,6 +220,41 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect("adds standard codex capabilities to custom codex models", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
codex: {
customModels: ["custom-codex-model"],
},
},
});
const status = yield* checkCodexProviderStatus().pipe(
Effect.provide(serverSettingsLayer),
);
const customModel = status.models.find((model) => model.slug === "custom-codex-model");
assert.ok(customModel);
assert.strictEqual(customModel.isCustom, true);
assert.deepStrictEqual(
customModel.capabilities?.reasoningEffortLevels.map((level) => level.value),
["xhigh", "high", "medium", "low"],
);
assert.strictEqual(customModel.capabilities?.supportsFastMode, true);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
@@ -20,7 +20,7 @@ import {
import { it, assert, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect";
import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -230,6 +232,17 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
const sleep = (ms: number) =>
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
function makeProviderServiceLayer() {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
@@ -1060,6 +1073,120 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
);
}),
);
it.effect("records provider metrics with the routed provider label", () =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-metrics"), {
provider: "claudeAgent",
threadId: asThreadId("thread-metrics"),
cwd: "/tmp/project",
runtimeMode: "full-access",
});
yield* provider.interruptTurn({ threadId: session.threadId });
yield* provider.respondToRequest({
threadId: session.threadId,
requestId: asRequestId("req-metrics-1"),
decision: "accept",
});
yield* provider.respondToUserInput({
threadId: session.threadId,
requestId: asRequestId("req-metrics-2"),
answers: {
sandbox_mode: "workspace-write",
},
});
yield* provider.rollbackConversation({
threadId: session.threadId,
numTurns: 1,
});
yield* provider.stopSession({ threadId: session.threadId });
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "interrupt",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "approval-response",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "user-input-response",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "rollback",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_sessions_total", {
provider: "claudeAgent",
operation: "stop",
outcome: "success",
}),
true,
);
}),
);
it.effect(
"records sendTurn metrics with the resolved provider when modelSelection is omitted",
() =>
Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(asThreadId("thread-send-metrics"), {
provider: "claudeAgent",
threadId: asThreadId("thread-send-metrics"),
cwd: "/tmp/project-send-metrics",
runtimeMode: "full-access",
});
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turns_total", {
provider: "claudeAgent",
operation: "send",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_provider_turn_duration", {
provider: "claudeAgent",
operation: "send",
}),
true,
);
}),
);
});
const validation = makeProviderServiceLayer();
+328 -174
View File
@@ -22,8 +22,18 @@ import {
type ProviderRuntimeEvent,
type ProviderSession,
} from "@t3tools/contracts";
import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect";
import {
increment,
providerMetricAttributes,
providerRuntimeEventsTotal,
providerSessionsTotal,
providerTurnDuration,
providerTurnsTotal,
providerTurnMetricAttributes,
withMetrics,
} from "../../observability/Metrics.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
@@ -146,7 +156,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const registry = yield* ProviderAdapterRegistry;
const directory = yield* ProviderSessionDirectory;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
@@ -179,75 +188,85 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const providers = yield* registry.listProviders();
const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
const worker = Effect.forever(
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
);
yield* Effect.forkScoped(worker);
increment(providerRuntimeEventsTotal, {
provider: event.provider,
eventType: event.type,
}).pipe(Effect.andThen(publishRuntimeEvent(event)));
yield* Effect.forEach(adapters, (adapter) =>
Stream.runForEach(adapter.streamEvents, (event) =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
).pipe(Effect.forkScoped),
Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped),
).pipe(Effect.asVoid);
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
readonly binding: ProviderRuntimeBinding;
readonly operation: string;
}) {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
yield* Effect.annotateCurrentSpan({
"provider.operation": "recover-session",
"provider.kind": input.binding.provider,
"provider.thread_id": input.binding.threadId,
});
return yield* Effect.gen(function* () {
const adapter = yield* registry.getByProvider(input.binding.provider);
const hasResumeCursor =
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
if (hasActiveSession) {
const activeSessions = yield* adapter.listSessions();
const existing = activeSessions.find(
(session) => session.threadId === input.binding.threadId,
);
if (existing) {
yield* upsertSessionBinding(existing, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: existing.provider,
strategy: "adopt-existing",
hasResumeCursor: existing.resumeCursor !== undefined,
});
return { adapter, session: existing } as const;
}
}
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
if (!hasResumeCursor) {
return yield* toValidationError(
input.operation,
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
);
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
if (resumed.provider !== adapter.provider) {
return yield* toValidationError(
input.operation,
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
);
}
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
yield* upsertSessionBinding(resumed, input.binding.threadId);
yield* analytics.record("provider.session.recovered", {
provider: resumed.provider,
strategy: "resume-thread",
hasResumeCursor: resumed.resumeCursor !== undefined,
});
return { adapter, session: resumed } as const;
}).pipe(
withMetrics({
counter: providerSessionsTotal,
attributes: providerMetricAttributes(input.binding.provider, {
operation: "recover",
}),
}),
);
});
const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
@@ -291,52 +310,69 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
threadId,
provider: parsed.provider ?? "codex",
};
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
yield* Effect.annotateCurrentSpan({
"provider.operation": "start-session",
"provider.kind": input.provider,
"provider.thread_id": threadId,
"provider.runtime_mode": input.runtimeMode,
});
return yield* Effect.gen(function* () {
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
),
),
),
);
if (!settings.providers[input.provider].enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
if (session.provider !== adapter.provider) {
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
}).pipe(
withMetrics({
counter: providerSessionsTotal,
attributes: providerMetricAttributes(input.provider, {
operation: "start",
}),
}),
);
if (!settings.providers[input.provider].enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
if (session.provider !== adapter.provider) {
return yield* toValidationError(
"ProviderService.startSession",
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
);
}
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
});
return session;
},
);
@@ -357,32 +393,61 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
"Either input text or at least one attachment is required",
);
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
"provider.interaction_mode": input.interactionMode,
"provider.attachment_count": input.attachments.length,
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
let metricProvider = "unknown";
let metricModel = input.modelSelection?.model;
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
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 } : {}),
});
const turn = yield* routed.adapter.sendTurn(input);
yield* directory.upsert({
threadId: input.threadId,
provider: routed.adapter.provider,
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
},
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
return turn;
}).pipe(
withMetrics({
counter: providerTurnsTotal,
timer: providerTurnDuration,
attributes: () =>
providerTurnMetricAttributes({
provider: metricProvider,
model: metricModel,
extra: {
operation: "send",
},
}),
}),
);
});
const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
@@ -392,15 +457,33 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
schema: ProviderInterruptTurnInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.interruptTurn",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "interrupt-turn",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.turn_id": input.turnId,
});
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
yield* analytics.record("provider.turn.interrupted", {
provider: routed.adapter.provider,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "interrupt",
}),
}),
);
},
);
@@ -411,16 +494,34 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
schema: ProviderRespondToRequestInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToRequest",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-request",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
yield* analytics.record("provider.request.responded", {
provider: routed.adapter.provider,
decision: input.decision,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "approval-response",
}),
}),
);
},
);
@@ -432,12 +533,30 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "respond-to-user-input",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.request_id": input.requestId,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "user-input-response",
}),
}),
);
});
const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
@@ -447,18 +566,35 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
schema: ProviderStopSessionInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.stopSession",
allowRecovery: false,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "stop-session",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
});
if (routed.isActive) {
yield* routed.adapter.stopSession(routed.threadId);
}
yield* directory.remove(input.threadId);
yield* analytics.record("provider.session.stopped", {
provider: routed.adapter.provider,
});
}).pipe(
withMetrics({
counter: providerSessionsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "stop",
}),
}),
);
},
);
@@ -524,16 +660,34 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
if (input.numTurns === 0) {
return;
}
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
let metricProvider = "unknown";
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.rollbackConversation",
allowRecovery: true,
});
metricProvider = routed.adapter.provider;
yield* Effect.annotateCurrentSpan({
"provider.operation": "rollback-conversation",
"provider.kind": routed.adapter.provider,
"provider.thread_id": input.threadId,
"provider.rollback_turns": input.numTurns,
});
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
yield* analytics.record("provider.conversation.rolled_back", {
provider: routed.adapter.provider,
turns: input.numTurns,
});
}).pipe(
withMetrics({
counter: providerTurnsTotal,
outcomeAttributes: () =>
providerMetricAttributes(metricProvider, {
operation: "rollback",
}),
}),
);
});
const runStopAll = Effect.fn("runStopAll")(function* () {
+3 -1
View File
@@ -1,4 +1,5 @@
import type {
ModelCapabilities,
ServerProvider,
ServerProviderAuth,
ServerProviderModel,
@@ -102,6 +103,7 @@ export function providerModelsFromSettings(
builtInModels: ReadonlyArray<ServerProviderModel>,
provider: ServerProvider["provider"],
customModels: ReadonlyArray<string>,
defaultCustomCapabilities: ModelCapabilities | null = null,
): ReadonlyArray<ServerProviderModel> {
const resolvedBuiltInModels = [...builtInModels];
const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
@@ -117,7 +119,7 @@ export function providerModelsFromSettings(
slug: normalized,
name: normalized,
isCustom: true,
capabilities: null,
capabilities: defaultCustomCapabilities,
});
}
File diff suppressed because it is too large. Load diff
+26 -15
View File
@@ -2,7 +2,12 @@ import { Effect, Layer } from "effect";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import { ServerConfig } from "./config";
import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http";
import {
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
staticAndDevRouteLayer,
} from "./http";
import { fixPath } from "./os-jank";
import { websocketRpcRouteLayer } from "./ws";
import { OpenLive } from "./open";
@@ -25,11 +30,11 @@ 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";
import { KeybindingsLive } from "./keybindings";
import { ServerLoggerLive } from "./serverLogger";
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup";
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor";
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
@@ -42,6 +47,8 @@ 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(
Effect.gen(function* () {
@@ -155,14 +162,16 @@ const ProviderLayerLive = Layer.unwrap(
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const GitManagerLayerLive = GitManagerLive.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
);
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(
GitManagerLive.pipe(
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(RoutingTextGenerationLive),
),
),
Layer.provideMerge(GitManagerLayerLive),
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
Layer.provideMerge(GitCoreLive),
);
@@ -177,15 +186,12 @@ const WorkspaceLayerLive = Layer.mergeAll(
),
);
const RuntimeServicesLive = Layer.empty.pipe(
Layer.provideMerge(ServerRuntimeStartupLive),
Layer.provideMerge(ReactorLayerLive),
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
// 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),
@@ -200,8 +206,13 @@ const RuntimeServicesLive = Layer.empty.pipe(
Layer.provideMerge(ServerLifecycleEventsLive),
);
const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
Layer.provideMerge(RuntimeDependenciesLive),
);
export const makeRoutesLayer = Layer.mergeAll(
attachmentsRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
@@ -231,7 +242,7 @@ export const makeServerLayer = Layer.unwrap(
return serverApplicationLayer.pipe(
Layer.provideMerge(RuntimeServicesLive),
Layer.provideMerge(HttpServerLive),
Layer.provide(ServerLoggerLive),
Layer.provide(ObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(PlatformServicesLive),
);
+1 -4
View File
@@ -4,11 +4,8 @@ import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const config = yield* ServerConfig;
const { serverLogPath } = config;
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel);
const loggerLayer = Logger.layer([Logger.consolePretty(), fileLogger], {
const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], {
mergeWithExisting: false,
});
+62 -31
View File
@@ -141,6 +141,8 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
});
export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
Effect.withSpan("server.startup.heartbeat.record"),
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
Effect.asVoid,
@@ -248,7 +250,14 @@ const maybeOpenBrowser = Effect.gen(function* () {
);
});
const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.annotateSpans({ "startup.phase": phase }),
Effect.withSpan(`server.startup.${phase}`),
);
const makeServerRuntimeStartup = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const keybindings = yield* Keybindings;
const orchestrationReactor = yield* OrchestrationReactor;
const lifecycleEvents = yield* ServerLifecycleEvents;
@@ -262,46 +271,65 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
const startup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting keybindings runtime");
yield* keybindings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start keybindings runtime", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
yield* runStartupPhase(
"keybindings.start",
keybindings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start keybindings runtime", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
),
Effect.forkScoped,
),
Effect.forkScoped,
);
yield* Effect.logDebug("startup phase: starting server settings runtime");
yield* serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
detail: error.detail,
cause: error.cause,
}),
yield* runStartupPhase(
"settings.start",
serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
detail: error.detail,
cause: error.cause,
}),
),
Effect.forkScoped,
),
Effect.forkScoped,
);
yield* Effect.logDebug("startup phase: starting orchestration reactors");
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* runStartupPhase(
"reactors.start",
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
);
yield* Effect.logDebug("startup phase: preparing welcome payload");
const welcome = yield* autoBootstrapWelcome;
const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome);
yield* Effect.logDebug("startup phase: publishing welcome event", {
cwd: welcome.cwd,
projectName: welcome.projectName,
bootstrapProjectId: welcome.bootstrapProjectId,
bootstrapThreadId: welcome.bootstrapThreadId,
});
yield* lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: welcome,
});
});
yield* runStartupPhase(
"welcome.publish",
lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: welcome,
}),
);
}).pipe(
Effect.annotateSpans({
"server.mode": serverConfig.mode,
"server.port": serverConfig.port,
"server.host": serverConfig.host ?? "default",
}),
Effect.withSpan("server.startup", { kind: "server", root: true }),
);
yield* Effect.forkScoped(
Effect.gen(function* () {
@@ -319,18 +347,21 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("Accepting commands");
yield* commandGate.signalCommandReady;
yield* Effect.logDebug("startup phase: waiting for http listener");
yield* Deferred.await(httpListening);
yield* runStartupPhase("http.wait", Deferred.await(httpListening));
yield* Effect.logDebug("startup phase: publishing ready event");
yield* lifecycleEvents.publish({
version: 1,
type: "ready",
payload: { at: new Date().toISOString() },
});
yield* runStartupPhase(
"ready.publish",
lifecycleEvents.publish({
version: 1,
type: "ready",
payload: { at: new Date().toISOString() },
}),
);
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
yield* maybeOpenBrowser;
yield* runStartupPhase("browser.open", maybeOpenBrowser);
yield* Effect.logDebug("startup phase: complete");
}),
);
+26
View File
@@ -171,6 +171,24 @@ 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;
@@ -197,6 +215,10 @@ 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",
@@ -208,6 +230,10 @@ 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",
@@ -125,17 +125,19 @@ const makeAnalyticsService = Effect.gen(function* () {
}
}).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const record: AnalyticsServiceShape["record"] = Effect.fn("record")(
function* (event, properties) {
if (!telemetryConfig.enabled || !identifier) return;
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
});
const enqueueResult = yield* enqueueBufferedEvent(event, properties);
if (enqueueResult.dropped) {
yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
size: enqueueResult.size,
event,
});
}
},
);
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
@@ -428,6 +428,85 @@ 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();
+64 -36
View File
@@ -23,6 +23,11 @@ import {
} from "effect";
import { ServerConfig } from "../../config";
import {
increment,
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics";
import { runProcess } from "../../processRunner";
import {
TerminalCwdError,
@@ -75,6 +80,7 @@ interface TerminalStartInput {
threadId: string;
terminalId: string;
cwd: string;
worktreePath?: string | null;
cols: number;
rows: number;
env?: Record<string, string>;
@@ -84,6 +90,7 @@ interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
@@ -138,6 +145,7 @@ 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,
@@ -1294,10 +1302,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
eventType: "started" | "restarted",
) {
yield* stopProcess(session);
yield* Effect.annotateCurrentSpan({
"terminal.thread_id": session.threadId,
"terminal.id": session.terminalId,
"terminal.event_type": eventType,
"terminal.cwd": input.cwd,
});
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;
@@ -1314,45 +1329,49 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
let startedShell: string | null = null;
const startResult = yield* Effect.result(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
Effect.andThen(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
const processPid = ptyProcess.pid;
const unsubscribeData = ptyProcess.onData((data) => {
if (!enqueueProcessEvent(session, processPid, { type: "output", data })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const unsubscribeExit = ptyProcess.onExit((event) => {
if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const processPid = ptyProcess.pid;
const unsubscribeData = ptyProcess.onData((data) => {
if (!enqueueProcessEvent(session, processPid, { type: "output", data })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
const unsubscribeExit = ptyProcess.onExit((event) => {
if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) {
return;
}
runFork(drainProcessEvents(session, processPid));
});
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = new Date().toISOString();
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: snapshot(session),
});
}),
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: snapshot(session),
});
}),
),
),
);
if (startResult._tag === "Success") {
@@ -1562,6 +1581,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history,
@@ -1595,6 +1615,7 @@ 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 } : {}),
@@ -1614,6 +1635,7 @@ 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 = "";
@@ -1627,6 +1649,7 @@ 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 = [];
@@ -1646,6 +1669,7 @@ 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 } : {}),
@@ -1722,6 +1746,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
withThreadLock(
input.threadId,
Effect.gen(function* () {
yield* increment(terminalRestartsTotal, { scope: "thread" });
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
yield* assertValidCwd(input.cwd);
@@ -1735,6 +1760,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
threadId: input.threadId,
terminalId,
cwd: input.cwd,
worktreePath: input.worktreePath ?? null,
status: "starting",
pid: null,
history: "",
@@ -1764,6 +1790,7 @@ 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);
}
@@ -1782,6 +1809,7 @@ 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,6 +37,7 @@ export interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: string;
+560 -118
View File
@@ -1,5 +1,8 @@
import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
import {
CommandId,
EventId,
type OrchestrationCommand,
type GitActionProgressEvent,
type GitManagerServiceError,
OrchestrationDispatchCommandError,
@@ -11,6 +14,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
OrchestrationReplayEventsError,
ThreadId,
type TerminalEvent,
WS_METHODS,
WsRpcGroup,
@@ -23,11 +27,17 @@ 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";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./observability/RpcInstrumentation";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { ServerLifecycleEvents } from "./serverLifecycleEvents";
import { ServerRuntimeStartup } from "./serverRuntimeStartup";
@@ -36,6 +46,7 @@ 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* () {
@@ -46,6 +57,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
const open = yield* Open;
const gitManager = yield* GitManager;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const terminalManager = yield* TerminalManager;
const providerRegistry = yield* ProviderRegistry;
const config = yield* ServerConfig;
@@ -54,6 +66,264 @@ 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;
@@ -67,72 +337,117 @@ const WsRpcLayer = WsRpcGroup.toLayer(
issues: keybindingsConfig.issues,
providers,
availableEditors: resolveAvailableEditors(),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
otlpTracesEnabled: config.otlpTracesUrl !== undefined,
...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}),
otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
},
settings,
};
});
const refreshGitStatus = (cwd: string) =>
gitStatusBroadcaster
.refreshStatus(cwd)
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
return WsRpcGroup.of({
[ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
projectionSnapshotQuery.getSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot",
cause,
}),
),
),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand));
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getSnapshot,
projectionSnapshotQuery.getSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
const result = yield* dispatchNormalizedCommand(normalizedCommand);
if (normalizedCommand.type === "thread.archive") {
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close thread terminals after archive", {
threadId: normalizedCommand.threadId,
error: error.message,
}),
),
);
}
return result;
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
checkpointDiffQuery.getTurnDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetTurnDiffError({
message: "Failed to load turn diff",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getTurnDiff,
checkpointDiffQuery.getTurnDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetTurnDiffError({
message: "Failed to load turn diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
checkpointDiffQuery.getFullThreadDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetFullThreadDiffError({
message: "Failed to load full thread diff",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
checkpointDiffQuery.getFullThreadDiff(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetFullThreadDiffError({
message: "Failed to load full thread diff",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
Stream.runCollect(
orchestrationEngine.readEvents(
clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
message: "Failed to replay orchestration events",
cause,
}),
observeRpcEffect(
ORCHESTRATION_WS_METHODS.replayEvents,
Stream.runCollect(
orchestrationEngine.readEvents(
clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
),
).pipe(
Effect.map((events) => Array.from(events)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
message: "Failed to replay orchestration events",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeOrchestrationDomainEvents,
Effect.gen(function* () {
const snapshot = yield* orchestrationEngine.getReadModel();
const fromSequenceExclusive = snapshot.snapshotSequence;
@@ -187,82 +502,202 @@ const WsRpcLayer = WsRpcGroup.toLayer(
Stream.flatMap((events) => Stream.fromIterable(events)),
);
}),
{ "rpc.aggregate": "orchestration" },
),
[WS_METHODS.serverGetConfig]: (_input) => loadServerConfig,
[WS_METHODS.serverRefreshProviders]: (_input) =>
providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
return { keybindings: keybindingsConfig, issues: [] };
[WS_METHODS.serverGetConfig]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverRefreshProviders]: (_input) =>
observeRpcEffect(
WS_METHODS.serverRefreshProviders,
providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
observeRpcEffect(
WS_METHODS.serverUpsertKeybinding,
Effect.gen(function* () {
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
return { keybindings: keybindingsConfig, issues: [] };
}),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverGetSettings]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverUpdateSettings]: ({ patch }) =>
observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings,
[WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch),
[WS_METHODS.projectsSearchEntries]: (input) =>
workspaceEntries.search(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchEntriesError({
message: `Failed to search workspace entries: ${cause.detail}`,
cause,
}),
observeRpcEffect(
WS_METHODS.projectsSearchEntries,
workspaceEntries.search(input).pipe(
Effect.mapError(
(cause) =>
new ProjectSearchEntriesError({
message: `Failed to search workspace entries: ${cause.detail}`,
cause,
}),
),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.projectsWriteFile]: (input) =>
workspaceFileSystem.writeFile(input).pipe(
Effect.mapError((cause) => {
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
? "Workspace file path must stay within the project root."
: "Failed to write workspace file";
return new ProjectWriteFileError({
message,
cause,
});
}),
),
[WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input),
[WS_METHODS.gitStatus]: (input) => gitManager.status(input),
[WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd),
[WS_METHODS.gitRunStackedAction]: (input) =>
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
gitManager
.runStackedAction(input, {
actionId: input.actionId,
progressReporter: {
publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
},
})
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () => Queue.end(queue).pipe(Effect.asVoid),
}),
),
),
[WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input),
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
gitManager.preparePullRequestThread(input),
[WS_METHODS.gitListBranches]: (input) => git.listBranches(input),
[WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input),
[WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input),
[WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input),
[WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)),
[WS_METHODS.gitInit]: (input) => git.initRepo(input),
[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
[WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
[WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
[WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
terminalManager.subscribe((event) => Queue.offer(queue, event)),
(unsubscribe) => Effect.sync(unsubscribe),
observeRpcEffect(
WS_METHODS.projectsWriteFile,
workspaceFileSystem.writeFile(input).pipe(
Effect.mapError((cause) => {
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
? "Workspace file path must stay within the project root."
: "Failed to write workspace file";
return new ProjectWriteFileError({
message,
cause,
});
}),
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.shellOpenInEditor]: (input) =>
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
"rpc.aggregate": "workspace",
}),
[WS_METHODS.subscribeGitStatus]: (input) =>
observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitRefreshStatus]: (input) =>
observeRpcEffect(
WS_METHODS.gitRefreshStatus,
gitStatusBroadcaster.refreshStatus(input.cwd),
{
"rpc.aggregate": "git",
},
),
[WS_METHODS.gitPull]: (input) =>
observeRpcEffect(
WS_METHODS.gitPull,
git.pullCurrentBranch(input.cwd).pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Effect.failCause(cause),
onSuccess: (result) =>
refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
}),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRunStackedAction]: (input) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
gitManager
.runStackedAction(input, {
actionId: input.actionId,
progressReporter: {
publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
},
})
.pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Queue.failCause(queue, cause),
onSuccess: () =>
refreshGitStatus(input.cwd).pipe(
Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
),
}),
),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitResolvePullRequest]: (input) =>
observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager
.preparePullRequestThread(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
"rpc.aggregate": "git",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateWorktree,
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitRemoveWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitRemoveWorktree,
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCreateBranch]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateBranch,
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitCheckout]: (input) =>
observeRpcEffect(
WS_METHODS.gitCheckout,
Effect.scoped(git.checkoutBranch(input)).pipe(
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitInit]: (input) =>
observeRpcEffect(
WS_METHODS.gitInit,
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalWrite]: (input) =>
observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalResize]: (input) =>
observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalClear]: (input) =>
observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalRestart]: (input) =>
observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.terminalClose]: (input) =>
observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
"rpc.aggregate": "terminal",
}),
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
observeRpcStream(
WS_METHODS.subscribeTerminalEvents,
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
terminalManager.subscribe((event) => Queue.offer(queue, event)),
(unsubscribe) => Effect.sync(unsubscribe),
),
),
{ "rpc.aggregate": "terminal" },
),
[WS_METHODS.subscribeServerConfig]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeServerConfig,
Effect.gen(function* () {
const keybindingsUpdates = keybindings.streamChanges.pipe(
Stream.map((event) => ({
@@ -297,9 +732,11 @@ const WsRpcLayer = WsRpcGroup.toLayer(
Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
);
}),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.subscribeServerLifecycle]: (_input) =>
Stream.unwrap(
observeRpcStreamEffect(
WS_METHODS.subscribeServerLifecycle,
Effect.gen(function* () {
const snapshot = yield* lifecycleEvents.snapshot;
const snapshotEvents = Array.from(snapshot.events).toSorted(
@@ -310,6 +747,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
);
return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
}),
{ "rpc.aggregate": "server" },
),
});
}),
@@ -317,9 +755,13 @@ const WsRpcLayer = WsRpcGroup.toLayer(
export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe(
Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)),
);
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
spanPrefix: "ws.rpc",
spanAttributes: {
"rpc.transport": "websocket",
"rpc.system": "effect-rpc",
},
}).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)));
return HttpRouter.add(
"GET",
"/ws",
+4 -52
View File
@@ -1,5 +1,9 @@
import type { GitBranch } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "@t3tools/shared/git";
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
@@ -43,58 +47,6 @@ export function resolveBranchToolbarValue(input: {
return currentGitBranch ?? activeThreadBranch;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
if (branch.remoteName !== "origin") {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
@@ -1,5 +1,5 @@
import type { GitBranch } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { ChevronDownIcon } from "lucide-react";
import {
@@ -14,16 +14,11 @@ import {
useTransition,
} from "react";
import {
gitBranchesQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
invalidateGitQueries,
} from "../lib/gitReactQuery";
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { readNativeApi } from "../nativeApi";
import { parsePullRequestReference } from "../pullRequestReference";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
EnvMode,
resolveBranchSelectionTarget,
@@ -38,6 +33,7 @@ import {
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxStatus,
ComboboxTrigger,
} from "./ui/combobox";
import { toastManager } from "./ui/toast";
@@ -89,11 +85,32 @@ export function BranchToolbarBranchSelector({
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branchStatusQuery = useQuery(gitStatusQueryOptions(branchCwd));
const branchStatusQuery = useGitStatus(branchCwd);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
useEffect(() => {
if (!branchCwd) return;
void queryClient.prefetchInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({ cwd: branchCwd, query: "" }),
);
}, [branchCwd, queryClient]);
const {
data: branchesSearchData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isPending: isBranchesSearchPending,
} = useInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
}),
);
const branches = useMemo(
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
[branchesQuery.data?.branches],
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
[branchesSearchData?.pages],
);
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
@@ -108,8 +125,6 @@ export function BranchToolbarBranchSelector({
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
[branches],
);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
const isSelectingWorktreeBase =
@@ -156,11 +171,21 @@ export function BranchToolbarBranchSelector({
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
? "Loading branches..."
: isFetchingNextPage
? "Loading more branches..."
: hasNextPage
? `Showing ${branches.length} of ${totalBranchCount} branches`
: null;
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.branches(branchCwd) })
.catch(() => undefined);
});
};
@@ -198,29 +223,26 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: selectionTarget.checkoutCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
const checkoutResult = await api.git.checkout({
cwd: selectionTarget.checkoutCwd,
branch: branch.name,
});
const nextBranchName = branch.isRemote
? (checkoutResult.branch ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
});
};
@@ -233,32 +255,24 @@ export function BranchToolbarBranchSelector({
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
const createBranchResult = await api.git.createBranch({
cwd: branchCwd,
branch: name,
checkout: true,
});
setOptimisticBranch(createBranchResult.branch);
onSetThreadBranch(createBranchResult.branch, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add({
type: "error",
title: "Failed to create branch.",
title: "Failed to create and checkout branch.",
description: toBranchActionErrorMessage(error),
});
return;
}
setOptimisticBranch(name);
onSetThreadBranch(name, activeWorktreePath);
setBranchQuery("");
});
};
@@ -295,6 +309,24 @@ export function BranchToolbarBranchSelector({
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const maybeFetchNextBranchPage = useCallback(() => {
if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
return;
}
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement) {
return;
}
const distanceFromBottom =
scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
if (distanceFromBottom > 96) {
return;
}
void fetchNextPage().catch(() => undefined);
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListVirtualizer = useVirtualizer({
count: filteredBranchPickerItems.length,
estimateSize: (index) =>
@@ -331,6 +363,35 @@ export function BranchToolbarBranchSelector({
shouldVirtualizeBranchList,
]);
useEffect(() => {
if (!isBranchMenuOpen) {
return;
}
branchListScrollElementRef.current?.scrollTo({ top: 0 });
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement || !isBranchMenuOpen) {
return;
}
const handleScroll = () => {
maybeFetchNextBranchPage();
};
scrollElement.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
return () => {
scrollElement.removeEventListener("scroll", handleScroll);
};
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
useEffect(() => {
maybeFetchNextBranchPage();
}, [branches.length, maybeFetchNextBranchPage]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
@@ -425,7 +486,7 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={(branchesQuery.isLoading && branches.length === 0) || isBranchActionPending}
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
>
<span className="max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon />
@@ -468,6 +529,7 @@ export function BranchToolbarBranchSelector({
filteredBranchPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))
)}
</ComboboxList>
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
);
+351 -51
View File
@@ -31,18 +31,28 @@ 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='300'></svg>";
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
interface TestFixture {
snapshot: OrchestrationReadModel;
@@ -92,9 +102,9 @@ const TEXT_VIEWPORT_MATRIX = [
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
] as const satisfies readonly ViewportSpec[];
const ATTACHMENT_VIEWPORT_MATRIX = [
DEFAULT_VIEWPORT,
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 56 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 56 },
{ ...DEFAULT_VIEWPORT, attachmentTolerancePx: 120 },
{ name: "mobile", width: 430, height: 932, textTolerancePx: 56, attachmentTolerancePx: 120 },
{ name: "narrow", width: 320, height: 700, textTolerancePx: 84, attachmentTolerancePx: 120 },
] as const satisfies readonly ViewportSpec[];
interface UserRowMeasurement {
@@ -135,6 +145,12 @@ function createBaseServerConfig(): ServerConfig {
},
],
availableEditors: [],
observability: {
logsDirectoryPath: "/repo/project/.t3/logs",
localTracingEnabled: true,
otlpTracesEnabled: false,
otlpMetricsEnabled: false,
},
settings: {
...DEFAULT_SERVER_SETTINGS,
...DEFAULT_CLIENT_SETTINGS,
@@ -217,6 +233,7 @@ function createSnapshotForTargetUser(options: {
name: `attachment-${attachmentIndex + 1}.png`,
mimeType: "image/png",
sizeBytes: 128,
previewUrl: `/attachments/attachment-${attachmentIndex + 1}`,
}))
: undefined;
@@ -390,6 +407,22 @@ async function waitForWsClient(): Promise<void> {
(request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents,
),
).toBe(true);
expect(
wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
).toBe(true);
expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe(
true,
);
},
{ timeout: 8_000, interval: 16 },
);
}
async function waitForAppBootstrap(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
expect(useStore.getState().bootstrapComplete).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
@@ -632,6 +665,8 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [
{
name: "main",
@@ -642,21 +677,6 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
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: [],
@@ -671,6 +691,12 @@ 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: "",
@@ -848,7 +874,7 @@ async function expectComposerActionsContained(): Promise<void> {
}
async function waitForInteractionModeButton(
expectedLabel: "Chat" | "Plan",
expectedLabel: "Build" | "Plan",
): Promise<HTMLButtonElement> {
return waitForElement(
() =>
@@ -1026,10 +1052,17 @@ async function mountChatView(options: {
}),
);
const screen = await render(<RouterProvider router={router} />, {
container: host,
});
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{
container: host,
},
);
await waitForWsClient();
await waitForAppBootstrap();
await waitForLayout();
const cleanup = async () => {
@@ -1120,7 +1153,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
return [];
},
});
__resetNativeApiForTests();
await __resetNativeApiForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
@@ -1138,6 +1171,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
threads: [],
bootstrapComplete: false,
});
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
});
afterEach(() => {
@@ -1274,7 +1314,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
snapshot: createSnapshotForTargetUser({
targetMessageId,
targetText: userText,
targetAttachmentCount: 3,
targetAttachmentCount: 2,
}),
});
@@ -1288,7 +1328,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{
role: "user",
text: userText,
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }, { id: "attachment-3" }],
attachments: [{ id: "attachment-1" }, { id: "attachment-2" }],
},
{ timelineWidthPx: timelineWidthMeasuredPx },
);
@@ -1361,6 +1401,74 @@ 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();
@@ -1702,7 +1810,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("runs setup scripts after preparing a pull request worktree thread", async () => {
it("lets the server own setup after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
@@ -1807,45 +1915,188 @@ 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 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",
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,
},
});
},
{ 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(
() => {
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",
});
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();
},
{ timeout: 8_000, interval: 16 },
);
} finally {
resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 });
await mounted.cleanup();
}
});
@@ -1860,7 +2111,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const initialModeButton = await waitForInteractionModeButton("Chat");
const initialModeButton = await waitForInteractionModeButton("Build");
expect(initialModeButton.title).toContain("enter plan mode");
window.dispatchEvent(
@@ -1873,7 +2124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
await waitForLayout();
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
@@ -1889,7 +2140,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Plan")).title).toContain(
"return to normal chat mode",
"return to normal build mode",
);
},
{ timeout: 8_000, interval: 16 },
@@ -1906,7 +2157,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
},
{ timeout: 8_000, interval: 16 },
);
@@ -2582,6 +2833,55 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("uses the active worktree path when saving a proposed plan to the workspace", async () => {
const snapshot = createSnapshotWithLongProposedPlan();
const threads = snapshot.threads.slice();
const targetThreadIndex = threads.findIndex((thread) => thread.id === THREAD_ID);
const targetThread = targetThreadIndex >= 0 ? threads[targetThreadIndex] : undefined;
if (targetThread) {
threads[targetThreadIndex] = {
...targetThread,
worktreePath: "/repo/worktrees/plan-thread",
};
}
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: {
...snapshot,
threads,
},
});
try {
const planActionsButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Plan actions"]'),
"Unable to find proposed plan actions button.",
);
planActionsButton.click();
const saveToWorkspaceItem = await waitForElement(
() =>
(Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find(
(item) => item.textContent?.trim() === "Save to workspace",
) ?? null) as HTMLElement | null,
'Unable to find "Save to workspace" menu item.',
);
saveToWorkspaceItem.click();
await vi.waitFor(
() => {
expect(document.body.textContent).toContain(
"Enter a path relative to /repo/worktrees/plan-thread.",
);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("keeps pending-question footer actions inside the composer after a real resize", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
@@ -3,10 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
waitForStartedServerThread,
} from "./ChatView.logic";
@@ -75,6 +77,98 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
describe("reconcileMountedTerminalThreadIds", () => {
it("keeps previously mounted open threads and adds the active open thread", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-hidden"),
ThreadId.makeUnsafe("thread-stale"),
],
openThreadIds: [ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")],
activeThreadId: ThreadId.makeUnsafe("thread-active"),
activeThreadTerminalOpen: true,
}),
).toEqual([ThreadId.makeUnsafe("thread-hidden"), ThreadId.makeUnsafe("thread-active")]);
});
it("drops mounted threads once their terminal drawer is no longer open", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [ThreadId.makeUnsafe("thread-closed")],
openThreadIds: [],
activeThreadId: ThreadId.makeUnsafe("thread-closed"),
activeThreadTerminalOpen: false,
}),
).toEqual([]);
});
it("keeps only the most recently active hidden terminal threads", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
],
openThreadIds: [
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
],
activeThreadId: ThreadId.makeUnsafe("thread-4"),
activeThreadTerminalOpen: true,
maxHiddenThreadCount: 2,
}),
).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-3"),
ThreadId.makeUnsafe("thread-4"),
]);
});
it("moves the active thread to the end so it is treated as most recently used", () => {
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds: [
ThreadId.makeUnsafe("thread-a"),
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
],
openThreadIds: [
ThreadId.makeUnsafe("thread-a"),
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
],
activeThreadId: ThreadId.makeUnsafe("thread-a"),
activeThreadTerminalOpen: true,
maxHiddenThreadCount: 2,
}),
).toEqual([
ThreadId.makeUnsafe("thread-b"),
ThreadId.makeUnsafe("thread-c"),
ThreadId.makeUnsafe("thread-a"),
]);
});
it("defaults to the hidden mounted terminal cap", () => {
const currentThreadIds = Array.from(
{ length: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS + 2 },
(_, index) => ThreadId.makeUnsafe(`thread-${index + 1}`),
);
expect(
reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: currentThreadIds,
activeThreadId: null,
activeThreadTerminalOpen: false,
}),
).toEqual(currentThreadIds.slice(-MAX_HIDDEN_MOUNTED_TERMINAL_THREADS));
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
+32
View File
@@ -11,6 +11,7 @@ import {
} from "../lib/terminalContext";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
const WORKTREE_BRANCH_PREFIX = "t3code";
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
@@ -43,6 +44,37 @@ export function buildLocalDraftThread(
};
}
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<ThreadId>;
openThreadIds: ReadonlyArray<ThreadId>;
activeThreadId: ThreadId | null;
activeThreadTerminalOpen: boolean;
maxHiddenThreadCount?: number;
}): ThreadId[] {
const openThreadIdSet = new Set(input.openThreadIds);
const hiddenThreadIds = input.currentThreadIds.filter(
(threadId) => threadId !== input.activeThreadId && openThreadIdSet.has(threadId),
);
const maxHiddenThreadCount = Math.max(
0,
input.maxHiddenThreadCount ?? MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
);
const nextThreadIds =
hiddenThreadIds.length > maxHiddenThreadCount
? hiddenThreadIds.slice(-maxHiddenThreadCount)
: hiddenThreadIds;
if (
input.activeThreadId &&
input.activeThreadTerminalOpen &&
!nextThreadIds.includes(input.activeThreadId)
) {
nextThreadIds.push(input.activeThreadId);
}
return nextThreadIds;
}
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
return;
+374 -217
View File
@@ -21,12 +21,13 @@ 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 { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { isElectron } from "../env";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
@@ -111,10 +112,7 @@ 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";
@@ -173,6 +171,7 @@ import {
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildTemporaryWorktreeBranchName,
@@ -186,6 +185,7 @@ import {
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
reconcileMountedTerminalThreadIds,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
@@ -197,6 +197,7 @@ import {
useServerConfig,
useServerKeybindings,
} from "~/rpc/serverState";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -331,12 +332,14 @@ interface ChatViewProps {
threadId: ThreadId;
}
interface PendingPullRequestSetupRequest {
interface TerminalLaunchContext {
threadId: ThreadId;
worktreePath: string;
scriptId: string;
cwd: string;
worktreePath: string | null;
}
type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
@@ -404,10 +407,176 @@ function useLocalDispatchState(input: {
};
}
interface PersistentThreadTerminalDrawerProps {
threadId: ThreadId;
visible: boolean;
launchContext: PersistentTerminalLaunchContext | null;
focusRequestId: number;
splitShortcutLabel: string | undefined;
newShortcutLabel: string | undefined;
closeShortcutLabel: string | undefined;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
}
function PersistentThreadTerminalDrawer({
threadId,
visible,
launchContext,
focusRequestId,
splitShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
const serverThread = useThreadById(threadId);
const draftThread = useComposerDraftStore(
(store) => store.draftThreadsByThreadId[threadId] ?? null,
);
const project = useProjectById(serverThread?.projectId ?? draftThread?.projectId);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, threadId),
);
const storeSetTerminalHeight = useTerminalStateStore((state) => state.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((state) => state.splitTerminal);
const storeNewTerminal = useTerminalStateStore((state) => state.newTerminal);
const storeSetActiveTerminal = useTerminalStateStore((state) => state.setActiveTerminal);
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
? projectScriptCwd({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: null),
[effectiveWorktreePath, launchContext?.cwd, project],
);
const runtimeEnv = useMemo(
() =>
project
? projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: effectiveWorktreePath,
})
: {},
[effectiveWorktreePath, project],
);
const bumpFocusRequestId = useCallback(() => {
if (!visible) {
return;
}
setLocalFocusRequestId((value) => value + 1);
}, [visible]);
const setTerminalHeight = useCallback(
(height: number) => {
storeSetTerminalHeight(threadId, height);
},
[storeSetTerminalHeight, threadId],
);
const splitTerminal = useCallback(() => {
storeSplitTerminal(threadId, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeSplitTerminal, threadId]);
const createNewTerminal = useCallback(() => {
storeNewTerminal(threadId, `terminal-${randomUUID()}`);
bumpFocusRequestId();
}, [bumpFocusRequestId, storeNewTerminal, threadId]);
const activateTerminal = useCallback(
(terminalId: string) => {
storeSetActiveTerminal(threadId, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeSetActiveTerminal, threadId],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
if (!api) return;
const isFinalTerminal = terminalState.terminalIds.length <= 1;
const fallbackExitWrite = () =>
api.terminal.write({ threadId, terminalId, data: "exit\n" }).catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void (async () => {
if (isFinalTerminal) {
await api.terminal.clear({ threadId, terminalId }).catch(() => undefined);
}
await api.terminal.close({
threadId,
terminalId,
deleteHistory: true,
});
})().catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
storeCloseTerminal(threadId, terminalId);
bumpFocusRequestId();
},
[bumpFocusRequestId, storeCloseTerminal, terminalState.terminalIds.length, threadId],
);
const handleAddTerminalContext = useCallback(
(selection: TerminalContextSelection) => {
if (!visible) {
return;
}
onAddTerminalContext(selection);
},
[onAddTerminalContext, visible],
);
if (!project || !terminalState.terminalOpen || !cwd) {
return null;
}
return (
<div className={visible ? undefined : "hidden"}>
<ThreadTerminalDrawer
threadId={threadId}
cwd={cwd}
worktreePath={effectiveWorktreePath}
runtimeEnv={runtimeEnv}
visible={visible}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={visible ? splitShortcutLabel : undefined}
newShortcutLabel={visible ? newShortcutLabel : undefined}
closeShortcutLabel={visible ? closeShortcutLabel : undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={handleAddTerminalContext}
/>
</div>
);
}
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],
@@ -423,8 +592,6 @@ 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;
@@ -515,8 +682,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [pullRequestDialogState, setPullRequestDialogState] =
useState<PullRequestDialogState | null>(null);
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
useState<PendingPullRequestSetupRequest | null>(null);
const [terminalLaunchContext, setTerminalLaunchContext] = useState<TerminalLaunchContext | null>(
null,
);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
Record<string, string[]>
>({});
@@ -565,15 +733,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
setMessagesScrollElement(element);
}, []);
const terminalState = useTerminalStateStore((state) =>
selectThreadTerminalState(state.terminalStateByThreadId, threadId),
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
const terminalState = useMemo(
() => selectThreadTerminalState(terminalStateByThreadId, threadId),
[terminalStateByThreadId, threadId],
);
const openTerminalThreadIds = useMemo(
() =>
Object.entries(terminalStateByThreadId).flatMap(([nextThreadId, nextTerminalState]) =>
nextTerminalState.terminalOpen ? [nextThreadId as ThreadId] : [],
),
[terminalStateByThreadId],
);
const storeSetTerminalOpen = useTerminalStateStore((s) => s.setTerminalOpen);
const storeSetTerminalHeight = useTerminalStateStore((s) => s.setTerminalHeight);
const storeSplitTerminal = useTerminalStateStore((s) => s.splitTerminal);
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);
const draftThreadIds = useMemo(
() => Object.keys(draftThreadsByThreadId) as ThreadId[],
[draftThreadsByThreadId],
);
const [mountedTerminalThreadIds, setMountedTerminalThreadIds] = useState<ThreadId[]>([]);
const setPrompt = useCallback(
(nextPrompt: string) => {
@@ -655,6 +845,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const existingOpenTerminalThreadIds = useMemo(() => {
const existingThreadIds = new Set<ThreadId>([...serverThreadIds, ...draftThreadIds]);
return openTerminalThreadIds.filter((nextThreadId) => existingThreadIds.has(nextThreadId));
}, [draftThreadIds, openTerminalThreadIds, serverThreadIds]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
@@ -673,6 +867,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
useEffect(() => {
setMountedTerminalThreadIds((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
currentThreadIds,
openThreadIds: existingOpenTerminalThreadIds,
activeThreadId,
activeThreadTerminalOpen: Boolean(activeThreadId && terminalState.terminalOpen),
maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
});
return currentThreadIds.length === nextThreadIds.length &&
currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])
? currentThreadIds
: nextThreadIds;
});
}, [activeThreadId, existingOpenTerminalThreadIds, terminalState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = useProjectById(activeThread?.projectId);
@@ -748,24 +957,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const handlePreparedPullRequestThread = useCallback(
async (input: { branch: string; worktreePath: string | null }) => {
const targetThreadId = await openOrReuseProjectDraftThread({
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);
}
},
[activeProject, openOrReuseProjectDraftThread],
[openOrReuseProjectDraftThread],
);
useEffect(() => {
@@ -1201,7 +1399,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
(debouncerState) => ({ isPending: debouncerState.isPending }),
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const gitStatusQuery = useGitStatus(gitCwd);
const keybindings = useServerKeybindings();
const availableEditors = useServerAvailableEditors();
const modelOptionsByProvider = useMemo(
@@ -1278,7 +1476,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
type: "slash-command",
command: "default",
label: "/default",
description: "Switch this thread back to normal chat mode",
description: "Switch this thread back to normal build mode",
},
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
const query = composerTrigger.query.trim().toLowerCase();
@@ -1328,17 +1526,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const threadTerminalRuntimeEnv = useMemo(() => {
if (!activeProjectCwd) return {};
return projectScriptRuntimeEnv({
project: {
cwd: activeProjectCwd,
},
worktreePath: activeThreadWorktreePath,
});
}, [activeProjectCwd, activeThreadWorktreePath]);
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -1407,17 +1601,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
const nextError = sanitizeThreadErrorMessage(error);
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
setStoreThreadError(targetThreadId, error);
setStoreThreadError(targetThreadId, nextError);
return;
}
setLocalDraftErrorsByThreadId((existing) => {
if ((existing[targetThreadId] ?? null) === error) {
if ((existing[targetThreadId] ?? null) === nextError) {
return existing;
}
return {
...existing,
[targetThreadId]: error,
[targetThreadId]: nextError,
};
});
},
@@ -1481,13 +1676,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
},
[activeThreadId, storeSetTerminalOpen],
);
const setTerminalHeight = useCallback(
(height: number) => {
if (!activeThreadId) return;
storeSetTerminalHeight(activeThreadId, height);
},
[activeThreadId, storeSetTerminalHeight],
);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
setTerminalOpen(!terminalState.terminalOpen);
@@ -1504,14 +1692,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
storeNewTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, storeNewTerminal]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
storeSetActiveTerminal(activeThreadId, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, storeSetActiveTerminal],
);
const closeTerminal = useCallback(
(terminalId: string) => {
const api = readNativeApi();
@@ -1572,7 +1752,13 @@ 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);
@@ -1585,7 +1771,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
project: {
cwd: activeProject.cwd,
},
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
worktreePath: targetWorktreePath,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
@@ -1593,6 +1779,7 @@ 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,
@@ -1601,6 +1788,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
env: runtimeEnv,
};
@@ -1634,44 +1822,6 @@ 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;
@@ -1993,13 +2143,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
if (scrolledUp && !isNearBottom) {
shouldAutoScrollRef.current = false;
}
} else if (shouldAutoScrollRef.current && !isNearBottom) {
@@ -2364,6 +2514,74 @@ export default function ChatView({ threadId }: ChatViewProps) {
? (draftThread?.envMode ?? "local")
: "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;
const timer = window.setInterval(() => {
@@ -2778,36 +2996,8 @@ 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];
@@ -2835,48 +3025,6 @@ 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({
@@ -2897,8 +3045,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginLocalDispatch({ preparingWorktree: false });
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 });
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
@@ -2913,19 +3090,11 @@ 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 &&
@@ -2987,14 +3156,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
})
.catch((err: unknown) => {
setStoreThreadError(
setThreadError(
activeThreadId,
err instanceof Error ? err.message : "Failed to submit approval decision.",
);
});
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
},
[activeThreadId, setStoreThreadError],
[activeThreadId, setThreadError],
);
const onRespondToUserInput = useCallback(
@@ -3015,14 +3184,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: new Date().toISOString(),
})
.catch((err: unknown) => {
setStoreThreadError(
setThreadError(
activeThreadId,
err instanceof Error ? err.message : "Failed to submit user input.",
);
});
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
},
[activeThreadId, setStoreThreadError],
[activeThreadId, setThreadError],
);
const setActivePendingUserInputQuestionIndex = useCallback(
@@ -3836,7 +4005,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
/>
</div>
@@ -3860,7 +4029,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
<form
ref={composerFormRef}
onSubmit={onSend}
className="mx-auto w-full min-w-0 max-w-[52rem]"
className="mx-auto w-full min-w-0 max-w-208"
data-chat-composer-form="true"
>
<div
@@ -4115,13 +4284,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
onClick={toggleInteractionMode}
title={
interactionMode === "plan"
? "Plan mode — click to return to normal chat mode"
? "Plan mode — click to return to normal build mode"
: "Default mode — click to enter plan mode"
}
>
<BotIcon />
<span className="sr-only sm:not-sr-only">
{interactionMode === "plan" ? "Plan" : "Chat"}
{interactionMode === "plan" ? "Plan" : "Build"}
</span>
</Button>
@@ -4250,6 +4419,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
<PullRequestThreadDialog
key={pullRequestDialogState.key}
open
threadId={activeThread.id}
cwd={activeProject?.cwd ?? null}
initialReference={pullRequestDialogState.initialReference}
onOpenChange={(open) => {
@@ -4269,7 +4439,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
@@ -4284,34 +4454,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
</div>
{/* end horizontal flex container */}
{(() => {
if (!terminalState.terminalOpen || !activeProject) {
return null;
}
return (
<ThreadTerminalDrawer
key={activeThread.id}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={terminalState.terminalHeight}
terminalIds={terminalState.terminalIds}
activeTerminalId={terminalState.activeTerminalId}
terminalGroups={terminalState.terminalGroups}
activeTerminalGroupId={terminalState.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={setTerminalHeight}
onAddTerminalContext={addTerminalContextToDraft}
/>
);
})()}
{mountedTerminalThreadIds.map((mountedThreadId) => (
<PersistentThreadTerminalDrawer
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}
closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
{expandedImage && expandedImageItem && (
<div
+3 -3
View File
@@ -19,7 +19,7 @@ import {
useState,
} from "react";
import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { useGitStatus } from "~/lib/gitStatusState";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
@@ -189,8 +189,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
const gitStatusQuery = useGitStatus(activeCwd ?? null);
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -0,0 +1,276 @@
import { ThreadId } from "@t3tools/contracts";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const THREAD_A = ThreadId.makeUnsafe("thread-a");
const THREAD_B = ThreadId.makeUnsafe("thread-b");
const GIT_CWD = "/repo/project";
const BRANCH_NAME = "feature/toast-scope";
const {
invalidateGitQueriesSpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
setThreadBranchSpy,
toastAddSpy,
toastCloseSpy,
toastPromiseSpy,
toastUpdateSpy,
} = vi.hoisted(() => ({
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionMutateAsyncSpy: vi.fn(() => new Promise<never>(() => undefined)),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
toastCloseSpy: vi.fn(),
toastPromiseSpy: vi.fn(),
toastUpdateSpy: vi.fn(),
}));
vi.mock("@tanstack/react-query", async () => {
const actual =
await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
return {
...actual,
useIsMutating: vi.fn(() => 0),
useMutation: vi.fn((options: { __kind?: string }) => {
if (options.__kind === "run-stacked-action") {
return {
mutateAsync: runStackedActionMutateAsyncSpy,
isPending: false,
};
}
if (options.__kind === "pull") {
return {
mutateAsync: vi.fn(),
isPending: false,
};
}
return {
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
};
}),
useQuery: vi.fn((options: { queryKey?: string[] }) => {
if (options.queryKey?.[0] === "git-branches") {
return {
data: {
isRepo: true,
hasOriginRemote: true,
branches: [
{
name: BRANCH_NAME,
current: true,
isDefault: false,
worktreePath: null,
},
],
},
error: null,
};
}
return { data: null, error: null };
}),
useQueryClient: vi.fn(() => ({})),
};
});
vi.mock("~/components/ui/toast", () => ({
toastManager: {
add: toastAddSpy,
close: toastCloseSpy,
promise: toastPromiseSpy,
update: toastUpdateSpy,
},
}));
vi.mock("~/editorPreferences", () => ({
openInPreferredEditor: vi.fn(),
}));
vi.mock("~/lib/gitReactQuery", () => ({
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
pull: vi.fn(() => ["pull"]),
runStackedAction: vi.fn(() => ["run-stacked-action"]),
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
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,
})),
}));
vi.mock("~/lib/utils", async () => {
const actual = await vi.importActual<typeof import("~/lib/utils")>("~/lib/utils");
return {
...actual,
newCommandId: vi.fn(() => "command-1"),
randomUUID: vi.fn(() => "action-1"),
};
});
vi.mock("~/nativeApi", () => ({
readNativeApi: vi.fn(() => null),
}));
vi.mock("~/store", () => ({
useStore: (selector: (state: unknown) => unknown) =>
selector({
setThreadBranch: setThreadBranchSpy,
threads: [
{ id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
{ id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
],
}),
}));
vi.mock("~/terminal-links", () => ({
resolvePathLinkTarget: vi.fn(),
}));
import GitActionsControl from "./GitActionsControl";
function findButtonByText(text: string): HTMLButtonElement | null {
return (Array.from(document.querySelectorAll("button")).find((button) =>
button.textContent?.includes(text),
) ?? null) as HTMLButtonElement | null;
}
function Harness() {
const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
return (
<>
<button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
Switch thread
</button>
<GitActionsControl gitCwd={GIT_CWD} activeThreadId={activeThreadId} />
</>
);
}
describe("GitActionsControl thread-scoped progress toast", () => {
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
document.body.innerHTML = "";
});
it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
vi.useFakeTimers();
const host = document.createElement("div");
document.body.append(host);
const screen = await render(<Harness />, { container: host });
try {
const quickActionButton = findButtonByText("Push & create PR");
expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy();
if (!(quickActionButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Push & create PR"');
}
quickActionButton.click();
expect(toastAddSpy).toHaveBeenCalledWith(
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
const switchThreadButton = findButtonByText("Switch thread");
expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
if (!(switchThreadButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Switch thread"');
}
switchThreadButton.click();
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
title: "Pushing...",
type: "loading",
}),
);
} finally {
await screen.unmount();
host.remove();
}
});
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();
}
});
});
@@ -13,6 +13,9 @@ import {
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasWorkingTreeChanges: false,
workingTree: {
@@ -440,7 +443,7 @@ describe("when: on default branch without open PR", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "push",
action: "commit_push",
label: "Push",
disabled: false,
});
@@ -754,7 +757,7 @@ describe("when: branch has no upstream configured", () => {
);
assert.deepInclude(quick, {
kind: "run_action",
action: "push",
action: "commit_push",
label: "Push",
disabled: false,
});
@@ -877,7 +880,12 @@ describe("buildGitActionProgressStages", () => {
pushTarget: "origin/feature/test",
shouldPushBeforePr: true,
});
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
assert.deepEqual(stages, [
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("shows only PR progress when create-pr can skip the push", () => {
@@ -887,7 +895,11 @@ describe("buildGitActionProgressStages", () => {
hasWorkingTreeChanges: false,
shouldPushBeforePr: false,
});
assert.deepEqual(stages, ["Creating PR..."]);
assert.deepEqual(stages, [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
it("includes commit stages for commit+push when working tree is dirty", () => {
@@ -903,6 +915,22 @@ describe("buildGitActionProgressStages", () => {
"Pushing to origin/feature/test...",
]);
});
it("includes granular PR stages for commit+push+PR actions", () => {
const stages = buildGitActionProgressStages({
action: "commit_push_pr",
hasCustomCommitMessage: true,
hasWorkingTreeChanges: true,
pushTarget: "origin/feature/test",
});
assert.deepEqual(stages, [
"Committing...",
"Pushing to origin/feature/test...",
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
]);
});
});
describe("resolveThreadBranchUpdate", () => {
@@ -47,12 +47,17 @@ export function buildGitActionProgressStages(input: {
}): string[] {
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
const prStages = [
"Preparing PR...",
"Generating PR content...",
"Creating GitHub pull request...",
];
if (input.action === "push") {
return [pushStage];
}
if (input.action === "create_pr") {
return input.shouldPushBeforePr ? [pushStage, "Creating PR..."] : ["Creating PR..."];
return input.shouldPushBeforePr ? [pushStage, ...prStages] : prStages;
}
const shouldIncludeCommitStages = input.action === "commit" || input.hasWorkingTreeChanges;
@@ -67,7 +72,7 @@ export function buildGitActionProgressStages(input: {
if (input.action === "commit_push") {
return [...branchStages, ...commitStages, pushStage];
}
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
return [...branchStages, ...commitStages, pushStage, ...prStages];
}
export function buildMenuItems(
@@ -214,7 +219,7 @@ export function resolveQuickAction(
label: "Push",
disabled: false,
kind: "run_action",
action: "push",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
@@ -248,7 +253,7 @@ export function resolveQuickAction(
label: "Push",
disabled: false,
kind: "run_action",
action: "push",
action: isDefaultBranch ? "commit_push" : "push",
};
}
return {
+97 -79
View File
@@ -5,7 +5,7 @@ import type {
GitStatusResult,
ThreadId,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
@@ -38,17 +38,15 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import { toastManager, type ThreadToastData } from "~/components/ui/toast";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
@@ -72,6 +70,7 @@ type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
toastId: GitActionToastId;
toastData: ThreadToastData | undefined;
actionId: string;
title: string;
phaseStartedAtMs: number | null;
@@ -92,6 +91,8 @@ interface RunGitActionWithToastInput {
filePaths?: string[];
}
const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
@@ -222,6 +223,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
const updateActiveProgressToast = useCallback(() => {
const progress = activeGitActionProgressRef.current;
@@ -233,9 +235,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progress.title,
description: resolveProgressDescription(progress),
timeout: 0,
data: threadToastData,
data: progress.toastData,
});
}, [threadToastData]);
}, []);
const persistThreadBranchSync = useCallback(
(branch: string | null) => {
@@ -274,22 +276,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
const { data: gitStatus = null, error: gitStatusError } = useGitStatus(gitCwd);
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const hasOriginRemote = branchList?.hasOriginRemote ?? false;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
const gitStatusForActions = gitStatus;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
@@ -333,11 +324,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
]);
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
return gitStatusForActions?.isDefaultBranch ?? false;
}, [gitStatusForActions?.isDefaultBranch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
@@ -372,6 +360,39 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
};
}, [updateActiveProgressToast]);
useEffect(() => {
if (gitCwd === null) {
return;
}
let refreshTimeout: number | null = null;
const scheduleRefreshCurrentGitStatus = () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
void refreshGitStatus(gitCwd).catch(() => undefined);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
};
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
scheduleRefreshCurrentGitStatus();
}
};
window.addEventListener("focus", scheduleRefreshCurrentGitStatus);
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
if (refreshTimeout !== null) {
window.clearTimeout(refreshTimeout);
}
window.removeEventListener("focus", scheduleRefreshCurrentGitStatus);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [gitCwd]);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
if (!api) {
@@ -401,7 +422,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}, [gitStatusForActions, threadToastData]);
const runGitActionWithToast = useEffectEvent(
runGitActionWithToast = useEffectEvent(
async ({
action,
commitMessage,
@@ -454,6 +475,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action === "create_pr" &&
(!actionStatus?.hasUpstream || (actionStatus?.aheadCount ?? 0) > 0),
});
const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
const actionId = randomUUID();
const resolvedProgressToastId =
progressToastId ??
@@ -462,11 +484,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
activeGitActionProgressRef.current = {
toastId: resolvedProgressToastId,
toastData: scopedToastData,
actionId,
title: progressStages[0] ?? "Running git action...",
phaseStartedAtMs: null,
@@ -482,7 +505,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
title: progressStages[0] ?? "Running git action...",
description: "Waiting for Git...",
timeout: 0,
data: threadToastData,
data: scopedToastData,
});
}
@@ -586,30 +609,38 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
};
}
toastManager.update(resolvedProgressToastId, {
const successToastBase = {
type: "success",
title: result.toast.title,
description: result.toast.description,
timeout: 0,
data: {
...threadToastData,
...scopedToastData,
dismissAfterVisibleMs: 10_000,
},
...(toastActionProps ? { actionProps: toastActionProps } : {}),
});
} as const;
if (toastActionProps) {
toastManager.update(resolvedProgressToastId, {
...successToastBase,
actionProps: toastActionProps,
});
} else {
toastManager.update(resolvedProgressToastId, successToastBase);
}
} catch (err) {
activeGitActionProgressRef.current = null;
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
data: scopedToastData,
});
}
},
);
const continuePendingDefaultBranchAction = useCallback(() => {
const continuePendingDefaultBranchAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
@@ -620,9 +651,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(filePaths ? { filePaths } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
const checkoutFeatureBranchAndContinuePendingAction = () => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
@@ -634,9 +665,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction]);
};
const runDialogActionOnNewBranch = useCallback(() => {
const runDialogActionOnNewBranch = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
@@ -652,9 +683,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
featureBranch: true,
skipDefaultBranchPrompt: true,
});
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
};
const runQuickAction = useCallback(() => {
const runQuickAction = () => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
return;
@@ -692,31 +723,28 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
};
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "create_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
},
[openExistingPr, setIsCommitDialogOpen],
);
const openDialogForMenuItem = (item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "push" });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "create_pr" });
return;
}
setExcludedFiles(new Set());
setIsEditingFiles(false);
setIsCommitDialogOpen(true);
};
const runDialogAction = useCallback(() => {
const runDialogAction = () => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
@@ -728,14 +756,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
...(commitMessage ? { commitMessage } : {}),
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
});
}, [
allSelected,
dialogCommitMessage,
isCommitDialogOpen,
selectedFiles,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
};
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -814,7 +835,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<GroupSeparator className="hidden @3xl/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
if (open) {
void refreshGitStatus(gitCwd).catch(() => undefined);
}
}}
>
<MenuTrigger
@@ -878,11 +901,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
+101
View File
@@ -310,6 +310,107 @@ 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,6 +1,7 @@
import "../index.css";
import {
DEFAULT_SERVER_SETTINGS,
ORCHESTRATION_WS_METHODS,
type MessageId,
type OrchestrationReadModel,
@@ -18,10 +19,19 @@ import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { __resetNativeApiForTests } from "../nativeApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { useStore } from "../store";
import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
vi.mock("../lib/gitStatusState", () => ({
useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
useGitStatuses: () => new Map(),
refreshGitStatus: () => Promise.resolve(null),
resetGitStatusStateForTests: () => undefined,
}));
const THREAD_ID = "thread-kb-toast-test" as ThreadId;
const PROJECT_ID = "project-1" as ProjectId;
const NOW_ISO = "2026-03-04T12:00:00.000Z";
@@ -56,7 +66,14 @@ function createBaseServerConfig(): ServerConfig {
},
],
availableEditors: [],
observability: {
logsDirectoryPath: "/repo/project/.t3/logs",
localTracingEnabled: true,
otlpTracesEnabled: false,
otlpMetricsEnabled: false,
},
settings: {
...DEFAULT_SERVER_SETTINGS,
enableAssistantStreaming: false,
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
@@ -157,20 +174,11 @@ function resolveWsRpc(tag: string): unknown {
return {
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 1,
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
};
}
if (tag === WS_METHODS.gitStatus) {
return {
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 };
}
@@ -245,6 +253,29 @@ async function waitForNoToast(title: string): Promise<void> {
);
}
async function waitForInitialWsSubscriptions(): Promise<void> {
await vi.waitFor(
() => {
expect(
rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
).toBe(true);
expect(
rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig),
).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
}
async function waitForServerConfigSnapshot(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
},
{ timeout: 8_000, interval: 16 },
);
}
async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const host = document.createElement("div");
host.style.position = "fixed";
@@ -257,8 +288,15 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
const screen = await render(<RouterProvider router={router} />, { container: host });
const screen = await render(
<AppAtomRegistryProvider>
<RouterProvider router={router} />
</AppAtomRegistryProvider>,
{ container: host },
);
await waitForComposerEditor();
await waitForInitialWsSubscriptions();
await waitForServerConfigSnapshot();
return {
cleanup: async () => {
@@ -309,7 +347,7 @@ describe("Keybindings update toast", () => {
return [];
},
});
__resetNativeApiForTests();
await __resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
useComposerDraftStore.setState({
@@ -1,4 +1,4 @@
import type { GitResolvePullRequestResult } from "@t3tools/contracts";
import type { GitResolvePullRequestResult, ThreadId } 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,6 +24,7 @@ import { Spinner } from "./ui/spinner";
interface PullRequestThreadDialogProps {
open: boolean;
threadId: ThreadId;
cwd: string | null;
initialReference: string | null;
onOpenChange: (open: boolean) => void;
@@ -32,6 +33,7 @@ interface PullRequestThreadDialogProps {
export function PullRequestThreadDialog({
open,
threadId,
cwd,
initialReference,
onOpenChange,
@@ -130,6 +132,7 @@ export function PullRequestThreadDialog({
const result = await preparePullRequestThreadMutation.mutateAsync({
reference: parsedReference,
mode,
...(mode === "worktree" ? { threadId } : {}),
});
await onPrepared({
branch: result.branch,
@@ -147,6 +150,7 @@ export function PullRequestThreadDialog({
parsedReference,
preparePullRequestThreadMutation,
resolvedPullRequest,
threadId,
],
);
+25 -53
View File
@@ -46,10 +46,12 @@ describe("hasUnseenCompletion", () => {
it("returns true when a thread completed after its last visit", () => {
expect(
hasUnseenCompletion({
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "default",
latestTurn: makeLatestTurn(),
lastVisitedAt: "2026-03-09T10:04:00.000Z",
proposedPlans: [],
session: null,
}),
).toBe(true);
@@ -322,17 +324,14 @@ describe("getVisibleSidebarThreadIds", () => {
expect(
getVisibleSidebarThreadIds([
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
{ id: ThreadId.makeUnsafe("thread-10") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-12"),
ThreadId.makeUnsafe("thread-11"),
ThreadId.makeUnsafe("thread-10"),
],
},
{
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-8") },
{ id: ThreadId.makeUnsafe("thread-6") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-8"), ThreadId.makeUnsafe("thread-6")],
},
]),
).toEqual([
@@ -349,17 +348,14 @@ describe("getVisibleSidebarThreadIds", () => {
getVisibleSidebarThreadIds([
{
shouldShowThreadPanel: false,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
renderedThreadIds: [
ThreadId.makeUnsafe("thread-hidden-2"),
ThreadId.makeUnsafe("thread-hidden-1"),
],
},
{
shouldShowThreadPanel: true,
renderedThreads: [
{ id: ThreadId.makeUnsafe("thread-12") },
{ id: ThreadId.makeUnsafe("thread-11") },
],
renderedThreadIds: [ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")],
},
]),
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
@@ -400,10 +396,12 @@ describe("isContextMenuPointerDown", () => {
describe("resolveThreadStatusPill", () => {
const baseThread = {
hasActionableProposedPlan: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
interactionMode: "plan" as const,
latestTurn: null,
lastVisitedAt: undefined,
proposedPlans: [],
session: {
provider: "codex" as const,
status: "running" as const,
@@ -416,9 +414,11 @@ describe("resolveThreadStatusPill", () => {
it("shows pending approval before all other statuses", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingApprovals: true,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Pending Approval", pulse: false });
});
@@ -426,9 +426,10 @@ describe("resolveThreadStatusPill", () => {
it("shows awaiting input when plan mode is blocked on user answers", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: true,
thread: {
...baseThread,
hasPendingUserInput: true,
},
}),
).toMatchObject({ label: "Awaiting Input", pulse: false });
});
@@ -437,8 +438,6 @@ describe("resolveThreadStatusPill", () => {
expect(
resolveThreadStatusPill({
thread: baseThread,
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Working", pulse: true });
});
@@ -448,26 +447,14 @@ describe("resolveThreadStatusPill", () => {
resolveThreadStatusPill({
thread: {
...baseThread,
hasActionableProposedPlan: true,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: null,
implementationThreadId: null,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Plan Ready", pulse: false });
});
@@ -478,25 +465,12 @@ describe("resolveThreadStatusPill", () => {
thread: {
...baseThread,
latestTurn: makeLatestTurn(),
proposedPlans: [
{
id: "plan-1" as never,
turnId: "turn-1" as never,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
planMarkdown: "# Plan",
implementedAt: "2026-03-09T10:06:00.000Z",
implementationThreadId: "thread-implement" as never,
},
],
session: {
...baseThread.session,
status: "ready",
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
@@ -515,8 +489,6 @@ describe("resolveThreadStatusPill", () => {
orchestrationStatus: "ready",
},
},
hasPendingApprovals: false,
hasPendingUserInput: false,
}),
).toMatchObject({ label: "Completed", pulse: false });
});
+16 -23
View File
@@ -1,12 +1,8 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import type { SidebarThreadSummary, Thread } from "../types";
import { cn } from "../lib/utils";
import {
findLatestProposedPlan,
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
import { isLatestTurnSettled } from "../session-logic";
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
@@ -47,8 +43,13 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
};
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
SidebarThreadSummary,
| "hasActionableProposedPlan"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "interactionMode"
| "latestTurn"
| "session"
> & {
lastVisitedAt?: string | undefined;
};
@@ -232,15 +233,11 @@ export function orderItemsByPreferredIds<TItem, TId>(input: {
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
renderedThreadIds: readonly TThreadId[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
);
}
@@ -313,12 +310,10 @@ export function resolveThreadRowClassName(input: {
export function resolveThreadStatusPill(input: {
thread: ThreadStatusInput;
hasPendingApprovals: boolean;
hasPendingUserInput: boolean;
}): ThreadStatusPill | null {
const { hasPendingApprovals, hasPendingUserInput, thread } = input;
const { thread } = input;
if (hasPendingApprovals) {
if (thread.hasPendingApprovals) {
return {
label: "Pending Approval",
colorClass: "text-amber-600 dark:text-amber-300/90",
@@ -327,7 +322,7 @@ export function resolveThreadStatusPill(input: {
};
}
if (hasPendingUserInput) {
if (thread.hasPendingUserInput) {
return {
label: "Awaiting Input",
colorClass: "text-indigo-600 dark:text-indigo-300/90",
@@ -355,12 +350,10 @@ export function resolveThreadStatusPill(input: {
}
const hasPlanReadyPrompt =
!hasPendingUserInput &&
!thread.hasPendingUserInput &&
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
hasActionableProposedPlan(
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null),
);
thread.hasActionableProposedPlan;
if (hasPlanReadyPrompt) {
return {
label: "Plan Ready",
File diff suppressed because it is too large. Load diff
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import {
resolveTerminalSelectionActionPosition,
selectPendingTerminalEventEntries,
selectTerminalEventEntriesAfterSnapshot,
shouldHandleTerminalSelectionMouseUp,
terminalSelectionActionDelayForClickCount,
} from "./ThreadTerminalDrawer";
@@ -72,4 +74,64 @@ describe("resolveTerminalSelectionActionPosition", () => {
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
});
it("replays only terminal events newer than the open snapshot", () => {
expect(
selectTerminalEventEntriesAfterSnapshot(
[
{
id: 1,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:00.000Z",
type: "output",
data: "before",
},
},
{
id: 2,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:01.000Z",
type: "output",
data: "after",
},
},
],
"2026-04-02T20:00:00.500Z",
).map((entry) => entry.id),
).toEqual([2]);
});
it("applies only terminal events that have not already been consumed", () => {
expect(
selectPendingTerminalEventEntries(
[
{
id: 1,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:00.000Z",
type: "output",
data: "one",
},
},
{
id: 2,
event: {
threadId: "thread-1",
terminalId: "default",
createdAt: "2026-04-02T20:00:01.000Z",
type: "output",
data: "two",
},
},
],
1,
).map((entry) => entry.id),
).toEqual([2]);
});
});
+173 -79
View File
@@ -1,12 +1,17 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import { type ThreadId } from "@t3tools/contracts";
import {
type TerminalEvent,
type TerminalSessionSnapshot,
type ThreadId,
} from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
@@ -27,6 +32,7 @@ import {
type ThreadTerminalGroup,
} from "../types";
import { readNativeApi } from "~/nativeApi";
import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -47,6 +53,27 @@ function writeSystemMessage(terminal: Terminal, message: string): void {
terminal.write(`\r\n[terminal] ${message}\r\n`);
}
function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void {
terminal.write("\u001bc");
if (snapshot.history.length > 0) {
terminal.write(snapshot.history);
}
}
export function selectTerminalEventEntriesAfterSnapshot(
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
snapshotUpdatedAt: string,
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
return entries.filter((entry) => entry.event.createdAt > snapshotUpdatedAt);
}
export function selectPendingTerminalEventEntries(
entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
lastAppliedTerminalEventId: number,
): ReadonlyArray<{ id: number; event: TerminalEvent }> {
return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
}
function terminalThemeFromApp(): ITheme {
const isDark = document.documentElement.classList.contains("dark");
const bodyStyles = getComputedStyle(document.body);
@@ -185,6 +212,7 @@ interface TerminalViewportProps {
terminalId: string;
terminalLabel: string;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
onSessionExited: () => void;
onAddTerminalContext: (selection: TerminalContextSelection) => void;
@@ -199,6 +227,7 @@ function TerminalViewport({
terminalId,
terminalLabel,
cwd,
worktreePath,
runtimeEnv,
onSessionExited,
onAddTerminalContext,
@@ -210,27 +239,21 @@ function TerminalViewport({
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const onSessionExitedRef = useRef(onSessionExited);
const onAddTerminalContextRef = useRef(onAddTerminalContext);
const terminalLabelRef = useRef(terminalLabel);
const hasHandledExitRef = useRef(false);
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
const selectionGestureActiveRef = useRef(false);
const selectionActionRequestIdRef = useRef(0);
const selectionActionOpenRef = useRef(false);
const selectionActionTimerRef = useRef<number | null>(null);
useEffect(() => {
onSessionExitedRef.current = onSessionExited;
}, [onSessionExited]);
useEffect(() => {
onAddTerminalContextRef.current = onAddTerminalContext;
}, [onAddTerminalContext]);
useEffect(() => {
terminalLabelRef.current = terminalLabel;
}, [terminalLabel]);
const lastAppliedTerminalEventIdRef = useRef(0);
const terminalHydratedRef = useRef(false);
const handleSessionExited = useEffectEvent(() => {
onSessionExited();
});
const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
useEffect(() => {
const mount = containerRef.current;
@@ -297,7 +320,7 @@ function TerminalViewport({
position,
selection: {
terminalId,
terminalLabel: terminalLabelRef.current,
terminalLabel: readTerminalLabel(),
lineStart,
lineEnd,
text: normalizedText,
@@ -324,7 +347,7 @@ function TerminalViewport({
if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
return;
}
onAddTerminalContextRef.current(nextAction.selection);
handleAddTerminalContext(nextAction.selection);
terminalRef.current?.clearSelection();
terminalRef.current?.focus();
} finally {
@@ -469,43 +492,15 @@ function TerminalViewport({
attributeFilter: ["class", "style"],
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
activeTerminal.write("\u001bc");
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const unsubscribe = api?.terminal.onEvent((event) => {
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const applyTerminalEvent = (event: TerminalEvent) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
if (!activeTerminal) {
return;
}
if (event.type === "activity") {
return;
}
if (event.type === "output") {
activeTerminal.write(event.data);
@@ -516,10 +511,7 @@ function TerminalViewport({
if (event.type === "started" || event.type === "restarted") {
hasHandledExitRef.current = false;
clearSelectionAction();
activeTerminal.write("\u001bc");
if (event.snapshot.history.length > 0) {
activeTerminal.write(event.snapshot.history);
}
writeTerminalSnapshot(activeTerminal, event.snapshot);
return;
}
@@ -535,30 +527,113 @@ function TerminalViewport({
return;
}
if (event.type === "exited") {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
if (hasHandledExitRef.current) {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
if (hasHandledExitRef.current) {
return;
}
hasHandledExitRef.current = true;
window.setTimeout(() => {
if (!hasHandledExitRef.current) {
return;
}
hasHandledExitRef.current = true;
window.setTimeout(() => {
if (!hasHandledExitRef.current) {
return;
}
onSessionExitedRef.current();
}, 0);
handleSessionExited();
}, 0);
};
const applyPendingTerminalEvents = (
terminalEventEntries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
) => {
const pendingEntries = selectPendingTerminalEventEntries(
terminalEventEntries,
lastAppliedTerminalEventIdRef.current,
);
if (pendingEntries.length === 0) {
return;
}
for (const entry of pendingEntries) {
applyTerminalEvent(entry.event);
}
lastAppliedTerminalEventIdRef.current =
pendingEntries.at(-1)?.id ?? lastAppliedTerminalEventIdRef.current;
};
const unsubscribeTerminalEvents = useTerminalStateStore.subscribe((state, previousState) => {
if (!terminalHydratedRef.current) {
return;
}
const previousLastEntryId =
selectTerminalEventEntries(
previousState.terminalEventEntriesByKey,
threadId,
terminalId,
).at(-1)?.id ?? 0;
const nextEntries = selectTerminalEventEntries(
state.terminalEventEntriesByKey,
threadId,
terminalId,
);
const nextLastEntryId = nextEntries.at(-1)?.id ?? 0;
if (nextLastEntryId === previousLastEntryId) {
return;
}
applyPendingTerminalEvents(nextEntries);
});
const openTerminal = async () => {
try {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
...(worktreePath !== undefined ? { worktreePath } : {}),
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
writeTerminalSnapshot(activeTerminal, snapshot);
const bufferedEntries = selectTerminalEventEntries(
useTerminalStateStore.getState().terminalEventEntriesByKey,
threadId,
terminalId,
);
const replayEntries = selectTerminalEventEntriesAfterSnapshot(
bufferedEntries,
snapshot.updatedAt,
);
for (const entry of replayEntries) {
applyTerminalEvent(entry.event);
}
lastAppliedTerminalEventIdRef.current = bufferedEntries.at(-1)?.id ?? 0;
terminalHydratedRef.current = true;
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
terminal,
err instanceof Error ? err.message : "Failed to open terminal",
);
}
};
const fitTimer = window.setTimeout(() => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
@@ -582,8 +657,10 @@ function TerminalViewport({
return () => {
disposed = true;
terminalHydratedRef.current = false;
lastAppliedTerminalEventIdRef.current = 0;
unsubscribeTerminalEvents();
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
selectionDisposable.dispose();
terminalLinksDisposable.dispose();
@@ -646,7 +723,9 @@ function TerminalViewport({
interface ThreadTerminalDrawerProps {
threadId: ThreadId;
cwd: string;
worktreePath?: string | null;
runtimeEnv?: Record<string, string>;
visible?: boolean;
height: number;
terminalIds: string[];
activeTerminalId: string;
@@ -696,7 +775,9 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
export default function ThreadTerminalDrawer({
threadId,
cwd,
worktreePath,
runtimeEnv,
visible = true,
height,
terminalIds,
activeTerminalId,
@@ -911,6 +992,10 @@ export default function ThreadTerminalDrawer({
);
useEffect(() => {
if (!visible) {
return;
}
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
@@ -927,7 +1012,14 @@ export default function ThreadTerminalDrawer({
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
}, [syncHeight, visible]);
useEffect(() => {
if (!visible) {
return;
}
setResizeEpoch((value) => value + 1);
}, [visible]);
useEffect(() => {
return () => {
@@ -1010,6 +1102,7 @@ export default function ThreadTerminalDrawer({
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -1030,6 +1123,7 @@ export default function ThreadTerminalDrawer({
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import type { WsConnectionStatus } from "../rpc/wsConnectionState";
import { shouldAutoReconnect } from "./WebSocketConnectionSurface";
function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionStatus {
return {
attemptCount: 0,
closeCode: null,
closeReason: null,
connectedAt: null,
disconnectedAt: null,
hasConnected: false,
lastError: null,
lastErrorAt: null,
nextRetryAt: null,
online: true,
phase: "idle",
reconnectAttemptCount: 0,
reconnectMaxAttempts: 8,
reconnectPhase: "idle",
socketUrl: null,
...overrides,
};
}
describe("WebSocketConnectionSurface.logic", () => {
it("forces reconnect on online when the app was offline", () => {
expect(
shouldAutoReconnect(
makeStatus({
disconnectedAt: "2026-04-03T20:00:00.000Z",
online: false,
phase: "disconnected",
}),
"online",
),
).toBe(true);
});
it("forces reconnect on focus only for previously connected disconnected states", () => {
expect(
shouldAutoReconnect(
makeStatus({
hasConnected: true,
online: true,
phase: "disconnected",
reconnectAttemptCount: 3,
reconnectPhase: "waiting",
}),
"focus",
),
).toBe(true);
expect(
shouldAutoReconnect(
makeStatus({
hasConnected: false,
online: true,
phase: "disconnected",
reconnectAttemptCount: 1,
reconnectPhase: "waiting",
}),
"focus",
),
).toBe(false);
});
it("forces reconnect on focus for exhausted reconnect loops", () => {
expect(
shouldAutoReconnect(
makeStatus({
hasConnected: true,
online: true,
phase: "disconnected",
reconnectAttemptCount: 8,
reconnectPhase: "exhausted",
}),
"focus",
),
).toBe(true);
});
});
@@ -0,0 +1,544 @@
import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react";
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
import { APP_DISPLAY_NAME } from "../branding";
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
import { useServerConfig } from "../rpc/serverState";
import {
exhaustWsReconnectIfStillWaiting,
getWsConnectionStatus,
getWsConnectionUiState,
setBrowserOnlineStatus,
type WsConnectionStatus,
type WsConnectionUiState,
useWsConnectionStatus,
WS_RECONNECT_MAX_ATTEMPTS,
} from "../rpc/wsConnectionState";
import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
import { getWsRpcClient } from "~/wsRpcClient";
const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000;
type WsAutoReconnectTrigger = "focus" | "online";
const connectionTimeFormatter = new Intl.DateTimeFormat(undefined, {
day: "numeric",
hour: "numeric",
minute: "2-digit",
month: "short",
second: "2-digit",
});
function formatConnectionMoment(isoDate: string | null): string | null {
if (!isoDate) {
return null;
}
return connectionTimeFormatter.format(new Date(isoDate));
}
function formatRetryCountdown(nextRetryAt: string, nowMs: number): string {
const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs);
return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`;
}
function describeOfflineToast(): string {
return "WebSocket disconnected. Waiting for network.";
}
function formatReconnectAttemptLabel(status: WsConnectionStatus): string {
const reconnectAttempt = Math.max(
1,
Math.min(status.reconnectAttemptCount, WS_RECONNECT_MAX_ATTEMPTS),
);
return `Attempt ${reconnectAttempt}/${status.reconnectMaxAttempts}`;
}
function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
function buildReconnectTitle(status: WsConnectionStatus): string {
if (status.nextRetryAt === null) {
return "Disconnected from T3 Server";
}
return "Disconnected from T3 Server";
}
function describeRecoveredToast(
previousDisconnectedAt: string | null,
connectedAt: string | null,
): string {
const reconnectedAtLabel = formatConnectionMoment(connectedAt);
const disconnectedAtLabel = formatConnectionMoment(previousDisconnectedAt);
if (disconnectedAtLabel && reconnectedAtLabel) {
return `Disconnected at ${disconnectedAtLabel} and reconnected at ${reconnectedAtLabel}.`;
}
if (reconnectedAtLabel) {
return `Connection restored at ${reconnectedAtLabel}.`;
}
return "Connection restored.";
}
function describeSlowRpcAckToast(requests: ReadonlyArray<SlowRpcAckRequest>): ReactNode {
const count = requests.length;
const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000);
return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
}
export function shouldAutoReconnect(
status: WsConnectionStatus,
trigger: WsAutoReconnectTrigger,
): boolean {
const uiState = getWsConnectionUiState(status);
if (trigger === "online") {
return (
uiState === "offline" ||
uiState === "reconnecting" ||
uiState === "error" ||
status.reconnectPhase === "exhausted"
);
}
return (
status.online &&
status.hasConnected &&
(uiState === "reconnecting" || status.reconnectPhase === "exhausted")
);
}
function buildBlockingCopy(
uiState: WsConnectionUiState,
status: WsConnectionStatus,
): {
readonly description: string;
readonly eyebrow: string;
readonly title: string;
} {
if (uiState === "connecting") {
return {
description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`,
eyebrow: "Starting Session",
title: `Connecting to ${APP_DISPLAY_NAME}`,
};
}
if (uiState === "offline") {
return {
description:
"Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.",
eyebrow: "Offline",
title: "WebSocket connection unavailable",
};
}
if (status.lastError?.trim()) {
return {
description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`,
eyebrow: "Connection Error",
title: "Cannot reach the T3 server",
};
}
return {
description:
"The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.",
eyebrow: "Connection Error",
title: "Cannot reach the T3 server",
};
}
function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string {
const details = [
`state: ${uiState}`,
`online: ${status.online ? "yes" : "no"}`,
`attempts: ${status.attemptCount}`,
];
if (status.socketUrl) {
details.push(`socket: ${status.socketUrl}`);
}
if (status.connectedAt) {
details.push(`connectedAt: ${status.connectedAt}`);
}
if (status.disconnectedAt) {
details.push(`disconnectedAt: ${status.disconnectedAt}`);
}
if (status.lastErrorAt) {
details.push(`lastErrorAt: ${status.lastErrorAt}`);
}
if (status.lastError) {
details.push(`lastError: ${status.lastError}`);
}
if (status.closeCode !== null) {
details.push(`closeCode: ${status.closeCode}`);
}
if (status.closeReason) {
details.push(`closeReason: ${status.closeReason}`);
}
return details.join("\n");
}
function WebSocketBlockingState({
status,
uiState,
}: {
readonly status: WsConnectionStatus;
readonly uiState: WsConnectionUiState;
}) {
const copy = buildBlockingCopy(uiState, status);
const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt);
const Icon =
uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle;
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-90">
<div className="absolute inset-x-0 top-0 h-56 bg-[radial-gradient(48rem_18rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
</div>
<section className="relative w-full max-w-xl rounded-[1.75rem] border border-border/80 bg-card/92 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{copy.eyebrow}
</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{copy.title}</h1>
</div>
<div className="rounded-2xl border border-border/70 bg-background/80 p-3 text-foreground shadow-sm">
<Icon className={uiState === "connecting" ? "size-5 animate-spin" : "size-5"} />
</div>
</div>
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">{copy.description}</p>
<div className="mt-5 grid gap-3 rounded-2xl border border-border/70 bg-background/60 p-4 text-sm sm:grid-cols-2">
<div>
<p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
Connection
</p>
<p className="mt-1 font-medium text-foreground">
{uiState === "connecting"
? "Opening WebSocket"
: uiState === "offline"
? "Waiting for network"
: "Retrying server connection"}
</p>
</div>
<div>
<p className="text-[11px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">
Latest Event
</p>
<p className="mt-1 font-medium text-foreground">{disconnectedAt ?? "Pending"}</p>
</div>
</div>
<div className="mt-5 flex flex-wrap gap-2">
<Button size="sm" onClick={() => window.location.reload()}>
<RotateCw />
Reload app
</Button>
</div>
<details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
<summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
<span className="group-open:hidden">Show connection details</span>
<span className="hidden group-open:inline">Hide connection details</span>
</summary>
<pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
{buildConnectionDetails(status, uiState)}
</pre>
</details>
</section>
</div>
);
}
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
const [nowMs, setNowMs] = useState(() => Date.now());
const lastForcedReconnectAtRef = useRef(0);
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
const toastResetTimerRef = useRef<number | null>(null);
const previousUiStateRef = useRef<WsConnectionUiState>(getWsConnectionUiState(status));
const previousDisconnectedAtRef = useRef<string | null>(status.disconnectedAt);
const runReconnect = useEffectEvent((showFailureToast: boolean) => {
if (toastResetTimerRef.current !== null) {
window.clearTimeout(toastResetTimerRef.current);
toastResetTimerRef.current = null;
}
lastForcedReconnectAtRef.current = Date.now();
void getWsRpcClient()
.reconnect()
.catch((error) => {
if (!showFailureToast) {
console.warn("Automatic WebSocket reconnect failed", { error });
return;
}
toastManager.add({
type: "error",
title: "Reconnect failed",
description: error instanceof Error ? error.message : "Unable to restart the WebSocket.",
data: {
dismissAfterVisibleMs: 8_000,
hideCopyButton: true,
},
});
});
});
const syncBrowserOnlineStatus = useEffectEvent(() => {
setBrowserOnlineStatus(navigator.onLine !== false);
});
const triggerManualReconnect = useEffectEvent(() => {
runReconnect(true);
});
const triggerAutoReconnect = useEffectEvent((trigger: WsAutoReconnectTrigger) => {
const currentStatus =
trigger === "online" ? setBrowserOnlineStatus(true) : getWsConnectionStatus();
if (!shouldAutoReconnect(currentStatus, trigger)) {
return;
}
if (Date.now() - lastForcedReconnectAtRef.current < FORCED_WS_RECONNECT_DEBOUNCE_MS) {
return;
}
runReconnect(false);
});
useEffect(() => {
const handleOnline = () => {
triggerAutoReconnect("online");
};
const handleFocus = () => {
triggerAutoReconnect("focus");
};
syncBrowserOnlineStatus();
window.addEventListener("online", handleOnline);
window.addEventListener("offline", syncBrowserOnlineStatus);
window.addEventListener("focus", handleFocus);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", syncBrowserOnlineStatus);
window.removeEventListener("focus", handleFocus);
};
}, []);
useEffect(() => {
if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) {
return;
}
setNowMs(Date.now());
const intervalId = window.setInterval(() => {
setNowMs(Date.now());
}, 1_000);
return () => {
window.clearInterval(intervalId);
};
}, [status.nextRetryAt, status.reconnectPhase]);
useEffect(() => {
if (
status.reconnectPhase !== "waiting" ||
status.nextRetryAt === null ||
!status.online ||
!status.hasConnected
) {
return;
}
const nextRetryAt = status.nextRetryAt;
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
const timeoutId = window.setTimeout(() => {
exhaustWsReconnectIfStillWaiting(nextRetryAt);
}, timeoutMs);
return () => {
window.clearTimeout(timeoutId);
};
}, [
status.hasConnected,
status.nextRetryAt,
status.online,
status.reconnectAttemptCount,
status.reconnectPhase,
]);
useEffect(() => {
const uiState = getWsConnectionUiState(status);
const previousUiState = previousUiStateRef.current;
const previousDisconnectedAt = previousDisconnectedAtRef.current;
const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting";
const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null;
const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted";
if (
toastResetTimerRef.current !== null &&
(shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast)
) {
window.clearTimeout(toastResetTimerRef.current);
toastResetTimerRef.current = null;
}
if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) {
const toastPayload = shouldShowOfflineToast
? {
description: describeOfflineToast(),
timeout: 0,
title: "Offline",
type: "warning" as const,
data: {
hideCopyButton: true,
},
}
: shouldShowExhaustedToast
? {
actionProps: {
children: "Retry",
onClick: triggerManualReconnect,
},
description: describeExhaustedToast(),
timeout: 0,
title: "Disconnected from T3 Server",
type: "error" as const,
data: {
hideCopyButton: true,
},
}
: {
actionProps: {
children: "Retry now",
onClick: triggerManualReconnect,
},
description:
status.nextRetryAt === null
? `Reconnecting... ${formatReconnectAttemptLabel(status)}`
: `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`,
timeout: 0,
title: buildReconnectTitle(status),
type: "loading" as const,
data: {
hideCopyButton: true,
},
};
if (toastIdRef.current) {
toastManager.update(toastIdRef.current, toastPayload);
} else {
toastIdRef.current = toastManager.add(toastPayload);
}
} else if (toastIdRef.current) {
toastManager.close(toastIdRef.current);
toastIdRef.current = null;
}
if (
uiState === "connected" &&
(previousUiState === "offline" || previousUiState === "reconnecting") &&
previousDisconnectedAt !== null
) {
const successToast = {
description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
title: "Reconnected to T3 Server",
type: "success" as const,
timeout: 0,
data: {
dismissAfterVisibleMs: 8_000,
hideCopyButton: true,
},
};
if (toastIdRef.current) {
toastManager.update(toastIdRef.current, successToast);
} else {
toastIdRef.current = toastManager.add(successToast);
}
toastResetTimerRef.current = window.setTimeout(() => {
toastIdRef.current = null;
toastResetTimerRef.current = null;
}, 8_250);
}
previousUiStateRef.current = uiState;
previousDisconnectedAtRef.current = status.disconnectedAt;
}, [nowMs, status]);
useEffect(() => {
return () => {
if (toastResetTimerRef.current !== null) {
window.clearTimeout(toastResetTimerRef.current);
}
};
}, []);
return null;
}
export function SlowRpcAckToastCoordinator() {
const slowRequests = useSlowRpcAckRequests();
const status = useWsConnectionStatus();
const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
useEffect(() => {
if (getWsConnectionUiState(status) !== "connected") {
if (toastIdRef.current) {
toastManager.close(toastIdRef.current);
toastIdRef.current = null;
}
return;
}
if (slowRequests.length === 0) {
if (toastIdRef.current) {
toastManager.close(toastIdRef.current);
toastIdRef.current = null;
}
return;
}
const nextToast = {
description: describeSlowRpcAckToast(slowRequests),
timeout: 0,
title: "Some requests are slow",
type: "warning" as const,
};
if (toastIdRef.current) {
toastManager.update(toastIdRef.current, nextToast);
} else {
toastIdRef.current = toastManager.add(nextToast);
}
}, [slowRequests, status]);
return null;
}
export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) {
const serverConfig = useServerConfig();
const status = useWsConnectionStatus();
if (serverConfig === null) {
const uiState = getWsConnectionUiState(status);
return (
<WebSocketBlockingState
status={status}
uiState={uiState === "connected" ? "connecting" : uiState}
/>
);
}
return children;
}
@@ -0,0 +1,116 @@
import { TurnId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { ChangedFilesTree } from "./ChangedFilesTree";
describe("ChangedFilesTree", () => {
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src"],
hiddenLabels: ["index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: ["apps/server/src"],
hiddenLabels: ["git", "provider", "GitCore.ts", "CodexAdapter.ts"],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: ["README.md", "packages"],
hiddenLabels: ["shared/src", "contracts/src", "git.ts", "orchestration.ts"],
},
])(
"renders $name collapsed on the first render when collapse-all is active",
({ files, visibleLabels, hiddenLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded={false}
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
for (const label of hiddenLabels) {
expect(markup).not.toContain(label);
}
},
);
it.each([
{
name: "a compacted single-chain directory",
files: [
{ path: "apps/web/src/index.ts", additions: 2, deletions: 1 },
{ path: "apps/web/src/main.ts", additions: 3, deletions: 0 },
],
visibleLabels: ["apps/web/src", "index.ts", "main.ts"],
},
{
name: "a branch point after a compacted prefix",
files: [
{ path: "apps/server/src/git/Layers/GitCore.ts", additions: 4, deletions: 3 },
{ path: "apps/server/src/provider/Layers/CodexAdapter.ts", additions: 7, deletions: 2 },
],
visibleLabels: [
"apps/server/src",
"git/Layers",
"provider/Layers",
"GitCore.ts",
"CodexAdapter.ts",
],
},
{
name: "mixed root files and nested compacted directories",
files: [
{ path: "README.md", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
{ path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
],
visibleLabels: [
"README.md",
"packages",
"shared/src",
"contracts/src",
"git.ts",
"orchestration.ts",
],
},
])(
"renders $name expanded on the first render when expand-all is active",
({ files, visibleLabels }) => {
const markup = renderToStaticMarkup(
<ChangedFilesTree
turnId={TurnId.makeUnsafe("turn-1")}
files={files}
allDirectoriesExpanded
resolvedTheme="light"
onOpenTurnDiff={() => {}}
/>,
);
for (const label of visibleLabels) {
expect(markup).toContain(label);
}
},
);
});
@@ -1,5 +1,5 @@
import { type TurnId } from "@t3tools/contracts";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useMemo, useState } from "react";
import { type TurnDiffFileChange } from "../../types";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
@@ -7,6 +7,8 @@ import { cn } from "~/lib/utils";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { VscodeEntryIcon } from "./VscodeEntryIcon";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
@@ -20,32 +22,39 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
() => collectDirectoryPaths(treeNodes).join("\u0000"),
[treeNodes],
);
const allDirectoryExpansionState = useMemo(
() =>
buildDirectoryExpansionState(
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
allDirectoriesExpanded,
),
[allDirectoriesExpanded, directoryPathsKey],
);
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(() =>
buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true),
);
useEffect(() => {
setExpandedDirectories(allDirectoryExpansionState);
}, [allDirectoryExpansionState]);
const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
const [directoryExpansionState, setDirectoryExpansionState] = useState<{
key: string;
overrides: Record<string, boolean>;
}>(() => ({
key: expansionStateKey,
overrides: {},
}));
const expandedDirectories =
directoryExpansionState.key === expansionStateKey
? directoryExpansionState.overrides
: EMPTY_DIRECTORY_OVERRIDES;
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
setExpandedDirectories((current) => ({
...current,
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
}));
}, []);
const toggleDirectory = useCallback(
(pathValue: string) => {
setDirectoryExpansionState((current) => {
const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
return {
key: expansionStateKey,
overrides: {
...nextOverrides,
[pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
},
};
});
},
[allDirectoriesExpanded, expansionStateKey],
);
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
const leftPadding = 8 + depth * 14;
if (node.kind === "directory") {
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
return (
<div key={`dir:${node.path}`}>
<button
@@ -53,7 +62,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
data-scroll-anchor-ignore
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
style={{ paddingLeft: `${leftPadding}px` }}
onClick={() => toggleDirectory(node.path, depth === 0)}
onClick={() => toggleDirectory(node.path)}
>
<ChevronRightIcon
aria-hidden="true"
@@ -124,14 +133,3 @@ function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[]
}
return paths;
}
function buildDirectoryExpansionState(
directoryPaths: ReadonlyArray<string>,
expanded: boolean,
): Record<string, boolean> {
const expandedState: Record<string, boolean> = {};
for (const directoryPath of directoryPaths) {
expandedState[directoryPath] = expanded;
}
return expandedState;
}
@@ -1,3 +1,11 @@
import { type MessageId } from "@t3tools/contracts";
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { estimateTimelineMessageHeight } from "../timelineHeight";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -5,6 +13,29 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
export type MessagesTimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: ChatMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: ProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
export function computeMessageDurationStart(
messages: ReadonlyArray<TimelineDurationMessage>,
): Map<string, string> {
@@ -27,3 +58,142 @@ export function computeMessageDurationStart(
export function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
isWorking: boolean;
activeTurnStartedAt: string | null;
}): MessagesTimelineRow[] {
const nextRows: MessagesTimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < input.timelineEntries.length; index += 1) {
const timelineEntry = input.timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < input.timelineEntries.length) {
const nextEntry = input.timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
input.completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (input.isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt,
});
}
return nextRows;
}
export function estimateMessagesTimelineRowHeight(
row: MessagesTimelineRow,
input: {
timelineWidthPx: number | null;
expandedWorkGroups?: Readonly<Record<string, boolean>>;
turnDiffSummaryByAssistantMessageId?: ReadonlyMap<MessageId, TurnDiffSummary>;
},
): number {
switch (row.kind) {
case "work":
return estimateWorkRowHeight(row, input);
case "proposed-plan":
return estimateTimelineProposedPlanHeight(row.proposedPlan);
case "working":
return 40;
case "message": {
let estimate = estimateTimelineMessageHeight(row.message, {
timelineWidthPx: input.timelineWidthPx,
});
const turnDiffSummary = input.turnDiffSummaryByAssistantMessageId?.get(row.message.id);
if (turnDiffSummary && turnDiffSummary.files.length > 0) {
estimate += estimateChangedFilesCardHeight(turnDiffSummary);
}
return estimate;
}
}
}
function estimateWorkRowHeight(
row: Extract<MessagesTimelineRow, { kind: "work" }>,
input: {
expandedWorkGroups?: Readonly<Record<string, boolean>>;
},
): number {
const isExpanded = input.expandedWorkGroups?.[row.id] ?? false;
const hasOverflow = row.groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded ? MAX_VISIBLE_WORK_LOG_ENTRIES : row.groupedEntries.length;
const onlyToolEntries = row.groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
// Card chrome, optional header, and one compact work-entry row per visible entry.
return 28 + (showHeader ? 26 : 0) + visibleEntries * 32;
}
function estimateTimelineProposedPlanHeight(proposedPlan: ProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
function estimateChangedFilesCardHeight(turnDiffSummary: TurnDiffSummary): number {
const treeNodes = buildTurnDiffTree(turnDiffSummary.files);
const visibleNodeCount = countTurnDiffTreeNodes(treeNodes);
// Card chrome: top/bottom padding, header row, and tree spacing.
return 60 + visibleNodeCount * 25;
}
function countTurnDiffTreeNodes(nodes: ReadonlyArray<TurnDiffTreeNode>): number {
let count = 0;
for (const node of nodes) {
count += 1;
if (node.kind === "directory") {
count += countTurnDiffTreeNodes(node.children);
}
}
return count;
}
+128 -116
View File
@@ -35,14 +35,20 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { clamp } from "effect/Number";
import { estimateTimelineMessageHeight } from "../timelineHeight";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
import {
MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
estimateMessagesTimelineRowHeight,
normalizeCompactToolLabel,
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
deriveDisplayedUserMessageState,
type ParsedTerminalContextEntry,
@@ -56,7 +62,6 @@ import {
textContainsInlineTerminalContextLabels,
} from "./userMessageTerminalContexts";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
interface MessagesTimelineProps {
@@ -81,6 +86,17 @@ interface MessagesTimelineProps {
resolvedTheme: "light" | "dark";
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
onVirtualizerSnapshot?: (snapshot: {
totalSize: number;
measurements: ReadonlyArray<{
id: string;
kind: MessagesTimelineRow["kind"];
index: number;
size: number;
start: number;
end: number;
}>;
}) => void;
}
export const MessagesTimeline = memo(function MessagesTimeline({
@@ -105,6 +121,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
timestampFormat,
workspaceRoot,
onVirtualizerSnapshot,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
@@ -134,70 +151,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
};
}, [hasMessages, isWorking]);
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
const durationStartByMessageId = computeMessageDurationStart(
timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
for (let index = 0; index < timelineEntries.length; index += 1) {
const timelineEntry = timelineEntries[index];
if (!timelineEntry) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < timelineEntries.length) {
const nextEntry = timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
index = cursor - 1;
continue;
}
if (timelineEntry.kind === "proposed-plan") {
nextRows.push({
kind: "proposed-plan",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
proposedPlan: timelineEntry.proposedPlan,
});
continue;
}
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider:
timelineEntry.message.role === "assistant" &&
completionDividerBeforeEntryId === timelineEntry.id,
});
}
if (isWorking) {
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: activeTurnStartedAt,
});
}
return nextRows;
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
const rows = useMemo(
() =>
deriveMessagesTimelineRows({
timelineEntries,
completionDividerBeforeEntryId,
isWorking,
activeTurnStartedAt,
}),
[timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt],
);
const firstUnvirtualizedRowIndex = useMemo(() => {
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
@@ -241,19 +204,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
minimum: 0,
maximum: rows.length,
});
const virtualMeasurementScopeKey =
timelineWidthPx === null ? "width:unknown" : `width:${Math.round(timelineWidthPx)}`;
const rowVirtualizer = useVirtualizer({
count: virtualizedRowCount,
getScrollElement: () => scrollContainer,
// Use stable row ids so virtual measurements do not leak across thread switches.
getItemKey: (index: number) => rows[index]?.id ?? index,
// Scope cached row measurements to the current timeline width so offscreen
// rows do not keep stale heights after wrapping changes.
getItemKey: (index: number) => {
const rowId = rows[index]?.id ?? String(index);
return `${virtualMeasurementScopeKey}:${rowId}`;
},
estimateSize: (index: number) => {
const row = rows[index];
if (!row) return 96;
if (row.kind === "work") return 112;
if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
if (row.kind === "working") return 40;
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
return estimateMessagesTimelineRowHeight(row, {
expandedWorkGroups,
timelineWidthPx,
turnDiffSummaryByAssistantMessageId,
});
},
measureElement: measureVirtualElement,
useAnimationFrameWithResizeObserver: true,
@@ -295,6 +265,32 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
};
}, []);
useLayoutEffect(() => {
if (!onVirtualizerSnapshot) {
return;
}
onVirtualizerSnapshot({
totalSize: rowVirtualizer.getTotalSize(),
measurements: rowVirtualizer.measurementsCache
.slice(0, virtualizedRowCount)
.flatMap((measurement) => {
const row = rows[measurement.index];
if (!row) {
return [];
}
return [
{
id: row.id,
kind: row.kind,
index: measurement.index,
size: measurement.size,
start: measurement.start,
end: measurement.end,
},
];
}),
});
}, [onVirtualizerSnapshot, rowVirtualizer, rows, virtualizedRowCount]);
const virtualRows = rowVirtualizer.getVirtualItems();
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
@@ -311,6 +307,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const renderRowContent = (row: TimelineRow) => (
<div
className="pb-4"
data-timeline-row-id={row.id}
data-timeline-row-kind={row.kind}
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
@@ -389,7 +386,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full object-cover"
className="block h-auto max-h-[220px] w-full object-cover"
onLoad={onTimelineImageLoad}
onError={onTimelineImageLoad}
/>
@@ -585,6 +582,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<div
key={`virtual-row:${row.id}`}
data-index={virtualRow.index}
data-virtual-row-id={row.id}
data-virtual-row-kind={row.kind}
data-virtual-row-size={virtualRow.size}
data-virtual-row-start={virtualRow.start}
ref={rowVirtualizer.measureElement}
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
@@ -605,35 +606,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
type TimelineRow =
| {
kind: "work";
id: string;
createdAt: string;
groupedEntries: TimelineWorkEntry[];
}
| {
kind: "message";
id: string;
createdAt: string;
message: TimelineMessage;
durationStart: string;
showCompletionDivider: boolean;
}
| {
kind: "proposed-plan";
id: string;
createdAt: string;
proposedPlan: TimelineProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null };
function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
return 120 + Math.min(estimatedLines * 22, 880);
}
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
type TimelineRow = MessagesTimelineRow;
function formatWorkingTimer(startIso: string, endIso: string): string | null {
const startedAtMs = Date.parse(startIso);
@@ -819,6 +793,16 @@ function workEntryPreview(
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
}
function workEntryRawCommand(
workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
): string | null {
const rawCommand = workEntry.rawCommand?.trim();
if (!rawCommand || !workEntry.command) {
return null;
}
return rawCommand === workEntry.command.trim() ? null : rawCommand;
}
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
if (workEntry.requestKind === "command") return TerminalIcon;
if (workEntry.requestKind === "file-read") return EyeIcon;
@@ -867,6 +851,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry);
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
@@ -880,19 +865,46 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
<EntryIcon className="size-3" />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
<p
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
</p>
<div className="max-w-full">
<p
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={rawCommand ? undefined : displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview &&
(rawCommand ? (
<Tooltip>
<TooltipTrigger
closeDelay={0}
delay={75}
render={
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
{" "}
- {preview}
</span>
}
/>
<TooltipPopup
align="start"
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
side="top"
>
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
{rawCommand}
</div>
</TooltipPopup>
</Tooltip>
) : (
<span className="text-muted-foreground/55"> - {preview}</span>
))}
</p>
</div>
</div>
</div>
{hasChangedFiles && !previewIsChangedFiles && (
File diff suppressed because it is too large. Load diff
+14 -1
View File
@@ -6,7 +6,15 @@ 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, VisualStudioCode, Zed } from "../Icons";
import {
AntigravityIcon,
CursorIcon,
Icon,
TraeIcon,
IntelliJIdeaIcon,
VisualStudioCode,
Zed,
} from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -47,6 +55,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
Icon: AntigravityIcon,
value: "antigravity",
},
{
label: "IntelliJ IDEA",
Icon: IntelliJIdeaIcon,
value: "idea",
},
{
label: isMacPlatform(platform)
? "Finder"
@@ -25,6 +25,7 @@ import {
} from "../ui/dialog";
import { toastManager } from "../ui/toast";
import { readNativeApi } from "~/nativeApi";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
export const ProposedPlanCard = memo(function ProposedPlanCard({
planMarkdown,
@@ -39,6 +40,15 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
const [savePath, setSavePath] = useState("");
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
const { copyToClipboard, isCopied } = useCopyToClipboard({
onError: (error) => {
toastManager.add({
type: "error",
title: "Could not copy plan",
description: error instanceof Error ? error.message : "An error occurred while copying.",
});
},
});
const savePathInputId = useId();
const title = proposedPlanTitle(planMarkdown) ?? "Proposed plan";
const lineCount = planMarkdown.split("\n").length;
@@ -54,6 +64,10 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
downloadPlanAsTextFile(downloadFilename, saveContents);
};
const handleCopyPlan = () => {
copyToClipboard(saveContents);
};
const openSaveDialog = () => {
if (!workspaceRoot) {
toastManager.add({
@@ -127,6 +141,9 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({
<EllipsisIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
<MenuItem onClick={handleCopyPlan}>
{isCopied ? "Copied!" : "Copy to clipboard"}
</MenuItem>
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
<MenuItem onClick={openSaveDialog} disabled={!workspaceRoot || isSavingToWorkspace}>
Save to workspace
@@ -477,6 +477,23 @@ describe("TraitsPicker (Codex)", () => {
});
});
it("shows default effort options for custom codex models without capabilities", async () => {
await using _ = await mountCodexPicker({
model: "custom-codex-model",
options: { reasoningEffort: "low" },
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Extra High");
expect(text).toContain("High");
expect(text).toContain("Medium");
expect(text).toContain("Low");
});
});
it("persists sticky codex model options when traits change", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: false },
@@ -149,6 +149,36 @@ describe("getComposerProviderState", () => {
});
});
it("uses standard codex defaults for custom codex models without capabilities", () => {
const state = getComposerProviderState({
provider: "codex",
model: "custom-codex-model",
models: [
...CODEX_MODELS,
{
slug: "custom-codex-model",
name: "custom-codex-model",
isCustom: true,
capabilities: null,
},
],
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "low",
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "low",
modelOptionsForDispatch: {
reasoningEffort: "low",
},
});
});
it("preserves codex fast mode when it is the only active option", () => {
const state = getComposerProviderState({
provider: "codex",
@@ -0,0 +1,91 @@
import "../../index.css";
import { DEFAULT_SERVER_SETTINGS, type NativeApi, type ServerConfig } from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { __resetNativeApiForTests } from "../../nativeApi";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
import { GeneralSettingsPanel } from "./SettingsPanels";
function createBaseServerConfig(): ServerConfig {
return {
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
issues: [],
providers: [],
availableEditors: ["cursor"],
observability: {
logsDirectoryPath: "/repo/project/.t3/logs",
localTracingEnabled: true,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpTracesEnabled: true,
otlpMetricsEnabled: false,
},
settings: DEFAULT_SERVER_SETTINGS,
};
}
describe("GeneralSettingsPanel observability", () => {
beforeEach(async () => {
resetServerStateForTests();
await __resetNativeApiForTests();
localStorage.clear();
document.body.innerHTML = "";
});
afterEach(async () => {
resetServerStateForTests();
await __resetNativeApiForTests();
document.body.innerHTML = "";
});
it("shows diagnostics inside About with a single logs-folder action", async () => {
setServerConfigSnapshot(createBaseServerConfig());
await render(
<AppAtomRegistryProvider>
<GeneralSettingsPanel />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("About")).toBeInTheDocument();
await expect.element(page.getByText("Diagnostics")).toBeInTheDocument();
await expect.element(page.getByText("Open logs folder")).toBeInTheDocument();
await expect
.element(page.getByText("/repo/project/.t3/logs", { exact: true }))
.toBeInTheDocument();
await expect
.element(
page.getByText(
"Local trace file. OTLP exporting traces to http://localhost:4318/v1/traces.",
),
)
.toBeInTheDocument();
});
it("opens the logs folder in the preferred editor", async () => {
const openInEditor = vi.fn<NativeApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
window.nativeApi = {
shell: {
openInEditor,
},
} as unknown as NativeApi;
setServerConfigSnapshot(createBaseServerConfig());
await render(
<AppAtomRegistryProvider>
<GeneralSettingsPanel />
</AppAtomRegistryProvider>,
);
const openLogsButton = page.getByText("Open logs folder");
await openLogsButton.click();
expect(openInEditor).toHaveBeenCalledWith("/repo/project/.t3/logs", "cursor");
});
});
@@ -61,6 +61,7 @@ import { ProjectFavicon } from "../ProjectFavicon";
import {
useServerAvailableEditors,
useServerKeybindingsConfigPath,
useServerObservability,
useServerProviders,
} from "../../rpc/serverState";
@@ -518,8 +519,13 @@ export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
const [openingPathByTarget, setOpeningPathByTarget] = useState({
keybindings: false,
logsDirectory: false,
});
const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState<
Partial<Record<"keybindings" | "logsDirectory", string | null>>
>({});
const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({
codex: Boolean(
settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath ||
@@ -561,8 +567,21 @@ export function GeneralSettingsPanel() {
const keybindingsConfigPath = useServerKeybindingsConfigPath();
const availableEditors = useServerAvailableEditors();
const observability = useServerObservability();
const serverProviders = useServerProviders();
const codexHomePath = settings.providers.codex.homePath;
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
const diagnosticsDescription = (() => {
const exports: string[] = [];
if (observability?.otlpTracesEnabled && observability.otlpTracesUrl) {
exports.push(`traces to ${observability.otlpTracesUrl}`);
}
if (observability?.otlpMetricsEnabled && observability.otlpMetricsUrl) {
exports.push(`metrics to ${observability.otlpMetricsUrl}`);
}
const mode = observability?.localTracingEnabled ? "Local trace file" : "Terminal logs only";
return exports.length > 0 ? `${mode}. OTLP exporting ${exports.join(" and ")}.` : `${mode}.`;
})();
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
const textGenProvider = textGenerationModelSelection.provider;
@@ -579,27 +598,49 @@ export function GeneralSettingsPanel() {
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
);
const openInPreferredEditor = useCallback(
(target: "keybindings" | "logsDirectory", path: string | null, failureMessage: string) => {
if (!path) return;
setOpenPathErrorByTarget((existing) => ({ ...existing, [target]: null }));
setOpeningPathByTarget((existing) => ({ ...existing, [target]: true }));
const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
if (!editor) {
setOpenPathErrorByTarget((existing) => ({
...existing,
[target]: "No available editors found.",
}));
setOpeningPathByTarget((existing) => ({ ...existing, [target]: false }));
return;
}
void ensureNativeApi()
.shell.openInEditor(path, editor)
.catch((error) => {
setOpenPathErrorByTarget((existing) => ({
...existing,
[target]: error instanceof Error ? error.message : failureMessage,
}));
})
.finally(() => {
setOpeningPathByTarget((existing) => ({ ...existing, [target]: false }));
});
},
[availableEditors],
);
const openKeybindingsFile = useCallback(() => {
if (!keybindingsConfigPath) return;
setOpenKeybindingsError(null);
setIsOpeningKeybindings(true);
const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
if (!editor) {
setOpenKeybindingsError("No available editors found.");
setIsOpeningKeybindings(false);
return;
}
void ensureNativeApi()
.shell.openInEditor(keybindingsConfigPath, editor)
.catch((error) => {
setOpenKeybindingsError(
error instanceof Error ? error.message : "Unable to open keybindings file.",
);
})
.finally(() => {
setIsOpeningKeybindings(false);
});
}, [availableEditors, keybindingsConfigPath]);
openInPreferredEditor("keybindings", keybindingsConfigPath, "Unable to open keybindings file.");
}, [keybindingsConfigPath, openInPreferredEditor]);
const openLogsDirectory = useCallback(() => {
openInPreferredEditor("logsDirectory", logsDirectoryPath, "Unable to open logs folder.");
}, [logsDirectoryPath, openInPreferredEditor]);
const openKeybindingsError = openPathErrorByTarget.keybindings ?? null;
const openDiagnosticsError = openPathErrorByTarget.logsDirectory ?? null;
const isOpeningKeybindings = openingPathByTarget.keybindings;
const isOpeningLogsDirectory = openingPathByTarget.logsDirectory;
const addCustomModel = useCallback(
(provider: ProviderKind) => {
@@ -1408,6 +1449,30 @@ export function GeneralSettingsPanel() {
description="Current version of the application."
/>
)}
<SettingsRow
title="Diagnostics"
description={diagnosticsDescription}
status={
<>
<span className="block break-all font-mono text-[11px] text-foreground">
{logsDirectoryPath ?? "Resolving logs directory..."}
</span>
{openDiagnosticsError ? (
<span className="mt-1 block text-destructive">{openDiagnosticsError}</span>
) : null}
</>
}
control={
<Button
size="xs"
variant="outline"
disabled={!logsDirectoryPath || isOpeningLogsDirectory}
onClick={openLogsDirectory}
>
{isOpeningLogsDirectory ? "Opening..." : "Open logs folder"}
</Button>
}
/>
</SettingsSection>
</SettingsPageContainer>
);
@@ -11,7 +11,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "assistant",
text: "a".repeat(144),
}),
).toBe(122);
).toBe(86.5);
});
it("uses assistant sizing rules for system messages", () => {
@@ -20,7 +20,7 @@ describe("estimateTimelineMessageHeight", () => {
role: "system",
text: "a".repeat(144),
}),
).toBe(122);
).toBe(86.5);
});
it("adds one attachment row for one or two user attachments", () => {
@@ -30,7 +30,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }],
}),
).toBe(346);
).toBe(234);
expect(
estimateTimelineMessageHeight({
@@ -38,7 +38,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }],
}),
).toBe(346);
).toBe(234);
});
it("adds a second attachment row for three or four user attachments", () => {
@@ -48,7 +48,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }],
}),
).toBe(574);
).toBe(350);
expect(
estimateTimelineMessageHeight({
@@ -56,7 +56,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "hello",
attachments: [{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }],
}),
).toBe(574);
).toBe(350);
});
it("does not cap long user message estimates", () => {
@@ -132,7 +132,7 @@ describe("estimateTimelineMessageHeight", () => {
text: "a".repeat(200),
};
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(188);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(122);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 320 })).toBe(154.75);
expect(estimateTimelineMessageHeight(message, { timelineWidthPx: 768 })).toBe(86.5);
});
});
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more