Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5281f994e | ||
|
|
5c8504d602 | ||
|
|
d3d096c6f7 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b | ||
|
|
a3dadf311e | ||
|
|
e3004ae806 | ||
|
|
9385314d26 | ||
|
|
a3f292770e | ||
|
|
2028d57e88 | ||
|
|
3405a64dd8 | ||
|
|
1cba2f64d3 |
No files matched your search
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -49,6 +49,14 @@ Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.17",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -36,6 +36,57 @@ describe("resolveDesktopBackendPort", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
@@ -46,7 +97,9 @@ describe("resolveDesktopBackendPort", () => {
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -21,10 +22,37 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
@@ -39,15 +67,17 @@ export async function resolveDesktopBackendPort({
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnHost(port, host)) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,6 +20,11 @@ describe("waitForHttpReady", () => {
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
@@ -80,4 +85,30 @@ describe("waitForHttpReady", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,11 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
@@ -57,6 +59,8 @@ export async function waitForHttpReady(
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
@@ -74,11 +78,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
if (isReady(response)) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -58,7 +58,7 @@ const clientSettings: ClientSettings = {
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.makeUnsafe("environment-1"),
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
|
||||
+198
-35
@@ -7,6 +7,7 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
@@ -54,6 +55,7 @@ import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -100,7 +102,7 @@ const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -117,6 +119,16 @@ const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -133,6 +145,8 @@ let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
|
||||
let backendListeningDetector: ServerListeningDetector | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -351,13 +365,17 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -372,6 +390,88 @@ function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInitialBackendWindowOpen(): void {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
|
||||
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
|
||||
})
|
||||
.finally(() => {
|
||||
if (backendInitialWindowOpenInFlight === nextOpen) {
|
||||
backendInitialWindowOpenInFlight = null;
|
||||
}
|
||||
});
|
||||
|
||||
backendInitialWindowOpenInFlight = nextOpen;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -449,14 +549,16 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
|
||||
stream?.on("data", (chunk: unknown) => {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink?.write(buffer);
|
||||
backendListeningDetector?.push(buffer);
|
||||
});
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -1211,7 +1313,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1248,6 +1350,8 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1266,6 +1370,10 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(error);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1278,6 +1386,14 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(
|
||||
new Error(
|
||||
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
|
||||
),
|
||||
);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1289,10 +1405,13 @@ function startBackend(): void {
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
backendListeningDetector = null;
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1648,19 +1767,58 @@ function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: isDevelopment,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
@@ -1695,6 +1853,14 @@ function createWindow(): BrowserWindow {
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -1721,20 +1887,23 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
void window.loadURL(backendHttpUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -1746,14 +1915,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -1773,6 +1934,7 @@ async function bootstrap(): Promise<void> {
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
@@ -1826,10 +1988,7 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -1863,7 +2022,11 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,12 @@ describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -77,11 +87,67 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
|
||||
@@ -1,36 +1,79 @@
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
}
|
||||
}
|
||||
@@ -438,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
|
||||
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
eventId: EventId.make(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
|
||||
@@ -30,14 +30,13 @@ import type {
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -150,7 +149,7 @@ const startTurn = (input: {
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
commandId: CommandId.make(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
@@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -875,7 +874,7 @@ it.live(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
|
||||
@@ -122,15 +122,12 @@ it.live("replays typed runtime fixture events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -157,15 +154,12 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -196,15 +190,12 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
@@ -250,15 +241,12 @@ it.live("rolls back provider conversation state only", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.17",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
repository: {
|
||||
type: string;
|
||||
url: string;
|
||||
directory: string;
|
||||
};
|
||||
bin: Record<string, string>;
|
||||
type: string;
|
||||
version: string;
|
||||
engines: Record<string, string>;
|
||||
files: string[];
|
||||
dependencies: Record<string, string>;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -177,7 +193,7 @@ const publishCmd = Command.make(
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
@@ -192,7 +208,7 @@ const publishCmd = Command.make(
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
const pkg: PackageJson = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
@@ -200,7 +216,8 @@ const publishCmd = Command.make(
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
dependencies: serverPackageJson.dependencies,
|
||||
overrides: rootPackageJson.overrides,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
@@ -208,6 +225,11 @@ const publishCmd = Command.make(
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
pkg.overrides = resolveCatalogDependencies(
|
||||
pkg.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"root overrides",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
@@ -20,7 +20,10 @@ import {
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
@@ -65,6 +68,13 @@ export const makeServerAuth = Effect.gen(function* () {
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
|
||||
@@ -33,10 +33,12 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -66,6 +68,7 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
@@ -30,7 +30,10 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: SESSION_COOKIE_NAME,
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -28,17 +28,14 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
|
||||
|
||||
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
|
||||
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
|
||||
Predicate.isTagged(u, "PlatformError");
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
isMissingSecretFileError(cause)
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
@@ -108,7 +105,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
return create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTag("SecretStoreError", (error) =>
|
||||
isAlreadyExistsSecretFileError(error.cause)
|
||||
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
|
||||
? get(name).pipe(
|
||||
Effect.flatMap((created) =>
|
||||
created !== null
|
||||
@@ -129,7 +126,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
isMissingSecretFileError(cause)
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
|
||||
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
@@ -81,11 +82,16 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
@@ -188,7 +194,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
|
||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -472,7 +478,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName: SESSION_COOKIE_NAME,
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
@@ -64,6 +64,6 @@ export interface AuthControlPlaneShape {
|
||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type BootstrapCredentialRole = "owner" | "client";
|
||||
@@ -51,7 +51,7 @@ export interface BootstrapCredentialServiceShape {
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialService extends ServiceMap.Service<
|
||||
export class BootstrapCredentialService extends Context.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, ServiceMap } from "effect";
|
||||
import { Data, DateTime, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
@@ -79,6 +79,6 @@ export interface ServerAuthShape {
|
||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Data, ServiceMap } from "effect";
|
||||
import { Data, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
||||
@@ -16,7 +16,6 @@ export interface ServerSecretStoreShape {
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
|
||||
export class ServerSecretStore extends ServiceMap.Service<
|
||||
ServerSecretStore,
|
||||
ServerSecretStoreShape
|
||||
>()("t3/auth/Services/ServerSecretStore") {}
|
||||
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
|
||||
"t3/auth/Services/ServerSecretStore",
|
||||
) {}
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type SessionRole = "owner" | "client";
|
||||
@@ -81,7 +81,7 @@ export interface SessionCredentialServiceShape {
|
||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class SessionCredentialService extends ServiceMap.Service<
|
||||
export class SessionCredentialService extends Context.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -2,7 +2,18 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
export const SESSION_COOKIE_NAME = "t3_session";
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
|
||||
@@ -26,7 +26,7 @@ function makeThreadCheckpointContext(input: {
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: {
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
@@ -82,10 +82,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -119,7 +124,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
@@ -136,10 +141,15 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
||||
const threadId = ThreadId.make("thread-checkpoint-store");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||
@@ -5,12 +5,12 @@
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"t3/checkpointing/Services/CheckpointStore",
|
||||
) {}
|
||||
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||
return CheckpointRef.makeUnsafe(
|
||||
return CheckpointRef.make(
|
||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -153,6 +153,69 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
|
||||
const fd = yield* openBootstrapFd({
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
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(false),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
|
||||
@@ -152,6 +152,10 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
|
||||
+37
-68
@@ -193,9 +193,6 @@ interface CliAuthLocationFlags {
|
||||
readonly devUrl?: Option.Option<URL>;
|
||||
}
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
@@ -241,12 +238,13 @@ export const resolveServerConfig = (
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
|
||||
Option.fromUndefinedOr(bootstrap?.mode),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
@@ -255,7 +253,7 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
|
||||
Option.fromUndefinedOr(bootstrap?.port),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
@@ -271,7 +269,7 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
|
||||
Option.fromUndefinedOr(bootstrap?.devUrl),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
@@ -280,9 +278,7 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -297,60 +293,41 @@ export const resolveServerConfig = (
|
||||
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
|
||||
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
|
||||
const startupPresentation = options?.startupPresentation ?? "browser";
|
||||
const noBrowser =
|
||||
startupPresentation === "headless"
|
||||
? true
|
||||
: resolveBooleanFlag(
|
||||
normalizedFlags.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const desktopBootstrapToken = Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
|
||||
const isHeadlessStartup = startupPresentation === "headless";
|
||||
const noBrowser = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
isHeadlessStartup ? Option.some(true) : Option.none(),
|
||||
normalizedFlags.noBrowser,
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.fromUndefinedOr(bootstrap?.noBrowser),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const autoBootstrapProjectFromCwd =
|
||||
options?.forceAutoBootstrapProjectFromCwd ??
|
||||
(startupPresentation === "headless"
|
||||
? false
|
||||
: resolveBooleanFlag(
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
));
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
isHeadlessStartup ? Option.some(false) : Option.none(),
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
() => mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
Option.fromUndefinedOr(bootstrap?.host),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
@@ -365,19 +342,11 @@ export const resolveServerConfig = (
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
|
||||
),
|
||||
) ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
persistedObservabilitySettings.otlpTracesUrl,
|
||||
otlpMetricsUrl:
|
||||
env.otlpMetricsUrl ??
|
||||
Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
|
||||
),
|
||||
) ??
|
||||
bootstrap?.otlpMetricsUrl ??
|
||||
persistedObservabilitySettings.otlpMetricsUrl,
|
||||
otlpExportIntervalMs: env.otlpExportIntervalMs,
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
@@ -1030,10 +999,10 @@ const projectAddCommand = Command.make("add", {
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
@@ -1071,7 +1040,7 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
@@ -1111,7 +1080,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
@@ -743,7 +743,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
@@ -780,7 +780,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
import { Effect, Context } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
@@ -439,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
constructor(services?: Context.Context<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
}
|
||||
@@ -640,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.stopSession(threadId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId,
|
||||
@@ -739,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (!turnIdRaw) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
@@ -840,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -879,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1061,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1134,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1153,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
context.pendingUserInputs.set(requestId, {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1164,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1254,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1266,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1282,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: EventId.make(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1341,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
@@ -1590,9 +1590,9 @@ function readResumeThreadId(input: {
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return brandIfNonEmpty(value, TurnId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, TurnId.make);
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
||||
return brandIfNonEmpty(value, ProviderItemId.make);
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -76,11 +77,13 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
@@ -110,6 +113,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||
],
|
||||
@@ -120,7 +124,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
|
||||
@@ -64,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
return generated;
|
||||
});
|
||||
|
||||
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName,
|
||||
|
||||
@@ -51,11 +51,13 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const result = yield* Effect.tryPromise(() =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
).pipe(Effect.orElseSucceed(() => null));
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
catch: () => null,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerEnvironmentShape {
|
||||
@@ -7,7 +7,6 @@ export interface ServerEnvironmentShape {
|
||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends ServiceMap.Service<
|
||||
ServerEnvironment,
|
||||
ServerEnvironmentShape
|
||||
>()("t3/environment/Services/ServerEnvironment") {}
|
||||
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
|
||||
"t3/environment/Services/ServerEnvironment",
|
||||
) {}
|
||||
@@ -40,6 +40,24 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
function git(
|
||||
cwd: string,
|
||||
@@ -219,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
|
||||
if (
|
||||
input.args.join(" ") !==
|
||||
"-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
|
||||
) {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
@@ -252,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
|
||||
Effect.gen(function* () {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
expect(input.args).toEqual([
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
]);
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "src/index.ts\0README.md\0",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.listWorkspaceFiles("/virtual/repo");
|
||||
expect(result.paths).toEqual(["src/index.ts", "README.md"]);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
@@ -267,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
|
||||
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.hasOriginRemote).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -617,8 +682,8 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const services = yield* Effect.services();
|
||||
const runPromise = Effect.runPromiseWith(services);
|
||||
const context = yield* Effect.context<never>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -761,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -780,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
@@ -791,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
@@ -821,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
@@ -982,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -1594,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
const core = yield* GitCore;
|
||||
|
||||
const status = yield* core.statusDetails(deletedDir);
|
||||
const localStatus = yield* core.statusDetailsLocal(deletedDir);
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
expect(localStatus).toEqual(status);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type GitStatusDetails,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
@@ -47,23 +48,39 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
] as const;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
|
||||
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -353,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function isMissingGitCwdError(error: GitCommandError): boolean {
|
||||
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
|
||||
return (
|
||||
normalized.includes("no such file or directory") ||
|
||||
normalized.includes("notfound: filesystem.access") ||
|
||||
normalized.includes("enoent") ||
|
||||
normalized.includes("not a directory")
|
||||
);
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
@@ -890,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
});
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
const fetchRemoteForStatus = (
|
||||
gitCommonDir: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
remoteName: string,
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -916,20 +942,15 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith({
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
lookup: refreshStatusUpstreamCacheEntry,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit)
|
||||
@@ -944,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1185,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (statusResult === null) {
|
||||
return NON_REPOSITORY_STATUS_DETAILS;
|
||||
}
|
||||
|
||||
if (statusResult.code !== 0) {
|
||||
const stderr = statusResult.stderr.trim();
|
||||
@@ -1317,7 +1340,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
@@ -1619,7 +1645,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
@@ -1637,7 +1670,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
@@ -1657,7 +1697,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
@@ -1671,7 +1711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
@@ -1700,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
@@ -1982,7 +2032,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
"GitCore.removeWorktree",
|
||||
input.cwd,
|
||||
args,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-list",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const mergedAt = input.mergedAt;
|
||||
const state = input.state;
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
return "merged";
|
||||
}
|
||||
if (state === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
const RawGitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
function normalizePullRequestSummary(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
|
||||
): GitHubPullRequestSummary {
|
||||
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
|
||||
const headRepositoryOwnerLogin =
|
||||
raw.headRepositoryOwner?.login ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizePullRequestState(raw),
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
@@ -154,7 +94,7 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -194,14 +134,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: decodeGitHubJson(
|
||||
raw,
|
||||
Schema.Array(RawGitHubPullRequestSchema),
|
||||
"listOpenPullRequests",
|
||||
"GitHub CLI returned invalid PR list JSON.",
|
||||
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubPullRequestSchema,
|
||||
"getPullRequest",
|
||||
"GitHub CLI returned invalid pull request JSON.",
|
||||
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizePullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
|
||||
@@ -186,6 +186,24 @@ function makeTempDir(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
@@ -694,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 14,
|
||||
title: " Existing PR title \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-trimmed-pr\t",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 15,
|
||||
title: " Valid PR title ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-valid-pr-entry\t",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 16,
|
||||
title: "Closed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/16",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "closed",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
|
||||
@@ -720,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
|
||||
const cwd = path.join(rootDir, "deleted-repo");
|
||||
yield* makeDirectory(cwd);
|
||||
yield* removePath(cwd);
|
||||
const { manager } = yield* makeManager();
|
||||
|
||||
const status = yield* manager.status({ cwd });
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
} from "effect";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitActionProgressPhase,
|
||||
@@ -34,6 +45,10 @@ import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScr
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import {
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -240,85 +255,6 @@ function matchesBranchHeadContext(
|
||||
return true;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
const isCrossRepository = record.isCrossRepository;
|
||||
const headRepositoryRecord =
|
||||
typeof record.headRepository === "object" && record.headRepository !== null
|
||||
? (record.headRepository as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryOwnerRecord =
|
||||
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
|
||||
? (record.headRepositoryOwner as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryNameWithOwner =
|
||||
typeof record.headRepositoryNameWithOwner === "string"
|
||||
? record.headRepositoryNameWithOwner
|
||||
: typeof headRepositoryRecord?.nameWithOwner === "string"
|
||||
? headRepositoryRecord.nameWithOwner
|
||||
: null;
|
||||
const headRepositoryOwnerLogin =
|
||||
typeof record.headRepositoryOwnerLogin === "string"
|
||||
? record.headRepositoryOwnerLogin
|
||||
: typeof headRepositoryOwnerRecord?.login === "string"
|
||||
? headRepositoryOwnerRecord.login
|
||||
: null;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if (
|
||||
(typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
|
||||
state === "MERGED" ||
|
||||
state === "merged"
|
||||
) {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED" || state === "closed") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||
return {
|
||||
number: summary.number,
|
||||
@@ -731,9 +667,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
workingTree: details.workingTree,
|
||||
} satisfies GitStatusLocalResult;
|
||||
});
|
||||
const localStatusResultCache = yield* Cache.makeWith({
|
||||
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
lookup: readLocalStatus,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||
@@ -764,9 +699,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
pr,
|
||||
} satisfies GitStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith({
|
||||
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
lookup: readRemoteStatus,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||
@@ -949,13 +883,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
gitManagerError(
|
||||
"findLatestPr",
|
||||
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
decoded.failure,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const pr of parsePullRequestList(parsedJson)) {
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const pr of pullRequests) {
|
||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
*
|
||||
* @module RoutingTextGeneration
|
||||
*/
|
||||
import { Effect, Layer, ServiceMap } from "effect";
|
||||
import { Effect, Layer, Context } from "effect";
|
||||
|
||||
import {
|
||||
TextGeneration,
|
||||
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
|
||||
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
||||
) {}
|
||||
|
||||
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
@@ -310,6 +310,4 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
|
||||
"t3/git/Services/GitCore",
|
||||
) {}
|
||||
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
|
||||
@@ -5,7 +5,7 @@
|
||||
*
|
||||
* @module GitHubCli
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
@@ -98,6 +98,6 @@ export interface GitHubCliShape {
|
||||
/**
|
||||
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||
*/
|
||||
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/git/Services/GitHubCli",
|
||||
) {}
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
@@ -99,6 +99,6 @@ export interface GitManagerShape {
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/GitManager",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
@@ -21,7 +21,7 @@ export interface GitStatusBroadcasterShape {
|
||||
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitStatusBroadcaster extends ServiceMap.Service<
|
||||
export class GitStatusBroadcaster extends Context.Service<
|
||||
GitStatusBroadcaster,
|
||||
GitStatusBroadcasterShape
|
||||
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module TextGeneration
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
@@ -118,6 +118,6 @@ export interface TextGenerationShape {
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
|
||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/git/Services/TextGeneration",
|
||||
) {}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const normalizedState = input.state?.trim().toUpperCase();
|
||||
if (
|
||||
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
|
||||
normalizedState === "MERGED"
|
||||
) {
|
||||
return "merged";
|
||||
}
|
||||
if (normalizedState === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
export const formatGitHubJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitHubPullRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -226,6 +226,7 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
@@ -188,6 +188,21 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const),
|
||||
);
|
||||
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.splitRight"), "mod+d");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.splitDown"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.close"), "mod+w");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.previous"), "mod+[");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.next"), "mod+]");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.left"), "mod+alt+arrowleft");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.right"), "mod+alt+arrowright");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.up"), "mod+alt+arrowup");
|
||||
assert.equal(defaultsByCommand.get("workspace.focus.down"), "mod+alt+arrowdown");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.toggleZoom"), "mod+shift+enter");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeLeft"), "mod+ctrl+arrowleft");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeRight"), "mod+ctrl+arrowright");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeUp"), "mod+ctrl+arrowup");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.resizeDown"), "mod+ctrl+arrowdown");
|
||||
assert.equal(defaultsByCommand.get("workspace.pane.equalize"), "mod+ctrl+=");
|
||||
assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+[");
|
||||
assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
|
||||
@@ -39,7 +39,7 @@ import {
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
Ref,
|
||||
ServiceMap,
|
||||
Context,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
@@ -60,7 +60,23 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+d", command: "workspace.pane.splitRight", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+d", command: "workspace.pane.splitDown", when: "!terminalFocus" },
|
||||
{ key: "mod+w", command: "workspace.pane.close", when: "!terminalFocus" },
|
||||
{ key: "mod+[", command: "workspace.focus.previous" },
|
||||
{ key: "mod+]", command: "workspace.focus.next" },
|
||||
{ key: "mod+alt+arrowup", command: "workspace.focus.up" },
|
||||
{ key: "mod+alt+arrowdown", command: "workspace.focus.down" },
|
||||
{ key: "mod+alt+arrowleft", command: "workspace.focus.left" },
|
||||
{ key: "mod+alt+arrowright", command: "workspace.focus.right" },
|
||||
{ key: "mod+shift+enter", command: "workspace.pane.toggleZoom" },
|
||||
{ key: "mod+ctrl+arrowup", command: "workspace.pane.resizeUp" },
|
||||
{ key: "mod+ctrl+arrowdown", command: "workspace.pane.resizeDown" },
|
||||
{ key: "mod+ctrl+arrowleft", command: "workspace.pane.resizeLeft" },
|
||||
{ key: "mod+ctrl+arrowright", command: "workspace.pane.resizeRight" },
|
||||
{ key: "mod+ctrl+=", command: "workspace.pane.equalize" },
|
||||
{ key: "mod+alt+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
@@ -521,7 +537,7 @@ export interface KeybindingsShape {
|
||||
/**
|
||||
* Keybindings - Service tag for keybinding configuration operations.
|
||||
*/
|
||||
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
|
||||
export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
|
||||
"t3/keybindings",
|
||||
) {}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TraceRecord } from "../TraceRecord.ts";
|
||||
@@ -7,7 +7,7 @@ export interface BrowserTraceCollectorShape {
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class BrowserTraceCollector extends ServiceMap.Service<
|
||||
export class BrowserTraceCollector extends Context.Service<
|
||||
BrowserTraceCollector,
|
||||
BrowserTraceCollectorShape
|
||||
>()("t3/observability/Services/BrowserTraceCollector") {}
|
||||
@@ -42,6 +42,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -122,6 +132,16 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -354,6 +374,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -361,7 +382,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+21
-8
@@ -11,7 +11,7 @@ import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Effect, Layer } from "effect";
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -75,6 +75,14 @@ function resolveCommandEditorArgs(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
@@ -247,7 +255,7 @@ export interface OpenShape {
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
@@ -273,7 +281,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -293,11 +301,16 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
|
||||
@@ -44,8 +44,8 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
@@ -81,7 +81,7 @@ function createProviderServiceHarness(
|
||||
provider: providerName,
|
||||
status: "ready",
|
||||
runtimeMode: "full-access",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
cwd: sessionCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -130,7 +130,7 @@ async function waitForThread(
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -310,7 +310,7 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
@@ -324,8 +324,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -344,21 +344,21 @@ describe("CheckpointReactor", () => {
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -378,10 +378,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-capture"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -395,26 +395,26 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
eventId: EventId.make("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
eventId: EventId.make("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -426,22 +426,22 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
@@ -456,10 +456,10 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-refresh-local-status"),
|
||||
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-refresh-local-status"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -476,10 +476,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-primary-running"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -493,45 +493,43 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
eventId: EventId.make("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
eventId: EventId.make("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
eventId: EventId.make("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -553,10 +551,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -570,24 +568,24 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
eventId: EventId.make("evt-turn-started-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
eventId: EventId.make("evt-turn-completed-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -600,7 +598,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -611,10 +609,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -628,11 +626,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
eventId: EventId.make("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -661,10 +659,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-for-baseline"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("message-user-1"),
|
||||
messageId: MessageId.make("message-user-1"),
|
||||
role: "user",
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
@@ -677,12 +675,12 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
@@ -699,10 +697,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-missing-provider-cwd"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -717,23 +715,23 @@ describe("CheckpointReactor", () => {
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
@@ -746,10 +744,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-checkpoint-captured"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -763,11 +761,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
eventId: EventId.make("evt-checkpoint-captured-3"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
@@ -775,7 +773,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await harness.drain();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
);
|
||||
@@ -796,10 +794,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-non-repo-runtime"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -813,31 +811,31 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
eventId: EventId.make("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -848,10 +846,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -866,11 +864,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-diff-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -880,11 +878,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-diff-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -895,8 +893,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-revert-request"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -910,12 +908,12 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -926,10 +924,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -944,11 +942,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -958,11 +956,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-claude-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -973,8 +971,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -983,7 +981,7 @@ describe("CheckpointReactor", () => {
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
@@ -995,10 +993,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-inline-revert"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1013,11 +1011,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-inline-revert-diff-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -1027,11 +1025,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-inline-revert-diff-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -1042,8 +1040,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-sequenced-revert-request-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -1051,8 +1049,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-sequenced-revert-request-0"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnCount: 0,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -1062,11 +1060,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
@@ -1078,8 +1076,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-revert-no-session"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
|
||||
@@ -38,7 +38,7 @@ type ReactorInput =
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.makeUnsafe(String(value));
|
||||
return value === undefined ? null : TurnId.make(String(value));
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
@@ -62,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis
|
||||
}
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -83,7 +83,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
@@ -108,7 +108,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
@@ -270,7 +270,7 @@ const make = Effect.gen(function* () {
|
||||
input.thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${input.turnId}`);
|
||||
MessageId.make(`assistant:${input.turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
@@ -307,7 +307,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
|
||||
@@ -32,10 +32,10 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
|
||||
|
||||
async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
@@ -115,7 +115,7 @@ describe("OrchestrationEngine", () => {
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-bootstrap"),
|
||||
id: ThreadId.make("thread-bootstrap"),
|
||||
projectId: asProjectId("project-bootstrap"),
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: {
|
||||
@@ -144,10 +144,20 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
@@ -183,7 +193,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-1-create"),
|
||||
commandId: CommandId.make("cmd-project-1-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
@@ -197,8 +207,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-1-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -215,8 +225,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-1"),
|
||||
role: "user",
|
||||
@@ -243,7 +253,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
|
||||
commandId: CommandId.make("cmd-project-archive-create"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Project Archive",
|
||||
workspaceRoot: "/tmp/project-archive",
|
||||
@@ -257,8 +267,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
commandId: CommandId.make("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Archive me",
|
||||
modelSelection: {
|
||||
@@ -276,8 +286,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
commandId: CommandId.make("cmd-thread-archive"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
@@ -289,8 +299,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.unarchive",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
commandId: CommandId.make("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
@@ -310,7 +320,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
|
||||
commandId: CommandId.make("cmd-project-replay-create"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
@@ -324,8 +334,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
commandId: CommandId.make("cmd-thread-replay-create"),
|
||||
threadId: ThreadId.make("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
modelSelection: {
|
||||
@@ -342,8 +352,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
commandId: CommandId.make("cmd-thread-replay-delete"),
|
||||
threadId: ThreadId.make("thread-replay"),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -368,7 +378,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
|
||||
commandId: CommandId.make("cmd-project-stream-create"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
@@ -392,8 +402,8 @@ describe("OrchestrationEngine", () => {
|
||||
yield* Effect.sleep("10 millis");
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
commandId: CommandId.make("cmd-stream-thread-create"),
|
||||
threadId: ThreadId.make("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
modelSelection: {
|
||||
@@ -408,8 +418,8 @@ describe("OrchestrationEngine", () => {
|
||||
});
|
||||
yield* engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
commandId: CommandId.make("cmd-stream-thread-update"),
|
||||
threadId: ThreadId.make("thread-stream"),
|
||||
title: "domain-stream-updated",
|
||||
});
|
||||
eventTypes.push((yield* Queue.take(eventQueue)).type);
|
||||
@@ -429,7 +439,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
|
||||
commandId: CommandId.make("cmd-project-ack-create"),
|
||||
projectId: asProjectId("project-ack"),
|
||||
title: "Ack Project",
|
||||
workspaceRoot: "/tmp/project-ack",
|
||||
@@ -444,8 +454,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-ack"),
|
||||
commandId: CommandId.make("cmd-thread-ack-create"),
|
||||
threadId: ThreadId.make("thread-ack"),
|
||||
projectId: asProjectId("project-ack"),
|
||||
title: "Ack Thread",
|
||||
modelSelection: {
|
||||
@@ -481,8 +491,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
|
||||
threadId: ThreadId.makeUnsafe("thread-missing-project"),
|
||||
commandId: CommandId.make("cmd-thread-missing-project"),
|
||||
threadId: ThreadId.make("thread-missing-project"),
|
||||
projectId: asProjectId("project-missing"),
|
||||
title: "Missing Project Thread",
|
||||
modelSelection: {
|
||||
@@ -518,7 +528,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
|
||||
commandId: CommandId.make("cmd-project-turn-diff-create"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
@@ -532,8 +542,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
commandId: CommandId.make("cmd-thread-turn-diff-create"),
|
||||
threadId: ThreadId.make("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
modelSelection: {
|
||||
@@ -550,8 +560,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
commandId: CommandId.make("cmd-turn-diff-complete"),
|
||||
threadId: ThreadId.make("thread-turn-diff"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
|
||||
@@ -590,7 +600,7 @@ describe("OrchestrationEngine", () => {
|
||||
|
||||
const flakyStore: OrchestrationEventStoreShape = {
|
||||
append(event) {
|
||||
if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
|
||||
if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
|
||||
shouldFailFirstAppend = false;
|
||||
return Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
@@ -637,7 +647,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
|
||||
commandId: CommandId.make("cmd-project-flaky-create"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
@@ -653,8 +663,8 @@ describe("OrchestrationEngine", () => {
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
commandId: CommandId.make("cmd-flaky-1"),
|
||||
threadId: ThreadId.make("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
modelSelection: {
|
||||
@@ -673,8 +683,8 @@ describe("OrchestrationEngine", () => {
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
commandId: CommandId.make("cmd-flaky-2"),
|
||||
threadId: ThreadId.make("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
modelSelection: {
|
||||
@@ -701,7 +711,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailRequestedProjection &&
|
||||
event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
|
||||
event.commandId === CommandId.make("cmd-turn-start-atomic") &&
|
||||
event.type === "thread.turn-start-requested"
|
||||
) {
|
||||
shouldFailRequestedProjection = false;
|
||||
@@ -732,7 +742,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
|
||||
commandId: CommandId.make("cmd-project-atomic-create"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
@@ -746,8 +756,8 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
commandId: CommandId.make("cmd-thread-atomic-create"),
|
||||
threadId: ThreadId.make("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
modelSelection: {
|
||||
@@ -764,8 +774,8 @@ describe("OrchestrationEngine", () => {
|
||||
|
||||
const turnStartCommand = {
|
||||
type: "thread.turn.start" as const,
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
commandId: CommandId.make("cmd-turn-start-atomic"),
|
||||
threadId: ThreadId.make("thread-atomic"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-atomic-1"),
|
||||
role: "user" as const,
|
||||
@@ -845,7 +855,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
|
||||
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
@@ -875,7 +885,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
|
||||
commandId: CommandId.make("cmd-project-sync-create"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
@@ -889,8 +899,8 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
commandId: CommandId.make("cmd-thread-sync-create"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
modelSelection: {
|
||||
@@ -909,8 +919,8 @@ describe("OrchestrationEngine", () => {
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
@@ -934,8 +944,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
|
||||
threadId: ThreadId.makeUnsafe("thread-missing"),
|
||||
commandId: CommandId.make("cmd-invariant-missing-thread"),
|
||||
threadId: ThreadId.make("thread-missing"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-missing"),
|
||||
role: "user",
|
||||
@@ -960,7 +970,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
|
||||
commandId: CommandId.make("cmd-project-duplicate-create"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
@@ -975,8 +985,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
commandId: CommandId.make("cmd-thread-duplicate-1"),
|
||||
threadId: ThreadId.make("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
modelSelection: {
|
||||
@@ -995,8 +1005,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
commandId: CommandId.make("cmd-thread-duplicate-2"),
|
||||
threadId: ThreadId.make("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
modelSelection: {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -86,7 +87,89 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return null;
|
||||
}
|
||||
const requestId = (payload as Record<string, unknown>).requestId;
|
||||
return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
if (detail === null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
const openRequestIds = new Set<string>();
|
||||
const ordered = [...activities].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const requestId = extractActivityRequestId(activity.payload);
|
||||
if (requestId === null) {
|
||||
continue;
|
||||
}
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
|
||||
if (activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
}): boolean {
|
||||
const sorted = [...input.proposedPlans].toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
|
||||
);
|
||||
|
||||
let latestForTurn: ProjectionThreadProposedPlan | null = null;
|
||||
if (input.latestTurnId !== null) {
|
||||
for (let index = sorted.length - 1; index >= 0; index -= 1) {
|
||||
const plan = sorted[index];
|
||||
if (plan?.turnId === input.latestTurnId) {
|
||||
latestForTurn = plan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (latestForTurn !== null) {
|
||||
return latestForTurn.implementedAt === null;
|
||||
}
|
||||
|
||||
const latestPlan = sorted.at(-1) ?? null;
|
||||
return latestPlan !== null && latestPlan.implementedAt === null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
@@ -432,6 +515,48 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const refreshThreadShellSummary = Effect.fn("refreshThreadShellSummary")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
|
||||
projectionThreadMessageRepository.listByThreadId({ threadId }),
|
||||
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
|
||||
projectionThreadActivityRepository.listByThreadId({ threadId }),
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
).length;
|
||||
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
|
||||
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
|
||||
latestTurnId: existingRow.value.latestTurnId,
|
||||
proposedPlans,
|
||||
});
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
pendingApprovalCount,
|
||||
pendingUserInputCount,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
@@ -450,6 +575,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
@@ -554,7 +683,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -565,6 +696,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -580,6 +712,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -595,6 +728,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -610,6 +744,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1121,6 +1256,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.payload.activity.kind === "provider.approval.respond.failed") {
|
||||
const payload =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null
|
||||
? (event.payload.activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail =
|
||||
typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (isStalePendingApprovalFailureDetail(detail)) {
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
if (existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: existingRow.value.threadId,
|
||||
turnId: existingRow.value.turnId,
|
||||
status: "resolved",
|
||||
decision: null,
|
||||
createdAt: existingRow.value.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
@@ -62,9 +62,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
@@ -74,9 +80,15 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
'2026-02-24T00:00:02.000Z',
|
||||
'2026-02-24T00:00:03.000Z',
|
||||
NULL
|
||||
@@ -259,7 +271,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
]);
|
||||
assert.deepEqual(snapshot.threads, [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
modelSelection: {
|
||||
@@ -278,7 +290,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
@@ -303,7 +315,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
turnId: asTurnId("turn-1"),
|
||||
planMarkdown: "# Ship it",
|
||||
implementedAt: "2026-02-24T00:00:05.500Z",
|
||||
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
|
||||
implementationThreadId: ThreadId.make("thread-2"),
|
||||
createdAt: "2026-02-24T00:00:05.000Z",
|
||||
updatedAt: "2026-02-24T00:00:05.500Z",
|
||||
},
|
||||
@@ -331,7 +343,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
],
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -341,6 +353,81 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
assert.equal(shellSnapshot.snapshotSequence, 5);
|
||||
assert.deepEqual(shellSnapshot.projects, [
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(shellSnapshot.threads, [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: asTurnId("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-24T00:00:08.000Z",
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
planId: "plan-1",
|
||||
},
|
||||
},
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
archivedAt: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
|
||||
hasPendingApprovals: true,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -473,7 +560,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
);
|
||||
assert.equal(firstThreadId._tag, "Some");
|
||||
if (firstThreadId._tag === "Some") {
|
||||
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
|
||||
assert.equal(firstThreadId.value, ThreadId.make("thread-first"));
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -596,12 +683,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
`;
|
||||
|
||||
const context = yield* snapshotQuery.getThreadCheckpointContext(
|
||||
ThreadId.makeUnsafe("thread-context"),
|
||||
ThreadId.make("thread-context"),
|
||||
);
|
||||
assert.equal(context._tag, "Some");
|
||||
if (context._tag === "Some") {
|
||||
assert.deepEqual(context.value, {
|
||||
threadId: ThreadId.makeUnsafe("thread-context"),
|
||||
threadId: ThreadId.make("thread-context"),
|
||||
projectId: asProjectId("project-context"),
|
||||
workspaceRoot: "/tmp/context-workspace",
|
||||
worktreePath: "/tmp/context-worktree",
|
||||
@@ -629,4 +716,309 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps thread detail activity ordering consistent with shell snapshot ordering", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-01T00:00:00.000Z',
|
||||
'2026-04-01T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-01T00:00:02.000Z',
|
||||
'2026-04-01T00:00:03.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-unsequenced',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'unsequenced first',
|
||||
'{"source":"unsequenced"}',
|
||||
NULL,
|
||||
'2026-04-01T00:00:06.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-2',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence two',
|
||||
'{"source":"sequence-2"}',
|
||||
2,
|
||||
'2026-04-01T00:00:04.000Z'
|
||||
),
|
||||
(
|
||||
'activity-sequence-1',
|
||||
'thread-1',
|
||||
NULL,
|
||||
'info',
|
||||
'runtime.note',
|
||||
'sequence one',
|
||||
'{"source":"sequence-1"}',
|
||||
1,
|
||||
'2026-04-01T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const snapshot = yield* snapshotQuery.getSnapshot();
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
|
||||
}
|
||||
|
||||
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
|
||||
{
|
||||
id: asEventId("activity-unsequenced"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "unsequenced first",
|
||||
payload: { source: "unsequenced" },
|
||||
turnId: null,
|
||||
createdAt: "2026-04-01T00:00:06.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence one",
|
||||
payload: { source: "sequence-1" },
|
||||
turnId: null,
|
||||
sequence: 1,
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
},
|
||||
{
|
||||
id: asEventId("activity-sequence-2"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "sequence two",
|
||||
payload: { source: "sequence-2" },
|
||||
turnId: null,
|
||||
sequence: 2,
|
||||
createdAt: "2026-04-01T00:00:04.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for targeted thread latest turn queries", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[]',
|
||||
'2026-04-02T00:00:00.000Z',
|
||||
'2026-04-02T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'full-access',
|
||||
'default',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-running',
|
||||
'2026-04-02T00:00:04.000Z',
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
'2026-04-02T00:00:02.000Z',
|
||||
'2026-04-02T00:00:03.000Z',
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
source_proposed_plan_thread_id,
|
||||
source_proposed_plan_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'thread-1',
|
||||
'turn-completed',
|
||||
'message-user-1',
|
||||
NULL,
|
||||
NULL,
|
||||
'message-assistant-1',
|
||||
'completed',
|
||||
'2026-04-02T00:00:05.000Z',
|
||||
'2026-04-02T00:00:06.000Z',
|
||||
'2026-04-02T00:00:20.000Z',
|
||||
5,
|
||||
'checkpoint-5',
|
||||
'ready',
|
||||
'[]'
|
||||
),
|
||||
(
|
||||
'thread-1',
|
||||
'turn-running',
|
||||
'message-user-2',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'running',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
'2026-04-02T00:00:30.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'[]'
|
||||
)
|
||||
`;
|
||||
|
||||
const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadShell._tag, "Some");
|
||||
if (threadShell._tag === "Some") {
|
||||
assert.equal(threadShell.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadShell.value.latestTurn?.state, "running");
|
||||
assert.equal(threadShell.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
|
||||
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
|
||||
assert.equal(threadDetail._tag, "Some");
|
||||
if (threadDetail._tag === "Some") {
|
||||
assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running"));
|
||||
assert.equal(threadDetail.value.latestTurn?.state, "running");
|
||||
assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -6,16 +6,19 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadShell,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -48,6 +51,8 @@ import {
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
|
||||
const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
@@ -155,6 +160,64 @@ function computeSnapshotSequence(
|
||||
return Number.isFinite(minSequence) ? minSequence : 0;
|
||||
}
|
||||
|
||||
function mapLatestTurn(
|
||||
row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,
|
||||
): OrchestrationLatestTurn {
|
||||
return {
|
||||
turnId: row.turnId,
|
||||
state:
|
||||
row.state === "error"
|
||||
? "error"
|
||||
: row.state === "interrupted"
|
||||
? "interrupted"
|
||||
: row.state === "completed"
|
||||
? "completed"
|
||||
: "running",
|
||||
requestedAt: row.requestedAt,
|
||||
startedAt: row.startedAt,
|
||||
completedAt: row.completedAt,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
|
||||
? {
|
||||
sourceProposedPlan: {
|
||||
threadId: row.sourceProposedPlanThreadId,
|
||||
planId: row.sourceProposedPlanId,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,
|
||||
): OrchestrationSession {
|
||||
return {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
runtimeMode: row.runtimeMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function mapProjectShellRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,
|
||||
repositoryIdentity: OrchestrationProject["repositoryIdentity"],
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
repositoryIdentity,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -204,6 +267,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
@@ -381,6 +448,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveProjectRowById = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionProjectLookupRowSchema,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_projects
|
||||
WHERE project_id = ${projectId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionThreadIdLookupRowSchema,
|
||||
@@ -415,6 +503,146 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getActiveThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadMessageRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
implemented_at AS "implementedAt",
|
||||
implementation_thread_id AS "implementationThreadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadSessionRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_sessions
|
||||
WHERE thread_id = ${threadId}
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getLatestTurnRowByThread = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionLatestTurnDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
turns.thread_id AS "threadId",
|
||||
turns.turn_id AS "turnId",
|
||||
turns.state,
|
||||
turns.requested_at AS "requestedAt",
|
||||
turns.started_at AS "startedAt",
|
||||
turns.completed_at AS "completedAt",
|
||||
turns.assistant_message_id AS "assistantMessageId",
|
||||
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
turns.source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_threads threads
|
||||
JOIN projection_turns turns
|
||||
ON turns.thread_id = threads.thread_id
|
||||
AND turns.turn_id = threads.latest_turn_id
|
||||
WHERE threads.thread_id = ${threadId}
|
||||
AND threads.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
@@ -724,6 +952,145 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
|
||||
Effect.gen(function* () {
|
||||
let updatedAt: string | null = null;
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of threadRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of latestTurnRows) {
|
||||
updatedAt = maxIso(updatedAt, row.requestedAt);
|
||||
if (row.startedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.startedAt);
|
||||
}
|
||||
if (row.completedAt !== null) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
}
|
||||
}
|
||||
for (const row of stateRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
const repositoryIdentities = new Map(
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) =>
|
||||
repositoryIdentityResolver
|
||||
.resolve(row.workspaceRoot)
|
||||
.pipe(Effect.map((identity) => [row.projectId, identity] as const)),
|
||||
{ concurrency: repositoryIdentityResolutionConcurrency },
|
||||
),
|
||||
);
|
||||
const latestTurnByThread = new Map(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
const sessionByThread = new Map(
|
||||
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
|
||||
);
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeShellSnapshot(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot",
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -770,6 +1137,27 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getProjectShellById: ProjectionSnapshotQueryShape["getProjectShellById"] = (projectId) =>
|
||||
getActiveProjectRowById({ projectId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getProjectShellById:query",
|
||||
"ProjectionSnapshotQuery.getProjectShellById:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((option) =>
|
||||
Option.isNone(option)
|
||||
? Effect.succeed(Option.none<OrchestrationProjectShell>())
|
||||
: repositoryIdentityResolver
|
||||
.resolve(option.value.workspaceRoot)
|
||||
.pipe(
|
||||
Effect.map((repositoryIdentity) =>
|
||||
Option.some(mapProjectShellRow(option.value, repositoryIdentity)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
|
||||
(projectId) =>
|
||||
getFirstActiveThreadIdByProject({ projectId }).pipe(
|
||||
@@ -826,12 +1214,217 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThreadShell>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell);
|
||||
});
|
||||
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
] = yield* Effect.all([
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadMessageRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
getLatestTurnRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
getThreadSessionRowByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
if (Option.isNone(threadRow)) {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
title: threadRow.value.title,
|
||||
modelSelection: threadRow.value.modelSelection,
|
||||
runtimeMode: threadRow.value.runtimeMode,
|
||||
interactionMode: threadRow.value.interactionMode,
|
||||
branch: threadRow.value.branch,
|
||||
worktreePath: threadRow.value.worktreePath,
|
||||
latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,
|
||||
createdAt: threadRow.value.createdAt,
|
||||
updatedAt: threadRow.value.updatedAt,
|
||||
archivedAt: threadRow.value.archivedAt,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
if (row.attachments !== null) {
|
||||
return Object.assign(message, { attachments: row.attachments });
|
||||
}
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map((row) => ({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
implementedAt: row.implementedAt,
|
||||
implementationThreadId: row.implementationThreadId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
})),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
checkpointRef: row.checkpointRef,
|
||||
status: row.status,
|
||||
files: row.files,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
};
|
||||
|
||||
return Option.some(
|
||||
yield* decodeThread(thread).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getThreadDetailById:decodeThread"),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getThreadCheckpointContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -27,6 +27,10 @@ import {
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
|
||||
import {
|
||||
GitStatusBroadcaster,
|
||||
type GitStatusBroadcasterShape,
|
||||
} from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
@@ -38,11 +42,10 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
|
||||
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
|
||||
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
|
||||
@@ -122,8 +125,8 @@ describe("ProviderCommandReactor", () => {
|
||||
input !== null &&
|
||||
"threadId" in input &&
|
||||
typeof input.threadId === "string"
|
||||
? ThreadId.makeUnsafe(input.threadId)
|
||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||
? ThreadId.make(input.threadId)
|
||||
: ThreadId.make(`thread-${sessionIndex}`);
|
||||
const session: ProviderSession = {
|
||||
provider: modelSelection.provider,
|
||||
status: "ready" as const,
|
||||
@@ -145,7 +148,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
}),
|
||||
);
|
||||
@@ -178,6 +181,24 @@ describe("ProviderCommandReactor", () => {
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: false,
|
||||
branch: "renamed-branch",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>((_) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
@@ -226,6 +247,15 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
|
||||
} satisfies GitStatusBroadcasterShape),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(TextGeneration, {
|
||||
generateBranchName,
|
||||
@@ -247,7 +277,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
@@ -258,8 +288,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: modelSelection,
|
||||
@@ -280,6 +310,7 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
refreshStatus,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
stateDir,
|
||||
@@ -294,8 +325,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-1"),
|
||||
role: "user",
|
||||
@@ -310,7 +341,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.make("thread-1"));
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
modelSelection: {
|
||||
@@ -321,7 +352,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
@@ -335,8 +366,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-title-seed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
);
|
||||
@@ -344,8 +375,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-title"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title"),
|
||||
role: "user",
|
||||
@@ -367,12 +398,12 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Generated title"
|
||||
);
|
||||
});
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
|
||||
@@ -384,8 +415,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-title-custom"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: "Keep this custom title",
|
||||
}),
|
||||
);
|
||||
@@ -393,8 +424,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-title-preserve"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-preserve"),
|
||||
role: "user",
|
||||
@@ -412,7 +443,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
|
||||
@@ -429,8 +460,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-title-formatted-seed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
title: seededTitle,
|
||||
}),
|
||||
);
|
||||
@@ -438,8 +469,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-title-formatted"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-title-formatted"),
|
||||
role: "user",
|
||||
@@ -457,13 +488,13 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"Reconnect spinner resume bug"
|
||||
);
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
|
||||
@@ -474,8 +505,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-branch"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
branch: "t3code/1234abcd",
|
||||
worktreePath: "/tmp/provider-project-worktree",
|
||||
}),
|
||||
@@ -499,8 +530,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-branch-model"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-branch-model"),
|
||||
role: "user",
|
||||
@@ -514,9 +545,11 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.refreshStatus.mock.calls.length === 1);
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({
|
||||
message: "Add a safer reconnect backoff.",
|
||||
});
|
||||
expect(harness.refreshStatus.mock.calls[0]?.[0]).toBe("/tmp/provider-project-worktree");
|
||||
});
|
||||
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
@@ -526,8 +559,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-fast"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-fast"),
|
||||
role: "user",
|
||||
@@ -561,7 +594,7 @@ describe("ProviderCommandReactor", () => {
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
@@ -582,8 +615,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-claude-effort"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort"),
|
||||
role: "user",
|
||||
@@ -615,7 +648,7 @@ describe("ProviderCommandReactor", () => {
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
@@ -635,8 +668,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-claude-fast-mode"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-fast-mode"),
|
||||
role: "user",
|
||||
@@ -668,7 +701,7 @@ describe("ProviderCommandReactor", () => {
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
@@ -686,8 +719,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-interaction-mode-set-plan"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -696,8 +729,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-plan"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-plan"),
|
||||
role: "user",
|
||||
@@ -712,7 +745,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
});
|
||||
});
|
||||
@@ -726,8 +759,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-provider-first"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-first"),
|
||||
role: "user",
|
||||
@@ -746,9 +779,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
@@ -759,7 +790,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session).toBeNull();
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -778,8 +809,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
@@ -797,8 +828,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
@@ -814,7 +845,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
@@ -829,8 +860,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-unchanged-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unchanged-1"),
|
||||
role: "user",
|
||||
@@ -849,8 +880,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-unchanged-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unchanged-2"),
|
||||
role: "user",
|
||||
@@ -877,8 +908,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-claude-effort-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort-1"),
|
||||
role: "user",
|
||||
@@ -904,8 +935,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-claude-effort-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort-2"),
|
||||
role: "user",
|
||||
@@ -946,8 +977,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -956,8 +987,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-runtime-mode-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-runtime-mode-1"),
|
||||
role: "user",
|
||||
@@ -976,8 +1007,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -985,17 +1016,15 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-runtime-mode-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-runtime-mode-2"),
|
||||
role: "user",
|
||||
@@ -1012,16 +1041,16 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
@@ -1035,10 +1064,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-runtime-mode-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
@@ -1053,8 +1082,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-claude-no-options"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -1078,8 +1107,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-1"),
|
||||
role: "user",
|
||||
@@ -1098,8 +1127,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-2"),
|
||||
role: "user",
|
||||
@@ -1118,9 +1147,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
@@ -1132,7 +1159,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -1152,8 +1179,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -1162,8 +1189,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
@@ -1186,8 +1213,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -1195,9 +1222,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
@@ -1207,7 +1232,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
@@ -1219,10 +1244,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1237,8 +1262,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-interrupt"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: now,
|
||||
}),
|
||||
@@ -1250,6 +1275,61 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a fresh session when only projected session state exists", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-stale"),
|
||||
role: "user",
|
||||
text: "resume codex",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1257,10 +1337,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-for-approval"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1275,8 +1355,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: asApprovalRequestId("approval-request-1"),
|
||||
decision: "accept",
|
||||
createdAt: now,
|
||||
@@ -1298,10 +1378,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-for-user-input"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1316,8 +1396,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-respond"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-user-input-respond"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: asApprovalRequestId("user-input-request-1"),
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
@@ -1352,10 +1432,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-for-approval-error"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1370,10 +1450,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-requested"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-approval-requested"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-approval-requested"),
|
||||
id: EventId.make("activity-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
@@ -1391,8 +1471,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-approval-respond-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: asApprovalRequestId("approval-request-1"),
|
||||
decision: "acceptForSession",
|
||||
createdAt: now,
|
||||
@@ -1401,9 +1481,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
(activity) => activity.kind === "provider.approval.respond.failed",
|
||||
@@ -1411,7 +1489,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
const failureActivity = thread?.activities.find(
|
||||
@@ -1449,10 +1527,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-for-user-input-error"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1467,10 +1545,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-user-input-requested"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-user-input-requested"),
|
||||
id: EventId.make("activity-user-input-requested"),
|
||||
tone: "info",
|
||||
kind: "user-input.requested",
|
||||
summary: "User input requested",
|
||||
@@ -1500,8 +1578,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-user-input-respond-stale"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
requestId: asApprovalRequestId("user-input-request-1"),
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
@@ -1512,9 +1590,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
(activity) => activity.kind === "provider.user-input.respond.failed",
|
||||
@@ -1522,7 +1598,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
const failureActivity = thread?.activities.find(
|
||||
@@ -1551,10 +1627,10 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-set-for-stop"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1569,15 +1645,15 @@ describe("ProviderCommandReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-stop"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-stop"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
|
||||
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
@@ -67,13 +69,11 @@ const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
|
||||
event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
const DEFAULT_THREAD_TITLE = "New thread";
|
||||
|
||||
function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {
|
||||
@@ -119,10 +119,6 @@ function stalePendingRequestDetail(
|
||||
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
@@ -150,6 +146,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
@@ -186,7 +183,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("provider-failure-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: input.kind,
|
||||
summary: input.summary,
|
||||
@@ -290,14 +287,14 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const activeSession = yield* resolveActiveSession(threadId);
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -452,6 +449,7 @@ const make = Effect.gen(function* () {
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
|
||||
@@ -47,12 +47,12 @@ function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||
return ServerSettingsService.layerTest(overrides);
|
||||
}
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
@@ -227,7 +227,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
|
||||
commandId: CommandId.make("cmd-provider-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot,
|
||||
@@ -241,8 +241,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -259,10 +259,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-seed"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -277,7 +277,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
});
|
||||
@@ -457,9 +457,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
|
||||
|
||||
@@ -486,10 +484,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-session-seed-claude-placeholder"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -564,9 +562,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
|
||||
@@ -618,9 +614,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
|
||||
@@ -770,7 +764,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
@@ -788,7 +782,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
|
||||
commandId: CommandId.make("cmd-session-set-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
@@ -805,7 +799,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
|
||||
commandId: CommandId.make("cmd-thread-create-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
@@ -823,7 +817,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
|
||||
commandId: CommandId.make("cmd-session-set-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
@@ -882,7 +876,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
|
||||
commandId: CommandId.make("cmd-turn-start-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target"),
|
||||
@@ -957,7 +951,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
@@ -975,7 +969,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
|
||||
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
@@ -1051,7 +1045,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
|
||||
commandId: CommandId.make("cmd-turn-start-plan-target-guarded"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-guarded"),
|
||||
@@ -1110,7 +1104,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
@@ -1128,7 +1122,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
|
||||
commandId: CommandId.make("cmd-session-set-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
@@ -1145,7 +1139,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
|
||||
commandId: CommandId.make("cmd-thread-create-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
@@ -1163,7 +1157,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
|
||||
commandId: CommandId.make("cmd-session-set-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
@@ -1213,7 +1207,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
|
||||
commandId: CommandId.make("cmd-turn-start-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-unrelated"),
|
||||
@@ -1364,9 +1358,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
midThread?.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) => message.id === "assistant:item-buffered",
|
||||
@@ -1407,8 +1399,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-streaming-mode"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("message-streaming-mode"),
|
||||
role: "user",
|
||||
@@ -1649,7 +1641,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-open"),
|
||||
requestId: ApprovalRequestId.make("req-open"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
@@ -1662,7 +1654,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-open"),
|
||||
requestId: ApprovalRequestId.make("req-open"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
@@ -1681,7 +1673,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
const requested = thread?.activities.find(
|
||||
@@ -2286,7 +2278,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-user-input"),
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
payload: {
|
||||
questions: [
|
||||
{
|
||||
@@ -2311,7 +2303,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-user-input"),
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
payload: {
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
|
||||
@@ -30,7 +30,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
CommandId.make(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||
@@ -57,11 +57,11 @@ type RuntimeIngestionInput =
|
||||
};
|
||||
|
||||
function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
|
||||
return value === undefined ? undefined : TurnId.makeUnsafe(String(value));
|
||||
return value === undefined ? undefined : TurnId.make(String(value));
|
||||
}
|
||||
|
||||
function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
|
||||
return value === undefined ? undefined : ApprovalRequestId.makeUnsafe(value);
|
||||
return value === undefined ? undefined : ApprovalRequestId.make(value);
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
@@ -857,7 +857,7 @@ const make = Effect.fn("make")(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: CommandId.makeUnsafe(
|
||||
commandId: CommandId.make(
|
||||
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
|
||||
),
|
||||
threadId: sourceThread.id,
|
||||
@@ -1003,7 +1003,7 @@ const make = Effect.fn("make")(function* () {
|
||||
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
|
||||
|
||||
if (assistantDelta && assistantDelta.length > 0) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
const assistantMessageId = MessageId.make(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
const turnId = toTurnId(event.turnId);
|
||||
@@ -1049,9 +1049,7 @@ const make = Effect.fn("make")(function* () {
|
||||
const assistantCompletion =
|
||||
event.type === "item.completed" && event.payload.itemType === "assistant_message"
|
||||
? {
|
||||
messageId: MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
),
|
||||
messageId: MessageId.make(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
|
||||
fallbackText: event.payload.detail,
|
||||
}
|
||||
: undefined;
|
||||
@@ -1186,7 +1184,7 @@ const make = Effect.fn("make")(function* () {
|
||||
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
|
||||
// Already tracked; no-op.
|
||||
} else {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
const assistantMessageId = MessageId.make(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
@@ -1199,7 +1197,7 @@ const make = Effect.fn("make")(function* () {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: now,
|
||||
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
|
||||
checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`),
|
||||
status: "missing",
|
||||
files: [],
|
||||
assistantMessageId,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module CheckpointReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
@@ -34,7 +34,6 @@ export interface CheckpointReactorShape {
|
||||
/**
|
||||
* CheckpointReactor - Service tag for checkpoint reactor workers.
|
||||
*/
|
||||
export class CheckpointReactor extends ServiceMap.Service<
|
||||
CheckpointReactor,
|
||||
CheckpointReactorShape
|
||||
>()("t3/orchestration/Services/CheckpointReactor") {}
|
||||
export class CheckpointReactor extends Context.Service<CheckpointReactor, CheckpointReactorShape>()(
|
||||
"t3/orchestration/Services/CheckpointReactor",
|
||||
) {}
|
||||
@@ -5,7 +5,7 @@
|
||||
* `OrchestrationEventStore` persistence. It does not own provider process
|
||||
* management or transport concerns (e.g. websocket request parsing).
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch,
|
||||
* Uses Effect `Context.Service` for dependency injection. Command dispatch,
|
||||
* replay, and unknown-input decoding all return typed domain errors.
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
@@ -15,7 +15,7 @@ import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
@@ -74,7 +74,7 @@ export interface OrchestrationEngineShape {
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class OrchestrationEngineService extends ServiceMap.Service<
|
||||
export class OrchestrationEngineService extends Context.Service<
|
||||
OrchestrationEngineService,
|
||||
OrchestrationEngineShape
|
||||
>()("t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module OrchestrationReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
@@ -25,7 +25,7 @@ export interface OrchestrationReactorShape {
|
||||
/**
|
||||
* OrchestrationReactor - Service tag for orchestration reactor coordination.
|
||||
*/
|
||||
export class OrchestrationReactor extends ServiceMap.Service<
|
||||
export class OrchestrationReactor extends Context.Service<
|
||||
OrchestrationReactor,
|
||||
OrchestrationReactorShape
|
||||
>()("t3/orchestration/Services/OrchestrationReactor") {}
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module OrchestrationProjectionPipeline
|
||||
*/
|
||||
import type { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
@@ -36,7 +36,7 @@ export interface OrchestrationProjectionPipelineShape {
|
||||
/**
|
||||
* OrchestrationProjectionPipeline - Service tag for orchestration projections.
|
||||
*/
|
||||
export class OrchestrationProjectionPipeline extends ServiceMap.Service<
|
||||
export class OrchestrationProjectionPipeline extends Context.Service<
|
||||
OrchestrationProjectionPipeline,
|
||||
OrchestrationProjectionPipelineShape
|
||||
>()("t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline") {}
|
||||
@@ -9,11 +9,15 @@
|
||||
import type {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Option } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -44,6 +48,17 @@ export interface ProjectionSnapshotQueryShape {
|
||||
*/
|
||||
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the latest orchestration shell snapshot.
|
||||
*
|
||||
* Returns only projects and thread shell summaries so clients can bootstrap
|
||||
* lightweight navigation state without hydrating every thread body.
|
||||
*/
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationShellSnapshot,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read aggregate projection counts without hydrating the full read model.
|
||||
*/
|
||||
@@ -56,6 +71,13 @@ export interface ProjectionSnapshotQueryShape {
|
||||
workspaceRoot: string,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active project shell row by id.
|
||||
*/
|
||||
readonly getProjectShellById: (
|
||||
projectId: ProjectId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read the earliest active thread for a project.
|
||||
*/
|
||||
@@ -69,12 +91,26 @@ export interface ProjectionSnapshotQueryShape {
|
||||
readonly getThreadCheckpointContext: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread shell row by id.
|
||||
*/
|
||||
readonly getThreadShellById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread detail snapshot by id.
|
||||
*/
|
||||
readonly getThreadDetailById: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectionSnapshotQuery - Service tag for projection snapshot queries.
|
||||
*/
|
||||
export class ProjectionSnapshotQuery extends ServiceMap.Service<
|
||||
export class ProjectionSnapshotQuery extends Context.Service<
|
||||
ProjectionSnapshotQuery,
|
||||
ProjectionSnapshotQueryShape
|
||||
>()("t3/orchestration/Services/ProjectionSnapshotQuery") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProviderCommandReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
@@ -34,7 +34,7 @@ export interface ProviderCommandReactorShape {
|
||||
/**
|
||||
* ProviderCommandReactor - Service tag for provider command reaction workers.
|
||||
*/
|
||||
export class ProviderCommandReactor extends ServiceMap.Service<
|
||||
export class ProviderCommandReactor extends Context.Service<
|
||||
ProviderCommandReactor,
|
||||
ProviderCommandReactorShape
|
||||
>()("t3/orchestration/Services/ProviderCommandReactor") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProviderRuntimeIngestionService
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
@@ -34,7 +34,7 @@ export interface ProviderRuntimeIngestionShape {
|
||||
/**
|
||||
* ProviderRuntimeIngestionService - Service tag for runtime ingestion workers.
|
||||
*/
|
||||
export class ProviderRuntimeIngestionService extends ServiceMap.Service<
|
||||
export class ProviderRuntimeIngestionService extends Context.Service<
|
||||
ProviderRuntimeIngestionService,
|
||||
ProviderRuntimeIngestionShape
|
||||
>()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {}
|
||||
@@ -15,7 +15,7 @@
|
||||
* @module RuntimeReceiptBus
|
||||
*/
|
||||
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import { Schema, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export const CheckpointBaselineCapturedReceipt = Schema.Struct({
|
||||
@@ -59,7 +59,6 @@ export interface RuntimeReceiptBusShape {
|
||||
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
|
||||
}
|
||||
|
||||
export class RuntimeReceiptBus extends ServiceMap.Service<
|
||||
RuntimeReceiptBus,
|
||||
RuntimeReceiptBusShape
|
||||
>()("t3/orchestration/Services/RuntimeReceiptBus") {}
|
||||
export class RuntimeReceiptBus extends Context.Service<RuntimeReceiptBus, RuntimeReceiptBusShape>()(
|
||||
"t3/orchestration/Services/RuntimeReceiptBus",
|
||||
) {}
|
||||
@@ -25,7 +25,7 @@ const readModel: OrchestrationReadModel = {
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.makeUnsafe("project-a"),
|
||||
id: ProjectId.make("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModelSelection: {
|
||||
@@ -38,7 +38,7 @@ const readModel: OrchestrationReadModel = {
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: ProjectId.makeUnsafe("project-b"),
|
||||
id: ProjectId.make("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModelSelection: {
|
||||
@@ -53,8 +53,8 @@ const readModel: OrchestrationReadModel = {
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "Thread A",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
@@ -76,8 +76,8 @@ const readModel: OrchestrationReadModel = {
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-b"),
|
||||
title: "Thread B",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
@@ -103,10 +103,10 @@ const readModel: OrchestrationReadModel = {
|
||||
|
||||
const messageSendCommand: OrchestrationCommand = {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("msg-1"),
|
||||
messageId: MessageId.make("msg-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
@@ -118,13 +118,11 @@ const messageSendCommand: OrchestrationCommand = {
|
||||
|
||||
describe("commandInvariants", () => {
|
||||
it("finds threads by id and project", () => {
|
||||
expect(findThreadById(readModel, ThreadId.makeUnsafe("thread-1"))?.projectId).toBe("project-a");
|
||||
expect(findThreadById(readModel, ThreadId.makeUnsafe("missing"))).toBeUndefined();
|
||||
expect(findThreadById(readModel, ThreadId.make("thread-1"))?.projectId).toBe("project-a");
|
||||
expect(findThreadById(readModel, ThreadId.make("missing"))).toBeUndefined();
|
||||
expect(
|
||||
listThreadsByProjectId(readModel, ProjectId.makeUnsafe("project-b")).map(
|
||||
(thread) => thread.id,
|
||||
),
|
||||
).toEqual([ThreadId.makeUnsafe("thread-2")]);
|
||||
listThreadsByProjectId(readModel, ProjectId.make("project-b")).map((thread) => thread.id),
|
||||
).toEqual([ThreadId.make("thread-2")]);
|
||||
});
|
||||
|
||||
it("requires existing thread", async () => {
|
||||
@@ -132,17 +130,17 @@ describe("commandInvariants", () => {
|
||||
requireThread({
|
||||
readModel,
|
||||
command: messageSendCommand,
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}),
|
||||
);
|
||||
expect(thread.id).toBe(ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread.id).toBe(ThreadId.make("thread-1"));
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
requireThread({
|
||||
readModel,
|
||||
command: messageSendCommand,
|
||||
threadId: ThreadId.makeUnsafe("missing"),
|
||||
threadId: ThreadId.make("missing"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("does not exist");
|
||||
@@ -154,9 +152,9 @@ describe("commandInvariants", () => {
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
commandId: CommandId.make("cmd-2"),
|
||||
threadId: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "new",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
@@ -168,7 +166,7 @@ describe("commandInvariants", () => {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
},
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
threadId: ThreadId.make("thread-3"),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -178,9 +176,9 @@ describe("commandInvariants", () => {
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-3"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
commandId: CommandId.make("cmd-3"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "dup",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
@@ -192,7 +190,7 @@ describe("commandInvariants", () => {
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
},
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already exists");
|
||||
|
||||
@@ -12,9 +12,9 @@ import { Effect } from "effect";
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
|
||||
describe("decider project scripts", () => {
|
||||
it("emits empty scripts on project.create", async () => {
|
||||
@@ -25,7 +25,7 @@ describe("decider project scripts", () => {
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
@@ -51,9 +51,9 @@ describe("decider project scripts", () => {
|
||||
aggregateId: asProjectId("project-scripts"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create-scripts"),
|
||||
correlationId: CommandId.make("cmd-project-create-scripts"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-scripts"),
|
||||
@@ -81,7 +81,7 @@ describe("decider project scripts", () => {
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-update-scripts"),
|
||||
commandId: CommandId.make("cmd-project-update-scripts"),
|
||||
projectId: asProjectId("project-scripts"),
|
||||
scripts: Array.from(scripts),
|
||||
},
|
||||
@@ -105,9 +105,9 @@ describe("decider project scripts", () => {
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
@@ -125,15 +125,15 @@ describe("decider project scripts", () => {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -154,8 +154,8 @@ describe("decider project scripts", () => {
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("message-user-1"),
|
||||
role: "user",
|
||||
@@ -189,7 +189,7 @@ describe("decider project scripts", () => {
|
||||
return;
|
||||
}
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
@@ -214,9 +214,9 @@ describe("decider project scripts", () => {
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
@@ -234,15 +234,15 @@ describe("decider project scripts", () => {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -263,8 +263,8 @@ describe("decider project scripts", () => {
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-runtime-mode-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
@@ -279,7 +279,7 @@ describe("decider project scripts", () => {
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
},
|
||||
});
|
||||
@@ -296,9 +296,9 @@ describe("decider project scripts", () => {
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
@@ -316,15 +316,15 @@ describe("decider project scripts", () => {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -345,8 +345,8 @@ describe("decider project scripts", () => {
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
commandId: CommandId.make("cmd-interaction-mode-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
},
|
||||
@@ -361,7 +361,7 @@ describe("decider project scripts", () => {
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -21,15 +21,15 @@ function makeEvent(input: {
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.makeUnsafe(`event-${input.sequence}`),
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: input.aggregateKind,
|
||||
aggregateId:
|
||||
input.aggregateKind === "project"
|
||||
? ProjectId.makeUnsafe(input.aggregateId)
|
||||
: ThreadId.makeUnsafe(input.aggregateId),
|
||||
? ProjectId.make(input.aggregateId)
|
||||
: ThreadId.make(input.aggregateId),
|
||||
occurredAt: input.occurredAt,
|
||||
commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId),
|
||||
commandId: input.commandId === null ? null : CommandId.make(input.commandId),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
|
||||
@@ -6,7 +6,7 @@ describe("fixPath", () => {
|
||||
it("hydrates PATH on linux using the resolved login shell", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
|
||||
@@ -17,6 +17,39 @@ describe("fixPath", () => {
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenCalledWith("/bin/zsh");
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readPath = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => undefined);
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
fixPath({
|
||||
env,
|
||||
platform: "darwin",
|
||||
readPath,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readPath).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu");
|
||||
expect(readPath).toHaveBeenNthCalledWith(2, "/bin/zsh");
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read PATH from login shell /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,28 +1,57 @@
|
||||
import * as OS from "node:os";
|
||||
import { Effect, Path } from "effect";
|
||||
import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell";
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readPathFromLoginShell,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
function logPathHydrationWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function fixPath(
|
||||
options: {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
platform?: NodeJS.Platform;
|
||||
readPath?: typeof readPathFromLoginShell;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const env = options.env ?? process.env;
|
||||
const logWarning = options.logWarning ?? logPathHydrationWarning;
|
||||
const readPath = options.readPath ?? readPathFromLoginShell;
|
||||
|
||||
try {
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
const result = (options.readPath ?? readPathFromLoginShell)(shell);
|
||||
if (result) {
|
||||
env.PATH = result;
|
||||
let shellPath: string | undefined;
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
shellPath = readPath(shell);
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
|
||||
}
|
||||
|
||||
if (shellPath) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellPath
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to hydrate PATH from the user environment.", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,18 +21,18 @@ layer("OrchestrationEventStore", (it) => {
|
||||
|
||||
const appended = yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-store-roundtrip"),
|
||||
eventId: EventId.make("evt-store-roundtrip"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
aggregateId: ProjectId.make("project-roundtrip"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-store-roundtrip"),
|
||||
commandId: CommandId.make("cmd-store-roundtrip"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-store-roundtrip"),
|
||||
correlationId: CommandId.make("cmd-store-roundtrip"),
|
||||
metadata: {
|
||||
adapterKey: "codex",
|
||||
},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
projectId: ProjectId.make("project-roundtrip"),
|
||||
title: "Roundtrip Project",
|
||||
workspaceRoot: "/tmp/project-roundtrip",
|
||||
defaultModelSelection: null,
|
||||
@@ -87,13 +87,13 @@ layer("OrchestrationEventStore", (it) => {
|
||||
metadata_json
|
||||
)
|
||||
VALUES (
|
||||
${EventId.makeUnsafe("evt-store-invalid-json")},
|
||||
${EventId.make("evt-store-invalid-json")},
|
||||
${"project"},
|
||||
${ProjectId.makeUnsafe("project-invalid-json")},
|
||||
${ProjectId.make("project-invalid-json")},
|
||||
${0},
|
||||
${"project.created"},
|
||||
${now},
|
||||
${CommandId.makeUnsafe("cmd-store-invalid-json")},
|
||||
${CommandId.make("cmd-store-invalid-json")},
|
||||
${null},
|
||||
${null},
|
||||
${"server"},
|
||||
|
||||
@@ -24,7 +24,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* projects.upsert({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
projectId: ProjectId.make("project-null-options"),
|
||||
title: "Null options project",
|
||||
workspaceRoot: "/tmp/project-null-options",
|
||||
defaultModelSelection: {
|
||||
@@ -58,7 +58,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
);
|
||||
|
||||
const persisted = yield* projects.getById({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
projectId: ProjectId.make("project-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
@@ -73,8 +73,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* threads.upsert({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
threadId: ThreadId.make("thread-null-options"),
|
||||
projectId: ProjectId.make("project-null-options"),
|
||||
title: "Null options thread",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
@@ -88,6 +88,10 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
createdAt: "2026-03-24T00:00:00.000Z",
|
||||
updatedAt: "2026-03-24T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
@@ -112,7 +116,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
);
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
threadId: ThreadId.make("thread-null-options"),
|
||||
});
|
||||
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
|
||||
@@ -14,8 +14,8 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
it.effect("preserves existing attachments when upsert omits attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
|
||||
const threadId = ThreadId.make("thread-preserve-attachments");
|
||||
const messageId = MessageId.make("message-preserve-attachments");
|
||||
const createdAt = "2026-02-28T19:00:00.000Z";
|
||||
const updatedAt = "2026-02-28T19:00:01.000Z";
|
||||
const persistedAttachments = [
|
||||
@@ -68,8 +68,8 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
it.effect("allows explicit attachment clearing with an empty array", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
|
||||
const messageId = MessageId.makeUnsafe("message-clear-attachments");
|
||||
const threadId = ThreadId.make("thread-clear-attachments");
|
||||
const messageId = MessageId.make("message-clear-attachments");
|
||||
const createdAt = "2026-02-28T19:10:00.000Z";
|
||||
|
||||
yield* repository.upsert({
|
||||
|
||||
@@ -40,6 +40,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -55,6 +59,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
${row.archivedAt},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
${row.hasActionableProposedPlan},
|
||||
${row.deletedAt}
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
@@ -70,6 +78,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
archived_at = excluded.archived_at,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
|
||||
deleted_at = excluded.deleted_at
|
||||
`,
|
||||
});
|
||||
@@ -92,6 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -116,6 +132,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
archived_at AS "archivedAt",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
WHERE project_id = ${projectId}
|
||||
|
||||
@@ -35,6 +35,8 @@ import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
|
||||
import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
|
||||
import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
|
||||
import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
|
||||
import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
|
||||
import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -69,6 +71,8 @@ export const migrationEntries = [
|
||||
[20, "AuthAccessManagement", Migration0020],
|
||||
[21, "AuthSessionClientMetadata", Migration0021],
|
||||
[22, "AuthSessionLastConnectedAt", Migration0022],
|
||||
[23, "ProjectionThreadShellSummary", Migration0023],
|
||||
[24, "BackfillProjectionThreadShellSummary", Migration0024],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN latest_user_message_at TEXT
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0
|
||||
`.pipe(Effect.catch(() => Effect.void));
|
||||
});
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("024_BackfillProjectionThreadShellSummary", (it) => {
|
||||
it.effect("backfills thread shell summary fields and clears stale projected approvals", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 23 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
has_actionable_proposed_plan,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'approval-required',
|
||||
'plan',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'message-user-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'user',
|
||||
'Need help',
|
||||
NULL,
|
||||
0,
|
||||
'2026-02-24T00:01:00.000Z',
|
||||
'2026-02-24T00:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'activity-approval-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'approval',
|
||||
'approval.requested',
|
||||
'Command approval requested',
|
||||
'{"requestId":"approval-1","requestKind":"command"}',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-approval-stale',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'error',
|
||||
'provider.approval.respond.failed',
|
||||
'Provider approval response failed',
|
||||
'{"requestId":"approval-1","detail":"Unknown pending permission request: approval-1"}',
|
||||
NULL,
|
||||
'2026-02-24T00:03:00.000Z'
|
||||
),
|
||||
(
|
||||
'activity-user-input-requested',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'user-input.requested',
|
||||
'User input requested',
|
||||
'{"requestId":"input-1","questions":[{"id":"area","header":"Area","question":"Which repo area should I inspect next?","options":[{"label":"Server","description":"Server orchestration."}]}]}',
|
||||
NULL,
|
||||
'2026-02-24T00:04:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'plan-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'# Do the thing',
|
||||
NULL,
|
||||
NULL,
|
||||
'2026-02-24T00:05:00.000Z',
|
||||
'2026-02-24T00:05:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
VALUES (
|
||||
'approval-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'pending',
|
||||
NULL,
|
||||
'2026-02-24T00:02:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 24 });
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly pendingApprovalCount: number;
|
||||
readonly pendingUserInputCount: number;
|
||||
readonly hasActionableProposedPlan: number;
|
||||
}>`
|
||||
SELECT
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
has_actionable_proposed_plan AS "hasActionableProposedPlan"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-1'
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{
|
||||
latestUserMessageAt: "2026-02-24T00:01:00.000Z",
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 1,
|
||||
hasActionableProposedPlan: 1,
|
||||
},
|
||||
]);
|
||||
|
||||
const approvalRows = yield* sql<{
|
||||
readonly status: string;
|
||||
readonly resolvedAt: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
status,
|
||||
resolved_at AS "resolvedAt"
|
||||
FROM projection_pending_approvals
|
||||
WHERE request_id = 'approval-1'
|
||||
`;
|
||||
assert.deepStrictEqual(approvalRows, [
|
||||
{
|
||||
status: "resolved",
|
||||
resolvedAt: "2026-02-24T00:03:00.000Z",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
INSERT OR IGNORE INTO projection_pending_approvals (
|
||||
request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
status,
|
||||
decision,
|
||||
created_at,
|
||||
resolved_at
|
||||
)
|
||||
SELECT
|
||||
requested.request_id,
|
||||
requested.thread_id,
|
||||
requested.turn_id,
|
||||
'pending',
|
||||
NULL,
|
||||
requested.created_at,
|
||||
NULL
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS requested
|
||||
WHERE requested.row_number = 1
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_resolutions AS (
|
||||
SELECT
|
||||
resolved.request_id,
|
||||
resolved.resolved_at,
|
||||
resolved.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'approval.resolved'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS resolved
|
||||
WHERE resolved.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_resolutions.decision
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_resolutions.resolved_at
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_resolutions
|
||||
WHERE latest_resolutions.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_response_events AS (
|
||||
SELECT
|
||||
response.request_id,
|
||||
response.resolved_at,
|
||||
response.decision
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
occurred_at AS resolved_at,
|
||||
CASE
|
||||
WHEN json_extract(payload_json, '$.decision') IN (
|
||||
'accept',
|
||||
'acceptForSession',
|
||||
'decline',
|
||||
'cancel'
|
||||
)
|
||||
THEN json_extract(payload_json, '$.decision')
|
||||
ELSE NULL
|
||||
END AS decision,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY occurred_at DESC, sequence DESC
|
||||
) AS row_number
|
||||
FROM orchestration_events
|
||||
WHERE event_type = 'thread.approval-response-requested'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
) AS response
|
||||
WHERE response.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = (
|
||||
SELECT latest_response_events.decision
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
),
|
||||
resolved_at = (
|
||||
SELECT latest_response_events.resolved_at
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_response_events
|
||||
WHERE latest_response_events.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH latest_stale_failures AS (
|
||||
SELECT
|
||||
failure.request_id,
|
||||
failure.resolved_at
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(payload_json, '$.requestId') AS request_id,
|
||||
created_at AS resolved_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities
|
||||
WHERE kind = 'provider.approval.respond.failed'
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
AND (
|
||||
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%stale pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending approval request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending permission request%'
|
||||
)
|
||||
) AS failure
|
||||
WHERE failure.row_number = 1
|
||||
)
|
||||
UPDATE projection_pending_approvals
|
||||
SET
|
||||
status = 'resolved',
|
||||
decision = NULL,
|
||||
resolved_at = (
|
||||
SELECT latest_stale_failures.resolved_at
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
WHERE status = 'pending'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM latest_stale_failures
|
||||
WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET
|
||||
latest_user_message_at = (
|
||||
SELECT MAX(message.created_at)
|
||||
FROM projection_thread_messages AS message
|
||||
WHERE message.thread_id = projection_threads.thread_id
|
||||
AND message.role = 'user'
|
||||
),
|
||||
pending_approval_count = COALESCE((
|
||||
SELECT COUNT(*)
|
||||
FROM projection_pending_approvals
|
||||
WHERE projection_pending_approvals.thread_id = projection_threads.thread_id
|
||||
AND projection_pending_approvals.status = 'pending'
|
||||
), 0),
|
||||
pending_user_input_count = COALESCE((
|
||||
WITH latest_user_input_states AS (
|
||||
SELECT
|
||||
latest.request_id,
|
||||
latest.kind,
|
||||
latest.detail
|
||||
FROM (
|
||||
SELECT
|
||||
json_extract(activity.payload_json, '$.requestId') AS request_id,
|
||||
activity.kind,
|
||||
lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(activity.payload_json, '$.requestId')
|
||||
ORDER BY activity.created_at DESC, activity.activity_id DESC
|
||||
) AS row_number
|
||||
FROM projection_thread_activities AS activity
|
||||
WHERE activity.thread_id = projection_threads.thread_id
|
||||
AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL
|
||||
AND activity.kind IN (
|
||||
'user-input.requested',
|
||||
'user-input.resolved',
|
||||
'provider.user-input.respond.failed'
|
||||
)
|
||||
) AS latest
|
||||
WHERE latest.row_number = 1
|
||||
)
|
||||
SELECT COUNT(*)
|
||||
FROM latest_user_input_states
|
||||
WHERE latest_user_input_states.kind = 'user-input.requested'
|
||||
OR (
|
||||
latest_user_input_states.kind = 'provider.user-input.respond.failed'
|
||||
AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'
|
||||
AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'
|
||||
)
|
||||
), 0),
|
||||
has_actionable_proposed_plan = COALESCE((
|
||||
SELECT CASE
|
||||
WHEN projection_threads.latest_turn_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan_exists
|
||||
WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_turn_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_turn_plan
|
||||
WHERE latest_turn_plan.thread_id = projection_threads.thread_id
|
||||
AND latest_turn_plan.turn_id = projection_threads.latest_turn_id
|
||||
ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_proposed_plans AS any_plan
|
||||
WHERE any_plan.thread_id = projection_threads.thread_id
|
||||
)
|
||||
THEN CASE
|
||||
WHEN (
|
||||
SELECT latest_plan.implemented_at
|
||||
FROM projection_thread_proposed_plans AS latest_plan
|
||||
WHERE latest_plan.thread_id = projection_threads.thread_id
|
||||
ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC
|
||||
LIMIT 1
|
||||
) IS NULL
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
ELSE 0
|
||||
END
|
||||
), 0)
|
||||
`;
|
||||
});
|
||||
@@ -15,7 +15,7 @@ import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as ServiceMap from "effect/ServiceMap";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
|
||||
import * as Client from "effect/unstable/sql/SqlClient";
|
||||
@@ -32,7 +32,7 @@ export type TypeId = "~local/sqlite-node/SqliteClient";
|
||||
/**
|
||||
* SqliteClient - Effect service tag for the sqlite SQL client.
|
||||
*/
|
||||
export const SqliteClient = ServiceMap.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
|
||||
export const SqliteClient = Context.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
|
||||
|
||||
export interface SqliteClientConfig {
|
||||
readonly filename: string;
|
||||
@@ -120,7 +120,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
|
||||
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
@@ -200,7 +200,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
|
||||
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
|
||||
const fiber = Fiber.getCurrent()!;
|
||||
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
|
||||
const scope = Context.getUnsafe(fiber.context, Scope.Scope);
|
||||
return Effect.as(
|
||||
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
|
||||
connection,
|
||||
@@ -251,27 +251,27 @@ const makeMemory = (
|
||||
export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
Layer.effectServices(
|
||||
Layer.effectContext(
|
||||
Config.unwrap(config)
|
||||
.asEffect()
|
||||
.pipe(
|
||||
Effect.flatMap(make),
|
||||
Effect.map((client) =>
|
||||
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
|
||||
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
|
||||
Layer.effectServices(
|
||||
Layer.effectContext(
|
||||
Effect.map(make(config), (client) =>
|
||||
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
|
||||
export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
|
||||
Layer.effectServices(
|
||||
Layer.effectContext(
|
||||
Effect.map(makeMemory(config), (client) =>
|
||||
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
).pipe(Layer.provide(Reactivity.layer));
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import { Option, Schema, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { AuthPairingLinkRepositoryError } from "../Errors.ts";
|
||||
@@ -70,7 +70,7 @@ export interface AuthPairingLinkRepositoryShape {
|
||||
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
|
||||
}
|
||||
|
||||
export class AuthPairingLinkRepository extends ServiceMap.Service<
|
||||
export class AuthPairingLinkRepository extends Context.Service<
|
||||
AuthPairingLinkRepository,
|
||||
AuthPairingLinkRepositoryShape
|
||||
>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import { Option, Schema, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { AuthSessionRepositoryError } from "../Errors.ts";
|
||||
@@ -87,7 +87,7 @@ export interface AuthSessionRepositoryShape {
|
||||
) => Effect.Effect<void, AuthSessionRepositoryError>;
|
||||
}
|
||||
|
||||
export class AuthSessionRepository extends ServiceMap.Service<
|
||||
export class AuthSessionRepository extends Context.Service<
|
||||
AuthSessionRepository,
|
||||
AuthSessionRepositoryShape
|
||||
>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {}
|
||||
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user