Merge upstream/main into web/atomic-store-refactor
This commit is contained in:
commit
5e009d61b4
118 files changed
+9436
-1333
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -20,6 +20,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
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,
|
||||
@@ -372,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") {
|
||||
@@ -444,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);
|
||||
}
|
||||
@@ -452,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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -609,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],
|
||||
@@ -716,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,
|
||||
|
||||
@@ -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),
|
||||
@@ -2176,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-");
|
||||
@@ -2360,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: {
|
||||
@@ -2371,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);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -2562,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-");
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
@@ -552,6 +553,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 = (
|
||||
@@ -1329,6 +1331,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);
|
||||
@@ -1461,6 +1481,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
path: null,
|
||||
});
|
||||
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
|
||||
yield* maybeRunSetupScript(worktree.worktree.path);
|
||||
|
||||
return {
|
||||
pullRequest,
|
||||
|
||||
+75
-2
@@ -1,6 +1,15 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import { Effect, FileSystem, Option, Path } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
import { Data, Effect, FileSystem, Layer, Option, Path } from "effect";
|
||||
import { cast } from "effect/Function";
|
||||
import {
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpClientResponse,
|
||||
HttpRouter,
|
||||
HttpServerResponse,
|
||||
HttpServerRequest,
|
||||
} from "effect/unstable/http";
|
||||
import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
@@ -9,10 +18,74 @@ import {
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
|
||||
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
|
||||
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
|
||||
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
|
||||
readonly cause: unknown;
|
||||
readonly bodyJson: OtlpTracer.TraceData;
|
||||
}> {}
|
||||
|
||||
export const otlpTracesProxyRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
OTLP_TRACES_PROXY_PATH,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const config = yield* ServerConfig;
|
||||
const otlpTracesUrl = config.otlpTracesUrl;
|
||||
const browserTraceCollector = yield* BrowserTraceCollector;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
|
||||
|
||||
yield* Effect.try({
|
||||
try: () => decodeOtlpTraceRecords(bodyJson),
|
||||
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
|
||||
}).pipe(
|
||||
Effect.flatMap((records) => browserTraceCollector.record(records)),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to decode browser OTLP traces", {
|
||||
cause,
|
||||
bodyJson,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (otlpTracesUrl === undefined) {
|
||||
return HttpServerResponse.empty({ status: 204 });
|
||||
}
|
||||
|
||||
return yield* httpClient
|
||||
.post(otlpTracesUrl, {
|
||||
body: HttpBody.jsonUnsafe(bodyJson),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.as(HttpServerResponse.empty({ status: 204 })),
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("Failed to export browser OTLP traces", {
|
||||
cause,
|
||||
otlpTracesUrl,
|
||||
}),
|
||||
),
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
|
||||
),
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
HttpRouter.cors({
|
||||
allowedMethods: ["POST", "OPTIONS"],
|
||||
allowedHeaders: ["content-type"],
|
||||
maxAge: 600,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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
@@ -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<
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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* () {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
GitCommandError,
|
||||
KeybindingRule,
|
||||
MessageId,
|
||||
OpenError,
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProjectId,
|
||||
@@ -19,9 +22,17 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
|
||||
import { Effect, FileSystem, Layer, Path, Stream } from "effect";
|
||||
import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
import { Effect, FileSystem, Layer, ManagedRuntime, Path, Stream } from "effect";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
HttpRouter,
|
||||
HttpServer,
|
||||
} from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import type { ServerConfigShape } from "./config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "./config.ts";
|
||||
@@ -39,6 +50,7 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
@@ -52,7 +64,15 @@ import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./server
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
|
||||
import {
|
||||
BrowserTraceCollector,
|
||||
type BrowserTraceCollectorShape,
|
||||
} from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
import {
|
||||
ProjectSetupScriptRunner,
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
} from "./project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
@@ -116,6 +136,113 @@ const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
ProjectFaviconResolverLive,
|
||||
);
|
||||
|
||||
const browserOtlpTracingLayer = Layer.mergeAll(
|
||||
FetchHttpClient.layer,
|
||||
OtlpSerialization.layerJson,
|
||||
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
|
||||
);
|
||||
|
||||
const makeBrowserOtlpPayload = (spanName: string) =>
|
||||
Effect.gen(function* () {
|
||||
const collector = yield* Effect.acquireRelease(
|
||||
Effect.promise(async () => {
|
||||
const NodeHttp = await import("node:http");
|
||||
|
||||
return await new Promise<{
|
||||
readonly close: () => Promise<void>;
|
||||
readonly firstRequest: Promise<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}>;
|
||||
readonly url: string;
|
||||
}>((resolve, reject) => {
|
||||
let resolveFirstRequest:
|
||||
| ((request: { readonly body: string; readonly contentType: string | null }) => void)
|
||||
| undefined;
|
||||
const firstRequest = new Promise<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}>((resolveRequest) => {
|
||||
resolveFirstRequest = resolveRequest;
|
||||
});
|
||||
|
||||
const server = NodeHttp.createServer((request, response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
request.on("end", () => {
|
||||
resolveFirstRequest?.({
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
contentType: request.headers["content-type"] ?? null,
|
||||
});
|
||||
resolveFirstRequest = undefined;
|
||||
response.statusCode = 204;
|
||||
response.end();
|
||||
});
|
||||
});
|
||||
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Expected TCP collector address"));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
url: `http://127.0.0.1:${address.port}/v1/traces`,
|
||||
firstRequest,
|
||||
close: () =>
|
||||
new Promise<void>((resolveClose, rejectClose) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
rejectClose(error);
|
||||
return;
|
||||
}
|
||||
resolveClose();
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}),
|
||||
({ close }) => Effect.promise(close),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OtlpTracer.layer({
|
||||
url: collector.url,
|
||||
exportInterval: "10 millis",
|
||||
resource: {
|
||||
serviceName: "t3-web",
|
||||
attributes: {
|
||||
"service.runtime": "t3-web",
|
||||
"service.mode": "browser",
|
||||
"service.version": "test",
|
||||
},
|
||||
},
|
||||
}).pipe(Layer.provide(browserOtlpTracingLayer)),
|
||||
);
|
||||
|
||||
try {
|
||||
yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName))));
|
||||
} finally {
|
||||
yield* Effect.promise(() => runtime.dispose());
|
||||
}
|
||||
|
||||
const request = yield* Effect.promise(() =>
|
||||
Promise.race([
|
||||
collector.firstRequest,
|
||||
new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000);
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
return JSON.parse(request.body) as OtlpTracer.TraceData;
|
||||
});
|
||||
|
||||
const buildAppUnderTest = (options?: {
|
||||
config?: Partial<ServerConfigShape>;
|
||||
layers?: {
|
||||
@@ -125,10 +252,12 @@ const buildAppUnderTest = (options?: {
|
||||
open?: Partial<OpenShape>;
|
||||
gitCore?: Partial<GitCoreShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
projectionSnapshotQuery?: Partial<ProjectionSnapshotQueryShape>;
|
||||
checkpointDiffQuery?: Partial<CheckpointDiffQueryShape>;
|
||||
browserTraceCollector?: Partial<BrowserTraceCollectorShape>;
|
||||
serverLifecycleEvents?: Partial<ServerLifecycleEventsShape>;
|
||||
serverRuntimeStartup?: Partial<ServerRuntimeStartupShape>;
|
||||
};
|
||||
@@ -139,8 +268,17 @@ const buildAppUnderTest = (options?: {
|
||||
const baseDir = options?.config?.baseDir ?? tempBaseDir;
|
||||
const devUrl = options?.config?.devUrl;
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const config = {
|
||||
const config: ServerConfigShape = {
|
||||
logLevel: "Info",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: "127.0.0.1",
|
||||
@@ -154,7 +292,7 @@ const buildAppUnderTest = (options?: {
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
...options?.config,
|
||||
} satisfies ServerConfigShape;
|
||||
};
|
||||
const layerConfig = Layer.succeed(ServerConfig, config);
|
||||
|
||||
const appLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
@@ -200,6 +338,12 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.gitManager,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
runForThread: () => Effect.succeed({ status: "no-script" as const }),
|
||||
...options?.layers?.projectSetupScriptRunner,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TerminalManager)({
|
||||
...options?.layers?.terminalManager,
|
||||
@@ -239,6 +383,12 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.checkpointDiffQuery,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(BrowserTraceCollector)({
|
||||
record: () => Effect.void,
|
||||
...options?.layers?.browserTraceCollector,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerLifecycleEvents)({
|
||||
publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }),
|
||||
@@ -256,6 +406,7 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(workspaceAndProjectServicesLayer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(layerConfig),
|
||||
);
|
||||
|
||||
@@ -413,6 +564,285 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("proxies browser OTLP trace exports through the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const upstreamRequests: Array<{
|
||||
readonly body: string;
|
||||
readonly contentType: string | null;
|
||||
}> = [];
|
||||
const localTraceRecords: Array<unknown> = [];
|
||||
const payload = {
|
||||
resourceSpans: [
|
||||
{
|
||||
resource: {
|
||||
attributes: [
|
||||
{
|
||||
key: "service.name",
|
||||
value: { stringValue: "t3-web" },
|
||||
},
|
||||
],
|
||||
},
|
||||
scopeSpans: [
|
||||
{
|
||||
scope: {
|
||||
name: "effect",
|
||||
version: "4.0.0-beta.43",
|
||||
},
|
||||
spans: [
|
||||
{
|
||||
traceId: "11111111111111111111111111111111",
|
||||
spanId: "2222222222222222",
|
||||
parentSpanId: "3333333333333333",
|
||||
name: "RpcClient.server.getSettings",
|
||||
kind: 3,
|
||||
startTimeUnixNano: "1000000",
|
||||
endTimeUnixNano: "2000000",
|
||||
attributes: [
|
||||
{
|
||||
key: "rpc.method",
|
||||
value: { stringValue: "server.getSettings" },
|
||||
},
|
||||
],
|
||||
events: [
|
||||
{
|
||||
name: "http.request",
|
||||
timeUnixNano: "1500000",
|
||||
attributes: [
|
||||
{
|
||||
key: "http.status_code",
|
||||
value: { intValue: "200" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
links: [],
|
||||
status: {
|
||||
code: "STATUS_CODE_OK",
|
||||
},
|
||||
flags: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const collector = yield* Effect.acquireRelease(
|
||||
Effect.promise(async () => {
|
||||
const NodeHttp = await import("node:http");
|
||||
|
||||
return await new Promise<{
|
||||
readonly close: () => Promise<void>;
|
||||
readonly url: string;
|
||||
}>((resolve, reject) => {
|
||||
const server = NodeHttp.createServer((request, response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
request.on("end", () => {
|
||||
upstreamRequests.push({
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
contentType: request.headers["content-type"] ?? null,
|
||||
});
|
||||
response.statusCode = 204;
|
||||
response.end();
|
||||
});
|
||||
});
|
||||
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Expected TCP collector address"));
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
url: `http://127.0.0.1:${address.port}/v1/traces`,
|
||||
close: () =>
|
||||
new Promise<void>((resolveClose, rejectClose) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
rejectClose(error);
|
||||
return;
|
||||
}
|
||||
resolveClose();
|
||||
});
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}),
|
||||
({ close }) => Effect.promise(close),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
otlpTracesUrl: collector.url,
|
||||
},
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
localTraceRecords.push(...records);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
origin: "http://localhost:5733",
|
||||
},
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers["access-control-allow-origin"], "*");
|
||||
assert.deepEqual(localTraceRecords, [
|
||||
{
|
||||
type: "otlp-span",
|
||||
name: "RpcClient.server.getSettings",
|
||||
traceId: "11111111111111111111111111111111",
|
||||
spanId: "2222222222222222",
|
||||
parentSpanId: "3333333333333333",
|
||||
sampled: true,
|
||||
kind: "client",
|
||||
startTimeUnixNano: "1000000",
|
||||
endTimeUnixNano: "2000000",
|
||||
durationMs: 1,
|
||||
attributes: {
|
||||
"rpc.method": "server.getSettings",
|
||||
},
|
||||
resourceAttributes: {
|
||||
"service.name": "t3-web",
|
||||
},
|
||||
scope: {
|
||||
name: "effect",
|
||||
version: "4.0.0-beta.43",
|
||||
attributes: {},
|
||||
},
|
||||
events: [
|
||||
{
|
||||
name: "http.request",
|
||||
timeUnixNano: "1500000",
|
||||
attributes: {
|
||||
"http.status_code": "200",
|
||||
},
|
||||
},
|
||||
],
|
||||
links: [],
|
||||
status: {
|
||||
code: "STATUS_CODE_OK",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(upstreamRequests, [
|
||||
{
|
||||
body: JSON.stringify(payload),
|
||||
contentType: "application/json",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("responds to browser OTLP trace preflight requests with CORS headers", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/api/observability/v1/traces");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(url, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://localhost:5733",
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
||||
assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS");
|
||||
assert.equal(response.headers.get("access-control-allow-headers"), "content-type");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"stores browser OTLP trace exports locally when no upstream collector is configured",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const localTraceRecords: Array<unknown> = [];
|
||||
const payload = yield* makeBrowserOtlpPayload("client.test");
|
||||
const resourceSpan = payload.resourceSpans[0];
|
||||
const scopeSpan = resourceSpan?.scopeSpans[0];
|
||||
const span = scopeSpan?.spans[0];
|
||||
|
||||
assert.notEqual(resourceSpan, undefined);
|
||||
assert.notEqual(scopeSpan, undefined);
|
||||
assert.notEqual(span, undefined);
|
||||
if (!resourceSpan || !scopeSpan || !span) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
browserTraceCollector: {
|
||||
record: (records) =>
|
||||
Effect.sync(() => {
|
||||
localTraceRecords.push(...records);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = yield* HttpClient.post("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(localTraceRecords.length, 1);
|
||||
const record = localTraceRecords[0] as {
|
||||
readonly type: string;
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly kind: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
readonly events: ReadonlyArray<unknown>;
|
||||
readonly links: ReadonlyArray<unknown>;
|
||||
readonly scope: {
|
||||
readonly name?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
readonly resourceAttributes: Readonly<Record<string, unknown>>;
|
||||
readonly status?: {
|
||||
readonly code?: string;
|
||||
};
|
||||
};
|
||||
|
||||
assert.equal(record.type, "otlp-span");
|
||||
assert.equal(record.name, span.name);
|
||||
assert.equal(record.traceId, span.traceId);
|
||||
assert.equal(record.spanId, span.spanId);
|
||||
assert.equal(record.kind, "internal");
|
||||
assert.deepEqual(record.attributes, {});
|
||||
assert.deepEqual(record.events, []);
|
||||
assert.deepEqual(record.links, []);
|
||||
assert.equal(record.scope.name, scopeSpan.scope.name);
|
||||
assert.deepEqual(record.scope.attributes, {});
|
||||
assert.equal(record.resourceAttributes["service.name"], "t3-web");
|
||||
assert.equal(record.status?.code, String(span.status.code));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("returns 404 for missing attachment id lookups", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -533,6 +963,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
} as const;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
config: {
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
},
|
||||
layers: {
|
||||
keybindings: {
|
||||
loadConfigState: Effect.succeed({
|
||||
@@ -561,6 +995,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.deepEqual(first.config.keybindings, []);
|
||||
assert.deepEqual(first.config.issues, []);
|
||||
assert.deepEqual(first.config.providers, providers);
|
||||
assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true);
|
||||
assert.equal(first.config.observability.localTracingEnabled, true);
|
||||
assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces");
|
||||
assert.equal(first.config.observability.otlpTracesEnabled, true);
|
||||
assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics");
|
||||
assert.equal(first.config.observability.otlpMetricsEnabled, true);
|
||||
assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS);
|
||||
}
|
||||
assert.deepEqual(second, {
|
||||
@@ -1228,6 +1668,413 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"bootstraps first-send worktree turns on the server before dispatching turn start",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
Effect.succeed({
|
||||
status: "started" as const,
|
||||
scriptId: "setup",
|
||||
scriptName: "Setup",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/tmp/bootstrap-worktree",
|
||||
}),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
projectSetupScriptRunner: {
|
||||
runForThread,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start"),
|
||||
threadId: ThreadId.makeUnsafe("thread-bootstrap"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("msg-bootstrap"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
},
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 5);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
[
|
||||
"thread.create",
|
||||
"thread.meta.update",
|
||||
"thread.activity.append",
|
||||
"thread.activity.append",
|
||||
"thread.turn.start",
|
||||
],
|
||||
);
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
branch: "main",
|
||||
newBranch: "t3code/bootstrap-branch",
|
||||
path: null,
|
||||
});
|
||||
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
|
||||
threadId: ThreadId.makeUnsafe("thread-bootstrap"),
|
||||
projectId: defaultProjectId,
|
||||
projectCwd: "/tmp/project",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
});
|
||||
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
command.type === "thread.activity.append",
|
||||
);
|
||||
assert.deepEqual(
|
||||
setupActivities.map((command) => command.activity.kind),
|
||||
["setup-script.requested", "setup-script.started"],
|
||||
);
|
||||
const finalCommand = dispatchedCommands[4];
|
||||
assertTrue(finalCommand?.type === "thread.turn.start");
|
||||
if (finalCommand?.type === "thread.turn.start") {
|
||||
assert.equal(finalCommand.bootstrap, undefined);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
Effect.fail(new Error("pty unavailable")),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
projectSetupScriptRunner: {
|
||||
runForThread,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-failure"),
|
||||
threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-failure"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("msg-bootstrap-setup-failure"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
},
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 4);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
|
||||
);
|
||||
const setupFailureActivity = dispatchedCommands.find(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
command.type === "thread.activity.append",
|
||||
);
|
||||
assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed");
|
||||
assert.deepEqual(setupFailureActivity?.activity.payload, {
|
||||
detail: "pty unavailable",
|
||||
worktreePath: "/tmp/bootstrap-worktree",
|
||||
});
|
||||
assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
|
||||
Effect.succeed({
|
||||
status: "started" as const,
|
||||
scriptId: "setup",
|
||||
scriptName: "Setup",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/tmp/bootstrap-worktree",
|
||||
}),
|
||||
);
|
||||
let setupActivityAppendAttempt = 0;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) => {
|
||||
if (
|
||||
command.type === "thread.activity.append" &&
|
||||
command.activity.kind.startsWith("setup-script.")
|
||||
) {
|
||||
setupActivityAppendAttempt += 1;
|
||||
if (setupActivityAppendAttempt === 2) {
|
||||
return Effect.fail(
|
||||
new OrchestrationListenerCallbackError({
|
||||
listener: "domain-event",
|
||||
detail: "failed to append setup-script.started activity",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
});
|
||||
},
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
projectSetupScriptRunner: {
|
||||
runForThread,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-activity-failure"),
|
||||
threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-activity-failure"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("msg-bootstrap-setup-activity-failure"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
},
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(response.sequence, 4);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"],
|
||||
);
|
||||
const setupActivities = dispatchedCommands.filter(
|
||||
(command): command is Extract<OrchestrationCommand, { type: "thread.activity.append" }> =>
|
||||
command.type === "thread.activity.append",
|
||||
);
|
||||
assert.deepEqual(
|
||||
setupActivities.map((command) => command.activity.kind),
|
||||
["setup-script.requested"],
|
||||
);
|
||||
assertTrue(
|
||||
setupActivities.every((command) => command.activity.kind !== "setup-script.failed"),
|
||||
);
|
||||
assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete"));
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.die(new Error("worktree exploded")),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-defect"),
|
||||
threadId: ThreadId.makeUnsafe("thread-bootstrap-defect"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("msg-bootstrap-defect"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: defaultProjectId,
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
},
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
},
|
||||
runSetupScript: false,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
).pipe(Effect.result),
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertTrue(result.failure._tag === "OrchestrationDispatchCommandError");
|
||||
assert.include(result.failure.message, "worktree exploded");
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.create", "thread.delete"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience",
|
||||
() =>
|
||||
@@ -1323,6 +2170,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
cwd: "/tmp/project",
|
||||
worktreePath: null,
|
||||
status: "running" as const,
|
||||
pid: 1234,
|
||||
history: "",
|
||||
|
||||
@@ -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";
|
||||
@@ -29,7 +34,6 @@ 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 +46,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* () {
|
||||
@@ -158,6 +164,7 @@ const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersisten
|
||||
const GitLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(
|
||||
GitManagerLive.pipe(
|
||||
Layer.provideMerge(ProjectSetupScriptRunnerLive),
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(RoutingTextGenerationLive),
|
||||
@@ -177,15 +184,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 +204,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 +240,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),
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
+519
-131
@@ -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,
|
||||
@@ -28,6 +32,11 @@ 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 +45,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* () {
|
||||
@@ -54,6 +64,265 @@ 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,85 +336,112 @@ 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,
|
||||
};
|
||||
});
|
||||
|
||||
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);
|
||||
const result = yield* startup.enqueueCommand(
|
||||
orchestrationEngine.dispatch(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",
|
||||
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;
|
||||
@@ -200,82 +496,167 @@ 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.gitStatus]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitPull]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), {
|
||||
"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: () => 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),
|
||||
{ "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), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitRemoveWorktree]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitCreateBranch]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitCheckout]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), {
|
||||
"rpc.aggregate": "git",
|
||||
}),
|
||||
[WS_METHODS.gitInit]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "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) => ({
|
||||
@@ -310,9 +691,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(
|
||||
@@ -323,6 +706,7 @@ const WsRpcLayer = WsRpcGroup.toLayer(
|
||||
);
|
||||
return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
});
|
||||
}),
|
||||
@@ -330,9 +714,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",
|
||||
|
||||
@@ -33,6 +33,7 @@ import { isMacPlatform } from "../lib/utils";
|
||||
import { __resetNativeApiForTests } from "../nativeApi";
|
||||
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";
|
||||
@@ -135,6 +136,12 @@ function createBaseServerConfig(): ServerConfig {
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
observability: {
|
||||
logsDirectoryPath: "/repo/project/.t3/logs",
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: false,
|
||||
otlpMetricsEnabled: false,
|
||||
},
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
@@ -676,6 +683,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: "",
|
||||
@@ -1157,6 +1170,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
sidebarThreadSummaryById: {},
|
||||
bootstrapComplete: false,
|
||||
});
|
||||
useTerminalStateStore.persist.clearStorage();
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadId: {},
|
||||
terminalLaunchContextByThreadId: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -1380,6 +1400,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();
|
||||
|
||||
@@ -1721,7 +1809,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]: {
|
||||
@@ -1826,45 +1914,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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 { gitCreateWorktreeMutationOptions, gitStatusQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { gitStatusQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { isElectron } from "../env";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
@@ -52,7 +53,6 @@ import {
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isSessionActivelyRunningTurn,
|
||||
isLatestTurnSettled,
|
||||
formatElapsed,
|
||||
} from "../session-logic";
|
||||
@@ -112,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";
|
||||
@@ -200,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`;
|
||||
@@ -352,12 +350,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;
|
||||
@@ -428,6 +428,7 @@ function useLocalDispatchState(input: {
|
||||
interface PersistentThreadTerminalDrawerProps {
|
||||
threadId: ThreadId;
|
||||
visible: boolean;
|
||||
launchContext: PersistentTerminalLaunchContext | null;
|
||||
focusRequestId: number;
|
||||
splitShortcutLabel: string | undefined;
|
||||
newShortcutLabel: string | undefined;
|
||||
@@ -438,6 +439,7 @@ interface PersistentThreadTerminalDrawerProps {
|
||||
function PersistentThreadTerminalDrawer({
|
||||
threadId,
|
||||
visible,
|
||||
launchContext,
|
||||
focusRequestId,
|
||||
splitShortcutLabel,
|
||||
newShortcutLabel,
|
||||
@@ -465,25 +467,32 @@ function PersistentThreadTerminalDrawer({
|
||||
const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal);
|
||||
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
|
||||
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const effectiveWorktreePath = useMemo(() => {
|
||||
if (launchContext !== null) {
|
||||
return launchContext.worktreePath;
|
||||
}
|
||||
return worktreePath;
|
||||
}, [launchContext, worktreePath]);
|
||||
const cwd = useMemo(
|
||||
() =>
|
||||
project
|
||||
launchContext?.cwd ??
|
||||
(project
|
||||
? projectScriptCwd({
|
||||
project: { cwd: project.cwd },
|
||||
worktreePath,
|
||||
worktreePath: effectiveWorktreePath,
|
||||
})
|
||||
: null,
|
||||
[project, worktreePath],
|
||||
: null),
|
||||
[effectiveWorktreePath, launchContext?.cwd, project],
|
||||
);
|
||||
const runtimeEnv = useMemo(
|
||||
() =>
|
||||
project
|
||||
? projectScriptRuntimeEnv({
|
||||
project: { cwd: project.cwd },
|
||||
worktreePath,
|
||||
worktreePath: effectiveWorktreePath,
|
||||
})
|
||||
: {},
|
||||
[project, worktreePath],
|
||||
[effectiveWorktreePath, project],
|
||||
);
|
||||
|
||||
const bumpFocusRequestId = useCallback(() => {
|
||||
@@ -566,6 +575,7 @@ function PersistentThreadTerminalDrawer({
|
||||
<ThreadTerminalDrawer
|
||||
threadId={threadId}
|
||||
cwd={cwd}
|
||||
worktreePath={effectiveWorktreePath}
|
||||
runtimeEnv={runtimeEnv}
|
||||
visible={visible}
|
||||
height={terminalState.terminalHeight}
|
||||
@@ -591,7 +601,6 @@ function PersistentThreadTerminalDrawer({
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const serverThread = useStore(useMemo(() => createThreadSelector(threadId), [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],
|
||||
@@ -607,8 +616,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;
|
||||
@@ -699,8 +706,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[]>
|
||||
>({});
|
||||
@@ -767,6 +775,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal);
|
||||
const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal);
|
||||
const serverThreadIds = useStore((state) => state.threadIds);
|
||||
const storeServerTerminalLaunchContext = useTerminalStateStore(
|
||||
(s) => s.terminalLaunchContextByThreadId[threadId] ?? null,
|
||||
);
|
||||
const storeClearTerminalLaunchContext = useTerminalStateStore(
|
||||
(s) => s.clearTerminalLaunchContext,
|
||||
);
|
||||
const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId);
|
||||
const draftThreadIds = useMemo(
|
||||
() => Object.keys(draftThreadsByThreadId) as ThreadId[],
|
||||
@@ -970,24 +984,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(() => {
|
||||
@@ -1148,11 +1151,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activePendingUserInput: activePendingUserInput?.requestId ?? null,
|
||||
threadError: activeThread?.error,
|
||||
});
|
||||
const isTurnRunning = isSessionActivelyRunningTurn(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
);
|
||||
const isWorking = isTurnRunning || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
@@ -1169,7 +1168,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (activePendingProgress) {
|
||||
return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`;
|
||||
}
|
||||
if (isTurnRunning) {
|
||||
if (phase === "running") {
|
||||
return "running";
|
||||
}
|
||||
if (showPlanFollowUpPrompt) {
|
||||
@@ -1183,7 +1182,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
isConnecting,
|
||||
isPreparingWorktree,
|
||||
isSendBusy,
|
||||
isTurnRunning,
|
||||
phase,
|
||||
prompt,
|
||||
showPlanFollowUpPrompt,
|
||||
]);
|
||||
@@ -1552,6 +1551,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
|
||||
[selectedProvider, providerStatuses],
|
||||
);
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const activeTerminalLaunchContext =
|
||||
terminalLaunchContext?.threadId === activeThreadId
|
||||
? terminalLaunchContext
|
||||
: (storeServerTerminalLaunchContext ?? null);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const terminalShortcutLabelOptions = useMemo(
|
||||
@@ -1622,17 +1627,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().threadShellById[targetThreadId] !== undefined) {
|
||||
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,
|
||||
};
|
||||
});
|
||||
},
|
||||
@@ -1772,7 +1778,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);
|
||||
@@ -1785,7 +1797,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
|
||||
@@ -1793,6 +1805,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,
|
||||
@@ -1801,6 +1814,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: activeThreadId,
|
||||
terminalId: targetTerminalId,
|
||||
cwd: targetCwd,
|
||||
...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
|
||||
env: runtimeEnv,
|
||||
};
|
||||
|
||||
@@ -1834,44 +1848,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;
|
||||
@@ -2343,10 +2319,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scheduleStickToBottom();
|
||||
}, [messageCount, scheduleStickToBottom]);
|
||||
useEffect(() => {
|
||||
if (!isTurnRunning) return;
|
||||
if (phase !== "running") return;
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
}, [isTurnRunning, scheduleStickToBottom, timelineEntries]);
|
||||
}, [phase, scheduleStickToBottom, timelineEntries]);
|
||||
|
||||
useEffect(() => {
|
||||
setExpandedWorkGroups({});
|
||||
@@ -2565,14 +2541,82 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: "local";
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTurnRunning) return;
|
||||
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(() => {
|
||||
setNowTick(Date.now());
|
||||
}, 1000);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [isTurnRunning]);
|
||||
}, [phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -2792,7 +2836,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThread || isRevertingCheckpoint) return;
|
||||
|
||||
if (isTurnRunning || isSendBusy || isConnecting) {
|
||||
if (phase === "running" || isSendBusy || isConnecting) {
|
||||
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||
return;
|
||||
}
|
||||
@@ -2825,7 +2869,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
setIsRevertingCheckpoint(false);
|
||||
},
|
||||
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, isTurnRunning, setThreadError],
|
||||
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
|
||||
);
|
||||
|
||||
const onSend = async (e?: { preventDefault: () => void }) => {
|
||||
@@ -2978,36 +3022,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];
|
||||
@@ -3035,48 +3051,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({
|
||||
@@ -3097,8 +3071,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(),
|
||||
@@ -3113,19 +3116,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 &&
|
||||
@@ -3187,14 +3182,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(
|
||||
@@ -3215,14 +3210,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(
|
||||
@@ -4414,7 +4409,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
: null
|
||||
}
|
||||
isRunning={isTurnRunning}
|
||||
isRunning={phase === "running"}
|
||||
showPlanFollowUpPrompt={
|
||||
pendingUserInputs.length === 0 && showPlanFollowUpPrompt
|
||||
}
|
||||
@@ -4450,6 +4445,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<PullRequestThreadDialog
|
||||
key={pullRequestDialogState.key}
|
||||
open
|
||||
threadId={activeThread.id}
|
||||
cwd={activeProject?.cwd ?? null}
|
||||
initialReference={pullRequestDialogState.initialReference}
|
||||
onOpenChange={(open) => {
|
||||
@@ -4489,6 +4485,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
key={mountedThreadId}
|
||||
threadId={mountedThreadId}
|
||||
visible={mountedThreadId === activeThreadId && terminalState.terminalOpen}
|
||||
launchContext={
|
||||
mountedThreadId === activeThreadId ? (activeTerminalLaunchContext ?? null) : null
|
||||
}
|
||||
focusRequestId={mountedThreadId === activeThreadId ? terminalFocusRequestId : 0}
|
||||
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
|
||||
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
|
||||
|
||||
@@ -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,
|
||||
@@ -56,7 +57,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" },
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -212,6 +212,7 @@ interface TerminalViewportProps {
|
||||
terminalId: string;
|
||||
terminalLabel: string;
|
||||
cwd: string;
|
||||
worktreePath?: string | null;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
onSessionExited: () => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
@@ -226,6 +227,7 @@ function TerminalViewport({
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
cwd,
|
||||
worktreePath,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
onAddTerminalContext,
|
||||
@@ -597,6 +599,7 @@ function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
...(worktreePath !== undefined ? { worktreePath } : {}),
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
@@ -720,6 +723,7 @@ function TerminalViewport({
|
||||
interface ThreadTerminalDrawerProps {
|
||||
threadId: ThreadId;
|
||||
cwd: string;
|
||||
worktreePath?: string | null;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
visible?: boolean;
|
||||
height: number;
|
||||
@@ -771,6 +775,7 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA
|
||||
export default function ThreadTerminalDrawer({
|
||||
threadId,
|
||||
cwd,
|
||||
worktreePath,
|
||||
runtimeEnv,
|
||||
visible = true,
|
||||
height,
|
||||
@@ -1097,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}
|
||||
@@ -1117,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;
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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(() => {
|
||||
resetServerStateForTests();
|
||||
__resetNativeApiForTests();
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetServerStateForTests();
|
||||
__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>
|
||||
);
|
||||
|
||||
@@ -23,6 +23,7 @@ export type ThreadToastData = {
|
||||
threadId?: ThreadId | null;
|
||||
tooltipStyle?: boolean;
|
||||
dismissAfterVisibleMs?: number;
|
||||
hideCopyButton?: boolean;
|
||||
};
|
||||
|
||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
||||
@@ -308,15 +309,15 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
className="min-w-0 wrap-break-word font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
{toast.type === "error" &&
|
||||
typeof toast.description === "string" &&
|
||||
!toast.data?.hideCopyButton && <CopyErrorButton text={toast.description} />}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 select-text wrap-break-word text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
@@ -402,15 +403,17 @@ function AnchoredToasts() {
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
className="min-w-0 wrap-break-word font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
{toast.type === "error" &&
|
||||
typeof toast.description === "string" &&
|
||||
!toast.data?.hideCopyButton && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
className="min-w-0 select-text wrap-break-word text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts";
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
type GitStackedAction,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
infiniteQueryOptions,
|
||||
mutationOptions,
|
||||
@@ -244,13 +248,22 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {
|
||||
mutationFn: async ({
|
||||
reference,
|
||||
mode,
|
||||
threadId,
|
||||
}: {
|
||||
reference: string;
|
||||
mode: "local" | "worktree";
|
||||
threadId?: ThreadId;
|
||||
}) => {
|
||||
const api = ensureNativeApi();
|
||||
if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");
|
||||
return api.git.preparePullRequestThread({
|
||||
cwd: input.cwd,
|
||||
reference,
|
||||
mode,
|
||||
...(threadId ? { threadId } : {}),
|
||||
});
|
||||
},
|
||||
mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd),
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect";
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { resolveServerUrl } from "../lib/utils";
|
||||
import { APP_VERSION } from "~/branding";
|
||||
|
||||
const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
|
||||
const CLIENT_TRACING_RESOURCE = {
|
||||
serviceName: "t3-web",
|
||||
attributes: {
|
||||
"service.runtime": "t3-web",
|
||||
"service.mode": isElectron ? "electron" : "browser",
|
||||
"service.version": APP_VERSION,
|
||||
},
|
||||
} as const;
|
||||
|
||||
const delegateRuntimeLayer = Layer.mergeAll(
|
||||
FetchHttpClient.layer,
|
||||
OtlpSerialization.layerJson,
|
||||
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
|
||||
);
|
||||
|
||||
let activeDelegate: Tracer.Tracer | null = null;
|
||||
let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
|
||||
let activeScope: Scope.Closeable | null = null;
|
||||
let activeConfigKey: string | null = null;
|
||||
let configurationGeneration = 0;
|
||||
let pendingConfiguration = Promise.resolve();
|
||||
|
||||
export interface ClientTracingConfig {
|
||||
readonly exportIntervalMs?: number;
|
||||
}
|
||||
|
||||
export const ClientTracingLive = Layer.succeed(
|
||||
Tracer.Tracer,
|
||||
Tracer.make({
|
||||
span(options) {
|
||||
return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
|
||||
if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
|
||||
return pendingConfiguration;
|
||||
}
|
||||
pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
|
||||
return pendingConfiguration;
|
||||
}
|
||||
|
||||
async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
|
||||
const otlpTracesUrl = resolveServerUrl({
|
||||
protocol: window.location.protocol === "https:" ? "https" : "http",
|
||||
pathname: "/api/observability/v1/traces",
|
||||
});
|
||||
const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
|
||||
const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
|
||||
|
||||
if (activeConfigKey === nextConfigKey && activeDelegate !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
activeConfigKey = nextConfigKey;
|
||||
const generation = ++configurationGeneration;
|
||||
|
||||
const previousRuntime = activeRuntime;
|
||||
const previousScope = activeScope;
|
||||
|
||||
activeDelegate = null;
|
||||
activeRuntime = null;
|
||||
activeScope = null;
|
||||
|
||||
await disposeTracerRuntime(previousRuntime, previousScope);
|
||||
|
||||
const runtime = ManagedRuntime.make(delegateRuntimeLayer);
|
||||
const scope = runtime.runSync(Scope.make());
|
||||
|
||||
try {
|
||||
const delegate = await runtime.runPromise(
|
||||
Scope.provide(scope)(
|
||||
OtlpTracer.make({
|
||||
url: otlpTracesUrl,
|
||||
exportInterval: `${exportIntervalMs} millis`,
|
||||
resource: CLIENT_TRACING_RESOURCE,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (generation !== configurationGeneration) {
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
return;
|
||||
}
|
||||
|
||||
activeDelegate = delegate;
|
||||
activeRuntime = runtime;
|
||||
activeScope = scope;
|
||||
} catch (error) {
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
|
||||
if (generation === configurationGeneration) {
|
||||
console.warn("Failed to configure client tracing exporter", {
|
||||
error: formatError(error),
|
||||
otlpTracesUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function disposeTracerRuntime(
|
||||
runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
|
||||
scope: Scope.Closeable | null,
|
||||
): Promise<void> {
|
||||
if (runtime === null || scope === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runtime
|
||||
.runPromise(Scope.close(scope, Exit.void))
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
runtime.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
function formatError(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export async function __resetClientTracingForTests() {
|
||||
configurationGeneration++;
|
||||
activeConfigKey = null;
|
||||
activeDelegate = null;
|
||||
pendingConfiguration = Promise.resolve();
|
||||
|
||||
const runtime = activeRuntime;
|
||||
const scope = activeScope;
|
||||
activeRuntime = null;
|
||||
activeScope = null;
|
||||
|
||||
await disposeTracerRuntime(runtime, scope);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
|
||||
import {
|
||||
createOrchestrationRecoveryCoordinator,
|
||||
deriveReplayRetryDecision,
|
||||
} from "./orchestrationRecovery";
|
||||
|
||||
describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
it("defers live events until bootstrap completes and then requests replay", () => {
|
||||
@@ -59,10 +62,13 @@ describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
coordinator.classifyDomainEvent(7);
|
||||
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
|
||||
|
||||
expect(coordinator.completeReplayRecovery()).toBe(true);
|
||||
expect(coordinator.completeReplayRecovery()).toEqual({
|
||||
replayMadeProgress: true,
|
||||
shouldReplay: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not immediately replay again when replay returns no new events", () => {
|
||||
it("retries replay when no progress was made but higher live sequences were observed", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
@@ -70,7 +76,10 @@ describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
coordinator.classifyDomainEvent(5);
|
||||
coordinator.beginReplayRecovery("sequence-gap");
|
||||
|
||||
expect(coordinator.completeReplayRecovery()).toBe(false);
|
||||
expect(coordinator.completeReplayRecovery()).toEqual({
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
});
|
||||
expect(coordinator.getState()).toMatchObject({
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
@@ -79,6 +88,19 @@ describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not request another replay when a replay made no progress and nothing newer was observed", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
coordinator.beginSnapshotRecovery("bootstrap");
|
||||
coordinator.completeSnapshotRecovery(3);
|
||||
coordinator.beginReplayRecovery("sequence-gap");
|
||||
|
||||
expect(coordinator.completeReplayRecovery()).toEqual({
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
|
||||
const coordinator = createOrchestrationRecoveryCoordinator();
|
||||
|
||||
@@ -131,3 +153,154 @@ describe("createOrchestrationRecoveryCoordinator", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveReplayRetryDecision", () => {
|
||||
it("retries immediately when replay made progress", () => {
|
||||
expect(
|
||||
deriveReplayRetryDecision({
|
||||
previousTracker: {
|
||||
attempts: 2,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
completion: {
|
||||
replayMadeProgress: true,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 5,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
}),
|
||||
).toEqual({
|
||||
shouldRetry: true,
|
||||
delayMs: 0,
|
||||
tracker: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("caps no-progress retries for the same frontier", () => {
|
||||
const first = deriveReplayRetryDecision({
|
||||
previousTracker: null,
|
||||
completion: {
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
});
|
||||
|
||||
const second = deriveReplayRetryDecision({
|
||||
previousTracker: first.tracker,
|
||||
completion: {
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
});
|
||||
|
||||
const third = deriveReplayRetryDecision({
|
||||
previousTracker: second.tracker,
|
||||
completion: {
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
});
|
||||
|
||||
const fourth = deriveReplayRetryDecision({
|
||||
previousTracker: third.tracker,
|
||||
completion: {
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
});
|
||||
|
||||
expect(first).toEqual({
|
||||
shouldRetry: true,
|
||||
delayMs: 100,
|
||||
tracker: {
|
||||
attempts: 1,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
});
|
||||
expect(second).toEqual({
|
||||
shouldRetry: true,
|
||||
delayMs: 200,
|
||||
tracker: {
|
||||
attempts: 2,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
});
|
||||
expect(third).toEqual({
|
||||
shouldRetry: true,
|
||||
delayMs: 400,
|
||||
tracker: {
|
||||
attempts: 3,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
},
|
||||
});
|
||||
expect(fourth).toEqual({
|
||||
shouldRetry: false,
|
||||
delayMs: 0,
|
||||
tracker: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("resets the retry budget when the replay frontier changes", () => {
|
||||
const exhausted = {
|
||||
attempts: 3,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 5,
|
||||
};
|
||||
|
||||
expect(
|
||||
deriveReplayRetryDecision({
|
||||
previousTracker: exhausted,
|
||||
completion: {
|
||||
replayMadeProgress: false,
|
||||
shouldReplay: true,
|
||||
},
|
||||
recoveryState: {
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 6,
|
||||
},
|
||||
baseDelayMs: 100,
|
||||
maxNoProgressRetries: 3,
|
||||
}),
|
||||
).toEqual({
|
||||
shouldRetry: true,
|
||||
delayMs: 100,
|
||||
tracker: {
|
||||
attempts: 1,
|
||||
latestSequence: 3,
|
||||
highestObservedSequence: 6,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
|
||||
export type OrchestrationRecoveryReason =
|
||||
| "bootstrap"
|
||||
| "sequence-gap"
|
||||
| "resubscribe"
|
||||
| "replay-failed";
|
||||
|
||||
export interface OrchestrationRecoveryPhase {
|
||||
kind: "snapshot" | "replay";
|
||||
@@ -13,8 +17,74 @@ export interface OrchestrationRecoveryState {
|
||||
inFlight: OrchestrationRecoveryPhase | null;
|
||||
}
|
||||
|
||||
export interface ReplayRecoveryCompletion {
|
||||
replayMadeProgress: boolean;
|
||||
shouldReplay: boolean;
|
||||
}
|
||||
|
||||
export interface ReplayRetryTracker {
|
||||
attempts: number;
|
||||
latestSequence: number;
|
||||
highestObservedSequence: number;
|
||||
}
|
||||
|
||||
export interface ReplayRetryDecision {
|
||||
shouldRetry: boolean;
|
||||
delayMs: number;
|
||||
tracker: ReplayRetryTracker | null;
|
||||
}
|
||||
|
||||
type SequencedEvent = Readonly<{ sequence: number }>;
|
||||
|
||||
export function deriveReplayRetryDecision(input: {
|
||||
previousTracker: ReplayRetryTracker | null;
|
||||
completion: ReplayRecoveryCompletion;
|
||||
recoveryState: Pick<OrchestrationRecoveryState, "latestSequence" | "highestObservedSequence">;
|
||||
baseDelayMs: number;
|
||||
maxNoProgressRetries: number;
|
||||
}): ReplayRetryDecision {
|
||||
if (!input.completion.shouldReplay) {
|
||||
return {
|
||||
shouldRetry: false,
|
||||
delayMs: 0,
|
||||
tracker: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (input.completion.replayMadeProgress) {
|
||||
return {
|
||||
shouldRetry: true,
|
||||
delayMs: 0,
|
||||
tracker: null,
|
||||
};
|
||||
}
|
||||
|
||||
const previousTracker = input.previousTracker;
|
||||
const sameFrontier =
|
||||
previousTracker !== null &&
|
||||
previousTracker.latestSequence === input.recoveryState.latestSequence &&
|
||||
previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence;
|
||||
|
||||
const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1;
|
||||
if (attempts > input.maxNoProgressRetries) {
|
||||
return {
|
||||
shouldRetry: false,
|
||||
delayMs: 0,
|
||||
tracker: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
shouldRetry: true,
|
||||
delayMs: input.baseDelayMs * 2 ** (attempts - 1),
|
||||
tracker: {
|
||||
attempts,
|
||||
latestSequence: input.recoveryState.latestSequence,
|
||||
highestObservedSequence: input.recoveryState.highestObservedSequence,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createOrchestrationRecoveryCoordinator() {
|
||||
let state: OrchestrationRecoveryState = {
|
||||
latestSequence: 0,
|
||||
@@ -120,16 +190,16 @@ export function createOrchestrationRecoveryCoordinator() {
|
||||
return true;
|
||||
},
|
||||
|
||||
completeReplayRecovery(): boolean {
|
||||
completeReplayRecovery(): ReplayRecoveryCompletion {
|
||||
const replayMadeProgress =
|
||||
replayStartSequence !== null && state.latestSequence > replayStartSequence;
|
||||
replayStartSequence = null;
|
||||
state.inFlight = null;
|
||||
if (!replayMadeProgress) {
|
||||
state.pendingReplay = false;
|
||||
return false;
|
||||
}
|
||||
return resolveReplayNeedAfterRecovery().shouldReplay;
|
||||
const replayResolution = resolveReplayNeedAfterRecovery();
|
||||
return {
|
||||
replayMadeProgress,
|
||||
shouldReplay: replayResolution.shouldReplay,
|
||||
};
|
||||
},
|
||||
|
||||
failReplayRecovery(): void {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
setupProjectScript,
|
||||
} from "@t3tools/shared/projectScripts";
|
||||
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
} from "./projectScripts";
|
||||
|
||||
describe("projectScripts helpers", () => {
|
||||
|
||||
@@ -55,43 +55,7 @@ export function nextProjectScriptId(name: string, existingIds: Iterable<string>)
|
||||
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
|
||||
}
|
||||
|
||||
interface ProjectScriptRuntimeEnvInput {
|
||||
project: {
|
||||
cwd: string;
|
||||
};
|
||||
worktreePath?: string | null;
|
||||
extraEnv?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function projectScriptCwd(input: {
|
||||
project: {
|
||||
cwd: string;
|
||||
};
|
||||
worktreePath?: string | null;
|
||||
}): string {
|
||||
return input.worktreePath ?? input.project.cwd;
|
||||
}
|
||||
|
||||
export function projectScriptRuntimeEnv(
|
||||
input: ProjectScriptRuntimeEnvInput,
|
||||
): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
T3CODE_PROJECT_ROOT: input.project.cwd,
|
||||
};
|
||||
if (input.worktreePath) {
|
||||
env.T3CODE_WORKTREE_PATH = input.worktreePath;
|
||||
}
|
||||
if (input.extraEnv) {
|
||||
return { ...env, ...input.extraEnv };
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
||||
const regular = scripts.find((script) => !script.runOnWorktreeCreate);
|
||||
return regular ?? scripts[0] ?? null;
|
||||
}
|
||||
|
||||
export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
||||
return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ describe("parsePullRequestReference", () => {
|
||||
});
|
||||
|
||||
it("accepts #number references", () => {
|
||||
expect(parsePullRequestReference("#42")).toBe("#42");
|
||||
expect(parsePullRequestReference("#42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with raw numbers", () => {
|
||||
@@ -22,7 +22,7 @@ describe("parsePullRequestReference", () => {
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with #number references", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
|
||||
if (numberMatch?.[1]) {
|
||||
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
|
||||
return numberMatch[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
OrchestrationEvent,
|
||||
ThreadId,
|
||||
type ServerLifecycleWelcomePayload,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Outlet,
|
||||
@@ -16,6 +16,11 @@ import { Throttler } from "@tanstack/react-pacer";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import {
|
||||
SlowRpcAckToastCoordinator,
|
||||
WebSocketConnectionCoordinator,
|
||||
WebSocketConnectionSurface,
|
||||
} from "../components/WebSocketConnectionSurface";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
@@ -36,13 +41,13 @@ import {
|
||||
import { selectProjects, selectThreadById, selectThreads, useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
|
||||
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
|
||||
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
|
||||
import { deriveReplayRetryDecision } from "../orchestrationRecovery";
|
||||
import { getWsRpcClient } from "~/wsRpcClient";
|
||||
|
||||
export const Route = createRootRouteWithContext<{
|
||||
@@ -73,9 +78,13 @@ function RootRouteView() {
|
||||
<AnchoredToastProvider>
|
||||
<ServerStateBootstrap />
|
||||
<EventRouter />
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
<WebSocketConnectionCoordinator />
|
||||
<SlowRpcAckToastCoordinator />
|
||||
<WebSocketConnectionSurface>
|
||||
<AppSidebarLayout>
|
||||
<Outlet />
|
||||
</AppSidebarLayout>
|
||||
</WebSocketConnectionSurface>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
@@ -189,6 +198,9 @@ function coalesceOrchestrationUiEvents(
|
||||
return coalesced;
|
||||
}
|
||||
|
||||
const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
|
||||
const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
|
||||
|
||||
function ServerStateBootstrap() {
|
||||
useEffect(() => startServerStateSync(getWsRpcClient().server), []);
|
||||
|
||||
@@ -206,6 +218,7 @@ function EventRouter() {
|
||||
const removeOrphanedTerminalStates = useTerminalStateStore(
|
||||
(store) => store.removeOrphanedTerminalStates,
|
||||
);
|
||||
const applyTerminalEvent = useTerminalStateStore((store) => store.applyTerminalEvent);
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
@@ -309,6 +322,7 @@ function EventRouter() {
|
||||
let disposed = false;
|
||||
disposedRef.current = false;
|
||||
const recovery = createOrchestrationRecoveryCoordinator();
|
||||
let replayRetryTracker: import("../orchestrationRecovery").ReplayRetryTracker | null = null;
|
||||
let needsProviderInvalidation = false;
|
||||
const pendingDomainEvents: OrchestrationEvent[] = [];
|
||||
let flushPendingDomainEventsScheduled = false;
|
||||
@@ -424,8 +438,8 @@ function EventRouter() {
|
||||
queueMicrotask(flushPendingDomainEvents);
|
||||
};
|
||||
|
||||
const recoverFromSequenceGap = async (): Promise<void> => {
|
||||
if (!recovery.beginReplayRecovery("sequence-gap")) {
|
||||
const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
|
||||
if (!recovery.beginReplayRecovery(reason)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -436,13 +450,42 @@ function EventRouter() {
|
||||
applyEventBatch(events);
|
||||
}
|
||||
} catch {
|
||||
replayRetryTracker = null;
|
||||
recovery.failReplayRecovery();
|
||||
void fallbackToSnapshotRecovery();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!disposed && recovery.completeReplayRecovery()) {
|
||||
void recoverFromSequenceGap();
|
||||
if (!disposed) {
|
||||
const replayCompletion = recovery.completeReplayRecovery();
|
||||
const retryDecision = deriveReplayRetryDecision({
|
||||
previousTracker: replayRetryTracker,
|
||||
completion: replayCompletion,
|
||||
recoveryState: recovery.getState(),
|
||||
baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS,
|
||||
maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES,
|
||||
});
|
||||
replayRetryTracker = retryDecision.tracker;
|
||||
|
||||
if (retryDecision.shouldRetry) {
|
||||
if (retryDecision.delayMs > 0) {
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, retryDecision.delayMs);
|
||||
});
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
void runReplayRecovery(reason);
|
||||
} else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
|
||||
console.warn(
|
||||
"[orchestration-recovery]",
|
||||
"Stopping replay recovery after no-progress retries.",
|
||||
{
|
||||
state: recovery.getState(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -472,7 +515,7 @@ function EventRouter() {
|
||||
syncServerReadModel(snapshot);
|
||||
reconcileSnapshotDerivedState();
|
||||
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
|
||||
void recoverFromSequenceGap();
|
||||
void runReplayRecovery("sequence-gap");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -489,35 +532,35 @@ function EventRouter() {
|
||||
const fallbackToSnapshotRecovery = async (): Promise<void> => {
|
||||
await runSnapshotRecovery("replay-failed");
|
||||
};
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
pendingDomainEvents.push(event);
|
||||
schedulePendingDomainEventFlush();
|
||||
return;
|
||||
}
|
||||
if (action === "recover") {
|
||||
flushPendingDomainEvents();
|
||||
void recoverFromSequenceGap();
|
||||
}
|
||||
});
|
||||
const unsubDomainEvent = api.orchestration.onDomainEvent(
|
||||
(event) => {
|
||||
const action = recovery.classifyDomainEvent(event.sequence);
|
||||
if (action === "apply") {
|
||||
pendingDomainEvents.push(event);
|
||||
schedulePendingDomainEventFlush();
|
||||
return;
|
||||
}
|
||||
if (action === "recover") {
|
||||
flushPendingDomainEvents();
|
||||
void runReplayRecovery("sequence-gap");
|
||||
}
|
||||
},
|
||||
{
|
||||
onResubscribe: () => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
flushPendingDomainEvents();
|
||||
void runReplayRecovery("resubscribe");
|
||||
},
|
||||
},
|
||||
);
|
||||
const unsubTerminalEvent = api.terminal.onEvent((event) => {
|
||||
const thread = selectThreadById(ThreadId.makeUnsafe(event.threadId))(useStore.getState());
|
||||
if (thread && thread.archivedAt !== null) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore.getState().recordTerminalEvent(event);
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
if (hasRunningSubprocess === null) {
|
||||
return;
|
||||
}
|
||||
useTerminalStateStore
|
||||
.getState()
|
||||
.setTerminalActivity(
|
||||
ThreadId.makeUnsafe(event.threadId),
|
||||
event.terminalId,
|
||||
hasRunningSubprocess,
|
||||
);
|
||||
applyTerminalEvent(event);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
@@ -535,6 +578,7 @@ function EventRouter() {
|
||||
queryClient,
|
||||
removeTerminalState,
|
||||
removeOrphanedTerminalStates,
|
||||
applyTerminalEvent,
|
||||
clearThreadUi,
|
||||
setProjectExpanded,
|
||||
syncProjects,
|
||||
|
||||
@@ -2,6 +2,10 @@ import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
configureClientTracing,
|
||||
__resetClientTracingForTests,
|
||||
} from "../observability/clientTracing";
|
||||
import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client";
|
||||
|
||||
type WsEventType = "open" | "message" | "close" | "error";
|
||||
@@ -66,6 +70,7 @@ class MockWebSocket {
|
||||
}
|
||||
|
||||
const originalWebSocket = globalThis.WebSocket;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
function getSocket(): MockWebSocket {
|
||||
const socket = sockets.at(-1);
|
||||
@@ -112,6 +117,7 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
__resetWsRpcAtomClientForTests();
|
||||
globalThis.WebSocket = originalWebSocket;
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -228,4 +234,46 @@ describe("WsRpcAtomClient", () => {
|
||||
release();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("attaches distributed trace ids when client OTLP tracing is enabled", async () => {
|
||||
await configureClientTracing({
|
||||
exportIntervalMs: 10,
|
||||
});
|
||||
|
||||
const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(socket.sent).toHaveLength(1);
|
||||
});
|
||||
|
||||
const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as {
|
||||
id: string;
|
||||
spanId?: string;
|
||||
tag: string;
|
||||
traceId?: string;
|
||||
};
|
||||
expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings);
|
||||
expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/);
|
||||
|
||||
socket.serverMessage(
|
||||
JSON.stringify({
|
||||
_tag: "Exit",
|
||||
requestId: requestMessage.id,
|
||||
exit: {
|
||||
_tag: "Success",
|
||||
value: DEFAULT_SERVER_SETTINGS,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,11 @@ import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
import { AtomRpc } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
__resetClientTracingForTests,
|
||||
ClientTracingLive,
|
||||
configureClientTracing,
|
||||
} from "../observability/clientTracing";
|
||||
import { createWsRpcProtocolLayer } from "./protocol";
|
||||
|
||||
export class WsRpcAtomClient extends AtomRpc.Service<WsRpcAtomClient>()("WsRpcAtomClient", {
|
||||
@@ -16,18 +21,22 @@ function getRuntime() {
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer);
|
||||
sharedRuntime = ManagedRuntime.make(Layer.mergeAll(WsRpcAtomClient.layer, ClientTracingLive));
|
||||
return sharedRuntime;
|
||||
}
|
||||
|
||||
export function runRpc<TSuccess, TError = never>(
|
||||
execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
return getRuntime().runPromise(WsRpcAtomClient.use(execute));
|
||||
return configureClientTracing().then(() => {
|
||||
const runtime = getRuntime();
|
||||
return runtime.runPromise(WsRpcAtomClient.use(execute));
|
||||
});
|
||||
}
|
||||
|
||||
export async function __resetWsRpcAtomClientForTests() {
|
||||
const runtime = sharedRuntime;
|
||||
sharedRuntime = null;
|
||||
await runtime?.dispose();
|
||||
await __resetClientTracingForTests();
|
||||
}
|
||||
@@ -1,9 +1,22 @@
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
|
||||
import { resolveServerUrl } from "../lib/utils";
|
||||
import {
|
||||
acknowledgeRpcRequest,
|
||||
clearAllTrackedRpcRequests,
|
||||
trackRpcRequestSent,
|
||||
} from "./requestLatencyState";
|
||||
import {
|
||||
getWsReconnectDelayMsForRetry,
|
||||
recordWsConnectionAttempt,
|
||||
recordWsConnectionClosed,
|
||||
recordWsConnectionErrored,
|
||||
recordWsConnectionOpened,
|
||||
WS_RECONNECT_MAX_RETRIES,
|
||||
} from "./wsConnectionState";
|
||||
|
||||
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
|
||||
|
||||
@@ -17,11 +30,75 @@ export function createWsRpcProtocolLayer(url?: string) {
|
||||
protocol: window.location.protocol === "https:" ? "wss" : "ws",
|
||||
pathname: "/ws",
|
||||
});
|
||||
const trackingWebSocketConstructorLayer = Layer.succeed(
|
||||
Socket.WebSocketConstructor,
|
||||
(socketUrl, protocols) => {
|
||||
recordWsConnectionAttempt(socketUrl);
|
||||
const socket = new globalThis.WebSocket(socketUrl, protocols);
|
||||
|
||||
socket.addEventListener(
|
||||
"open",
|
||||
() => {
|
||||
recordWsConnectionOpened();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"error",
|
||||
() => {
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
socket.addEventListener(
|
||||
"close",
|
||||
(event) => {
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionClosed({
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
});
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
return socket;
|
||||
},
|
||||
);
|
||||
const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe(
|
||||
Layer.provide(Socket.layerWebSocketConstructorGlobal),
|
||||
Layer.provide(trackingWebSocketConstructorLayer),
|
||||
);
|
||||
const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) =>
|
||||
Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)),
|
||||
);
|
||||
const protocolLayer = Layer.effect(
|
||||
RpcClient.Protocol,
|
||||
Effect.map(
|
||||
RpcClient.makeProtocolSocket({
|
||||
retryPolicy,
|
||||
retryTransientErrors: true,
|
||||
}),
|
||||
(protocol) => ({
|
||||
...protocol,
|
||||
run: (writeResponse) =>
|
||||
protocol.run((response) => {
|
||||
if (response._tag === "Chunk" || response._tag === "Exit") {
|
||||
acknowledgeRpcRequest(response.requestId);
|
||||
} else if (response._tag === "ClientProtocolError" || response._tag === "Defect") {
|
||||
clearAllTrackedRpcRequests();
|
||||
}
|
||||
return writeResponse(response);
|
||||
}),
|
||||
send: (request, transferables) => {
|
||||
if (request._tag === "Request") {
|
||||
trackRpcRequestSent(request.id, request.tag);
|
||||
}
|
||||
return protocol.send(request, transferables);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe(
|
||||
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)),
|
||||
);
|
||||
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
acknowledgeRpcRequest,
|
||||
getSlowRpcAckRequests,
|
||||
resetRequestLatencyStateForTests,
|
||||
trackRpcRequestSent,
|
||||
SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
MAX_TRACKED_RPC_ACK_REQUESTS,
|
||||
} from "./requestLatencyState";
|
||||
|
||||
describe("requestLatencyState", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
resetRequestLatencyStateForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("marks unary requests as slow when the ack threshold is exceeded", () => {
|
||||
trackRpcRequestSent("1", "server.getConfig");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS - 1);
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(getSlowRpcAckRequests()).toMatchObject([
|
||||
{
|
||||
requestId: "1",
|
||||
tag: "server.getConfig",
|
||||
thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("clears the slow request once the server acknowledges it", () => {
|
||||
trackRpcRequestSent("1", "git.status");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
expect(getSlowRpcAckRequests()).toHaveLength(1);
|
||||
|
||||
acknowledgeRpcRequest("1");
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores long-lived subscribe requests", () => {
|
||||
trackRpcRequestSent("1", "subscribeServerConfig");
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS * 2);
|
||||
|
||||
expect(getSlowRpcAckRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it("evicts the oldest pending requests once the tracker reaches capacity", () => {
|
||||
for (let index = 0; index < MAX_TRACKED_RPC_ACK_REQUESTS + 1; index += 1) {
|
||||
trackRpcRequestSent(String(index), "server.getConfig");
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
|
||||
const slowRequests = getSlowRpcAckRequests();
|
||||
expect(slowRequests).toHaveLength(MAX_TRACKED_RPC_ACK_REQUESTS);
|
||||
expect(slowRequests[0]?.requestId).toBe("1");
|
||||
expect(slowRequests.at(-1)?.requestId).toBe(String(MAX_TRACKED_RPC_ACK_REQUESTS));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atomRegistry";
|
||||
|
||||
export const SLOW_RPC_ACK_THRESHOLD_MS = 2_500;
|
||||
export const MAX_TRACKED_RPC_ACK_REQUESTS = 256;
|
||||
|
||||
export interface SlowRpcAckRequest {
|
||||
readonly requestId: string;
|
||||
readonly startedAt: string;
|
||||
readonly startedAtMs: number;
|
||||
readonly tag: string;
|
||||
readonly thresholdMs: number;
|
||||
}
|
||||
|
||||
interface PendingRpcAckRequest {
|
||||
readonly request: SlowRpcAckRequest;
|
||||
readonly timeoutId: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const pendingRpcAckRequests = new Map<string, PendingRpcAckRequest>();
|
||||
|
||||
const slowRpcAckRequestsAtom = Atom.make<ReadonlyArray<SlowRpcAckRequest>>([]).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("slow-rpc-ack-requests"),
|
||||
);
|
||||
|
||||
function setSlowRpcAckRequests(requests: ReadonlyArray<SlowRpcAckRequest>) {
|
||||
appAtomRegistry.set(slowRpcAckRequestsAtom, [...requests]);
|
||||
}
|
||||
|
||||
function getSlowRpcAckRequestsValue(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return appAtomRegistry.get(slowRpcAckRequestsAtom);
|
||||
}
|
||||
|
||||
function shouldTrackRpcAck(tag: string): boolean {
|
||||
return !tag.startsWith("subscribe");
|
||||
}
|
||||
|
||||
export function getSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return getSlowRpcAckRequestsValue();
|
||||
}
|
||||
|
||||
export function trackRpcRequestSent(requestId: string, tag: string): void {
|
||||
if (!shouldTrackRpcAck(tag)) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTrackedRpcRequest(requestId);
|
||||
evictOldestPendingRpcRequestIfNeeded();
|
||||
|
||||
const startedAtMs = Date.now();
|
||||
const request: SlowRpcAckRequest = {
|
||||
requestId,
|
||||
startedAt: new Date(startedAtMs).toISOString(),
|
||||
startedAtMs,
|
||||
tag,
|
||||
thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS,
|
||||
};
|
||||
const timeoutId = setTimeout(() => {
|
||||
pendingRpcAckRequests.delete(requestId);
|
||||
appendSlowRpcAckRequest(request);
|
||||
}, SLOW_RPC_ACK_THRESHOLD_MS);
|
||||
|
||||
pendingRpcAckRequests.set(requestId, {
|
||||
request,
|
||||
timeoutId,
|
||||
});
|
||||
}
|
||||
|
||||
export function acknowledgeRpcRequest(requestId: string): void {
|
||||
clearTrackedRpcRequest(requestId);
|
||||
const slowRequests = getSlowRpcAckRequestsValue();
|
||||
if (!slowRequests.some((request) => request.requestId === requestId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSlowRpcAckRequests(slowRequests.filter((request) => request.requestId !== requestId));
|
||||
}
|
||||
|
||||
export function clearAllTrackedRpcRequests(): void {
|
||||
for (const pending of pendingRpcAckRequests.values()) {
|
||||
clearTimeout(pending.timeoutId);
|
||||
}
|
||||
pendingRpcAckRequests.clear();
|
||||
setSlowRpcAckRequests([]);
|
||||
}
|
||||
|
||||
function clearTrackedRpcRequest(requestId: string): void {
|
||||
const pending = pendingRpcAckRequests.get(requestId);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeoutId);
|
||||
pendingRpcAckRequests.delete(requestId);
|
||||
}
|
||||
|
||||
function appendSlowRpcAckRequest(request: SlowRpcAckRequest): void {
|
||||
const requests = [...getSlowRpcAckRequestsValue(), request];
|
||||
if (requests.length <= MAX_TRACKED_RPC_ACK_REQUESTS) {
|
||||
setSlowRpcAckRequests(requests);
|
||||
return;
|
||||
}
|
||||
|
||||
setSlowRpcAckRequests(requests.slice(-MAX_TRACKED_RPC_ACK_REQUESTS));
|
||||
}
|
||||
|
||||
function evictOldestPendingRpcRequestIfNeeded(): void {
|
||||
while (pendingRpcAckRequests.size >= MAX_TRACKED_RPC_ACK_REQUESTS) {
|
||||
const oldestRequestId = pendingRpcAckRequests.keys().next().value;
|
||||
if (oldestRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTrackedRpcRequest(oldestRequestId);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetRequestLatencyStateForTests(): void {
|
||||
clearAllTrackedRpcRequests();
|
||||
}
|
||||
|
||||
export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
|
||||
return useAtomValue(slowRpcAckRequestsAtom);
|
||||
}
|
||||
@@ -57,6 +57,12 @@ const baseServerConfig: ServerConfig = {
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
availableEditors: ["cursor"],
|
||||
observability: {
|
||||
logsDirectoryPath: "/tmp/workspace/.config/logs",
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: false,
|
||||
otlpMetricsEnabled: false,
|
||||
},
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
};
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray<Edit
|
||||
const selectKeybindings = (config: ServerConfig | null) => config?.keybindings ?? EMPTY_KEYBINDINGS;
|
||||
const selectKeybindingsConfigPath = (config: ServerConfig | null) =>
|
||||
config?.keybindingsConfigPath ?? null;
|
||||
const selectObservability = (config: ServerConfig | null) => config?.observability ?? null;
|
||||
const selectProviders = (config: ServerConfig | null) =>
|
||||
config?.providers ?? EMPTY_SERVER_PROVIDERS;
|
||||
const selectSettings = (config: ServerConfig | null): ServerSettings =>
|
||||
@@ -281,6 +282,10 @@ export function useServerKeybindingsConfigPath(): string | null {
|
||||
return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath);
|
||||
}
|
||||
|
||||
export function useServerObservability(): ServerConfig["observability"] | null {
|
||||
return useAtomValue(serverConfigAtom, selectObservability);
|
||||
}
|
||||
|
||||
export function useServerWelcomeSubscription(
|
||||
listener: (payload: ServerLifecycleWelcomePayload) => void,
|
||||
): void {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isTransportConnectionErrorMessage, sanitizeThreadErrorMessage } from "./transportError";
|
||||
|
||||
describe("transportError", () => {
|
||||
it("detects websocket transport failures", () => {
|
||||
expect(isTransportConnectionErrorMessage("SocketCloseError: 1006")).toBe(true);
|
||||
expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isTransportConnectionErrorMessage("SocketOpenError: Timeout")).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves non-transport thread errors", () => {
|
||||
expect(sanitizeThreadErrorMessage("Turn failed")).toBe("Turn failed");
|
||||
expect(sanitizeThreadErrorMessage("Select a base branch before sending.")).toBe(
|
||||
"Select a base branch before sending.",
|
||||
);
|
||||
});
|
||||
|
||||
it("drops transport failures from thread surfaces", () => {
|
||||
expect(sanitizeThreadErrorMessage("SocketCloseError: 1006")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
const TRANSPORT_ERROR_PATTERNS = [
|
||||
/\bSocketCloseError\b/i,
|
||||
/\bSocketOpenError\b/i,
|
||||
/Unable to connect to the T3 server WebSocket\./i,
|
||||
/\bping timeout\b/i,
|
||||
] as const;
|
||||
|
||||
export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean {
|
||||
if (typeof message !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedMessage = message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage));
|
||||
}
|
||||
|
||||
export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null {
|
||||
return isTransportConnectionErrorMessage(message) ? null : (message ?? null);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
exhaustWsReconnectIfStillWaiting,
|
||||
getWsConnectionStatus,
|
||||
getWsReconnectDelayMsForRetry,
|
||||
getWsConnectionUiState,
|
||||
recordWsConnectionAttempt,
|
||||
recordWsConnectionClosed,
|
||||
recordWsConnectionErrored,
|
||||
recordWsConnectionOpened,
|
||||
resetWsConnectionStateForTests,
|
||||
setBrowserOnlineStatus,
|
||||
WS_RECONNECT_MAX_ATTEMPTS,
|
||||
} from "./wsConnectionState";
|
||||
|
||||
describe("wsConnectionState", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-04-03T20:30:00.000Z"));
|
||||
resetWsConnectionStateForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("treats a disconnected browser as offline once the websocket drops", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionOpened();
|
||||
recordWsConnectionClosed({ code: 1006, reason: "offline" });
|
||||
setBrowserOnlineStatus(false);
|
||||
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("offline");
|
||||
});
|
||||
|
||||
it("stays in the initial connecting state until the first disconnect", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
attemptCount: 1,
|
||||
hasConnected: false,
|
||||
phase: "connecting",
|
||||
});
|
||||
expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("connecting");
|
||||
});
|
||||
|
||||
it("schedules the next retry after a failed websocket attempt", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
|
||||
const firstRetryDelayMs = getWsReconnectDelayMsForRetry(0);
|
||||
if (firstRetryDelayMs === null) {
|
||||
throw new Error("Expected an initial retry delay.");
|
||||
}
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: new Date(Date.now() + firstRetryDelayMs).toISOString(),
|
||||
reconnectAttemptCount: 1,
|
||||
reconnectPhase: "waiting",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks the reconnect cycle as exhausted after the final attempt fails", () => {
|
||||
for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS; attempt += 1) {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
}
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "exhausted",
|
||||
});
|
||||
});
|
||||
|
||||
it("can exhaust a stalled final retry window when no new attempt starts", () => {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionOpened();
|
||||
|
||||
for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS - 1; attempt += 1) {
|
||||
recordWsConnectionAttempt("ws://localhost:3020/ws");
|
||||
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
|
||||
}
|
||||
|
||||
const finalRetryDelayMs = getWsReconnectDelayMsForRetry(WS_RECONNECT_MAX_ATTEMPTS - 2);
|
||||
if (finalRetryDelayMs === null) {
|
||||
throw new Error("Expected a final retry delay.");
|
||||
}
|
||||
|
||||
const statusBeforeExhaust = getWsConnectionStatus();
|
||||
expect(statusBeforeExhaust).toMatchObject({
|
||||
nextRetryAt: new Date(Date.now() + finalRetryDelayMs).toISOString(),
|
||||
reconnectAttemptCount: 7,
|
||||
reconnectPhase: "waiting",
|
||||
});
|
||||
|
||||
const nextRetryAt = statusBeforeExhaust.nextRetryAt;
|
||||
if (!nextRetryAt) {
|
||||
throw new Error("Expected a scheduled retry.");
|
||||
}
|
||||
|
||||
vi.setSystemTime(new Date(Date.now() + finalRetryDelayMs + 1_000));
|
||||
exhaustWsReconnectIfStillWaiting(nextRetryAt);
|
||||
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "exhausted",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "./atomRegistry";
|
||||
|
||||
export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting";
|
||||
export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting";
|
||||
|
||||
export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000;
|
||||
export const WS_RECONNECT_BACKOFF_FACTOR = 2;
|
||||
export const WS_RECONNECT_MAX_DELAY_MS = 64_000;
|
||||
export const WS_RECONNECT_MAX_RETRIES = 7;
|
||||
export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1;
|
||||
|
||||
export interface WsConnectionStatus {
|
||||
readonly attemptCount: number;
|
||||
readonly closeCode: number | null;
|
||||
readonly closeReason: string | null;
|
||||
readonly connectedAt: string | null;
|
||||
readonly disconnectedAt: string | null;
|
||||
readonly hasConnected: boolean;
|
||||
readonly lastError: string | null;
|
||||
readonly lastErrorAt: string | null;
|
||||
readonly nextRetryAt: string | null;
|
||||
readonly online: boolean;
|
||||
readonly phase: "idle" | "connecting" | "connected" | "disconnected";
|
||||
readonly reconnectAttemptCount: number;
|
||||
readonly reconnectMaxAttempts: number;
|
||||
readonly reconnectPhase: WsReconnectPhase;
|
||||
readonly socketUrl: string | null;
|
||||
}
|
||||
|
||||
const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
|
||||
attemptCount: 0,
|
||||
closeCode: null,
|
||||
closeReason: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
hasConnected: false,
|
||||
lastError: null,
|
||||
lastErrorAt: null,
|
||||
nextRetryAt: null,
|
||||
online: typeof navigator === "undefined" ? true : navigator.onLine !== false,
|
||||
phase: "idle",
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
|
||||
reconnectPhase: "idle",
|
||||
socketUrl: null,
|
||||
});
|
||||
|
||||
export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("ws-connection-status"),
|
||||
);
|
||||
|
||||
function isoNow() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function updateWsConnectionStatus(
|
||||
updater: (current: WsConnectionStatus) => WsConnectionStatus,
|
||||
): WsConnectionStatus {
|
||||
const nextStatus = updater(getWsConnectionStatus());
|
||||
appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
|
||||
return nextStatus;
|
||||
}
|
||||
|
||||
export function getWsConnectionStatus(): WsConnectionStatus {
|
||||
return appAtomRegistry.get(wsConnectionStatusAtom);
|
||||
}
|
||||
|
||||
export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState {
|
||||
if (status.phase === "connected") {
|
||||
return "connected";
|
||||
}
|
||||
|
||||
if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) {
|
||||
return "offline";
|
||||
}
|
||||
|
||||
if (!status.hasConnected) {
|
||||
return status.phase === "disconnected" ? "error" : "connecting";
|
||||
}
|
||||
|
||||
return "reconnecting";
|
||||
}
|
||||
|
||||
export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
attemptCount: current.attemptCount + 1,
|
||||
nextRetryAt: null,
|
||||
phase: "connecting",
|
||||
reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
|
||||
reconnectPhase: "attempting",
|
||||
socketUrl,
|
||||
}));
|
||||
}
|
||||
|
||||
export function recordWsConnectionOpened(): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
closeCode: null,
|
||||
closeReason: null,
|
||||
connectedAt: isoNow(),
|
||||
disconnectedAt: null,
|
||||
hasConnected: true,
|
||||
nextRetryAt: null,
|
||||
phase: "connected",
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectPhase: "idle",
|
||||
}));
|
||||
}
|
||||
|
||||
export function recordWsConnectionErrored(message?: string | null): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) =>
|
||||
applyDisconnectState(current, {
|
||||
lastError: message?.trim() ? message : current.lastError,
|
||||
lastErrorAt: isoNow(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function recordWsConnectionClosed(details?: {
|
||||
readonly code?: number;
|
||||
readonly reason?: string;
|
||||
}): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) =>
|
||||
applyDisconnectState(current, {
|
||||
closeCode: details?.code ?? current.closeCode,
|
||||
closeReason: details?.reason?.trim() ? details.reason : current.closeReason,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
online,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resetWsReconnectBackoff(): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => ({
|
||||
...current,
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: 0,
|
||||
reconnectPhase: "idle",
|
||||
}));
|
||||
}
|
||||
|
||||
export function exhaustWsReconnectIfStillWaiting(expectedNextRetryAt: string): WsConnectionStatus {
|
||||
return updateWsConnectionStatus((current) => {
|
||||
if (
|
||||
current.reconnectPhase !== "waiting" ||
|
||||
current.nextRetryAt !== expectedNextRetryAt ||
|
||||
!current.online ||
|
||||
!current.hasConnected
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
nextRetryAt: null,
|
||||
reconnectAttemptCount: current.reconnectMaxAttempts,
|
||||
reconnectPhase: "exhausted",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function resetWsConnectionStateForTests(): void {
|
||||
appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
|
||||
}
|
||||
|
||||
export function useWsConnectionStatus(): WsConnectionStatus {
|
||||
return useAtomValue(wsConnectionStatusAtom);
|
||||
}
|
||||
|
||||
export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
|
||||
if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.min(
|
||||
Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
|
||||
WS_RECONNECT_MAX_DELAY_MS,
|
||||
);
|
||||
}
|
||||
|
||||
function applyDisconnectState(
|
||||
current: WsConnectionStatus,
|
||||
updates: Partial<
|
||||
Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
|
||||
>,
|
||||
): WsConnectionStatus {
|
||||
const disconnectedAt = current.disconnectedAt ?? isoNow();
|
||||
const nextRetryDelayMs =
|
||||
current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
|
||||
? null
|
||||
: getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
|
||||
|
||||
return {
|
||||
...current,
|
||||
...updates,
|
||||
disconnectedAt,
|
||||
nextRetryAt:
|
||||
nextRetryDelayMs === null
|
||||
? current.nextRetryAt
|
||||
: new Date(Date.now() + nextRetryDelayMs).toISOString(),
|
||||
phase: "disconnected",
|
||||
reconnectPhase:
|
||||
current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
|
||||
? current.reconnectPhase
|
||||
: nextRetryDelayMs === null
|
||||
? "exhausted"
|
||||
: "waiting",
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
findSidebarProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isSessionActivelyRunningTurn,
|
||||
isLatestTurnSettled,
|
||||
} from "./session-logic";
|
||||
|
||||
@@ -1073,30 +1072,15 @@ describe("isLatestTurnSettled", () => {
|
||||
} as const;
|
||||
|
||||
it("returns false while the same turn is still active in a running session", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(
|
||||
{
|
||||
...latestTurn,
|
||||
completedAt: null,
|
||||
},
|
||||
{
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
},
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when the turn completed but the session status stayed stale-running", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(latestTurn, {
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
}),
|
||||
).toBe(true);
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false while a different turn is still running", () => {
|
||||
it("returns false while any turn is running to avoid stale latest-turn banners", () => {
|
||||
expect(
|
||||
isLatestTurnSettled(latestTurn, {
|
||||
orchestrationStatus: "running",
|
||||
@@ -1128,56 +1112,6 @@ describe("isLatestTurnSettled", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSessionActivelyRunningTurn", () => {
|
||||
const completedTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
startedAt: "2026-02-27T21:10:00.000Z",
|
||||
completedAt: "2026-02-27T21:10:06.000Z",
|
||||
} as const;
|
||||
|
||||
it("returns true when the current turn has not completed yet", () => {
|
||||
expect(
|
||||
isSessionActivelyRunningTurn(
|
||||
{
|
||||
...completedTurn,
|
||||
completedAt: null,
|
||||
},
|
||||
{
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
},
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the same turn already completed and only the session is stale", () => {
|
||||
expect(
|
||||
isSessionActivelyRunningTurn(completedTurn, {
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when a different turn is still active", () => {
|
||||
expect(
|
||||
isSessionActivelyRunningTurn(completedTurn, {
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-2"),
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the session is not running", () => {
|
||||
expect(
|
||||
isSessionActivelyRunningTurn(completedTurn, {
|
||||
orchestrationStatus: "ready",
|
||||
activeTurnId: undefined,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveActiveWorkStartedAt", () => {
|
||||
const latestTurn = {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
@@ -1186,22 +1120,6 @@ describe("deriveActiveWorkStartedAt", () => {
|
||||
} as const;
|
||||
|
||||
it("prefers the in-flight turn start when the latest turn is not settled", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
{
|
||||
...latestTurn,
|
||||
completedAt: null,
|
||||
},
|
||||
{
|
||||
orchestrationStatus: "running",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:10:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to sendStartedAt when only the session status is stale-running", () => {
|
||||
expect(
|
||||
deriveActiveWorkStartedAt(
|
||||
latestTurn,
|
||||
@@ -1211,7 +1129,7 @@ describe("deriveActiveWorkStartedAt", () => {
|
||||
},
|
||||
"2026-02-27T21:11:00.000Z",
|
||||
),
|
||||
).toBe("2026-02-27T21:11:00.000Z");
|
||||
).toBe("2026-02-27T21:10:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to sendStartedAt once the latest turn is settled", () => {
|
||||
|
||||
@@ -128,30 +128,15 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str
|
||||
type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
|
||||
type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
|
||||
|
||||
export function isSessionActivelyRunningTurn(
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
): boolean {
|
||||
if (!session || session.orchestrationStatus !== "running") return false;
|
||||
if (!latestTurn) return true;
|
||||
|
||||
const activeTurnId = session.activeTurnId;
|
||||
if (activeTurnId === undefined) {
|
||||
return latestTurn.completedAt === null;
|
||||
}
|
||||
if (latestTurn.turnId !== activeTurnId) {
|
||||
return true;
|
||||
}
|
||||
return latestTurn.completedAt === null;
|
||||
}
|
||||
|
||||
export function isLatestTurnSettled(
|
||||
latestTurn: LatestTurnTiming | null,
|
||||
session: SessionActivityState | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
return !isSessionActivelyRunningTurn(latestTurn, session);
|
||||
if (!session) return true;
|
||||
if (session.orchestrationStatus === "running") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deriveActiveWorkStartedAt(
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
type ThreadTurnState,
|
||||
type TurnDiffSummary,
|
||||
} from "./types";
|
||||
import { sanitizeThreadErrorMessage } from "./rpc/transportError";
|
||||
|
||||
export interface AppState {
|
||||
projectIds: ProjectId[];
|
||||
@@ -194,7 +195,7 @@ function mapThread(thread: OrchestrationThread): Thread {
|
||||
session: thread.session ? mapSession(thread.session) : null,
|
||||
messages: thread.messages.map(mapMessage),
|
||||
proposedPlans: thread.proposedPlans.map(mapProposedPlan),
|
||||
error: thread.session?.lastError ?? null,
|
||||
error: sanitizeThreadErrorMessage(thread.session?.lastError),
|
||||
createdAt: thread.createdAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
@@ -1293,7 +1294,7 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve
|
||||
return updateThreadState(state, event.payload.threadId, (thread) => ({
|
||||
...thread,
|
||||
session: mapSession(event.payload.session),
|
||||
error: event.payload.session.lastError ?? null,
|
||||
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
|
||||
latestTurn:
|
||||
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
|
||||
? buildLatestTurn({
|
||||
|
||||
@@ -7,6 +7,7 @@ const snapshot: TerminalSessionSnapshot = {
|
||||
threadId: "thread-1",
|
||||
terminalId: "default",
|
||||
cwd: "/tmp",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeTerminalEvent(
|
||||
threadId: THREAD_ID,
|
||||
terminalId: "default",
|
||||
cwd: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
status: "running",
|
||||
pid: 123,
|
||||
history: "",
|
||||
@@ -56,6 +57,7 @@ describe("terminalStateStore actions", () => {
|
||||
useTerminalStateStore.persist.clearStorage();
|
||||
useTerminalStateStore.setState({
|
||||
terminalStateByThreadId: {},
|
||||
terminalLaunchContextByThreadId: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
});
|
||||
@@ -132,6 +134,23 @@ describe("terminalStateStore actions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("ensures unknown server terminals are registered, opened, and activated", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.ensureTerminal(THREAD_ID, "setup-setup", { open: true, active: true });
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.terminalIds).toEqual(["default", "setup-setup"]);
|
||||
expect(terminalState.activeTerminalId).toBe("setup-setup");
|
||||
expect(terminalState.terminalGroups).toEqual([
|
||||
{ id: "group-default", terminalIds: ["default"] },
|
||||
{ id: "group-setup-setup", terminalIds: ["setup-setup"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("allows unlimited groups while keeping each group capped at four terminals", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.splitTerminal(THREAD_ID, "terminal-2");
|
||||
@@ -219,6 +238,84 @@ describe("terminalStateStore actions", () => {
|
||||
expect(entries.map((entry) => entry.event.type)).toEqual(["output", "activity"]);
|
||||
});
|
||||
|
||||
it("applies started terminal events to terminal state, launch context, and event buffer", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.applyTerminalEvent(
|
||||
makeTerminalEvent("started", {
|
||||
terminalId: "setup-bootstrap",
|
||||
snapshot: {
|
||||
threadId: THREAD_ID,
|
||||
terminalId: "setup-bootstrap",
|
||||
cwd: "/tmp/worktree",
|
||||
worktreePath: "/tmp/worktree",
|
||||
status: "running",
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-04-02T20:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_ID,
|
||||
"setup-bootstrap",
|
||||
);
|
||||
|
||||
expect(terminalState.terminalOpen).toBe(true);
|
||||
expect(terminalState.activeTerminalId).toBe("setup-bootstrap");
|
||||
expect(terminalState.terminalIds).toEqual(["default", "setup-bootstrap"]);
|
||||
expect(useTerminalStateStore.getState().terminalLaunchContextByThreadId[THREAD_ID]).toEqual({
|
||||
cwd: "/tmp/worktree",
|
||||
worktreePath: "/tmp/worktree",
|
||||
});
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.event.type).toBe("started");
|
||||
});
|
||||
|
||||
it("applies activity and exited terminal events to subprocess state while buffering events", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.ensureTerminal(THREAD_ID, "terminal-2", { open: true, active: true });
|
||||
|
||||
store.applyTerminalEvent(
|
||||
makeTerminalEvent("activity", {
|
||||
terminalId: "terminal-2",
|
||||
hasRunningSubprocess: true,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)
|
||||
.runningTerminalIds,
|
||||
).toEqual(["terminal-2"]);
|
||||
|
||||
store.applyTerminalEvent(
|
||||
makeTerminalEvent("exited", {
|
||||
terminalId: "terminal-2",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalState = selectThreadTerminalState(
|
||||
useTerminalStateStore.getState().terminalStateByThreadId,
|
||||
THREAD_ID,
|
||||
);
|
||||
const entries = selectTerminalEventEntries(
|
||||
useTerminalStateStore.getState().terminalEventEntriesByKey,
|
||||
THREAD_ID,
|
||||
"terminal-2",
|
||||
);
|
||||
|
||||
expect(terminalState.runningTerminalIds).toEqual([]);
|
||||
expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]);
|
||||
});
|
||||
|
||||
it("clears buffered terminal events when a thread terminal state is removed", () => {
|
||||
const store = useTerminalStateStore.getState();
|
||||
store.recordTerminalEvent(makeTerminalEvent("output"));
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
* API constrained to store actions/selectors.
|
||||
*/
|
||||
|
||||
import type { TerminalEvent, ThreadId } from "@t3tools/contracts";
|
||||
import { ThreadId, type TerminalEvent } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { resolveStorage } from "./lib/storage";
|
||||
import { terminalRunningSubprocessFromEvent } from "./terminalActivity";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -26,6 +27,11 @@ interface ThreadTerminalState {
|
||||
activeTerminalGroupId: string;
|
||||
}
|
||||
|
||||
export interface ThreadTerminalLaunchContext {
|
||||
cwd: string;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
|
||||
export interface TerminalEventEntry {
|
||||
id: number;
|
||||
event: TerminalEvent;
|
||||
@@ -245,6 +251,40 @@ function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[
|
||||
}));
|
||||
}
|
||||
|
||||
function appendTerminalEventEntry(
|
||||
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>,
|
||||
nextTerminalEventId: number,
|
||||
event: TerminalEvent,
|
||||
) {
|
||||
const key = terminalEventBufferKey(ThreadId.makeUnsafe(event.threadId), event.terminalId);
|
||||
const currentEntries = terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES;
|
||||
const nextEntry: TerminalEventEntry = {
|
||||
id: nextTerminalEventId,
|
||||
event,
|
||||
};
|
||||
const nextEntries =
|
||||
currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER
|
||||
? [...currentEntries.slice(1), nextEntry]
|
||||
: [...currentEntries, nextEntry];
|
||||
|
||||
return {
|
||||
terminalEventEntriesByKey: {
|
||||
...terminalEventEntriesByKey,
|
||||
[key]: nextEntries,
|
||||
},
|
||||
nextTerminalEventId: nextTerminalEventId + 1,
|
||||
};
|
||||
}
|
||||
|
||||
function launchContextFromStartEvent(
|
||||
event: Extract<TerminalEvent, { type: "started" | "restarted" }>,
|
||||
): ThreadTerminalLaunchContext {
|
||||
return {
|
||||
cwd: event.snapshot.cwd,
|
||||
worktreePath: event.snapshot.worktreePath,
|
||||
};
|
||||
}
|
||||
|
||||
function upsertTerminalIntoGroups(
|
||||
state: ThreadTerminalState,
|
||||
terminalId: string,
|
||||
@@ -498,20 +538,29 @@ export function selectTerminalEventEntries(
|
||||
|
||||
interface TerminalStateStoreState {
|
||||
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
|
||||
terminalLaunchContextByThreadId: Record<ThreadId, ThreadTerminalLaunchContext>;
|
||||
terminalEventEntriesByKey: Record<string, ReadonlyArray<TerminalEventEntry>>;
|
||||
nextTerminalEventId: number;
|
||||
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
|
||||
setTerminalHeight: (threadId: ThreadId, height: number) => void;
|
||||
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
newTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
ensureTerminal: (
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
options?: { open?: boolean; active?: boolean },
|
||||
) => void;
|
||||
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
|
||||
setTerminalLaunchContext: (threadId: ThreadId, context: ThreadTerminalLaunchContext) => void;
|
||||
clearTerminalLaunchContext: (threadId: ThreadId) => void;
|
||||
setTerminalActivity: (
|
||||
threadId: ThreadId,
|
||||
terminalId: string,
|
||||
hasRunningSubprocess: boolean,
|
||||
) => void;
|
||||
recordTerminalEvent: (event: TerminalEvent) => void;
|
||||
applyTerminalEvent: (event: TerminalEvent) => void;
|
||||
clearTerminalState: (threadId: ThreadId) => void;
|
||||
removeTerminalState: (threadId: ThreadId) => void;
|
||||
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
|
||||
@@ -541,6 +590,7 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
|
||||
return {
|
||||
terminalStateByThreadId: {},
|
||||
terminalLaunchContextByThreadId: {},
|
||||
terminalEventEntriesByKey: {},
|
||||
nextTerminalEventId: 1,
|
||||
setTerminalOpen: (threadId, open) =>
|
||||
@@ -551,33 +601,104 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
|
||||
newTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
|
||||
ensureTerminal: (threadId, terminalId, options) =>
|
||||
updateTerminal(threadId, (state) => {
|
||||
let nextState = state;
|
||||
if (!state.terminalIds.includes(terminalId)) {
|
||||
nextState = newThreadTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.active === false) {
|
||||
nextState = {
|
||||
...nextState,
|
||||
activeTerminalId: state.activeTerminalId,
|
||||
activeTerminalGroupId: state.activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
if (options?.active ?? true) {
|
||||
nextState = setThreadActiveTerminal(nextState, terminalId);
|
||||
}
|
||||
if (options?.open) {
|
||||
nextState = setThreadTerminalOpen(nextState, true);
|
||||
}
|
||||
return normalizeThreadTerminalState(nextState);
|
||||
}),
|
||||
setActiveTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
|
||||
closeTerminal: (threadId, terminalId) =>
|
||||
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
|
||||
setTerminalLaunchContext: (threadId, context) =>
|
||||
set((state) => ({
|
||||
terminalLaunchContextByThreadId: {
|
||||
...state.terminalLaunchContextByThreadId,
|
||||
[threadId]: context,
|
||||
},
|
||||
})),
|
||||
clearTerminalLaunchContext: (threadId) =>
|
||||
set((state) => {
|
||||
if (!state.terminalLaunchContextByThreadId[threadId]) {
|
||||
return state;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId;
|
||||
return { terminalLaunchContextByThreadId: rest };
|
||||
}),
|
||||
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
|
||||
updateTerminal(threadId, (state) =>
|
||||
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
|
||||
),
|
||||
recordTerminalEvent: (event) =>
|
||||
set((state) => {
|
||||
const key = terminalEventBufferKey(event.threadId as ThreadId, event.terminalId);
|
||||
const currentEntries =
|
||||
state.terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES;
|
||||
const nextEntry: TerminalEventEntry = {
|
||||
id: state.nextTerminalEventId,
|
||||
set((state) =>
|
||||
appendTerminalEventEntry(
|
||||
state.terminalEventEntriesByKey,
|
||||
state.nextTerminalEventId,
|
||||
event,
|
||||
};
|
||||
const nextEntries =
|
||||
currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER
|
||||
? [...currentEntries.slice(1), nextEntry]
|
||||
: [...currentEntries, nextEntry];
|
||||
),
|
||||
),
|
||||
applyTerminalEvent: (event) =>
|
||||
set((state) => {
|
||||
const threadId = ThreadId.makeUnsafe(event.threadId);
|
||||
let nextTerminalStateByThreadId = state.terminalStateByThreadId;
|
||||
let nextTerminalLaunchContextByThreadId = state.terminalLaunchContextByThreadId;
|
||||
|
||||
if (event.type === "started" || event.type === "restarted") {
|
||||
nextTerminalStateByThreadId = updateTerminalStateByThreadId(
|
||||
nextTerminalStateByThreadId,
|
||||
threadId,
|
||||
(current) => {
|
||||
let nextState = current;
|
||||
if (!current.terminalIds.includes(event.terminalId)) {
|
||||
nextState = newThreadTerminal(nextState, event.terminalId);
|
||||
}
|
||||
nextState = setThreadActiveTerminal(nextState, event.terminalId);
|
||||
nextState = setThreadTerminalOpen(nextState, true);
|
||||
return normalizeThreadTerminalState(nextState);
|
||||
},
|
||||
);
|
||||
nextTerminalLaunchContextByThreadId = {
|
||||
...nextTerminalLaunchContextByThreadId,
|
||||
[threadId]: launchContextFromStartEvent(event),
|
||||
};
|
||||
}
|
||||
|
||||
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
|
||||
if (hasRunningSubprocess !== null) {
|
||||
nextTerminalStateByThreadId = updateTerminalStateByThreadId(
|
||||
nextTerminalStateByThreadId,
|
||||
threadId,
|
||||
(current) =>
|
||||
setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess),
|
||||
);
|
||||
}
|
||||
|
||||
const nextEventState = appendTerminalEventEntry(
|
||||
state.terminalEventEntriesByKey,
|
||||
state.nextTerminalEventId,
|
||||
event,
|
||||
);
|
||||
|
||||
return {
|
||||
terminalEventEntriesByKey: {
|
||||
...state.terminalEventEntriesByKey,
|
||||
[key]: nextEntries,
|
||||
},
|
||||
nextTerminalEventId: state.nextTerminalEventId + 1,
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
terminalLaunchContextByThreadId: nextTerminalLaunchContextByThreadId,
|
||||
...nextEventState,
|
||||
};
|
||||
}),
|
||||
clearTerminalState: (threadId) =>
|
||||
@@ -587,6 +708,9 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
threadId,
|
||||
() => createDefaultThreadTerminalState(),
|
||||
);
|
||||
const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined;
|
||||
const { [threadId]: _removed, ...remainingLaunchContexts } =
|
||||
state.terminalLaunchContextByThreadId;
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
@@ -597,18 +721,21 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
}
|
||||
if (
|
||||
nextTerminalStateByThreadId === state.terminalStateByThreadId &&
|
||||
!hadLaunchContext &&
|
||||
!removedEventEntries
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
terminalLaunchContextByThreadId: remainingLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
removeTerminalState: (threadId) =>
|
||||
set((state) => {
|
||||
const hasThreadState = state.terminalStateByThreadId[threadId] !== undefined;
|
||||
const hadTerminalState = state.terminalStateByThreadId[threadId] !== undefined;
|
||||
const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined;
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
@@ -617,13 +744,16 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
removedEventEntries = true;
|
||||
}
|
||||
}
|
||||
if (!hasThreadState && !removedEventEntries) {
|
||||
if (!hadTerminalState && !hadLaunchContext && !removedEventEntries) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.terminalStateByThreadId };
|
||||
delete next[threadId];
|
||||
const nextTerminalStateByThreadId = { ...state.terminalStateByThreadId };
|
||||
delete nextTerminalStateByThreadId[threadId];
|
||||
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId };
|
||||
delete nextLaunchContexts[threadId];
|
||||
return {
|
||||
terminalStateByThreadId: next,
|
||||
terminalStateByThreadId: nextTerminalStateByThreadId,
|
||||
terminalLaunchContextByThreadId: nextLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
@@ -632,6 +762,9 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
|
||||
(id) => !activeThreadIds.has(id as ThreadId),
|
||||
);
|
||||
const orphanedLaunchContextIds = Object.keys(
|
||||
state.terminalLaunchContextByThreadId,
|
||||
).filter((id) => !activeThreadIds.has(id as ThreadId));
|
||||
const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey };
|
||||
let removedEventEntries = false;
|
||||
for (const key of Object.keys(nextTerminalEventEntriesByKey)) {
|
||||
@@ -641,13 +774,24 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
|
||||
removedEventEntries = true;
|
||||
}
|
||||
}
|
||||
if (orphanedIds.length === 0 && !removedEventEntries) return state;
|
||||
if (
|
||||
orphanedIds.length === 0 &&
|
||||
orphanedLaunchContextIds.length === 0 &&
|
||||
!removedEventEntries
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.terminalStateByThreadId };
|
||||
for (const id of orphanedIds) {
|
||||
delete next[id as ThreadId];
|
||||
}
|
||||
const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId };
|
||||
for (const id of orphanedLaunchContextIds) {
|
||||
delete nextLaunchContexts[id as ThreadId];
|
||||
}
|
||||
return {
|
||||
terminalStateByThreadId: next,
|
||||
terminalLaunchContextByThreadId: nextLaunchContexts,
|
||||
terminalEventEntriesByKey: nextTerminalEventEntriesByKey,
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -159,6 +159,12 @@ const baseServerConfig: ServerConfig = {
|
||||
issues: [],
|
||||
providers: defaultProviders,
|
||||
availableEditors: ["cursor"],
|
||||
observability: {
|
||||
logsDirectoryPath: "/tmp/workspace/.config/logs",
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: false,
|
||||
otlpMetricsEnabled: false,
|
||||
},
|
||||
settings: DEFAULT_SERVER_SETTINGS,
|
||||
};
|
||||
|
||||
@@ -237,6 +243,20 @@ describe("wsNativeApi", () => {
|
||||
expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
|
||||
});
|
||||
|
||||
it("forwards orchestration stream subscription options to the RPC client", async () => {
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
const onDomainEvent = vi.fn();
|
||||
const onResubscribe = vi.fn();
|
||||
|
||||
api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe });
|
||||
|
||||
expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, {
|
||||
onResubscribe,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends orchestration dispatch commands as the direct RPC payload", async () => {
|
||||
rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { type ContextMenuItem, type NativeApi } from "@t3tools/contracts";
|
||||
|
||||
import { showContextMenuFallback } from "./contextMenuFallback";
|
||||
import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
|
||||
import { resetServerStateForTests } from "./rpc/serverState";
|
||||
import { resetWsConnectionStateForTests } from "./rpc/wsConnectionState";
|
||||
import { __resetWsRpcClientForTests, getWsRpcClient } from "./wsRpcClient";
|
||||
|
||||
let instance: { api: NativeApi } | null = null;
|
||||
@@ -9,7 +11,9 @@ let instance: { api: NativeApi } | null = null;
|
||||
export function __resetWsNativeApiForTests() {
|
||||
instance = null;
|
||||
__resetWsRpcClientForTests();
|
||||
resetRequestLatencyStateForTests();
|
||||
resetServerStateForTests();
|
||||
resetWsConnectionStateForTests();
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
@@ -98,7 +102,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
rpcClient.orchestration
|
||||
.replayEvents({ fromSequenceExclusive })
|
||||
.then((events) => [...events]),
|
||||
onDomainEvent: (callback) => rpcClient.orchestration.onDomainEvent(callback),
|
||||
onDomainEvent: (callback, options) =>
|
||||
rpcClient.orchestration.onDomainEvent(callback, options),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user