Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7154e7cec3 | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb |
No files matched your search
@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -286,6 +302,12 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -114,18 +115,60 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -18,16 +19,25 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -44,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -81,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
@@ -97,6 +109,8 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -250,6 +264,197 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -511,6 +716,178 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -378,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
artifactDirectory: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<never>();
|
||||
@@ -854,11 +857,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
commandParams?: Record<string, unknown>,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
|
||||
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
|
||||
send: SendCommand,
|
||||
enableRuntime: boolean,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
...(enableRuntime ? [send("Runtime.enable")] : []),
|
||||
send("Input.setIgnoreInputEvents", { ignore: false }),
|
||||
],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
action: string,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -899,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
return yield* use(send);
|
||||
// Cleanup commands must still run after human input invalidates the action's
|
||||
// control epoch. Otherwise a partially dispatched input can leave Chromium
|
||||
// with a held key or focus emulation enabled for subsequent actions.
|
||||
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
|
||||
function* (method, commandParams) {
|
||||
return yield* attemptPromise(
|
||||
{
|
||||
operation: `${action}.cleanup.${method}`,
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
return yield* use(send, sendCleanup);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1091,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
const navStatus =
|
||||
preserveLoadFailure &&
|
||||
current.navStatus.kind === "LoadFailed" &&
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
description: string,
|
||||
validatedUrl: string,
|
||||
isMainFrame: boolean,
|
||||
): void => {
|
||||
if (code === -3 || !isMainFrame) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: wc.getURL(),
|
||||
url: validatedUrl || wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1161,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1173,8 +1244,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1280,21 +1351,40 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
}
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(tab.zoomFactor);
|
||||
return tab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
@@ -1313,6 +1403,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1330,11 +1421,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
@@ -1946,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
yield* prepareAutomationInput(send, true);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2011,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2021,8 +2104,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const locatorJson = locator
|
||||
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
|
||||
: null;
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
const result = yield* evaluateWithDebugger<
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2030,12 +2120,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try {
|
||||
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
|
||||
if (!element) return { notFound: true };
|
||||
const textControl =
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
(element instanceof HTMLInputElement &&
|
||||
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
|
||||
const editable = textControl || element.isContentEditable;
|
||||
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
|
||||
element.focus();
|
||||
if (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
if (document.activeElement !== element) return { notEditable: true };
|
||||
const clear = ${input.clear ?? false};
|
||||
if (clear) {
|
||||
if (textControl) {
|
||||
element.select();
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = document.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
const text = ${textJson};
|
||||
let inserted = true;
|
||||
if (text.length > 0) {
|
||||
inserted = document.execCommand("insertText", false, text);
|
||||
} else if (clear) {
|
||||
document.execCommand("delete", false);
|
||||
const cleared = textControl
|
||||
? element.value.length === 0
|
||||
: (element.textContent ?? "").length === 0;
|
||||
if (!cleared) {
|
||||
if (textControl) {
|
||||
const prototype = element instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype;
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
||||
if (valueSetter) valueSetter.call(element, "");
|
||||
else element.value = "";
|
||||
} else {
|
||||
element.replaceChildren();
|
||||
}
|
||||
element.dispatchEvent(new InputEvent("input", {
|
||||
bubbles: true,
|
||||
inputType: "deleteContentBackward",
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!inserted) return { notEditable: true };
|
||||
element.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { invalidSelector: true, message: String(error) };
|
||||
@@ -2059,6 +2191,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
if ("notEditable" in result) {
|
||||
return yield* new PreviewAutomationTargetNotEditableError({
|
||||
tabId,
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
|
||||
@@ -2066,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* send("Runtime.enable");
|
||||
yield* focusAutomationTarget(tabId, send, input);
|
||||
yield* send("Input.insertText", { text: input.text });
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
yield* evaluateWithDebugger(
|
||||
tabId,
|
||||
send,
|
||||
`(() => {
|
||||
const element = document.activeElement;
|
||||
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
|
||||
element?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`,
|
||||
false,
|
||||
);
|
||||
// CDP Input.insertText silently drops text until Electron has activated a hidden
|
||||
// guest WebContents with a pointer event. Editing in the page runtime keeps
|
||||
// background automation deterministic without stealing foreground app focus.
|
||||
yield* typeIntoAutomationTarget(tabId, send, input);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2097,32 +2222,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
input: PreviewAutomationPressInput,
|
||||
send: SendCommand,
|
||||
sendCleanup: SendCommand,
|
||||
) {
|
||||
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
yield* prepareAutomationInput(send, false);
|
||||
const keySequence = makePreviewAutomationKeySequence(input, {
|
||||
isMac: hostPlatform === "darwin",
|
||||
});
|
||||
const previouslyFocused = yield* attempt(
|
||||
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
|
||||
() => webContents.getFocusedWebContents(),
|
||||
);
|
||||
let keyDownAttempted = false;
|
||||
const releaseInput = Effect.gen(function* () {
|
||||
if (keyDownAttempted) {
|
||||
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
|
||||
}
|
||||
}, 0);
|
||||
const key = input.key;
|
||||
const text = key.length === 1 ? key : undefined;
|
||||
const params = {
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
modifiers,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
};
|
||||
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
|
||||
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "automationPress.restoreFocusedWebContents",
|
||||
tabId,
|
||||
webContentsId: previouslyFocused.id,
|
||||
},
|
||||
() => previouslyFocused.focus(),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
// Focus the guest WebContents itself, not its containing BrowserWindow. This
|
||||
// activates native keyboard behavior for hidden/background previews without
|
||||
// changing which thread is mounted in the UI. Restore the previous renderer
|
||||
// after dispatch so automation never leaves the app's input focus behind.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* attempt(
|
||||
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
|
||||
() => wc.focus(),
|
||||
);
|
||||
yield* send("Page.bringToFront");
|
||||
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
|
||||
yield* expectAgentInput(tabId, keySequence.signal);
|
||||
keyDownAttempted = true;
|
||||
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
|
||||
}).pipe(Effect.ensuring(releaseInput));
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2130,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2529,6 +2676,20 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
|
||||
"PreviewAutomationTargetNotEditableError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
selectorKind: PreviewAutomationSelectorKind,
|
||||
selectorLength: Schema.optionalKey(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
|
||||
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
|
||||
"PreviewAutomationCoordinatesOutsideViewportError",
|
||||
{
|
||||
@@ -2631,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
@@ -47,12 +48,14 @@ function makeFakeBrowserWindow() {
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
replaceMisspelling: vi.fn(),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
@@ -79,6 +82,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -237,6 +241,73 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
if (!didFailLoad || !didFinishLoad) {
|
||||
return yield* Effect.die("renderer load listeners were not registered");
|
||||
}
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(100);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
|
||||
["t3code-dev://app/"],
|
||||
["t3code-dev://app/"],
|
||||
]);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
didFinishLoad();
|
||||
yield* TestClock.adjust(250);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it("retries only transient failures for the development renderer", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -3,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "https://example.com/",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -22,6 +23,16 @@ 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";
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
|
||||
-102, // ERR_CONNECTION_REFUSED
|
||||
-105, // ERR_NAME_NOT_RESOLVED
|
||||
-106, // ERR_INTERNET_DISCONNECTED
|
||||
-118, // ERR_CONNECTION_TIMED_OUT
|
||||
]);
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
Electron.BrowserWindowConstructorOptions,
|
||||
@@ -86,6 +97,22 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly errorCode: number;
|
||||
readonly isMainFrame: boolean;
|
||||
readonly validatedUrl: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isMainFrame &&
|
||||
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
|
||||
isSameOriginRendererNavigation({
|
||||
applicationUrl: input.applicationUrl,
|
||||
navigationUrl: input.validatedUrl,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -152,6 +179,7 @@ export const make = Effect.gen(function* () {
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
@@ -277,7 +305,61 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -286,11 +368,22 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -312,14 +405,13 @@ export const make = Effect.gen(function* () {
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^6.0.4"
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -93,9 +93,9 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -30,7 +30,9 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow, selectedProject]);
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -91,7 +92,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -447,9 +448,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
void onSendMessage();
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
@@ -13,8 +16,8 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -25,7 +28,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -73,7 +76,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -206,25 +209,33 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const composerRef = useRef<ComposerEditorHandle>(null);
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
|
||||
const selectedThreadKeyRef = useRef(selectedThreadKey);
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight,
|
||||
measuredOverlayHeight,
|
||||
gap: 8,
|
||||
});
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
|
||||
@@ -254,15 +265,67 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
|
||||
contentPresentationKind !== "ready" ||
|
||||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
anchorMessageId,
|
||||
freeze,
|
||||
contentPresentationKind,
|
||||
selectedThreadFeed,
|
||||
scrollMessageToEnd,
|
||||
selectedThreadKey,
|
||||
]);
|
||||
|
||||
const handleSendMessage = useCallback(async () => {
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const messageId = await props.onSendMessage();
|
||||
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
setAnchorMessageId(messageId);
|
||||
composerEditorRef.current?.blur();
|
||||
return messageId;
|
||||
}, [props.onSendMessage, selectedThreadKey]);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerRef.current?.blur();
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -315,10 +378,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -332,7 +398,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -361,7 +427,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerRef}
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -380,7 +446,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -15,8 +25,6 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -29,6 +37,7 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -64,14 +73,11 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -93,10 +99,13 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -812,30 +821,6 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-base leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
@@ -1122,17 +1107,12 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const suppressAutoFollowRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const isNearEndRef = useRef(true);
|
||||
const initialScrollReadyRef = useRef(false);
|
||||
const lastContentHeightRef = useRef(0);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1214,6 +1194,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
for (const entry of props.feed) {
|
||||
@@ -1229,54 +1219,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1308,9 +1250,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1358,7 +1297,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
suppressAutoFollowRef.current = true;
|
||||
setFoldToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1376,7 +1315,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
suppressAutoFollowRef.current = false;
|
||||
setFoldToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
@@ -1458,59 +1397,60 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
foldToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThread}
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
);
|
||||
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
},
|
||||
[selectedModel, selectedModelIdentity],
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedProject],
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -359,7 +359,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -399,7 +399,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -10,7 +9,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -88,13 +86,6 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -104,7 +95,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1255,8 +1246,6 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1273,13 +1262,6 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
export interface ThreadFeedScrollMetrics {
|
||||
readonly contentHeight: number;
|
||||
readonly viewportHeight: number;
|
||||
readonly offsetY: number;
|
||||
readonly bottomInset: number;
|
||||
}
|
||||
|
||||
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
|
||||
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
|
||||
}
|
||||
|
||||
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
|
||||
return threadFeedDistanceFromEnd(metrics) <= threshold;
|
||||
}
|
||||
|
||||
export function resolveThreadFeedBottomInset(input: {
|
||||
readonly estimatedOverlayHeight: number;
|
||||
readonly measuredOverlayHeight: number;
|
||||
readonly gap: number;
|
||||
}): number {
|
||||
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
|
||||
}
|
||||
@@ -1,32 +1,38 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -40,9 +46,37 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -119,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
@@ -66,6 +76,54 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -271,4 +329,23 @@ describe("thread outbox", () => {
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains queued messages when settings synchronization fails before startTurn", () => {
|
||||
const deterministicFailure = new Error("Thread no longer exists");
|
||||
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "settings-sync",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("retry");
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "start-turn",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,136 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
composerDraftsAtom,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftsForEnvironment,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
it("hydrates selector state even when the message content is empty", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": DRAFT,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": DRAFT,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": {
|
||||
...DRAFT,
|
||||
runtimeMode: "sometimes-safe",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("clears sent content without clearing the selected model or workspace", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
|
||||
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
|
||||
removeComposerDraftsForEnvironment(
|
||||
{
|
||||
[`${environmentId}:thread-cloud`]: DRAFT,
|
||||
[`new-task:${environmentId}:project-cloud`]: DRAFT,
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
},
|
||||
environmentId,
|
||||
),
|
||||
).toEqual({
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,18 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
interface PersistedComposerDrafts {
|
||||
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
ComposerDraft,
|
||||
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
|
||||
>;
|
||||
|
||||
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
|
||||
});
|
||||
|
||||
const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
PersistedComposerDraftsSchema,
|
||||
);
|
||||
|
||||
const EMPTY_DRAFT: ComposerDraft = {
|
||||
text: "",
|
||||
attachments: [],
|
||||
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
return EMPTY_DRAFT;
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
text: draft.text,
|
||||
attachments: draft.attachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return draft.text.length === 0 && draft.attachments.length === 0;
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
draft.attachments.length === 0 &&
|
||||
draft.modelSelection === undefined &&
|
||||
draft.runtimeMode === undefined &&
|
||||
draft.interactionMode === undefined &&
|
||||
draft.workspaceSelection === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
}
|
||||
|
||||
async function getComposerDraftsFile() {
|
||||
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
|
||||
const draft = entry[1];
|
||||
return (
|
||||
typeof draft?.text === "string" &&
|
||||
Array.isArray(draft.attachments) &&
|
||||
!isEmptyDraft(draft)
|
||||
);
|
||||
}),
|
||||
);
|
||||
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document: PersistedComposerDrafts = {
|
||||
const document = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
};
|
||||
} as const;
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
): void {
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
...settings,
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const draft = {
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): Record<string, ComposerDraft> {
|
||||
const environmentPrefix = `${environmentId}:`;
|
||||
const newTaskPrefix = `new-task:${environmentId}:`;
|
||||
return Object.fromEntries(
|
||||
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
|
||||
Object.entries(drafts).filter(
|
||||
([draftKey]) =>
|
||||
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
appendComposerDraftText,
|
||||
clearComposerDraft,
|
||||
clearComposerDraftContent,
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
@@ -30,7 +40,6 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -67,7 +76,6 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -81,23 +89,19 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
@@ -111,7 +115,6 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -121,51 +124,52 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
queuedSendStartedAt,
|
||||
null,
|
||||
);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = composerDrafts[threadKey];
|
||||
const text = (draft?.text ?? "").trim();
|
||||
const attachments = draft?.attachments ?? [];
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraft(threadKey);
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -255,12 +259,45 @@ export function useThreadComposerState() {
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = useCallback(
|
||||
(value: ModelSelection) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
@@ -268,5 +305,8 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
onUpdateInteractionMode,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
@@ -44,8 +48,21 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "model-selection"),
|
||||
threadId: queuedMessage.threadId,
|
||||
modelSelection: settings.modelSelection,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(updateResult)) {
|
||||
reportFailure(updateResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.runtimeMode !== thread.runtimeMode) {
|
||||
const runtimeResult = await setThreadRuntimeMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(runtimeResult)) {
|
||||
reportFailure(runtimeResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.interactionMode !== thread.interactionMode) {
|
||||
const interactionResult = await setThreadInteractionMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(interactionResult)) {
|
||||
reportFailure(interactionResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(deliveryResult)) {
|
||||
const error = Cause.squash(deliveryResult.cause);
|
||||
const retry =
|
||||
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
cause: deliveryResult.cause,
|
||||
retry,
|
||||
});
|
||||
if (retry) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return completeDelivery(deliveryResult);
|
||||
},
|
||||
[startTurn],
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -33,13 +33,17 @@ import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
|
||||
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import * as ProviderService from "../src/provider/ProviderService.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
|
||||
@@ -174,7 +178,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService.ProviderService["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
|
||||
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
|
||||
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
|
||||
@@ -237,7 +241,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistry,
|
||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
||||
)
|
||||
: null;
|
||||
@@ -258,11 +262,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexSettings = yield* decodeCodexSettings({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
@@ -275,18 +279,15 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
||||
const providerLayer = useRealCodex
|
||||
? ProviderService.layer.pipe(
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
)
|
||||
: ProviderService.layer.pipe(
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
@@ -394,7 +395,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService.ProviderService)),
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
|
||||
|
||||
@@ -206,16 +206,21 @@ function nowIso(): string {
|
||||
return "2026-01-01T00:00:00.000Z";
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
}),
|
||||
);
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
@@ -512,12 +517,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
}),
|
||||
),
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,13 +10,20 @@ import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
|
||||
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
|
||||
import * as ProviderService from "../src/provider/ProviderService.ts";
|
||||
import * as ServerSettings from "../src/serverSettings.ts";
|
||||
import * as AnalyticsService from "../src/telemetry/AnalyticsService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
|
||||
|
||||
@@ -44,7 +51,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService.ProviderService, unknown, never>;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
@@ -55,22 +62,19 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry),
|
||||
ServerSettings.ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = ProviderService.layer.pipe(Layer.provide(shared));
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
@@ -101,7 +105,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
});
|
||||
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderService.ProviderService["Service"];
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
@@ -125,7 +129,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -162,7 +166,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -199,7 +203,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -251,7 +255,7 @@ it.live("rolls back provider conversation state only", () =>
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
|
||||
@@ -19,6 +19,23 @@ const emitInterleavedAssistantToolCalls =
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
|
||||
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
|
||||
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
|
||||
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
|
||||
const emitStaleXAiPromptCompleteBeforeSecondHang =
|
||||
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
|
||||
const emitOverlappingXAiPromptCompleteOutOfOrder =
|
||||
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
|
||||
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
@@ -36,8 +53,21 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let promptCount = 0;
|
||||
let overlappingFirstPromptId: string | undefined;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function promptIdFromRequestMeta(
|
||||
request: Pick<AcpSchema.PromptRequest, "_meta">,
|
||||
): string | undefined {
|
||||
const meta = request._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
@@ -45,6 +75,10 @@ function logExit(reason: string): void {
|
||||
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
@@ -284,22 +318,66 @@ const program = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const emitLoadReplayNotifications = (requestedSessionId: string) => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "replay-tool-1",
|
||||
title: "Replay tool",
|
||||
kind: "search",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
_meta: { isReplay: true },
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed assistant text" },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (failLoadSession) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
|
||||
}
|
||||
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay-tail" },
|
||||
},
|
||||
});
|
||||
yield* Effect.sleep(loadSessionDelayMs);
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}
|
||||
if (emitLoadReplay) {
|
||||
emitLoadReplayNotifications(requestedSessionId);
|
||||
}
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -356,19 +434,152 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
Effect.gen(function* () {
|
||||
const cancelledSessionId = String(sessionId ?? "mock-session-1");
|
||||
cancelledSessions.add(cancelledSessionId);
|
||||
if (emitLateUpdateAfterCancel) {
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "late after cancel" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
promptCount += 1;
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (failPrompt) {
|
||||
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
|
||||
return {
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
requestId: "mock-stale-xai-prompt-1",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
|
||||
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: "mock-stale-xai-prompt-1",
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: currentPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
|
||||
overlappingFirstPromptId = promptIdFromRequestMeta(request);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
|
||||
const secondPromptId = promptIdFromRequestMeta(request);
|
||||
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: secondPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: overlappingFirstPromptId,
|
||||
stopReason: "end_turn",
|
||||
agentResult: null,
|
||||
});
|
||||
}
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from " },
|
||||
},
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child before completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
|
||||
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
|
||||
agentResult: null,
|
||||
});
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child after completion" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -599,6 +810,42 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitForeignSessionUpdates) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "root before child" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "child content" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: "mock-child-session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "child-tool-call-1",
|
||||
title: "Child-only tool",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: " root after child" },
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,11 +104,29 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
|
||||
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
|
||||
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
|
||||
expect(sessionError.cause).toBe(repositoryFailure);
|
||||
expect(websocketError.cause).toBe(repositoryFailure);
|
||||
if (sessionError._tag === "SessionCredentialVerificationError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
if (websocketError._tag === "WebSocketTokenVerificationError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
expect(revokeError).toMatchObject({
|
||||
_tag: "SessionRevocationError",
|
||||
sessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
expect(revokeOthersError).toMatchObject({
|
||||
_tag: "OtherSessionsRevocationError",
|
||||
currentSessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
expect(error._tag).toBe("WebSocketSessionExpiredError");
|
||||
if (error._tag === "WebSocketSessionExpiredError") {
|
||||
expect(error.sessionId).toBe(issued.sessionId);
|
||||
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
error.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("includes expiry context when session and websocket tokens expire", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-access-token",
|
||||
subject: "short-lived-token",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionTokenExpiredError");
|
||||
if (sessionError._tag === "SessionTokenExpiredError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
sessionError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
|
||||
if (websocketError._tag === "WebSocketTokenExpiredError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
expect(websocketError.expiresAt.epochMilliseconds).toBe(
|
||||
websocket.expiresAt.epochMilliseconds,
|
||||
);
|
||||
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
websocketError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -173,12 +236,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
const revokedClientWebSocket = yield* Effect.flip(
|
||||
sessions.verifyWebSocketToken(clientWebSocket.token),
|
||||
);
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
|
||||
if (revokedClient._tag === "SessionTokenRevokedError") {
|
||||
expect(revokedClient.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
|
||||
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
|
||||
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type AuthEnvironmentScope,
|
||||
type ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -93,7 +92,11 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
|
||||
|
||||
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
|
||||
"SessionTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token expired.";
|
||||
@@ -102,7 +105,9 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
|
||||
"UnknownSessionTokenError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown session token.";
|
||||
@@ -111,7 +116,10 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
|
||||
|
||||
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
|
||||
"SessionTokenRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token revoked.";
|
||||
@@ -120,7 +128,10 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
|
||||
"InvalidSessionExpirationClaimError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expirationClaim: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid `exp` claim";
|
||||
@@ -158,7 +169,11 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
|
||||
|
||||
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
|
||||
"WebSocketTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket token expired.";
|
||||
@@ -167,7 +182,9 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
|
||||
|
||||
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
|
||||
"UnknownWebSocketSessionError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown websocket session.";
|
||||
@@ -176,7 +193,11 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
|
||||
|
||||
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
|
||||
"WebSocketSessionExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session expired.";
|
||||
@@ -185,7 +206,10 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
|
||||
|
||||
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
|
||||
"WebSocketSessionRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session revoked.";
|
||||
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -539,7 +570,11 @@ export const make = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
|
||||
function* (input) {
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_session_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* authSessions
|
||||
.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -604,7 +649,6 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies IssuedSession;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
|
||||
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new SessionTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -652,95 +711,111 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new SessionCredentialVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.issueWebSocketToken",
|
||||
)(
|
||||
function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
)(function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebSocketTokenIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_websocket_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
|
||||
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.verifyWebSocketToken",
|
||||
)(
|
||||
function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
)(function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new WebSocketTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new WebSocketSessionExpiredError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketSessionExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
});
|
||||
|
||||
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -768,10 +843,12 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -782,39 +859,41 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionRevocationError({ cause })),
|
||||
);
|
||||
|
||||
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
|
||||
"SessionStore.revokeAllExcept",
|
||||
)(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
)(function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions
|
||||
.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
|
||||
),
|
||||
);
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
},
|
||||
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
@@ -13,22 +14,6 @@ import {
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||||
const first = value?.split(",")[0]?.trim();
|
||||
return first && first.length > 0 ? first : undefined;
|
||||
}
|
||||
|
||||
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
|
||||
try {
|
||||
return new URL(request.originalUrl).href;
|
||||
} catch {
|
||||
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
|
||||
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
|
||||
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
|
||||
return new URL(request.originalUrl, `${proto}://${host}`).href;
|
||||
}
|
||||
}
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
url: url.value.href,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
|
||||
@@ -44,13 +44,18 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
||||
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
|
||||
|
||||
export const browserApiCorsLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const devOrigin = config.devUrl?.origin;
|
||||
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
|
||||
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
|
||||
return HttpRouter.cors({
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
|
||||
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -34,7 +35,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -54,36 +55,26 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-failure-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const snapshot = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: {} })
|
||||
@@ -163,60 +154,50 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-test-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result:
|
||||
event.request.operation === "snapshot"
|
||||
? {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
}
|
||||
: event.request.operation === "press"
|
||||
? undefined
|
||||
: {
|
||||
available: true,
|
||||
visible: true,
|
||||
tabId,
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
|
||||
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
|
||||
@@ -214,7 +214,4 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -1,20 +1,28 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewTabId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
|
||||
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
const scope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
@@ -22,27 +30,42 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
|
||||
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
type RoutedRequest = PreviewAutomationRequest & {
|
||||
readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
|
||||
};
|
||||
|
||||
const requestsFrom = (
|
||||
events: Stream.Stream<PreviewAutomationStreamEvent>,
|
||||
onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
|
||||
): Stream.Stream<RoutedRequest> =>
|
||||
events.pipe(
|
||||
Stream.filterMap((event) => {
|
||||
if (event.type === "connected") {
|
||||
onConnected(event.connectionId);
|
||||
return Result.failVoid;
|
||||
}
|
||||
return Result.succeed({ ...event.request, connectionId: event.connectionId });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("atomically registers a connected host and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { available: true },
|
||||
@@ -61,6 +84,39 @@ it.effect("atomically registers a connected owner and correlates its response",
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("announces a live replacement stream before delivering requests", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const events = yield* broker.connect(makeHost());
|
||||
const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
|
||||
const consumer = yield* events.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runForEach((event) => {
|
||||
receivedTypes.push(event.type);
|
||||
return event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result: "ready",
|
||||
});
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
yield* Fiber.join(consumer);
|
||||
|
||||
expect(receivedTypes).toEqual(["connected", "request"]);
|
||||
expect(result).toBe("ready");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
const locator = "role=button[name='request-secret']";
|
||||
const remoteMessage = "Unexpected token near remote-secret.";
|
||||
@@ -72,10 +128,12 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
@@ -88,6 +146,7 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
scope,
|
||||
operation: "click",
|
||||
input: { locator },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
timeoutMs: 1_234,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
@@ -121,13 +180,61 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("classifies a remote non-editable target without collapsing it to execution", () => {
|
||||
const remoteError = {
|
||||
_tag: "PreviewAutomationTargetNotEditableError",
|
||||
message: "remote target details",
|
||||
detail: { selectorKind: "focused-element" },
|
||||
} as const;
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({
|
||||
scope,
|
||||
operation: "type",
|
||||
input: { text: "hello" },
|
||||
tabId: PreviewTabId.make("tab-1"),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "type",
|
||||
tabId: "tab-1",
|
||||
selectorKind: "focused-element",
|
||||
remoteTag: "PreviewAutomationTargetNotEditableError",
|
||||
});
|
||||
expect(error.message).toBe("Preview automation type requires an editable focused element.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("distinguishes malformed remote failures", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -150,13 +257,14 @@ it.effect("distinguishes malformed remote failures", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
it.effect("rejects calls when no connected host exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const broker = yield* makeBroker;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
@@ -167,32 +275,425 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
it.effect("does not create host state from focus updates without a live stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-missing",
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removes host availability when the authoritative request stream disconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(
|
||||
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
|
||||
);
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const beforeAcquisition = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Fiber.interrupt(consumer);
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
it.effect("routes requests for background threads through an environment-level host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
const broker = yield* makeBroker;
|
||||
const backgroundThreadId = ThreadId.make("thread-background");
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
let routedThreadId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedThreadId = request.threadId;
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "background",
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const result = yield* broker.invoke<string>({
|
||||
scope: {
|
||||
...scope,
|
||||
threadId: backgroundThreadId,
|
||||
providerSessionId: "provider-session-background",
|
||||
},
|
||||
operation: "status",
|
||||
input: {},
|
||||
});
|
||||
|
||||
expect(result).toBe("background");
|
||||
expect(routedThreadId).toBe(backgroundThreadId);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("never routes a provider session to a host from another environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const matchingRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-matching" })),
|
||||
);
|
||||
const foreignRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({
|
||||
clientId: "client-foreign",
|
||||
environmentId: EnvironmentId.make("environment-foreign"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(matchingRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-matching",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "matching",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(foreignRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"matching",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("pins a provider session to its initial host despite later focus changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let secondConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
(connectionId) => {
|
||||
secondConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: "connection-stale",
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
const firstPinnedScope = {
|
||||
...scope,
|
||||
providerSessionId: "provider-session-first-pinned",
|
||||
};
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-second",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: secondConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
|
||||
).toBe("first");
|
||||
expect(
|
||||
yield* broker.invoke<string>({
|
||||
scope: { ...scope, providerSessionId: "provider-session-second-pinned" },
|
||||
operation: "status",
|
||||
input: {},
|
||||
}),
|
||||
).toBe("second");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not route new operations to legacy hosts that did not advertise support", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyEvents = yield* broker.connect(makeHost());
|
||||
yield* Stream.runDrain(legacyEvents).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(
|
||||
yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
|
||||
).toBe("capable");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const legacyRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
|
||||
);
|
||||
yield* Stream.runForEach(legacyRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-legacy",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "legacy",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
|
||||
const capableRequests = requestsFrom(
|
||||
yield* broker.connect(
|
||||
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
|
||||
),
|
||||
);
|
||||
yield* Stream.runForEach(capableRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-capable",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "capable",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"legacy",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale focus updates for a different environment", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: EnvironmentId.make("environment-stale"),
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails over a pinned provider session only after its host disconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
const firstRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-first" })),
|
||||
(connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
const secondRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost({ clientId: "client-second" })),
|
||||
);
|
||||
const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-first",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "first",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(secondRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-second",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "second",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.focusHost({
|
||||
clientId: "client-first",
|
||||
environmentId: scope.environmentId,
|
||||
connectionId: firstConnectionId,
|
||||
focused: true,
|
||||
});
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
|
||||
|
||||
yield* Fiber.interrupt(firstConsumer);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
|
||||
"second",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab locally", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -203,61 +704,55 @@ it.effect("lets the browser host resolve an active tab that has not been reporte
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let replacementConnectionId = "";
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
});
|
||||
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
|
||||
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
|
||||
|
||||
const reconnectedRequests = yield* broker.connect(makeOwner());
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(reconnectedRequests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
|
||||
expect(routedTabId).toBe("tab-current");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
const replacementRequests = requestsFrom(
|
||||
yield* broker.connect(makeHost()),
|
||||
(connectionId) => {
|
||||
replacementConnectionId = connectionId;
|
||||
},
|
||||
);
|
||||
yield* Stream.runForEach(replacementRequests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "replacement",
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* broker.clearOwner({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: ThreadId.make("thread-stale"),
|
||||
});
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
|
||||
expect(replacementConnectionId).not.toBe(firstConnectionId);
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("replacement");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
@@ -275,25 +770,40 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
it.effect("accepts responses only from the host that received the request", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
Effect.gen(function* () {
|
||||
yield* broker.respond({
|
||||
clientId: "client-foreign",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "foreign",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: "connection-stale",
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "stale",
|
||||
});
|
||||
yield* broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: "owner",
|
||||
});
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* broker.reportOwner(
|
||||
makeOwner({
|
||||
clientId: "client-report-only",
|
||||
focusedAt: "2026-06-11T00:00:01.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
|
||||
expect(result).toBe("connected");
|
||||
expect(result).toBe("owner");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,26 +1,29 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -43,12 +46,9 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -60,7 +60,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -69,6 +74,13 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly queue: ClientConnection["queue"];
|
||||
readonly expiresAt: number;
|
||||
}
|
||||
|
||||
interface PreviewAutomationRequestErrorContext {
|
||||
readonly operation: PreviewAutomationOperation;
|
||||
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
|
||||
@@ -76,6 +88,7 @@ interface PreviewAutomationRequestErrorContext {
|
||||
readonly providerSessionId: string;
|
||||
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
|
||||
readonly clientId: string;
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
readonly requestId: string;
|
||||
readonly tabId?: PreviewTabId;
|
||||
readonly timeoutMs: number;
|
||||
@@ -85,11 +98,36 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
readonly pending: ReadonlyMap<string, PendingRequest>;
|
||||
readonly requestSequence: number;
|
||||
readonly focusSequence: number;
|
||||
}
|
||||
|
||||
const removeConnectionFromState = (
|
||||
current: BrokerState,
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
|
||||
const clients = new Map(current.clients);
|
||||
const assignments = new Map(current.assignments);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
|
||||
for (const [assignmentKey, assignment] of assignments) {
|
||||
if (assignment.queue === queue) assignments.delete(assignmentKey);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue !== queue) continue;
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
return {
|
||||
state: { ...current, clients, assignments, pending },
|
||||
disconnected,
|
||||
};
|
||||
};
|
||||
|
||||
const selectorDiagnosticsFromInput = (
|
||||
input: unknown,
|
||||
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
|
||||
@@ -103,6 +141,14 @@ const selectorDiagnosticsFromInput = (
|
||||
return {};
|
||||
};
|
||||
|
||||
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
|
||||
`${scope.environmentId}\u0000${scope.providerSessionId}`;
|
||||
|
||||
const supportsOperation = (
|
||||
connection: ClientConnection,
|
||||
operation: PreviewAutomationOperation,
|
||||
): boolean => connection.supportedOperations.has(operation);
|
||||
|
||||
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
|
||||
|
||||
function remoteDetailKind(detail: unknown): RemoteDetailKind {
|
||||
@@ -131,8 +177,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -162,6 +208,36 @@ const classifyResponseError = (
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationTargetNotEditableError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
const remoteSelectorKind =
|
||||
detail &&
|
||||
"selectorKind" in detail &&
|
||||
(detail.selectorKind === "focused-element" ||
|
||||
detail.selectorKind === "locator" ||
|
||||
detail.selectorKind === "selector")
|
||||
? detail.selectorKind
|
||||
: undefined;
|
||||
const remoteSelectorLength =
|
||||
detail &&
|
||||
"selectorLength" in detail &&
|
||||
typeof detail.selectorLength === "number" &&
|
||||
Number.isInteger(detail.selectorLength) &&
|
||||
detail.selectorLength >= 0
|
||||
? detail.selectorLength
|
||||
: undefined;
|
||||
return new PreviewAutomationTargetNotEditableError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
...(remoteSelectorKind === undefined && context.selectorKind === undefined
|
||||
? {}
|
||||
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
|
||||
...(remoteSelectorLength === undefined && context.selectorLength === undefined
|
||||
? {}
|
||||
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
|
||||
});
|
||||
}
|
||||
case "PreviewAutomationResultTooLargeError": {
|
||||
const detail =
|
||||
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
|
||||
@@ -193,36 +269,21 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
assignments: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
queue: ClientConnection["queue"],
|
||||
disconnected: ReadonlyArray<PendingRequest>,
|
||||
) {
|
||||
const toFail = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const pending = new Map(current.pending);
|
||||
const disconnected: PendingRequest[] = [];
|
||||
if (current.clients.get(clientId)?.queue === queue) {
|
||||
clients.delete(clientId);
|
||||
owners.delete(clientId);
|
||||
}
|
||||
for (const [requestId, entry] of pending) {
|
||||
if (entry.queue === queue) {
|
||||
pending.delete(requestId);
|
||||
disconnected.push(entry);
|
||||
}
|
||||
}
|
||||
return [disconnected, { ...current, clients, owners, pending }] as const;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
toFail,
|
||||
disconnected,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -230,54 +291,89 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
yield* Queue.shutdown(queue);
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
queue: ClientConnection["queue"],
|
||||
) {
|
||||
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const removed = removeConnectionFromState(current, clientId, queue);
|
||||
return [removed.disconnected, removed.state] as const;
|
||||
});
|
||||
yield* closeConnection(queue, disconnected);
|
||||
});
|
||||
|
||||
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
|
||||
host: PreviewAutomationHost,
|
||||
) {
|
||||
const clientId = host.clientId;
|
||||
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
|
||||
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
|
||||
yield* Queue.offer(queue, { type: "connected", connectionId });
|
||||
const connection: ClientConnection = {
|
||||
clientId,
|
||||
connectionId,
|
||||
environmentId: host.environmentId,
|
||||
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
|
||||
focused: false,
|
||||
focusOrder: 0,
|
||||
queue,
|
||||
};
|
||||
const registration = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const previousConnection = current.clients.get(clientId);
|
||||
const removed = previousConnection
|
||||
? removeConnectionFromState(current, clientId, previousConnection.queue)
|
||||
: { state: current, disconnected: [] };
|
||||
const clients = new Map(removed.state.clients);
|
||||
const focusSequence = removed.state.focusSequence + 1;
|
||||
const registeredConnection = { ...connection, focusOrder: focusSequence };
|
||||
clients.set(clientId, registeredConnection);
|
||||
return [
|
||||
{
|
||||
previousConnection,
|
||||
disconnected: removed.disconnected,
|
||||
registeredConnection,
|
||||
},
|
||||
{ ...removed.state, clients, focusSequence },
|
||||
] as const;
|
||||
});
|
||||
if (registration.previousConnection) {
|
||||
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
|
||||
}
|
||||
return registration.registeredConnection;
|
||||
});
|
||||
|
||||
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
|
||||
"PreviewAutomationBroker.connect",
|
||||
)(function* (owner) {
|
||||
const clientId = owner.clientId;
|
||||
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
|
||||
const previous = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const clients = new Map(current.clients);
|
||||
const owners = new Map(current.owners);
|
||||
const existingOwner = current.owners.get(clientId);
|
||||
clients.set(clientId, { clientId, queue });
|
||||
owners.set(
|
||||
clientId,
|
||||
existingOwner?.environmentId === owner.environmentId &&
|
||||
existingOwner.threadId === owner.threadId
|
||||
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
|
||||
: owner,
|
||||
);
|
||||
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
|
||||
});
|
||||
if (previous) yield* disconnect(clientId, previous.queue);
|
||||
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
|
||||
});
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const owners = new Map(current.owners);
|
||||
owners.set(owner.clientId, owner);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.clearOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentOwner = current.owners.get(owner.clientId);
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
if (
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
const clients = new Map(current.clients);
|
||||
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
|
||||
clients.set(host.clientId, {
|
||||
...currentHost,
|
||||
focused: host.focused,
|
||||
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
|
||||
});
|
||||
return { ...current, clients, focusSequence };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -286,7 +382,13 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
)(function* (response) {
|
||||
const pending = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const entry = current.pending.get(response.requestId);
|
||||
if (!entry) return [undefined, current] as const;
|
||||
if (
|
||||
!entry ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -307,52 +409,60 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
|
||||
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
|
||||
): Effect.fn.Return<A, PreviewAutomationError> {
|
||||
const current = yield* SynchronizedRef.get(state);
|
||||
const candidates = Array.from(current.owners.values())
|
||||
.filter(
|
||||
(owner) =>
|
||||
owner.environmentId === input.scope.environmentId &&
|
||||
owner.threadId === input.scope.threadId &&
|
||||
owner.supportsAutomation,
|
||||
)
|
||||
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
|
||||
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
|
||||
if (!owner) {
|
||||
const disconnectedOwner = candidates[0];
|
||||
if (disconnectedOwner) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: disconnectedOwner.clientId,
|
||||
});
|
||||
}
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const connection = current.clients.get(owner.clientId);
|
||||
if (!connection) {
|
||||
return yield* new PreviewAutomationHostNotConnectedError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
});
|
||||
}
|
||||
const timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
|
||||
const requestId = `preview-${next.requestSequence}`;
|
||||
const tabId = input.tabId ?? owner.tabId ?? undefined;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const route = yield* SynchronizedRef.modify(state, (current) => {
|
||||
const assignments = new Map(
|
||||
Array.from(current.assignments).filter(([, assignment]) => {
|
||||
const connection = current.clients.get(assignment.clientId);
|
||||
return (
|
||||
assignment.expiresAt > now &&
|
||||
connection?.connectionId === assignment.connectionId &&
|
||||
connection.queue === assignment.queue
|
||||
);
|
||||
}),
|
||||
);
|
||||
const assignmentKey = hostAssignmentKey(input.scope);
|
||||
const assigned = assignments.get(assignmentKey);
|
||||
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
|
||||
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
|
||||
// Keep one provider session on one physical desktop runtime so a
|
||||
// multi-step browser interaction cannot jump between independent
|
||||
// Electron cookie/DOM state. A live assignment that predates an
|
||||
// operation is not silently moved to a newer client: the caller gets a
|
||||
// capability failure and can deliberately start a fresh provider
|
||||
// session. A dead lease is pruned above and may fail over.
|
||||
const connection =
|
||||
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
|
||||
? assignedConnection
|
||||
: hasLiveAssignment
|
||||
? undefined
|
||||
: Array.from(current.clients.values())
|
||||
.filter(
|
||||
(host) =>
|
||||
host.environmentId === input.scope.environmentId &&
|
||||
supportsOperation(host, input.operation),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.supportedOperations.size - left.supportedOperations.size ||
|
||||
Number(right.focused) - Number(left.focused) ||
|
||||
right.focusOrder - left.focusOrder,
|
||||
)[0];
|
||||
if (!connection) {
|
||||
if (!hasLiveAssignment) assignments.delete(assignmentKey);
|
||||
return [undefined, { ...current, assignments }] as const;
|
||||
}
|
||||
assignments.set(assignmentKey, {
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
queue: connection.queue,
|
||||
expiresAt: input.scope.expiresAt,
|
||||
});
|
||||
|
||||
const requestId = `preview-${current.requestSequence}`;
|
||||
const tabId = input.tabId;
|
||||
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
@@ -360,19 +470,30 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext } = route;
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -381,12 +502,16 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -404,7 +529,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -39,6 +40,8 @@ const handlers = {
|
||||
reuseExistingTab: input.reuseExistingTab ?? true,
|
||||
}),
|
||||
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
|
||||
preview_resize: (input) =>
|
||||
invoke<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
|
||||
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
@@ -35,7 +37,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
|
||||
export const PreviewStatusTool = Tool.make("preview_status", {
|
||||
description:
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -69,6 +71,19 @@ export const PreviewNavigateTool = safeBrowserTool(
|
||||
}).annotate(Tool.Title, "Navigate browser preview"),
|
||||
);
|
||||
|
||||
export const PreviewResizeTool = safeBrowserTool(
|
||||
Tool.make("preview_resize", {
|
||||
description:
|
||||
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
|
||||
parameters: PreviewAutomationResizeInput,
|
||||
success: PreviewAutomationResizeResult,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Resize browser viewport")
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
@@ -168,6 +183,7 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -183,6 +199,7 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -49,7 +49,10 @@ import {
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
|
||||
@@ -99,7 +102,7 @@ function createProviderServiceHarness(
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderSession>)
|
||||
: Effect.succeed([] as ReadonlyArray<ProviderSession>);
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -325,7 +328,7 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -80,7 +80,7 @@ const make = Effect.gen(function* () {
|
||||
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
|
||||
@@ -37,7 +37,10 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
@@ -219,12 +222,8 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||
const respondToRequest = vi.fn<ProviderService.ProviderService["Service"]["respondToRequest"]>(
|
||||
() => Effect.void,
|
||||
);
|
||||
const respondToUserInput = vi.fn<
|
||||
ProviderService.ProviderService["Service"]["respondToUserInput"]
|
||||
>(() => Effect.void);
|
||||
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
|
||||
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
|
||||
const stopSession = vi.fn((input: unknown) =>
|
||||
Effect.sync(() => {
|
||||
const threadId =
|
||||
@@ -295,15 +294,13 @@ describe("ProviderCommandReactor", () => {
|
||||
];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
startSession: startSession as ProviderService.ProviderService["Service"]["startSession"],
|
||||
sendTurn: sendTurn as ProviderService.ProviderService["Service"]["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderService.ProviderService["Service"]["interruptTurn"],
|
||||
respondToRequest:
|
||||
respondToRequest as ProviderService.ProviderService["Service"]["respondToRequest"],
|
||||
respondToUserInput:
|
||||
respondToUserInput as ProviderService.ProviderService["Service"]["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderService.ProviderService["Service"]["stopSession"],
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: startSession as ProviderServiceShape["startSession"],
|
||||
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
|
||||
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (_provider) =>
|
||||
Effect.succeed({
|
||||
@@ -349,7 +346,7 @@ describe("ProviderCommandReactor", () => {
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
|
||||
@@ -30,8 +30,8 @@ import { increment, orchestrationEventsProcessedTotal } from "../../observabilit
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -190,8 +190,8 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerService = yield* ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
@@ -35,7 +35,10 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
@@ -94,7 +97,7 @@ function createProviderServiceHarness() {
|
||||
const runtimeSessions: ProviderSession[] = [];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -234,7 +237,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -27,7 +27,7 @@ import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
@@ -631,7 +631,7 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
@@ -38,7 +38,7 @@ export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
|
||||
@@ -151,6 +151,61 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const collector = yield* collectEvents;
|
||||
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
|
||||
|
||||
const resized = yield* manager.resize({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
viewport: { _tag: "freeform", width: 1024, height: 768 },
|
||||
});
|
||||
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
|
||||
|
||||
const navigated = yield* manager.navigate({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
url: "http://localhost:5173/resized",
|
||||
});
|
||||
expect(navigated.viewport).toEqual(resized.viewport);
|
||||
|
||||
yield* manager.reportStatus({
|
||||
threadId,
|
||||
tabId: opened.tabId,
|
||||
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
});
|
||||
const listed = yield* manager.list({ threadId });
|
||||
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
|
||||
|
||||
const events = yield* collector.drain;
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"opened",
|
||||
"resized",
|
||||
"navigated",
|
||||
"navigated",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects resize for an unknown tab", () =>
|
||||
Effect.gen(function* () {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
const error = yield* Effect.flip(
|
||||
manager.resize({
|
||||
threadId: freshThreadId(),
|
||||
tabId: "tab_missing",
|
||||
viewport: { _tag: "fill" },
|
||||
}),
|
||||
);
|
||||
expect(error._tag).toBe("PreviewSessionLookupError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reportStatus emits failed for LoadFailed nav", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = freshThreadId();
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -45,6 +47,9 @@ export class PreviewManager extends Context.Service<
|
||||
input: PreviewNavigateInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly resize: (
|
||||
input: PreviewResizeInput,
|
||||
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
|
||||
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
|
||||
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
|
||||
@@ -114,6 +119,7 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -127,6 +133,7 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -237,6 +244,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: { _tag: "Success", url, title: resolvedTitle },
|
||||
canGoBack: session.snapshot.canGoBack,
|
||||
canGoForward: session.snapshot.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
@@ -269,6 +277,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
navStatus: input.navStatus,
|
||||
canGoBack: input.canGoBack,
|
||||
canGoForward: input.canGoForward,
|
||||
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt,
|
||||
};
|
||||
const emit: PreviewEvent =
|
||||
@@ -299,6 +308,34 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
);
|
||||
});
|
||||
|
||||
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
|
||||
function* (input) {
|
||||
return yield* mutateExistingSession(
|
||||
input.threadId,
|
||||
input.tabId,
|
||||
Effect.fn("PreviewManager.resizeSession")(function* (session) {
|
||||
const updatedAt = yield* currentIsoTimestamp;
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
...session.snapshot,
|
||||
viewport: input.viewport,
|
||||
updatedAt,
|
||||
};
|
||||
return {
|
||||
next: { ...session, snapshot },
|
||||
emit: {
|
||||
type: "resized",
|
||||
threadId: session.threadId,
|
||||
tabId: session.tabId,
|
||||
createdAt: snapshot.updatedAt,
|
||||
snapshot,
|
||||
},
|
||||
result: snapshot,
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
|
||||
function* (input) {
|
||||
// Verify the session exists; the desktop bridge handles the actual reload
|
||||
@@ -360,6 +397,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -20,12 +20,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
makePendingClaudeProvider,
|
||||
probeClaudeCapabilities,
|
||||
} from "../Layers/ClaudeProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -87,9 +87,9 @@ export type ClaudeDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -120,8 +120,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -193,7 +193,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Claude provider snapshot.",
|
||||
detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -28,16 +28,16 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
@@ -79,9 +79,9 @@ export type CodexDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
/**
|
||||
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
|
||||
@@ -117,8 +117,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
const continuationIdentity = codexContinuationIdentity(homeLayout);
|
||||
@@ -134,7 +134,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to materialize the Codex shadow home.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -193,7 +193,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Codex provider snapshot.",
|
||||
detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -18,11 +18,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
checkCursorProviderStatus,
|
||||
enrichCursorSnapshot,
|
||||
} from "../Layers/CursorProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -70,9 +70,9 @@ export type CursorDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -104,8 +104,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -165,7 +165,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Cursor provider snapshot.",
|
||||
detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -5,11 +5,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
checkGrokProviderStatus,
|
||||
enrichGrokSnapshot,
|
||||
} from "../Layers/GrokProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -54,9 +54,9 @@ export type GrokDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -86,8 +86,8 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -141,7 +141,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Grok provider snapshot.",
|
||||
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -19,21 +19,21 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
checkOpenCodeProviderStatus,
|
||||
makePendingOpenCodeProvider,
|
||||
} from "../Layers/OpenCodeProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
@@ -82,11 +82,11 @@ export type OpenCodeDriverEnv =
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime.OpenCodeRuntime
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -114,11 +114,11 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -147,10 +147,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
effectiveConfig,
|
||||
serverConfig.cwd,
|
||||
processEnv,
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
|
||||
);
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
|
||||
@@ -177,7 +174,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the OpenCode provider snapshot.",
|
||||
detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -64,7 +64,7 @@ export class ProviderAdapterRequestError extends Schema.TaggedErrorClass<Provide
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter request failed (${this.provider}) for ${this.method}.`;
|
||||
return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,13 +76,12 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
stage: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter process failed (${this.provider}) during ${this.stage} for thread ${this.threadId}.`;
|
||||
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,8 +171,6 @@ export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<Provid
|
||||
}
|
||||
}
|
||||
|
||||
export const isProviderSessionNotFoundError = Schema.is(ProviderSessionNotFoundError);
|
||||
|
||||
/**
|
||||
* ProviderSessionDirectoryPersistenceError - Session directory persistence failure.
|
||||
*/
|
||||
|
||||
@@ -327,7 +327,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ProviderAdapterProcessError);
|
||||
assert.equal(error.stage, "session-start");
|
||||
assert.equal(error.detail, "Failed to start Claude runtime session.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notMatch(error.message, /credential material/u);
|
||||
|
||||
@@ -2893,7 +2893,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-stream",
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
@@ -2906,7 +2905,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-event",
|
||||
detail: "Failed to process Claude runtime event.",
|
||||
cause,
|
||||
}),
|
||||
@@ -2994,7 +2992,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-query-close",
|
||||
detail: "Failed to close Claude runtime query.",
|
||||
cause,
|
||||
}),
|
||||
@@ -3518,7 +3515,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
|
||||
@@ -34,11 +34,11 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
type CodexSessionRuntimeOptions,
|
||||
type CodexSessionRuntimeSendTurnInput,
|
||||
@@ -211,17 +211,14 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
|
||||
};
|
||||
}
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(
|
||||
ProviderSessionDirectory.ProviderSessionDirectory,
|
||||
{
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
},
|
||||
);
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationRuntimeFactory = makeRuntimeFactory();
|
||||
const validationLayer = it.layer(
|
||||
@@ -235,7 +232,7 @@ const validationLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -304,7 +301,7 @@ const sessionErrorLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -376,7 +373,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -430,7 +427,7 @@ const lifecycleLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1103,7 +1100,7 @@ const scopedLifecycleLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1147,7 +1144,7 @@ const scopedFailureLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1199,7 +1196,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -116,7 +116,7 @@ function mapCodexRuntimeError(
|
||||
return new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail: "Codex runtime request failed.",
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -1432,8 +1432,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-runtime-create",
|
||||
detail: "Failed to create Codex runtime session.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1462,8 +1461,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start Codex runtime session.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1510,7 +1508,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: "Failed to read attachment file.",
|
||||
detail: `Failed to read attachment file: ${cause.message}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -113,6 +113,23 @@ async function waitForFileContent(filePath: string, attempts = 40) {
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
function waitForJsonLogMatch(
|
||||
filePath: string,
|
||||
predicate: (entry: Record<string, unknown>) => boolean,
|
||||
attempts = 40,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const requests = yield* Effect.promise(() => readJsonLines(filePath));
|
||||
if (requests.some(predicate)) {
|
||||
return requests;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.promise(() => readJsonLines(filePath));
|
||||
});
|
||||
}
|
||||
|
||||
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
|
||||
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
|
||||
// captures `cursorSettings` once at construction, so without a resolver
|
||||
@@ -1004,7 +1021,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
|
||||
@@ -41,7 +41,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as Config from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -319,7 +319,7 @@ export function makeCursorAdapter(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(Config.ServerConfig);
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -564,8 +564,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start the Cursor ACP session process.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -786,6 +785,9 @@ export function makeCursorAdapter(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event._tag) {
|
||||
case "EventStreamBarrier":
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
case "ModeChanged":
|
||||
return;
|
||||
case "AssistantItemStarted":
|
||||
@@ -980,7 +982,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings } from "@t3tools/contracts";
|
||||
@@ -24,7 +25,11 @@ import {
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
const cursorAcpDiscoveryFailedMessage = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
|
||||
const cursorCliCommandMissingMessage = [
|
||||
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
].join(" ");
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
discoveryWarning: cursorAcpDiscoveryFailedMessage,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
it("reports the install docs when the Cursor CLI command is missing", async () => {
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus({
|
||||
enabled: true,
|
||||
binaryPath: missingCursorBinaryPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: cursorCliCommandMissingMessage,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the injected environment to ACP model discovery", async () => {
|
||||
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
|
||||
|
||||
const provider = await Effect.runPromise(
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus(
|
||||
{
|
||||
enabled: true,
|
||||
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
|
||||
...process.env,
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(provider.models.map((model) => model.slug)).toEqual([
|
||||
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await runNode(makeMockAgentWrapper());
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
const models = await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
makeExitLogFixture("cursor-provider-exit-log-"),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
const exitLog = await runNode(waitForFileContent(exitLogPath));
|
||||
|
||||
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
|
||||
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Cursor CLI command \`${binaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildCursorProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly cursorSettings: CursorSettings;
|
||||
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
|
||||
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
|
||||
: "Failed to execute Cursor Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
yield* Effect.logWarning("Cursor ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
|
||||
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
|
||||
@@ -10,20 +10,23 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
GrokSettings,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -45,7 +48,11 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
function waitForFileContent(
|
||||
filePath: string,
|
||||
attempts = 40,
|
||||
expectedContent?: string,
|
||||
): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
@@ -54,7 +61,10 @@ function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<stri
|
||||
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (raw.trim().length > 0) {
|
||||
if (
|
||||
raw.trim().length > 0 &&
|
||||
(expectedContent === undefined || raw.includes(expectedContent))
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
@@ -79,6 +89,39 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
|
||||
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("requires a settlement to match the live Grok turn", () => {
|
||||
const staleTurnId = TurnId.make("stale-turn");
|
||||
const replacementTurnId = TurnId.make("replacement-turn");
|
||||
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: replacementTurnId,
|
||||
liveSessionActiveTurnId: replacementTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "replacement-session",
|
||||
expectedAcpSessionId: "stale-session",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: "session-1",
|
||||
expectedAcpSessionId: "session-1",
|
||||
liveActiveTurnId: staleTurnId,
|
||||
liveSessionActiveTurnId: staleTurnId,
|
||||
turnId: staleTurnId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -175,6 +218,783 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports a Grok session running only while the prompt is in flight", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-session-ready-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const requestOpened =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "request.opened" }>>();
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? Deferred.succeed(requestOpened, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "check lifecycle", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const requestOpenedEvent = yield* Deferred.await(requestOpened);
|
||||
|
||||
const runningSessions = yield* adapter.listSessions();
|
||||
const runningSession = runningSessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(runningSession?.status, "running");
|
||||
assert.isDefined(runningSession?.activeTurnId);
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(requestOpenedEvent.requestId)),
|
||||
"accept",
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores ready without completing an unstarted turn when preparation fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-preparation-failure-while-connecting");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "prepare invalid attachment",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "missing-image",
|
||||
name: "missing.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.isUndefined(turnCompletedEvent);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-fallback");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnResult = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise fallback",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
const eventTypes = runtimeEvents.map((event) => event.type);
|
||||
const content = runtimeEvents
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "content.delta" }> =>
|
||||
event.type === "content.delta" && String(event.threadId) === String(threadId),
|
||||
)
|
||||
.map((event) => event.payload.delta)
|
||||
.join("");
|
||||
const terminalIndex = runtimeEvents.findIndex(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterTerminal = runtimeEvents
|
||||
.slice(terminalIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
const toolTitles = runtimeEvents.flatMap((event) =>
|
||||
event.type === "item.updated" && event.payload.title ? [event.payload.title] : [],
|
||||
);
|
||||
|
||||
assert.equal(sendTurnResult.threadId, threadId);
|
||||
assert.include(eventTypes, "turn.completed");
|
||||
assert.equal(content, "hello from mock");
|
||||
assert.isAtLeast(terminalIndex, 0);
|
||||
assert.deepEqual(outputAfterTerminal, []);
|
||||
assert.notInclude(toolTitles, "Child-only tool");
|
||||
assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "interrupt after prompt",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
yield* Deferred.await(contentDelta);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* Fiber.interrupt(sendTurnFiber);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const snapshot = yield* adapter.readThread(threadId);
|
||||
assert.equal(snapshot.turns.length, 1);
|
||||
assert.equal(snapshot.turns[0]?.items.length, 1);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not report a synthetic stop reason when xAI omits one", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.completed"
|
||||
? Deferred.succeed(turnCompleted, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise missing stop reason",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
yield* Deferred.await(turnCompleted);
|
||||
const turnCompletedEvent = runtimeEvents.find(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
|
||||
assert.equal(turnCompletedEvent?.payload.state, "completed");
|
||||
assert.isNull(turnCompletedEvent?.payload.stopReason);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-after-full-silence");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep("500 millis");
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
}).pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hang forever",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(cancelledEvents, 1);
|
||||
assert.equal(cancelledEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
const followUpEventsBefore = runtimeEvents.length;
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "continue after stop",
|
||||
attachments: [],
|
||||
});
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const followUpCompletedEvents = runtimeEvents
|
||||
.slice(followUpEventsBefore)
|
||||
.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
assert.lengthOf(followUpCompletedEvents, 1);
|
||||
assert.equal(followUpCompletedEvents[0]?.payload.state, "completed");
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")),
|
||||
);
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const firstTurnStarted = yield* Deferred.make<TurnId>();
|
||||
const twoTurnsCompleted = yield* Deferred.make<void>();
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started" && event.turnId !== undefined) {
|
||||
yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
|
||||
return;
|
||||
}
|
||||
if (event.type !== "turn.completed") {
|
||||
return;
|
||||
}
|
||||
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
|
||||
if (completedCount === 2) {
|
||||
yield* Deferred.succeed(twoTurnsCompleted, undefined);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel this prompt", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
|
||||
|
||||
yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
const followUp = yield* adapter
|
||||
.sendTurn({ threadId, input: "complete the follow-up", attachments: [] })
|
||||
.pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.notEqual(String(followUp.turnId), String(firstTurnId));
|
||||
assert.deepEqual(
|
||||
turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]),
|
||||
[
|
||||
[String(firstTurnId), "cancelled"],
|
||||
[String(followUp.turnId), "completed"],
|
||||
],
|
||||
);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("drops late ACP notifications after a turn is cancelled", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_PROMPT_FOREVER: "1",
|
||||
T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1",
|
||||
}),
|
||||
);
|
||||
const lateNativeUpdate = yield* Deferred.make<void>();
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://grok-cancelled-native-events",
|
||||
write: (record: unknown) =>
|
||||
JSON.stringify(record).includes("late after cancel")
|
||||
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnStarted = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
event.type === "turn.started" &&
|
||||
event.turnId !== undefined &&
|
||||
String(event.threadId) === String(threadId)
|
||||
? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "cancel before the late update", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds"));
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
const cancelledIndex = runtimeEvents.findIndex(
|
||||
(event) =>
|
||||
event.type === "turn.completed" &&
|
||||
String(event.threadId) === String(threadId) &&
|
||||
String(event.turnId) === String(turnId) &&
|
||||
event.payload.state === "cancelled",
|
||||
);
|
||||
const turnOutputTypes = new Set([
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.plan.updated",
|
||||
]);
|
||||
const outputAfterCancellation = runtimeEvents
|
||||
.slice(cancelledIndex + 1)
|
||||
.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
|
||||
);
|
||||
|
||||
assert.isAtLeast(cancelledIndex, 0);
|
||||
assert.deepEqual(outputAfterCancellation, []);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("lets Stop cancel during the xAI completion drain window", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-stop-during-completion-drain");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const activeTurnIdRef = yield* Ref.make<TurnId | undefined>(undefined);
|
||||
const trailingChunkTurnId = yield* Deferred.make<TurnId>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeEvents.push(event);
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.started") {
|
||||
yield* Ref.set(activeTurnIdRef, event.turnId);
|
||||
}
|
||||
if (event.type !== "content.delta" || event.payload.delta !== "mock") {
|
||||
return;
|
||||
}
|
||||
const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef));
|
||||
if (turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "cancel during completion drain",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
const turnCompletedEvents = runtimeEvents.filter(
|
||||
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
|
||||
event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.lengthOf(turnCompletedEvents, 1);
|
||||
assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles the in-flight prompt before emitting completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-completion-before-next-turn");
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const secondTurnCompleted = yield* Deferred.make<void>();
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return Ref.modify(completedCountRef, (count) => {
|
||||
const nextCount = count + 1;
|
||||
return [nextCount, nextCount] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((count) => {
|
||||
if (count === 1) {
|
||||
return adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "second turn after completion",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild, Effect.asVoid);
|
||||
}
|
||||
if (count === 2) {
|
||||
return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid);
|
||||
}
|
||||
return Effect.void;
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first turn",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Deferred.await(secondTurnCompleted);
|
||||
|
||||
const completedCount = yield* Ref.get(completedCountRef);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
|
||||
assert.equal(completedCount, 2);
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restores a Grok session to ready when the prompt RPC fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-prompt-failure-ready");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_FAIL_PROMPT: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "fail prompt",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const failedTurnCompleted = runtimeEvents.find(
|
||||
(event) => event.type === "turn.completed" && event.threadId === threadId,
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
assert.equal(failedTurnCompleted?.type, "turn.completed");
|
||||
if (failedTurnCompleted?.type === "turn.completed") {
|
||||
assert.equal(failedTurnCompleted.payload.state, "failed");
|
||||
assert.isString(failedTurnCompleted.payload.errorMessage);
|
||||
}
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-load-replay-filter");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" },
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "after resume",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "mock-session-1",
|
||||
});
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) => event.type === "item.completed" && event.payload.title === "Replay tool",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
runtimeEvents.some(
|
||||
(event) =>
|
||||
event.type === "content.delta" && event.payload.delta === "replayed assistant text",
|
||||
),
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects startSession when provider mismatches", () =>
|
||||
Effect.gen(function* () {
|
||||
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
|
||||
@@ -331,6 +1151,7 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
assert.deepEqual(resolvedEvent.payload.answers, {
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
});
|
||||
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
|
||||
@@ -22,6 +22,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -32,7 +33,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as Config from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
@@ -108,6 +110,8 @@ interface GrokSessionContext {
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
|
||||
interruptedTurnIds: Set<TurnId>;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
@@ -136,10 +140,38 @@ function settlePendingUserInputsAsCancelled(
|
||||
);
|
||||
}
|
||||
|
||||
function appendPromptResultToTurn(
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId,
|
||||
promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,
|
||||
result: EffectAcpSchema.PromptResponse,
|
||||
): void {
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }
|
||||
: turn,
|
||||
)
|
||||
: [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
const resolveSessionCallbackTurnId = (
|
||||
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
|
||||
threadId: ThreadId,
|
||||
): TurnId | undefined => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx ? resolveCallbackTurnId(ctx) : undefined;
|
||||
};
|
||||
|
||||
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw)) return undefined;
|
||||
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
|
||||
@@ -170,13 +202,35 @@ function selectAutoApprovedPermissionOption(
|
||||
);
|
||||
}
|
||||
|
||||
function completedStopReasonFromPromptResponse(
|
||||
response: EffectAcpSchema.PromptResponse | undefined,
|
||||
): EffectAcpSchema.StopReason | null {
|
||||
if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {
|
||||
return null;
|
||||
}
|
||||
return response.stopReason;
|
||||
}
|
||||
|
||||
export function grokPromptSettlementBelongsToContext(input: {
|
||||
readonly liveAcpSessionId: string;
|
||||
readonly expectedAcpSessionId: string;
|
||||
readonly liveActiveTurnId: TurnId | undefined;
|
||||
readonly liveSessionActiveTurnId: TurnId | undefined;
|
||||
readonly turnId: TurnId;
|
||||
}): boolean {
|
||||
return (
|
||||
input.liveAcpSessionId === input.expectedAcpSessionId &&
|
||||
(input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)
|
||||
);
|
||||
}
|
||||
|
||||
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(Config.ServerConfig);
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -240,6 +294,144 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const settlePromptInFlight = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
expectedAcpSessionId: string,
|
||||
options?: {
|
||||
readonly errorMessage?: string;
|
||||
readonly completedStopReason?: EffectAcpSchema.StopReason | null;
|
||||
readonly emitTurnCompletion?: boolean;
|
||||
/** Interrupt/cancel: drop every outstanding prompt slot and settle once. */
|
||||
readonly settleAllPrompts?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({
|
||||
liveAcpSessionId: liveCtx.acpSessionId,
|
||||
expectedAcpSessionId,
|
||||
liveActiveTurnId: liveCtx.activeTurnId,
|
||||
liveSessionActiveTurnId: liveCtx.session.activeTurnId,
|
||||
turnId,
|
||||
});
|
||||
if (!settlementBelongsToLiveContext) {
|
||||
// interruptTurn already consumed every prompt slot for this turn. A
|
||||
// late prompt result must neither emit a second terminal event nor
|
||||
// consume a slot belonging to a newer turn on the same ACP session.
|
||||
if (
|
||||
liveCtx.acpSessionId !== expectedAcpSessionId ||
|
||||
liveCtx.interruptedTurnIds.has(turnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (options?.emitTurnCompletion !== false) {
|
||||
if (options?.errorMessage !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (options?.completedStopReason !== undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let settleTurnId = turnId;
|
||||
if (options?.settleAllPrompts) {
|
||||
liveCtx.promptsInFlight = 0;
|
||||
if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {
|
||||
const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;
|
||||
if (!fallbackTurnId) {
|
||||
if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") {
|
||||
const updatedAt = yield* nowIso;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
settleTurnId = fallbackTurnId;
|
||||
}
|
||||
} else {
|
||||
const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
if (
|
||||
remainingPrompts > 0 ||
|
||||
liveCtx.activeTurnId !== settleTurnId ||
|
||||
liveCtx.session.activeTurnId !== settleTurnId
|
||||
) {
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
return;
|
||||
}
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
}
|
||||
const updatedAt = yield* nowIso;
|
||||
const canEmitTurnCompletion =
|
||||
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
|
||||
const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;
|
||||
const shouldEmitCompletedTurn =
|
||||
options?.completedStopReason !== undefined && canEmitTurnCompletion;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
if (options?.emitTurnCompletion === false) {
|
||||
return;
|
||||
}
|
||||
if (shouldEmitFailedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: options.errorMessage,
|
||||
},
|
||||
});
|
||||
} else if (shouldEmitCompletedTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: settleTurnId,
|
||||
payload: {
|
||||
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: options.completedStopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
@@ -271,6 +463,8 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
|
||||
const emitPlanUpdate = (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId | undefined,
|
||||
stamp: { readonly eventId: EventId; readonly createdAt: string },
|
||||
payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
@@ -282,17 +476,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
@@ -408,8 +602,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start the Grok ACP session process.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -425,13 +618,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const resolution = yield* Deferred.make<PendingUserInputResolution>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingUserInputs.set(requestId, { resolution });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
@@ -448,7 +642,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
@@ -487,13 +681,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
@@ -513,7 +708,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
@@ -579,6 +774,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
@@ -587,14 +783,39 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const nf = yield* Stream.runDrain(
|
||||
Stream.mapEffect(acp.getEvents(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
yield* Deferred.succeed(event.acknowledge, undefined);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event._tag === "PlanUpdated" ||
|
||||
event._tag === "ToolCallUpdated" ||
|
||||
event._tag === "ContentDelta"
|
||||
) {
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
}
|
||||
|
||||
if (event._tag === "ModeChanged") {
|
||||
return;
|
||||
}
|
||||
|
||||
const notificationTurnId = resolveNotificationTurnId(ctx);
|
||||
if (
|
||||
notificationTurnId === undefined ||
|
||||
ctx.interruptedTurnIds.has(notificationTurnId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
|
||||
switch (event._tag) {
|
||||
case "AssistantItemStarted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
@@ -603,40 +824,44 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
stamp,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
@@ -698,6 +923,15 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
// resolving from here on does not settle the turn; decremented on
|
||||
// preparation failure here, and after the prompt below otherwise.
|
||||
ctx.promptsInFlight += 1;
|
||||
// Bind the turn id before cooperative yields so interruptTurn can
|
||||
// settle this prompt even if stop arrives during preparation.
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: steeringTurnId === undefined ? "connecting" : "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
@@ -737,7 +971,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -766,12 +1000,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(turnId)) {
|
||||
yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
emitTurnCompletion: false,
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok prompt was interrupted during preparation.",
|
||||
});
|
||||
}
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
@@ -797,13 +1046,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (!liveCtx) {
|
||||
return;
|
||||
}
|
||||
yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {
|
||||
errorMessage: "Grok prompt preparation failed.",
|
||||
emitTurnCompletion: false,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const promptSettled = yield* Ref.make(false);
|
||||
const promptRpcSucceeded = yield* Ref.make(false);
|
||||
const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* prepared.acp
|
||||
@@ -811,6 +1074,18 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((promptResult) =>
|
||||
Effect.all([
|
||||
Ref.set(promptRpcSucceeded, true),
|
||||
Ref.set(promptResultRef, promptResult),
|
||||
]),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
Ref.set(
|
||||
promptFailureMessageRef,
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
|
||||
).pipe(Effect.andThen(prepared.acp.drainEvents)),
|
||||
),
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
@@ -821,38 +1096,88 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
// Keep prompt settlement atomic with respect to Stop and steering.
|
||||
// interruptTurn marks its target before waiting for this lock, so
|
||||
// cancellation can still win while queued ACP events are drained.
|
||||
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* prepared.acp.drainEvents;
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === prepared.turnId
|
||||
? {
|
||||
...turn,
|
||||
items: [...turn.items, { prompt: prepared.promptParts, result }],
|
||||
}
|
||||
: turn,
|
||||
)
|
||||
: [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
|
||||
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);
|
||||
ctx.promptsInFlight = remainingPrompts;
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
// Only the last remaining prompt settles the turn. A steer-
|
||||
// superseded prompt resolving while another is in flight or
|
||||
// pending must leave the merged turn running.
|
||||
if (
|
||||
remainingPrompts === 0 &&
|
||||
ctx.activeTurnId === prepared.turnId &&
|
||||
ctx.session.activeTurnId === prepared.turnId
|
||||
) {
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}
|
||||
const completedAt = yield* nowIso;
|
||||
const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;
|
||||
ctx.activeTurnId = undefined;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt: completedAt,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
const completedStopReason = completedStopReasonFromPromptResponse(result);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -861,9 +1186,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
stopReason: completedStopReason,
|
||||
},
|
||||
});
|
||||
ctx.interruptedTurnIds.delete(prepared.turnId);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
} else if (remainingPrompts > 0) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -875,27 +1204,153 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(promptSettled)) {
|
||||
return;
|
||||
}
|
||||
}),
|
||||
|
||||
if (yield* Ref.get(promptRpcSucceeded)) {
|
||||
const promptResult = yield* Ref.get(promptResultRef);
|
||||
if (promptResult === undefined) {
|
||||
return;
|
||||
}
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
errorMessage: "Grok session changed before the turn completed.",
|
||||
settleAllPrompts: true,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
ctx.session.activeTurnId !== prepared.turnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
appendPromptResultToTurn(
|
||||
ctx,
|
||||
prepared.turnId,
|
||||
prepared.promptParts,
|
||||
promptResult,
|
||||
);
|
||||
yield* settlePromptInFlight(
|
||||
input.threadId,
|
||||
prepared.turnId,
|
||||
prepared.acpSessionId,
|
||||
{
|
||||
completedStopReason: completedStopReasonFromPromptResponse(promptResult),
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const errorMessage = yield* Ref.get(promptFailureMessageRef);
|
||||
yield* withThreadLock(
|
||||
input.threadId,
|
||||
settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {
|
||||
errorMessage: errorMessage ?? "Grok prompt request failed.",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
const observed = yield* Effect.sync(() => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || ctx.stopped) {
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: undefined,
|
||||
interruptedTurnId: turnId,
|
||||
};
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return { _tag: "Ignore" as const };
|
||||
}
|
||||
const interruptedTurnId = turnId ?? activeTurnId;
|
||||
if (interruptedTurnId !== undefined) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
}
|
||||
return {
|
||||
_tag: "Proceed" as const,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
interruptedTurnId,
|
||||
};
|
||||
});
|
||||
if (observed._tag === "Ignore") {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {
|
||||
return;
|
||||
}
|
||||
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
|
||||
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
observed.interruptedTurnId !== undefined &&
|
||||
activeTurnId !== undefined &&
|
||||
activeTurnId !== observed.interruptedTurnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const interruptedTurnId =
|
||||
observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (interruptedTurnId) {
|
||||
ctx.interruptedTurnIds.add(interruptedTurnId);
|
||||
yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {
|
||||
completedStopReason: "cancelled",
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
} else if (
|
||||
ctx.promptsInFlight > 0 ||
|
||||
ctx.session.status === "running" ||
|
||||
ctx.session.status === "connecting"
|
||||
) {
|
||||
const updatedAt = yield* nowIso;
|
||||
ctx.promptsInFlight = 0;
|
||||
ctx.activeTurnId = undefined;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;
|
||||
ctx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -20,11 +20,15 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import * as Config from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapter,
|
||||
@@ -75,7 +79,7 @@ const runtimeMock = {
|
||||
},
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
@@ -163,12 +167,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
})(),
|
||||
}),
|
||||
},
|
||||
}) as unknown as ReturnType<
|
||||
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
|
||||
>,
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
@@ -176,17 +178,14 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
),
|
||||
};
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(
|
||||
ProviderSessionDirectory.ProviderSessionDirectory,
|
||||
{
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
},
|
||||
);
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
// The adapter now receives its settings as a plain argument (the old design
|
||||
// read from `ServerSettingsService` internally). The test-only
|
||||
@@ -204,10 +203,10 @@ const OpenCodeAdapterTestLayer = Layer.effect(
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
@@ -335,11 +334,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings),
|
||||
).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -369,8 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const promptFailure = new Error("prompt failed");
|
||||
runtimeMock.state.promptAsyncError = promptFailure;
|
||||
runtimeMock.state.promptAsyncError = new Error("prompt failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
@@ -387,17 +383,15 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
if (error._tag !== "ProviderAdapterRequestError") {
|
||||
throw new Error("Unexpected error type");
|
||||
}
|
||||
NodeAssert.equal(error.detail, "OpenCode SDK request failed.");
|
||||
NodeAssert.equal(error.detail, "prompt failed");
|
||||
NodeAssert.equal(
|
||||
error.message,
|
||||
"Provider adapter request failed (opencode) for session.promptAsync.",
|
||||
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
|
||||
);
|
||||
NodeAssert.ok(OpenCodeRuntime.isOpenCodeRuntimeError(error.cause));
|
||||
NodeAssert.strictEqual(error.cause.cause, promptFailure);
|
||||
NodeAssert.equal(sessions.length, 1);
|
||||
NodeAssert.equal(sessions[0]?.status, "ready");
|
||||
NodeAssert.equal(sessions[0]?.activeTurnId, undefined);
|
||||
NodeAssert.equal(sessions[0]?.lastError, "OpenCode SDK request failed.");
|
||||
NodeAssert.equal(sessions[0]?.lastError, "prompt failed");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -486,9 +480,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -533,9 +527,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -575,9 +569,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -798,12 +792,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
nativeEventLogger,
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
@@ -882,12 +874,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
nativeEventLogger,
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
|
||||
@@ -25,7 +25,7 @@ import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import {
|
||||
@@ -36,7 +36,19 @@ import {
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
buildOpenCodePermissionRules,
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
openCodeQuestionId,
|
||||
openCodeRuntimeErrorDetail,
|
||||
parseOpenCodeModelSlug,
|
||||
runOpenCodeSdk,
|
||||
toOpenCodeFileParts,
|
||||
toOpenCodePermissionReply,
|
||||
toOpenCodeQuestionAnswers,
|
||||
type OpenCodeServerConnection,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
@@ -56,7 +68,7 @@ type OpenCodeSubscribedEvent =
|
||||
interface OpenCodeSessionContext {
|
||||
session: ProviderSession;
|
||||
readonly client: OpencodeClient;
|
||||
readonly server: OpenCodeRuntime.OpenCodeServerConnection;
|
||||
readonly server: OpenCodeServerConnection;
|
||||
readonly directory: string;
|
||||
readonly openCodeSessionId: string;
|
||||
readonly pendingPermissions: Map<string, PermissionRequest>;
|
||||
@@ -96,16 +108,30 @@ export interface OpenCodeAdapterLiveOptions {
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
/**
|
||||
* Map a tagged OpenCodeRuntimeError produced by {@link OpenCodeRuntime.runOpenCodeSdk} into
|
||||
* Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
|
||||
* the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call
|
||||
* sites pipe through this in `Effect.mapError` so they never build the error
|
||||
* shape by hand.
|
||||
*/
|
||||
const toRequestError = (cause: OpenCodeRuntime.OpenCodeRuntimeError): ProviderAdapterRequestError =>
|
||||
const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: cause.operation,
|
||||
detail: "OpenCode SDK request failed.",
|
||||
detail: cause.detail,
|
||||
cause: cause.cause,
|
||||
});
|
||||
|
||||
/**
|
||||
* Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The
|
||||
* typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),
|
||||
* in which case we preserve its `detail`; otherwise we fall back to
|
||||
* {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).
|
||||
*/
|
||||
const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
});
|
||||
|
||||
@@ -227,7 +253,7 @@ function ensureSessionContext(
|
||||
|
||||
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
|
||||
return request.questions.map((question, index) => ({
|
||||
id: OpenCodeRuntime.openCodeQuestionId(index, question),
|
||||
id: openCodeQuestionId(index, question),
|
||||
header: question.header,
|
||||
question: question.question,
|
||||
options: question.options.map((option) => ({
|
||||
@@ -387,7 +413,7 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (
|
||||
// Best-effort remote abort. The scope close below tears down the local
|
||||
// handles (event-pump fiber, server-exit fiber, event-subscribe fetch),
|
||||
// but we still want to tell OpenCode that this session is done.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.ignore({ log: true }));
|
||||
|
||||
@@ -404,8 +430,8 @@ export function makeOpenCodeAdapter(
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -543,7 +569,7 @@ export function makeOpenCodeAdapter(
|
||||
// Inline the teardown that `stopOpenCodeContext` would do; we can't
|
||||
// delegate to it because our `getAndSet` above already flipped the
|
||||
// one-shot guard, so the call would no-op.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.ignore({ log: true }));
|
||||
yield* Scope.close(context.sessionScope, Exit.void);
|
||||
@@ -815,7 +841,7 @@ export function makeOpenCodeAdapter(
|
||||
context.pendingQuestions.delete(event.properties.requestID);
|
||||
const answers = Object.fromEntries(
|
||||
(request?.questions ?? []).map((question, index) => [
|
||||
OpenCodeRuntime.openCodeQuestionId(index, question),
|
||||
openCodeQuestionId(index, question),
|
||||
event.properties.answers[index]?.join(", ") ?? "",
|
||||
]),
|
||||
);
|
||||
@@ -949,18 +975,20 @@ export function makeOpenCodeAdapter(
|
||||
// Fibers forked into `context.sessionScope` are interrupted
|
||||
// automatically when the scope closes — no bookkeeping required.
|
||||
yield* Effect.flatMap(
|
||||
OpenCodeRuntime.runOpenCodeSdk("event.subscribe", () =>
|
||||
runOpenCodeSdk("event.subscribe", () =>
|
||||
context.client.event.subscribe(undefined, {
|
||||
signal: eventsAbortController.signal,
|
||||
}),
|
||||
),
|
||||
(subscription) =>
|
||||
Stream.fromAsyncIterable(subscription.stream, (cause) =>
|
||||
OpenCodeRuntime.OpenCodeRuntimeError.fromCause({
|
||||
operation: "event.subscribe",
|
||||
detail: "OpenCode event subscription failed.",
|
||||
cause,
|
||||
}),
|
||||
Stream.fromAsyncIterable(
|
||||
subscription.stream,
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "event.subscribe",
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
|
||||
).pipe(
|
||||
Effect.exit,
|
||||
@@ -974,7 +1002,7 @@ export function makeOpenCodeAdapter(
|
||||
if (Exit.isFailure(exit)) {
|
||||
yield* emitUnexpectedExit(
|
||||
context,
|
||||
OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(Cause.squash(exit.cause)),
|
||||
openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),
|
||||
);
|
||||
}
|
||||
}),
|
||||
@@ -1028,7 +1056,7 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
if (mcpSession && !server.external) {
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
|
||||
yield* runOpenCodeSdk("mcp.add", () =>
|
||||
client.mcp.add({
|
||||
name: "t3-code",
|
||||
config: {
|
||||
@@ -1042,14 +1070,14 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
);
|
||||
}
|
||||
const openCodeSession = yield* OpenCodeRuntime.runOpenCodeSdk("session.create", () =>
|
||||
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
|
||||
client.session.create({
|
||||
title: `T3 Code ${input.threadId}`,
|
||||
permission: OpenCodeRuntime.buildOpenCodePermissionRules(input.runtimeMode),
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
if (!openCodeSession.data) {
|
||||
return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "session.create",
|
||||
detail: "OpenCode session.create returned no session payload.",
|
||||
});
|
||||
@@ -1064,14 +1092,7 @@ export function makeOpenCodeAdapter(
|
||||
);
|
||||
if (Exit.isFailure(startedExit)) {
|
||||
yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);
|
||||
const cause = Cause.squash(startedExit.cause);
|
||||
return yield* new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start OpenCode runtime session.",
|
||||
cause,
|
||||
});
|
||||
return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));
|
||||
}
|
||||
return startedExit.value;
|
||||
});
|
||||
@@ -1082,7 +1103,7 @@ export function makeOpenCodeAdapter(
|
||||
if (raceWinner) {
|
||||
// Another call won the race – clean up the session we just created
|
||||
// (including the remote SDK session) and return the existing one.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
started.client.session.abort({
|
||||
sessionID: started.openCodeSession.id,
|
||||
}),
|
||||
@@ -1164,7 +1185,7 @@ export function makeOpenCodeAdapter(
|
||||
issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,
|
||||
});
|
||||
}
|
||||
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(modelSelection?.model);
|
||||
const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);
|
||||
if (!parsedModel) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
@@ -1174,7 +1195,7 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
|
||||
const text = input.input?.trim();
|
||||
const fileParts = OpenCodeRuntime.toOpenCodeFileParts({
|
||||
const fileParts = toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
resolveAttachmentPath({
|
||||
@@ -1217,7 +1238,7 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.promptAsync", () =>
|
||||
yield* runOpenCodeSdk("session.promptAsync", () =>
|
||||
context.client.session.promptAsync({
|
||||
sessionID: context.openCodeSessionId,
|
||||
model: parsedModel,
|
||||
@@ -1271,7 +1292,7 @@ export function makeOpenCodeAdapter(
|
||||
const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
function* (threadId, turnId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
if (turnId ?? context.activeTurnId) {
|
||||
@@ -1301,10 +1322,10 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("permission.reply", () =>
|
||||
yield* runOpenCodeSdk("permission.reply", () =>
|
||||
context.client.permission.reply({
|
||||
requestID: requestId,
|
||||
reply: OpenCodeRuntime.toOpenCodePermissionReply(decision),
|
||||
reply: toOpenCodePermissionReply(decision),
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
});
|
||||
@@ -1322,10 +1343,10 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("question.reply", () =>
|
||||
yield* runOpenCodeSdk("question.reply", () =>
|
||||
context.client.question.reply({
|
||||
requestID: requestId,
|
||||
answers: OpenCodeRuntime.toOpenCodeQuestionAnswers(request, answers),
|
||||
answers: toOpenCodeQuestionAnswers(request, answers),
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
});
|
||||
@@ -1365,7 +1386,7 @@ export function makeOpenCodeAdapter(
|
||||
const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
|
||||
function* (threadId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
}),
|
||||
@@ -1391,7 +1412,7 @@ export function makeOpenCodeAdapter(
|
||||
const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
|
||||
function* (threadId, numTurns) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
}),
|
||||
@@ -1402,7 +1423,7 @@ export function makeOpenCodeAdapter(
|
||||
);
|
||||
const targetIndex = assistantMessages.length - numTurns - 1;
|
||||
const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.revert", () =>
|
||||
yield* runOpenCodeSdk("session.revert", () =>
|
||||
context.client.session.revert({
|
||||
sessionID: context.openCodeSessionId,
|
||||
...(target ? { messageID: target.info.id } : {}),
|
||||
|
||||
@@ -8,10 +8,14 @@ import * as Schema from "effect/Schema";
|
||||
import { beforeEach } from "vite-plus/test";
|
||||
|
||||
import { OpenCodeSettings } from "@t3tools/contracts";
|
||||
import * as Config from "../../config.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import { checkOpenCodeProviderStatus, OpenCodeProbeError } from "./OpenCodeProvider.ts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
|
||||
@@ -48,7 +52,7 @@ const runtimeMock = {
|
||||
},
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.succeed({
|
||||
url: "http://127.0.0.1:4301",
|
||||
@@ -72,7 +76,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
runOpenCodeCommand: () =>
|
||||
runtimeMock.state.runVersionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: runtimeMock.state.runVersionError.message,
|
||||
cause: runtimeMock.state.runVersionError,
|
||||
@@ -80,27 +84,25 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
)
|
||||
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: () =>
|
||||
({}) as unknown as ReturnType<
|
||||
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
|
||||
>,
|
||||
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: runtimeMock.state.inventoryError.message,
|
||||
cause: runtimeMock.state.inventoryError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeRuntime.OpenCodeInventory),
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const testLayer = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -114,24 +116,6 @@ const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSe
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("structures OpenCode probe failures without deriving messages from causes", () => {
|
||||
const cause = new Error("401 Unauthorized");
|
||||
const runtimeError = new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
});
|
||||
const probeError = OpenCodeProbeError.fromCause("load-inventory")(runtimeError);
|
||||
const versionProbeError = OpenCodeProbeError.fromCause("probe-version")(runtimeError);
|
||||
|
||||
NodeAssert.equal(probeError.operation, "load-inventory");
|
||||
NodeAssert.equal(probeError.detail, "401 Unauthorized");
|
||||
NodeAssert.strictEqual(probeError.cause, runtimeError);
|
||||
NodeAssert.strictEqual(runtimeError.cause, cause);
|
||||
NodeAssert.equal(probeError.message, "OpenCode probe failed during load-inventory.");
|
||||
NodeAssert.equal(versionProbeError.message, "OpenCode probe failed during probe-version.");
|
||||
});
|
||||
|
||||
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
it.effect("shows a codex-style missing binary message", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -228,7 +212,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
|
||||
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://url-user:[email protected]:9999/private?token=secret#fragment",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
@@ -262,28 +246,6 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
NodeAssert.doesNotMatch(
|
||||
snapshot.message ?? "",
|
||||
/url-user|url-password|private|token|secret|fragment/,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps IPv6 brackets in configured server diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("fetch failed: connect ECONNREFUSED ::1:9999");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://[::1]:9999/private",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
);
|
||||
|
||||
NodeAssert.equal(
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://[::1]:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -5,9 +5,9 @@ import {
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
@@ -18,7 +18,11 @@ import {
|
||||
providerModelsFromSettings,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
@@ -28,29 +32,10 @@ const OPENCODE_PRESENTATION = {
|
||||
} as const;
|
||||
const MINIMUM_OPENCODE_VERSION = "1.14.19";
|
||||
|
||||
export class OpenCodeProbeError extends Schema.TaggedErrorClass<OpenCodeProbeError>()(
|
||||
"OpenCodeProbeError",
|
||||
{
|
||||
operation: Schema.Literals(["probe-version", "load-inventory"]),
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode probe failed during ${this.operation}.`;
|
||||
}
|
||||
|
||||
static fromCause(operation: "probe-version" | "load-inventory") {
|
||||
return (cause: unknown): OpenCodeProbeError =>
|
||||
new OpenCodeProbeError({
|
||||
operation,
|
||||
detail: OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(cause),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);
|
||||
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
|
||||
readonly cause: unknown;
|
||||
readonly detail: string;
|
||||
}> {}
|
||||
|
||||
function normalizeProbeMessage(message: string): string | undefined {
|
||||
const trimmed = message.trim();
|
||||
@@ -67,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined {
|
||||
}
|
||||
|
||||
function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
if (isOpenCodeProbeError(cause)) {
|
||||
if (cause instanceof OpenCodeProbeError) {
|
||||
return normalizeProbeMessage(cause.detail);
|
||||
}
|
||||
|
||||
@@ -78,15 +63,6 @@ function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
return normalizeProbeMessage(cause.message);
|
||||
}
|
||||
|
||||
function openCodeServerDisplayTarget(input: string): string | undefined {
|
||||
try {
|
||||
const url = new URL(input);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function formatOpenCodeProbeError(input: {
|
||||
readonly cause: unknown;
|
||||
readonly isExternalServer: boolean;
|
||||
@@ -117,13 +93,9 @@ function formatOpenCodeProbeError(input: {
|
||||
lower.includes("timeout") ||
|
||||
lower.includes("socket hang up")
|
||||
) {
|
||||
const serverTarget = openCodeServerDisplayTarget(input.serverUrl);
|
||||
return {
|
||||
installed: true,
|
||||
message:
|
||||
serverTarget === undefined
|
||||
? "Couldn't reach the configured OpenCode server. Check that the server is running and the URL is correct."
|
||||
: `Couldn't reach the configured OpenCode server at ${serverTarget}. Check that the server is running and the URL is correct.`,
|
||||
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -247,9 +219,7 @@ function openCodeCapabilitiesForModel(input: {
|
||||
});
|
||||
}
|
||||
|
||||
function flattenOpenCodeModels(
|
||||
input: OpenCodeRuntime.OpenCodeInventory,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
@@ -332,18 +302,20 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime.OpenCodeRuntime> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const customModels = openCodeSettings.customModels;
|
||||
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
|
||||
|
||||
const buildFailureSnapshot = (
|
||||
failure: { readonly installed: boolean; readonly message: string },
|
||||
version: string | null,
|
||||
) =>
|
||||
buildServerProvider({
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: openCodeSettings.enabled,
|
||||
checkedAt,
|
||||
@@ -361,16 +333,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) =>
|
||||
buildFailureSnapshot(
|
||||
formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
}),
|
||||
version,
|
||||
);
|
||||
};
|
||||
|
||||
if (!openCodeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
@@ -404,7 +367,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
args: ["--version"],
|
||||
environment: resolvedEnvironment,
|
||||
})
|
||||
.pipe(Effect.mapError(OpenCodeProbeError.fromCause("probe-version"))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
@@ -412,11 +379,10 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
|
||||
if (!version) {
|
||||
return buildFailureSnapshot(
|
||||
{
|
||||
installed: true,
|
||||
message: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
},
|
||||
return fallback(
|
||||
new Error(
|
||||
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
),
|
||||
null,
|
||||
);
|
||||
}
|
||||
@@ -459,7 +425,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.mapError(OpenCodeProbeError.fromCause("load-inventory"))),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
|
||||
+20
-16
@@ -10,15 +10,16 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { ClaudeAdapterShape } from "./Services/ClaudeAdapter.ts";
|
||||
import type { CodexAdapterShape } from "./Services/CodexAdapter.ts";
|
||||
import type { CursorAdapterShape } from "./Services/CursorAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "./Services/OpenCodeAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import type * as ClaudeAdapter from "../Services/ClaudeAdapter.ts";
|
||||
import type * as CodexAdapter from "../Services/CodexAdapter.ts";
|
||||
import type * as CursorAdapter from "../Services/CursorAdapter.ts";
|
||||
import type * as OpenCodeAdapter from "../Services/OpenCodeAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";
|
||||
import * as ProviderAdapterRegistryLayer from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
@@ -26,7 +27,7 @@ const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
|
||||
const fakeCodexAdapter: CodexAdapterShape = {
|
||||
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
|
||||
provider: CODEX_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -43,7 +44,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -60,7 +61,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
|
||||
provider: OPENCODE_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -77,7 +78,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
|
||||
provider: CURSOR_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -94,7 +95,7 @@ const fakeCursorAdapter: CursorAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
// ProviderAdapterRegistry is a facade over ProviderInstanceRegistry —
|
||||
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
|
||||
// it walks `listInstances` once at boot and surfaces the default-instance
|
||||
// adapter keyed by its driver kind. To test the facade we supply four fake
|
||||
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
|
||||
@@ -146,11 +147,14 @@ const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.Provide
|
||||
});
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.provide(ProviderAdapterRegistry.layer, fakeInstanceRegistryLayer),
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
|
||||
fakeInstanceRegistryLayer,
|
||||
),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
it.layer(layer)("ProviderAdapterRegistry", (it) => {
|
||||
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
|
||||
it("resolves adapters and routing metadata from provider instances", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
|
||||
*
|
||||
* `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
|
||||
* adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
|
||||
* refactor moved adapter construction inside each `ProviderDriver.create()`:
|
||||
* adapters are now bundled on the `ProviderInstance` that the
|
||||
* `ProviderInstanceRegistry` owns.
|
||||
*
|
||||
* This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
|
||||
* dynamic look-ups against `ProviderInstanceRegistry` on every call. That
|
||||
* means settings-driven hot-reload shows up here automatically — adding a
|
||||
* new instance via settings makes `getByInstance` resolve immediately
|
||||
* without rebuilding the facade.
|
||||
*
|
||||
* @module ProviderAdapterRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
|
||||
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: instanceId,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(instance.adapter),
|
||||
),
|
||||
);
|
||||
|
||||
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: instanceId,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
displayName: instance.displayName,
|
||||
accentColor: instance.accentColor,
|
||||
enabled: instance.enabled,
|
||||
continuationIdentity: instance.continuationIdentity,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
|
||||
);
|
||||
|
||||
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => {
|
||||
const kinds = new Set<ProviderDriverKind>();
|
||||
for (const instance of instances) {
|
||||
const defaultId = defaultInstanceIdForDriver(instance.driverKind);
|
||||
if (instance.instanceId === defaultId) {
|
||||
// Only the default-instance rows show up through the legacy
|
||||
// shim — custom instances like `codex_personal` have no
|
||||
// `ProviderDriverKind` equivalent.
|
||||
kinds.add(instance.driverKind);
|
||||
}
|
||||
}
|
||||
return Array.from(kinds);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
getByInstance,
|
||||
getInstanceInfo,
|
||||
listInstances,
|
||||
listProviders,
|
||||
// Proxy directly — the facade has no state of its own; the instance
|
||||
// registry already coalesces adds/removes/rebuilds into one emission.
|
||||
streamChanges: registry.streamChanges,
|
||||
subscribeChanges: registry.subscribeChanges,
|
||||
} satisfies ProviderAdapterRegistryShape;
|
||||
});
|
||||
|
||||
export const ProviderAdapterRegistryLive = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
makeProviderAdapterRegistry(),
|
||||
);
|
||||
|
||||
// Exposed for tests that want to build a facade over a pre-assembled
|
||||
// `ProviderInstanceRegistry` without pulling in the whole boot graph.
|
||||
export { makeProviderAdapterRegistry };
|
||||
|
||||
// Re-export for consumers that need the accessor shape. The service tag
|
||||
// itself lives in `Services/ProviderAdapterRegistry.ts`.
|
||||
export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
// Re-export for consumers (including tests) that construct a
|
||||
// `ProviderInstanceId` before calling `getByInstance`.
|
||||
export { ProviderInstanceId };
|
||||
+28
-22
@@ -25,37 +25,39 @@
|
||||
* rather than failing the boot Layer, matching the previous best-effort
|
||||
* behavior of `server.ts`.
|
||||
*
|
||||
* @module provider/ProviderEventLoggers
|
||||
* @module provider/Layers/ProviderEventLoggers
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderEventLoggersShape {
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared logger pair for native + canonical provider event streams.
|
||||
*
|
||||
* Service value is intentionally a struct of two optional loggers rather
|
||||
* than two parallel tags. Construction site is one place
|
||||
* (`layer`); consumers (drivers, `ProviderService`) read
|
||||
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
|
||||
* one tag and pluck the field they need.
|
||||
*/
|
||||
export class ProviderEventLoggers extends Context.Service<
|
||||
ProviderEventLoggers,
|
||||
{
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger | undefined;
|
||||
}
|
||||
>()("t3/provider/ProviderEventLoggers") {}
|
||||
ProviderEventLoggersShape
|
||||
>()("t3/provider/Layers/ProviderEventLoggers") {}
|
||||
|
||||
/**
|
||||
* Constant value used by tests / boot layers that want to opt out of native
|
||||
* + canonical logging entirely. Keeps the tag non-optional in the type
|
||||
* system while letting the runtime treat absence as a no-op.
|
||||
*/
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
|
||||
native: undefined,
|
||||
canonical: undefined,
|
||||
};
|
||||
@@ -65,15 +67,19 @@ export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
|
||||
* If the directory create fails for either stream, the corresponding field
|
||||
* is `undefined` and writes from that stream become no-ops downstream.
|
||||
*/
|
||||
export const make = Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* Config.ServerConfig;
|
||||
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
return ProviderEventLoggers.of({ native, canonical });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderEventLoggers, make);
|
||||
export const ProviderEventLoggersLive = Layer.effect(
|
||||
ProviderEventLoggers,
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
return {
|
||||
native,
|
||||
canonical,
|
||||
} satisfies ProviderEventLoggersShape;
|
||||
}),
|
||||
);
|
||||
@@ -29,7 +29,7 @@
|
||||
* ----------
|
||||
* On layer build we:
|
||||
* 1. Read the current `ServerSettings` once and use it to seed the
|
||||
* registry's initial state via `ProviderInstanceRegistry.mutableLayer`.
|
||||
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
|
||||
* 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
|
||||
* subscribes to `ServerSettingsService.streamChanges` and calls
|
||||
* `ProviderInstanceRegistryMutator.reconcile` on every emission.
|
||||
@@ -51,9 +51,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerSettingsModule from "../../serverSettings.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
|
||||
import * as ProviderInstanceRegistry from "../ProviderInstanceRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
|
||||
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
/**
|
||||
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
|
||||
@@ -114,8 +116,8 @@ export const deriveProviderInstanceConfigMap = (
|
||||
*/
|
||||
const SettingsWatcherLive = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const mutator = yield* ProviderInstanceRegistry.ProviderInstanceRegistryMutator;
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const mutator = yield* ProviderInstanceRegistryMutator;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
yield* serverSettings.streamChanges.pipe(
|
||||
Stream.runForEach((next) =>
|
||||
mutator
|
||||
@@ -136,7 +138,7 @@ const SettingsWatcherLive = Layer.effectDiscard(
|
||||
* sync with subsequent `streamChanges` emissions.
|
||||
*
|
||||
* The Layer's two halves:
|
||||
* - `ProviderInstanceRegistry.mutableLayer` produces the registry +
|
||||
* - `ProviderInstanceRegistryMutableLayer` produces the registry +
|
||||
* mutator from the initial config map. Its scope owns every
|
||||
* per-instance child scope created during reconcile.
|
||||
* - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
|
||||
@@ -148,12 +150,12 @@ const SettingsWatcherLive = Layer.effectDiscard(
|
||||
* it, so the visibility leak is harmless in practice.
|
||||
*/
|
||||
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
ProviderInstanceRegistry,
|
||||
never,
|
||||
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
|
||||
BuiltInDriversEnv | ServerSettingsService
|
||||
> = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
@@ -162,15 +164,11 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
|
||||
? ({} as ProviderInstanceConfigMap)
|
||||
: deriveProviderInstanceConfigMap(initialSettings);
|
||||
|
||||
const mutableLayer = ProviderInstanceRegistry.mutableLayer({
|
||||
const mutableLayer = ProviderInstanceRegistryMutableLayer({
|
||||
drivers: BUILT_IN_DRIVERS,
|
||||
configMap: initialConfigMap,
|
||||
});
|
||||
|
||||
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
|
||||
}),
|
||||
) as Layer.Layer<
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
never,
|
||||
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
|
||||
>;
|
||||
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
|
||||
+27
-38
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Multi-instance validation slices for `ProviderInstanceRegistry`.
|
||||
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
|
||||
*
|
||||
* Two axes of the driver/registry refactor are exercised here:
|
||||
*
|
||||
@@ -36,19 +36,18 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import { ClaudeDriver } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "./Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "./Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "./Drivers/OpenCodeDriver.ts";
|
||||
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -99,24 +98,19 @@ const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSetti
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
|
||||
// directory. `Layer.merge` just unions requirements, so we have to push
|
||||
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
|
||||
// dependency while still surfacing NodeServices to the test body (the
|
||||
// codex driver's `create` yields `ChildProcessSpawner` directly).
|
||||
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
|
||||
const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
|
||||
@@ -148,7 +142,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver],
|
||||
configMap,
|
||||
});
|
||||
@@ -214,7 +208,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver],
|
||||
configMap,
|
||||
});
|
||||
@@ -234,32 +228,27 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistry — all drivers slice", () => {
|
||||
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
|
||||
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
|
||||
// at construction time, so we wire `OpenCodeRuntime.layer` into the stack.
|
||||
// `OpenCodeRuntime.layer` bundles its own `NetService.layer` via
|
||||
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
|
||||
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
|
||||
// `Layer.provide`, so the only external requirement it still exposes is
|
||||
// `ChildProcessSpawner` — resolved here by piping it through
|
||||
// `provideMerge(NodeServices.layer)`.
|
||||
//
|
||||
// The nested `provideMerge`s read bottom-up: `NodeServices.layer`
|
||||
// provides `OpenCodeRuntime.layer`'s deps while keeping its own outputs
|
||||
// provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
|
||||
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
|
||||
// `FileSystem` dep while keeping everything else surfaced to the test.
|
||||
const infraLayer = OpenCodeRuntime.layer.pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
|
||||
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
it.live("boots one instance of every shipped driver from a single config map", () =>
|
||||
@@ -312,7 +301,7 @@ describe("ProviderInstanceRegistry — all drivers slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
|
||||
configMap,
|
||||
});
|
||||
+26
-97
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* ProviderInstanceRegistry — runtime implementation of
|
||||
* ProviderInstanceRegistryLive — runtime implementation of
|
||||
* `ProviderInstanceRegistry` plus its sibling mutator.
|
||||
*
|
||||
* Materializes every entry in a `ProviderInstanceConfigMap`:
|
||||
@@ -30,7 +30,7 @@
|
||||
* tears every instance down in reverse order; closing a single instance
|
||||
* (via `reconcile` removing it) leaves the rest untouched.
|
||||
*
|
||||
* @module provider/ProviderInstanceRegistry
|
||||
* @module provider/Layers/ProviderInstanceRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
@@ -48,86 +48,19 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts";
|
||||
import type { AnyProviderDriver, ProviderInstance } from "./ProviderDriver.ts";
|
||||
|
||||
export class ProviderInstanceRegistry extends Context.Service<
|
||||
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
|
||||
import {
|
||||
ProviderInstanceRegistry,
|
||||
{
|
||||
/**
|
||||
* Look up one instance by id. Returns `undefined` (not `Option`) when the
|
||||
* id is unknown; callers branch on absence and emit the appropriate domain
|
||||
* error.
|
||||
*/
|
||||
readonly getInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstance | undefined>;
|
||||
|
||||
/**
|
||||
* Every available (driver-registered, successfully created) instance, in
|
||||
* stable settings-author order.
|
||||
*/
|
||||
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
|
||||
|
||||
/**
|
||||
* Wire-shape shadow snapshots for instances whose driver is unknown to this
|
||||
* build or whose config failed to decode. Suitable for merging directly
|
||||
* into `ProviderRegistry` output.
|
||||
*/
|
||||
readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Push notification stream emitted whenever the registry's contents change.
|
||||
* The payload is `void` because consumers always re-pull `listInstances`
|
||||
* and `listUnavailable` together.
|
||||
*
|
||||
* `Stream.fromPubSub` defers `PubSub.subscribe` until the stream starts
|
||||
* running, so forking a consumer races the next publish. Hot-reload
|
||||
* consumers that cannot miss a publish should use `subscribeChanges`
|
||||
* instead, which acquires the subscription synchronously before the
|
||||
* consumer loop is forked.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
|
||||
/**
|
||||
* Acquire a scoped subscription to the change channel synchronously in the
|
||||
* caller's fiber. Consumers typically `yield*` this in the same fiber that
|
||||
* forks their consumer loop, then drain it with `PubSub.take` or
|
||||
* `Stream.fromSubscription`. Because the subscription is registered before
|
||||
* this effect returns, no subsequent publish can land in a gap.
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/provider/ProviderInstanceRegistry") {}
|
||||
|
||||
/**
|
||||
* Internal mutation boundary used only by registry hydration.
|
||||
*
|
||||
* `reconcile` diffs by instance id, closes removed or replaced child scopes
|
||||
* before creating replacements, materializes additions in fresh child scopes,
|
||||
* and publishes one change tick after the batch. Reapplying an unchanged map
|
||||
* is a no-op.
|
||||
*/
|
||||
export class ProviderInstanceRegistryMutator extends Context.Service<
|
||||
type ProviderInstanceRegistryShape,
|
||||
} from "../Services/ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
ProviderInstanceRegistryMutator,
|
||||
{
|
||||
/**
|
||||
* Bring the live registry in line with the supplied config map. The
|
||||
* operation closes removed or replaced scopes before creating replacements
|
||||
* and publishes a single change tick after the batch. Reapplying an
|
||||
* unchanged map is a no-op.
|
||||
*
|
||||
* The effect never fails: individual driver creation failures become
|
||||
* unavailable shadow snapshots, keeping settings-watcher loops alive when
|
||||
* one entry is invalid.
|
||||
*/
|
||||
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/provider/ProviderInstanceRegistry/ProviderInstanceRegistryMutator") {}
|
||||
type ProviderInstanceRegistryMutatorShape,
|
||||
} from "../Services/ProviderInstanceRegistryMutator.ts";
|
||||
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
|
||||
/**
|
||||
* Live registry entry: the materialized `ProviderInstance` + the fresh
|
||||
@@ -160,8 +93,6 @@ interface RegistryState {
|
||||
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
|
||||
Equal.equals(a, b);
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
|
||||
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
|
||||
return undefined;
|
||||
@@ -206,13 +137,12 @@ const buildEntry = <R>(input: {
|
||||
const decoder = Schema.decodeUnknownEffect(driver.configSchema);
|
||||
const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
|
||||
if (decodeResult._tag === "Failure") {
|
||||
const cause = decodeResult.failure;
|
||||
const detail = formatSchemaIssue(cause.issue);
|
||||
const issue = decodeResult.failure;
|
||||
const detail = issue.message ?? String(issue);
|
||||
yield* Effect.logError("Failed to decode provider instance config", {
|
||||
instanceId: rawInstanceId,
|
||||
driver: entry.driver,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
return {
|
||||
kind: "unavailable" as const,
|
||||
@@ -250,7 +180,6 @@ const buildEntry = <R>(input: {
|
||||
instanceId: rawInstanceId,
|
||||
driver: entry.driver,
|
||||
detail: createResult.failure.detail,
|
||||
cause: createResult.failure,
|
||||
});
|
||||
yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
|
||||
return {
|
||||
@@ -386,9 +315,9 @@ const makeReconcile = <R>(input: {
|
||||
* Build the registry's runtime state from a concrete configMap. Returns a
|
||||
* record containing:
|
||||
*
|
||||
* - `registry`: the read-only `ProviderInstanceRegistry["Service"]` to expose
|
||||
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
|
||||
* under `ProviderInstanceRegistry`.
|
||||
* - `mutator`: the `ProviderInstanceRegistryMutator["Service"]` to expose
|
||||
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
|
||||
* under `ProviderInstanceRegistryMutator`.
|
||||
* - `reconcile`: the raw reconcile function, provided for convenience so
|
||||
* boot-time layers can hydrate an initial map before publishing the
|
||||
@@ -398,13 +327,13 @@ const makeReconcile = <R>(input: {
|
||||
* created during `reconcile`. Closing that scope closes every live
|
||||
* instance.
|
||||
*/
|
||||
export const make = <R>(input: {
|
||||
export const makeProviderInstanceRegistry = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Effect.Effect<
|
||||
{
|
||||
readonly registry: ProviderInstanceRegistry["Service"];
|
||||
readonly mutator: ProviderInstanceRegistryMutator["Service"];
|
||||
readonly registry: ProviderInstanceRegistryShape;
|
||||
readonly mutator: ProviderInstanceRegistryMutatorShape;
|
||||
},
|
||||
never,
|
||||
R | Scope.Scope
|
||||
@@ -433,14 +362,14 @@ export const make = <R>(input: {
|
||||
|
||||
const state: RegistryState = { entries, unavailable, changes };
|
||||
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
|
||||
const reconcile: ProviderInstanceRegistryMutator["Service"]["reconcile"] = (configMap) =>
|
||||
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
|
||||
reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
|
||||
|
||||
// Hydrate the initial configMap synchronously so callers can read
|
||||
// `listInstances` immediately after this effect completes.
|
||||
yield* reconcile(input.configMap);
|
||||
|
||||
const registry = ProviderInstanceRegistry.of({
|
||||
const registry: ProviderInstanceRegistryShape = {
|
||||
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
|
||||
listInstances: Ref.get(entries).pipe(
|
||||
Effect.map(
|
||||
@@ -466,9 +395,9 @@ export const make = <R>(input: {
|
||||
get subscribeChanges() {
|
||||
return PubSub.subscribe(changes);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const mutator = ProviderInstanceRegistryMutator.of({ reconcile });
|
||||
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
|
||||
|
||||
return { registry, mutator };
|
||||
});
|
||||
@@ -480,15 +409,15 @@ export const make = <R>(input: {
|
||||
* wiring up the settings watcher.
|
||||
*
|
||||
* Only exposes the public registry tag — hot-reload consumers should use
|
||||
* `mutableLayer` (below) or the hydration layer.
|
||||
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
|
||||
*/
|
||||
export const layer = <R>(input: {
|
||||
export const ProviderInstanceRegistryLayer = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
|
||||
Layer.effect(
|
||||
ProviderInstanceRegistry,
|
||||
make(input).pipe(Effect.map((built) => built.registry)),
|
||||
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
|
||||
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
|
||||
|
||||
/**
|
||||
@@ -497,12 +426,12 @@ export const layer = <R>(input: {
|
||||
* changes. Tests that exercise the mutator directly can pair this Layer
|
||||
* with a test-local `ServerSettingsService`.
|
||||
*/
|
||||
export const mutableLayer = <R>(input: {
|
||||
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
|
||||
Layer.effectContext(
|
||||
make(input).pipe(
|
||||
makeProviderInstanceRegistry(input).pipe(
|
||||
Effect.map(({ registry, mutator }) =>
|
||||
Context.make(ProviderInstanceRegistry, registry).pipe(
|
||||
Context.add(ProviderInstanceRegistryMutator, mutator),
|
||||
+49
-154
@@ -2,7 +2,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
@@ -25,32 +24,31 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import {
|
||||
checkCodexProviderStatus,
|
||||
type CodexAppServerProviderSnapshot,
|
||||
} from "./Layers/CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./Layers/ClaudeProvider.ts";
|
||||
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
|
||||
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import * as ProviderRegistry from "./ProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerSettingsModule from "../serverSettings.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
import {
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettingsModule from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
|
||||
import * as ProviderRegistry from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
const decodeServerSettings = Schema.decodeSync(ServerSettings);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
|
||||
@@ -473,7 +471,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderRegistry", () => {
|
||||
describe("ProviderRegistryLive", () => {
|
||||
it("treats equal provider snapshots as unchanged", () => {
|
||||
const providers = [
|
||||
{
|
||||
@@ -504,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
assert.strictEqual(ProviderRegistry.haveProvidersChanged(providers, [...providers]), false);
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it("preserves previously discovered provider models when a refresh returns none", () => {
|
||||
@@ -542,10 +540,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(
|
||||
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
|
||||
[...previousProvider.models],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it("fills missing capabilities from the previous provider snapshot", () => {
|
||||
@@ -592,10 +589,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(
|
||||
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
|
||||
[...previousProvider.models],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("does not run provider probes during layer construction", () =>
|
||||
@@ -654,10 +650,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-background-refresh-",
|
||||
}),
|
||||
),
|
||||
@@ -722,10 +718,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = ProviderRegistry.mergeProviderSnapshots(previousProviders, [
|
||||
refreshedCursor,
|
||||
]);
|
||||
const persistedProviders = ProviderRegistry.selectProvidersByKind(
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
@@ -811,10 +805,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
@@ -854,105 +848,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("only keeps hydrated cache state while the boot snapshot is still initial", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
const fallbackProvider = {
|
||||
instanceId: codexInstanceId,
|
||||
driver: codexDriver,
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-04-29T10:01:00.000Z",
|
||||
version: null,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
message: "Codex provider status has not been checked in this session yet.",
|
||||
} as const satisfies ServerProvider;
|
||||
const cachedProvider = {
|
||||
...fallbackProvider,
|
||||
status: "ready",
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-29T10:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
message: "Loaded from the provider status cache.",
|
||||
} as const satisfies ServerProvider;
|
||||
const loadProviders = (snapshotState: "initial" | "live") =>
|
||||
Effect.gen(function* () {
|
||||
const instance = {
|
||||
instanceId: codexInstanceId,
|
||||
driverKind: codexDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: codexDriver,
|
||||
continuationKey: "codex:instance:codex",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(fallbackProvider),
|
||||
isInitialSnapshot: () => snapshotState === "initial",
|
||||
refresh: Effect.succeed(fallbackProvider),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
{
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
},
|
||||
);
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: `t3-provider-registry-cache-${snapshotState}-`,
|
||||
});
|
||||
const configLayer = ServerConfig.layerTest(process.cwd(), baseDir);
|
||||
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(configLayer));
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: codexInstanceId,
|
||||
});
|
||||
yield* writeProviderStatusCache({ filePath, provider: cachedProvider });
|
||||
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.fresh(
|
||||
ProviderRegistry.layer.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(configLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
return yield* ProviderRegistry.ProviderRegistry.pipe(
|
||||
Effect.flatMap((registry) => registry.getProviders),
|
||||
Effect.provide(runtimeServices),
|
||||
);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* loadProviders("initial"), [cachedProvider]);
|
||||
assert.deepStrictEqual(yield* loadProviders("live"), [fallbackProvider]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -1007,10 +902,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-refresh-failure-",
|
||||
}),
|
||||
),
|
||||
@@ -1114,10 +1009,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-sync-failure-",
|
||||
}),
|
||||
),
|
||||
@@ -1207,13 +1102,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1224,7 +1119,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
// outer `NodeServices.layer` on `it.layer(...)` and will
|
||||
// genuinely spawn a subprocess. The missing-binary ENOENT is
|
||||
@@ -1299,13 +1194,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1316,7 +1211,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
|
||||
ChildProcessSpawner.make((command) => {
|
||||
spawnedCommands.push((command as { readonly command: string }).command);
|
||||
@@ -1420,13 +1315,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1437,7 +1332,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
@@ -1481,13 +1376,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
let cursorSpawned = false;
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1498,7 +1393,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
@@ -0,0 +1,698 @@
|
||||
/**
|
||||
* ProviderRegistryLive — aggregates per-instance snapshot streams into a
|
||||
* single materialized list.
|
||||
*
|
||||
* Historically this Layer composed four per-kind Live Layers
|
||||
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
|
||||
* `ServerProviderShape`. Those Lives were deleted during the driver /
|
||||
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
|
||||
* bundled onto the `ProviderInstance` the registry produces.
|
||||
*
|
||||
* Each configured instance (including multi-instance setups like
|
||||
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
|
||||
* keyed by `instanceId`. Instances whose driver is unavailable or whose
|
||||
* config failed to decode are merged from `instanceRegistry.listUnavailable`
|
||||
* as shadow snapshots so the UI can render their exact unavailable reason.
|
||||
*
|
||||
* Cache paths on disk are now keyed by `instanceId`. Because
|
||||
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
|
||||
* `<kind>.json` files remain the on-disk location for that driver's default
|
||||
* instance. Identity-less legacy cache contents are ignored and replaced by
|
||||
* the first live refresh.
|
||||
*
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
isCachedProviderCorrelated,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
|
||||
Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) =>
|
||||
providerSource.getSnapshot.pipe(
|
||||
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
|
||||
const mergedModels = nextModels.map((model) => {
|
||||
const previousModel = previousBySlug.get(model.slug);
|
||||
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
capabilities: previousModel.capabilities,
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
previousProvider: ServerProvider | undefined,
|
||||
nextProvider: ServerProvider,
|
||||
): ServerProvider =>
|
||||
!previousProvider
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
const correlateSnapshotWithSource = (
|
||||
source: ProviderSnapshotSource,
|
||||
snapshot: ServerProvider,
|
||||
): Effect.Effect<ServerProvider> => {
|
||||
if (snapshot.instanceId !== source.instanceId) {
|
||||
return Effect.die(
|
||||
new Error(
|
||||
`Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (snapshot.driver !== source.driverKind) {
|
||||
return Effect.die(
|
||||
new Error(
|
||||
`Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(snapshot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Key a snapshot for aggregation and persistence. Snapshot sources
|
||||
* must be correlated by instance id before reaching this map; missing
|
||||
* identities are defects, not runtime routing fallbacks.
|
||||
*/
|
||||
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
|
||||
return provider.instanceId;
|
||||
};
|
||||
|
||||
// Project a live `ProviderInstance` into the aggregator's consumption
|
||||
// shape. Each call re-captures the instance's `snapshot` closures, so
|
||||
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
|
||||
// its settings changed), a fresh source rides the new PubSub instead
|
||||
// of a closed one.
|
||||
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
getSnapshot: instance.snapshot.getSnapshot,
|
||||
refresh: instance.snapshot.refresh,
|
||||
streamChanges: instance.snapshot.streamChanges,
|
||||
});
|
||||
|
||||
export const ProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const instanceRegistry = yield* ProviderInstanceRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
|
||||
// coalesced updates across every instance.
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
|
||||
// Boot-only: hydrate `providersRef` from the on-disk per-instance
|
||||
// cache so the UI has something to render during the first refresh.
|
||||
// Instances added post-boot skip this path; their first entry in
|
||||
// `providersRef` comes from the reactive `syncLiveSources` pass
|
||||
// below.
|
||||
const bootInstances = yield* instanceRegistry.listInstances;
|
||||
const bootSources = bootInstances.map(buildSnapshotSource);
|
||||
const fallbackProviders = yield* loadProviders(bootSources);
|
||||
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
|
||||
for (let index = 0; index < fallbackProviders.length; index++) {
|
||||
const provider = fallbackProviders[index];
|
||||
const source = bootSources[index];
|
||||
if (provider === undefined || source === undefined) {
|
||||
continue;
|
||||
}
|
||||
fallbackByInstance.set(source.instanceId, provider);
|
||||
}
|
||||
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
bootSources,
|
||||
(source) =>
|
||||
Effect.gen(function* () {
|
||||
// One cache file per configured instance. For the default
|
||||
// instance of a built-in kind the path equals `<kind>.json` —
|
||||
// identical to the legacy filename. We still require the cache
|
||||
// payload to carry matching instance id + driver kind; old
|
||||
// identity-less payloads are discarded and the awaited refresh
|
||||
// below repopulates the cache.
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: source.instanceId,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
const fallbackProvider = fallbackByInstance.get(source.instanceId);
|
||||
if (fallbackProvider === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return yield* readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.flatMap((cachedProvider) => {
|
||||
if (cachedProvider === undefined) {
|
||||
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
// reference is used for identity equality so "no-op" reconciles
|
||||
// (settings unchanged) skip re-subscribing + re-probing.
|
||||
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
|
||||
new Map(),
|
||||
);
|
||||
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
|
||||
// interleave two passes clobbering each other's fiber bookkeeping.
|
||||
const syncSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
|
||||
liveSubsRef,
|
||||
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
|
||||
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
Effect.gen(function* () {
|
||||
// Persist every instance — the file name is the instance id, so
|
||||
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
|
||||
// get their own cache. We resolve the path fresh so snapshots
|
||||
// produced by newly-added instances post-boot still land on disk
|
||||
// without the aggregator holding a stale `cachePathByInstance`
|
||||
// entry.
|
||||
const key = snapshotInstanceKey(provider);
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: key,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
yield* writeProviderStatusCache({ filePath, provider }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
readonly persist?: boolean;
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
? provider
|
||||
: mergeProviderSnapshot(mergedProviders.get(key), provider),
|
||||
);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
return yield* providerSource.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) =>
|
||||
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshAll = Effect.fn("refreshAll")(function* () {
|
||||
const sources = yield* getLiveSources;
|
||||
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
|
||||
if (provider === undefined) {
|
||||
return yield* refreshAll();
|
||||
}
|
||||
// Kind-scoped refreshes target the default instance for that driver.
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(provider);
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find(
|
||||
(candidate) => candidate.instanceId === defaultInstanceId,
|
||||
);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const refreshInstance = Effect.fn("refreshInstance")(function* (
|
||||
instanceId: ProviderInstanceId,
|
||||
) {
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
* down and our `Stream.runForEach` fiber exits naturally.
|
||||
*/
|
||||
const syncLiveSources = syncSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const instances = yield* instanceRegistry.listInstances;
|
||||
const unavailableProviders = yield* instanceRegistry.listUnavailable;
|
||||
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
|
||||
instances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
|
||||
for (const provider of unavailableProviders) {
|
||||
knownInstanceIds.add(snapshotInstanceKey(provider));
|
||||
}
|
||||
const previousSubs = yield* Ref.get(liveSubsRef);
|
||||
|
||||
// Carry over subscriptions for instances whose identity is
|
||||
// unchanged (reconcile treated them as no-op). Instances that
|
||||
// disappeared, or were rebuilt with a different reference,
|
||||
// fall through to the "newly-added" branch below.
|
||||
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
|
||||
for (const [instanceId, previousInstance] of previousSubs) {
|
||||
const nextInstance = nextByInstance.get(instanceId);
|
||||
if (nextInstance !== undefined && nextInstance === previousInstance) {
|
||||
carriedOver.set(instanceId, previousInstance);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect new/rebuilt instances in `nextByInstance` insertion
|
||||
// order (which preserves settings-author order).
|
||||
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
|
||||
for (const [instanceId, instance] of nextByInstance) {
|
||||
if (carriedOver.has(instanceId)) {
|
||||
continue;
|
||||
}
|
||||
newlyAdded.push([instanceId, instance] as const);
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([, instance]) =>
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
);
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
persist: false,
|
||||
replace: true,
|
||||
});
|
||||
|
||||
const nextSubs = new Map(carriedOver);
|
||||
for (const [instanceId, instance] of newlyAdded) {
|
||||
nextSubs.set(instanceId, instance);
|
||||
}
|
||||
yield* Ref.set(liveSubsRef, nextSubs);
|
||||
|
||||
// Drop aggregator state for instances that have disappeared —
|
||||
// otherwise the UI would keep rendering ghosts.
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const providers = orderProviderSnapshots(
|
||||
previousProviders.filter((provider) =>
|
||||
knownInstanceIds.has(snapshotInstanceKey(provider)),
|
||||
),
|
||||
);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.logError(
|
||||
"provider registry instance sync failed; keeping subscription alive",
|
||||
{
|
||||
cause: Cause.pretty(cause),
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// Seed `providersRef` with the boot-time fallback snapshots so
|
||||
// consumers calling `getProviders` immediately after layer build see
|
||||
// a populated list — even before the first `syncLiveSources` refresh
|
||||
// resolves. Cached snapshots (already in `providersRef`) merge with
|
||||
// these via `upsertProviders` so on-disk state wins where present
|
||||
// and pending fallbacks fill the gaps.
|
||||
yield* upsertProviders(fallbackProviders, { publish: false });
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the dequeue synchronously in this
|
||||
// fibre; the subscription is active the instant this `yield*`
|
||||
// returns. Forking the consumer loop later cannot lose a publish
|
||||
// because no publish can reach a not-yet-subscribed dequeue.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
|
||||
// and `forkScoped` only schedules the fibre — so a reconcile that
|
||||
// published between "fibre scheduled" and "fibre starts running"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the `PubSub.Subscription` synchronously
|
||||
// in this fibre; the subscription is registered with the PubSub the
|
||||
// instant this `yield*` returns, so any subsequent publish is
|
||||
// buffered in the subscription regardless of when the consumer
|
||||
// fibre below actually starts running.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
|
||||
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
|
||||
// schedules the consumer fibre — so a reconcile that published
|
||||
// between "fibre scheduled" and "fibre starts running + subscribes"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
// subscription rather than subscribing on stream start, which is
|
||||
// what closes the race.
|
||||
yield* Stream.runForEach(
|
||||
Stream.fromSubscription(instanceChanges),
|
||||
() => syncLiveSourcesAndContinue,
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
|
||||
cause: Cause.Cause<unknown>,
|
||||
) {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
return yield* Ref.get(providersRef);
|
||||
});
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderDriverKind) =>
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
);
|
||||
+38
-84
@@ -30,7 +30,6 @@ import * as Metric from "effect/Metric";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
@@ -42,27 +41,23 @@ import {
|
||||
ProviderUnsupportedError,
|
||||
ProviderValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
} from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "./ProviderService.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
|
||||
import { makeAdapterRegistryMock } from "./testUtils/providerAdapterRegistryMock.ts";
|
||||
|
||||
// Several tests build two ProviderService instances in one scope to simulate a
|
||||
// process restart. Construct a fresh Layer for each build so Layer memoization
|
||||
// cannot reuse the first service instance.
|
||||
const makeFreshProviderServiceLayer = (options?: ProviderService.ProviderServiceOptions) =>
|
||||
Layer.effect(ProviderService.ProviderService, ProviderService.make(options));
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
|
||||
|
||||
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
|
||||
@@ -289,11 +284,11 @@ function makeProviderServiceLayer() {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
makeFreshProviderServiceLayer().pipe(
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -342,11 +337,9 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = Layer.mergeAll(
|
||||
makeFreshProviderServiceLayer().pipe(
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -404,10 +397,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -488,10 +479,10 @@ it.effect(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(serverSettingsLayer),
|
||||
@@ -560,10 +551,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -607,10 +596,8 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer({
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive({
|
||||
canonicalEventLogger: {
|
||||
filePath: "memory://provider-canonical-events",
|
||||
write: (event, threadId) => {
|
||||
@@ -669,9 +656,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
@@ -682,7 +667,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
});
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -743,10 +728,10 @@ it.effect(
|
||||
[ProviderDriverKind.make("codex")]: firstCodex.adapter,
|
||||
});
|
||||
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -802,10 +787,10 @@ it.effect(
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: secondCodex.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1086,18 +1071,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
const exit = yield* Effect.exit(provider.listSessions());
|
||||
assert.equal(Exit.hasDies(exit), true);
|
||||
const defect = Exit.findDefect(exit);
|
||||
assert.equal(Result.isSuccess(defect), true);
|
||||
if (Result.isSuccess(defect)) {
|
||||
assert.instanceOf(defect.success, ProviderService.ProviderSessionBindingCorrelationError);
|
||||
assert.deepInclude(defect.success, {
|
||||
threadId,
|
||||
sessionProvider: ProviderDriverKind.make("codex"),
|
||||
bindingProvider: ProviderDriverKind.make("claudeAgent"),
|
||||
sessionInstanceId: codexInstanceId,
|
||||
bindingInstanceId: claudeAgentInstanceId,
|
||||
});
|
||||
}
|
||||
yield* directory.upsert({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -1325,10 +1298,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const firstRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
|
||||
});
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -1363,10 +1336,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1431,10 +1404,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const firstRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
|
||||
});
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -1464,10 +1437,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1810,25 +1783,6 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
|
||||
const validation = makeProviderServiceLayer();
|
||||
validation.layer("ProviderServiceLive validation", (it) => {
|
||||
it.effect("rejects whitespace-only turns without attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
validation.codex.sendTurn.mockClear();
|
||||
const failure = yield* provider
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-whitespace-only"),
|
||||
input: " \n\t ",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(failure, ProviderValidationError);
|
||||
assert.equal(failure.operation, "ProviderService.sendTurn");
|
||||
assert.equal(validation.codex.sendTurn.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects session starts without an explicit provider instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
+225
-326
@@ -1,15 +1,13 @@
|
||||
/**
|
||||
* ProviderService - Cross-provider session and turn service.
|
||||
* ProviderServiceLive - Cross-provider orchestration layer.
|
||||
*
|
||||
* Routes validated transport/API calls to provider adapters through
|
||||
* `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
|
||||
* unified provider event stream for subscribers.
|
||||
*
|
||||
* It does not implement provider protocol details (adapter concern).
|
||||
* Uses Effect `Context.Service` for dependency injection and returns typed
|
||||
* domain errors for validation, session, codex, and checkpoint workflows.
|
||||
*
|
||||
* @module ProviderService
|
||||
* @module ProviderServiceLive
|
||||
*/
|
||||
import {
|
||||
ModelSelection,
|
||||
@@ -21,13 +19,12 @@ import {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -47,141 +44,17 @@ import {
|
||||
providerTurnsTotal,
|
||||
providerTurnMetricAttributes,
|
||||
withMetrics,
|
||||
} from "../observability/Metrics.ts";
|
||||
import {
|
||||
type ProviderAdapterError,
|
||||
type ProviderServiceError,
|
||||
ProviderValidationError,
|
||||
} from "./Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterCapabilities,
|
||||
ProviderAdapterShape,
|
||||
} from "./Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
|
||||
} from "../../observability/Metrics.ts";
|
||||
import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
|
||||
import {
|
||||
clearAllMcpProviderSessions,
|
||||
clearMcpProviderSession,
|
||||
setMcpProviderSession,
|
||||
} from "../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
issueActiveMcpCredential,
|
||||
revokeActiveMcpThread,
|
||||
revokeAllActiveMcpCredentials,
|
||||
} from "../mcp/McpSessionRegistry.ts";
|
||||
|
||||
export class ProviderBindingInstanceIdMissingError extends Schema.TaggedErrorClass<ProviderBindingInstanceIdMissingError>()(
|
||||
"ProviderBindingInstanceIdMissingError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
provider: Schema.optional(ProviderDriverKind),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const provider = this.provider === undefined ? "" : ` for provider '${this.provider}'`;
|
||||
return `Provider binding is missing an instance id${provider} in ${this.operation}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderRuntimeEventCorrelationError extends Schema.TaggedErrorClass<ProviderRuntimeEventCorrelationError>()(
|
||||
"ProviderRuntimeEventCorrelationError",
|
||||
{
|
||||
sourceInstanceId: ProviderInstanceId,
|
||||
sourceProvider: ProviderDriverKind,
|
||||
eventInstanceId: Schema.optional(ProviderInstanceId),
|
||||
eventProvider: ProviderDriverKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const eventInstanceId = this.eventInstanceId ?? "unattributed";
|
||||
return `Provider runtime event correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceProvider}) and emitted instance '${eventInstanceId}' (${this.eventProvider}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderSessionBindingCorrelationError extends Schema.TaggedErrorClass<ProviderSessionBindingCorrelationError>()(
|
||||
"ProviderSessionBindingCorrelationError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
sessionProvider: ProviderDriverKind,
|
||||
bindingProvider: ProviderDriverKind,
|
||||
sessionInstanceId: ProviderInstanceId,
|
||||
bindingInstanceId: ProviderInstanceId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Active provider session and persisted binding disagree for thread '${this.threadId}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderService extends Context.Service<
|
||||
ProviderService,
|
||||
{
|
||||
/** Start a provider session. */
|
||||
readonly startSession: (
|
||||
threadId: ThreadId,
|
||||
input: ProviderSessionStartInput,
|
||||
) => Effect.Effect<ProviderSession, ProviderServiceError>;
|
||||
|
||||
/** Send a turn through the adapter bound to the session. */
|
||||
readonly sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;
|
||||
|
||||
/** Interrupt a running provider turn. */
|
||||
readonly interruptTurn: (
|
||||
input: ProviderInterruptTurnInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/** Respond to a provider approval request. */
|
||||
readonly respondToRequest: (
|
||||
input: ProviderRespondToRequestInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/** Respond to a structured provider user-input request. */
|
||||
readonly respondToUserInput: (
|
||||
input: ProviderRespondToUserInputInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/** Stop a provider session. */
|
||||
readonly stopSession: (
|
||||
input: ProviderStopSessionInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* List active provider sessions.
|
||||
*
|
||||
* Aggregates runtime session lists from all registered adapters.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
|
||||
|
||||
/** Read capabilities for the adapter bound to a configured provider instance. */
|
||||
readonly getCapabilities: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;
|
||||
|
||||
/** Read routing metadata for a configured provider instance. */
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterRegistry.ProviderInstanceRoutingInfo, ProviderServiceError>;
|
||||
|
||||
/** Roll back provider conversation state by a number of turns. */
|
||||
readonly rollbackConversation: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly numTurns: number;
|
||||
}) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Canonical provider runtime event stream.
|
||||
*
|
||||
* Fan-out is owned by ProviderService (not by a standalone event-bus service).
|
||||
*/
|
||||
readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;
|
||||
}
|
||||
>()("t3/provider/ProviderService") {}
|
||||
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
@@ -189,15 +62,30 @@ const isModelSelection = Schema.is(ModelSelection);
|
||||
* from `ProviderEventLoggers`. Production wiring leaves this undefined and
|
||||
* reads the logger off the tag.
|
||||
*/
|
||||
export interface ProviderServiceOptions {
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
|
||||
ProviderService.ProviderService["Service"][Name];
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
numTurns: NonNegativeInt,
|
||||
});
|
||||
|
||||
function toValidationError(
|
||||
operation: string,
|
||||
issue: string,
|
||||
cause?: unknown,
|
||||
): ProviderValidationError {
|
||||
return new ProviderValidationError({
|
||||
operation,
|
||||
issue,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const decodeInputOrValidationError = <S extends Schema.Top>(input: {
|
||||
readonly operation: string;
|
||||
readonly schema: S;
|
||||
@@ -284,10 +172,11 @@ const dieOnMissingBindingInstanceId = (
|
||||
if (payload.providerInstanceId !== undefined) {
|
||||
return payload.providerInstanceId;
|
||||
}
|
||||
throw new ProviderBindingInstanceIdMissingError({
|
||||
operation,
|
||||
...(payload.provider === undefined ? {} : { provider: payload.provider }),
|
||||
});
|
||||
throw new Error(
|
||||
payload.provider
|
||||
? `${operation}: provider instance id is required for provider '${payload.provider}'.`
|
||||
: `${operation}: provider instance id is required.`,
|
||||
);
|
||||
};
|
||||
|
||||
const correlateRuntimeEventWithInstance = (
|
||||
@@ -297,23 +186,22 @@ const correlateRuntimeEventWithInstance = (
|
||||
},
|
||||
event: ProviderRuntimeEvent,
|
||||
): ProviderRuntimeEvent => {
|
||||
if (
|
||||
event.provider !== source.provider ||
|
||||
(event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId)
|
||||
) {
|
||||
throw new ProviderRuntimeEventCorrelationError({
|
||||
sourceInstanceId: source.instanceId,
|
||||
sourceProvider: source.provider,
|
||||
...(event.providerInstanceId === undefined
|
||||
? {}
|
||||
: { eventInstanceId: event.providerInstanceId }),
|
||||
eventProvider: event.provider,
|
||||
});
|
||||
if (event.provider !== source.provider) {
|
||||
throw new Error(
|
||||
`ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
|
||||
);
|
||||
}
|
||||
if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
|
||||
throw new Error(
|
||||
`ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
|
||||
);
|
||||
}
|
||||
return { ...event, providerInstanceId: source.instanceId };
|
||||
};
|
||||
|
||||
export const make = Effect.fn("ProviderService.make")(function* (options?: ProviderServiceOptions) {
|
||||
const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
options?: ProviderServiceLiveOptions,
|
||||
) {
|
||||
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
// Options-provided logger wins (test overrides); otherwise we take whatever
|
||||
@@ -327,14 +215,16 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
Effect.tap((credential) =>
|
||||
credential ? Effect.sync(() => setMcpProviderSession(credential.config)) : Effect.void,
|
||||
credential
|
||||
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
const clearMcpSession = (threadId: ThreadId) =>
|
||||
revokeActiveMcpThread(threadId).pipe(
|
||||
Effect.tap(() => Effect.sync(() => clearMcpProviderSession(threadId))),
|
||||
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
|
||||
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
|
||||
);
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
@@ -358,12 +248,12 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
payload.providerInstanceId !== undefined
|
||||
? Effect.succeed(payload.providerInstanceId)
|
||||
: Effect.fail(
|
||||
new ProviderValidationError({
|
||||
toValidationError(
|
||||
operation,
|
||||
issue: payload.provider
|
||||
payload.provider
|
||||
? `Provider instance id is required for provider '${payload.provider}'.`
|
||||
: "Provider instance id is required.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsertSessionBinding = (
|
||||
@@ -498,10 +388,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
@@ -521,10 +411,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
.pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(input.binding.threadId);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(
|
||||
@@ -555,10 +445,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const bindingOption = yield* directory.getBinding(input.threadId);
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (!binding) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
);
|
||||
}
|
||||
const instanceId = yield* requireBindingInstanceId(input.operation, binding);
|
||||
const adapter = yield* registry.getByInstance(instanceId);
|
||||
@@ -629,7 +519,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
);
|
||||
});
|
||||
|
||||
const startSession: ProviderService["Service"]["startSession"] = Effect.fn("startSession")(
|
||||
const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
|
||||
function* (threadId, rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
@@ -653,10 +543,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const resolvedProvider = instanceInfo.driverKind;
|
||||
metricProvider = resolvedProvider;
|
||||
if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
);
|
||||
}
|
||||
const input = {
|
||||
...parsed,
|
||||
@@ -664,10 +554,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
provider: resolvedProvider,
|
||||
};
|
||||
if (!instanceInfo.enabled) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
@@ -712,10 +602,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(threadId);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
);
|
||||
}
|
||||
const sessionWithInstance = {
|
||||
...session,
|
||||
@@ -752,84 +642,82 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const sendTurn: ProviderService["Service"]["sendTurn"] = Effect.fn("sendTurn")(
|
||||
function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input?.trim() && input.attachments.length === 0) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
issue: "Either input text or at least one attachment is required",
|
||||
});
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "send-turn",
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.interaction_mode": input.interactionMode,
|
||||
"provider.attachment_count": input.attachments.length,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
let metricModel = input.modelSelection?.model;
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
metricModel = input.modelSelection?.model;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.kind": routed.adapter.provider,
|
||||
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
providerInstanceId: routed.instanceId,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: yield* nowIso,
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
timer: providerTurnDuration,
|
||||
attributes: () =>
|
||||
providerTurnMetricAttributes({
|
||||
provider: metricProvider,
|
||||
model: metricModel,
|
||||
extra: {
|
||||
operation: "send",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input && input.attachments.length === 0) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.sendTurn",
|
||||
"Either input text or at least one attachment is required",
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "send-turn",
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.interaction_mode": input.interactionMode,
|
||||
"provider.attachment_count": input.attachments.length,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
let metricModel = input.modelSelection?.model;
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
metricModel = input.modelSelection?.model;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.kind": routed.adapter.provider,
|
||||
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
providerInstanceId: routed.instanceId,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: yield* nowIso,
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
timer: providerTurnDuration,
|
||||
attributes: () =>
|
||||
providerTurnMetricAttributes({
|
||||
provider: metricProvider,
|
||||
model: metricModel,
|
||||
extra: {
|
||||
operation: "send",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderService["Service"]["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.interruptTurn",
|
||||
@@ -866,45 +754,45 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const respondToRequest: ProviderService["Service"]["respondToRequest"] = Effect.fn(
|
||||
"respondToRequest",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "respond-to-request",
|
||||
"provider.kind": routed.adapter.provider,
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.request_id": input.requestId,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
outcomeAttributes: () =>
|
||||
providerMetricAttributes(metricProvider, {
|
||||
operation: "approval-response",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "respond-to-request",
|
||||
"provider.kind": routed.adapter.provider,
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.request_id": input.requestId,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
outcomeAttributes: () =>
|
||||
providerMetricAttributes(metricProvider, {
|
||||
operation: "approval-response",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const respondToUserInput: ProviderService["Service"]["respondToUserInput"] = Effect.fn(
|
||||
const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
|
||||
"respondToUserInput",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -938,7 +826,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
);
|
||||
});
|
||||
|
||||
const stopSession: ProviderService["Service"]["stopSession"] = Effect.fn("stopSession")(
|
||||
const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.stopSession",
|
||||
@@ -986,7 +874,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const listSessions: ProviderService["Service"]["listSessions"] = Effect.fn("listSessions")(
|
||||
const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
|
||||
function* () {
|
||||
const currentAdapters = yield* getAdapterEntries;
|
||||
const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
|
||||
@@ -1047,18 +935,18 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
"ProviderService.listSessions",
|
||||
binding,
|
||||
);
|
||||
if (
|
||||
binding.provider !== session.provider ||
|
||||
overrides.providerInstanceId !== session.providerInstanceId
|
||||
) {
|
||||
if (binding.provider !== session.provider) {
|
||||
return yield* Effect.die(
|
||||
new ProviderSessionBindingCorrelationError({
|
||||
threadId: session.threadId,
|
||||
sessionProvider: session.provider,
|
||||
bindingProvider: binding.provider,
|
||||
sessionInstanceId: session.providerInstanceId,
|
||||
bindingInstanceId: overrides.providerInstanceId,
|
||||
}),
|
||||
new Error(
|
||||
`ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (overrides.providerInstanceId !== session.providerInstanceId) {
|
||||
return yield* Effect.die(
|
||||
new Error(
|
||||
`ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
@@ -1073,13 +961,13 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const getCapabilities: ProviderService["Service"]["getCapabilities"] = (instanceId) =>
|
||||
const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
|
||||
registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
|
||||
const getInstanceInfo: ProviderService["Service"]["getInstanceInfo"] = (instanceId) =>
|
||||
const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
|
||||
registry.getInstanceInfo(instanceId);
|
||||
|
||||
const rollbackConversation: ProviderService["Service"]["rollbackConversation"] = Effect.fn(
|
||||
const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
|
||||
"rollbackConversation",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -1142,8 +1030,8 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* revokeAllActiveMcpCredentials();
|
||||
clearAllMcpProviderSessions();
|
||||
yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
|
||||
McpProviderSession.clearAllMcpProviderSessions();
|
||||
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
|
||||
yield* Effect.forEach(bindings, (binding) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1172,11 +1060,15 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
runStopAll().pipe(
|
||||
Effect.catchCause((cause) => Effect.logWarning("failed to stop provider service", { cause })),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to stop provider service", {
|
||||
errorTag: causeErrorTag(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return ProviderService.of({
|
||||
return {
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -1190,10 +1082,17 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
get streamEvents(): ProviderService["Service"]["streamEvents"] {
|
||||
get streamEvents(): ProviderServiceMethod<"streamEvents"> {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
});
|
||||
} satisfies ProviderService.ProviderService["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderService, make());
|
||||
export const ProviderServiceLive = Layer.effect(
|
||||
ProviderService.ProviderService,
|
||||
makeProviderService(),
|
||||
);
|
||||
|
||||
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
|
||||
return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
|
||||
}
|
||||
+11
-22
@@ -15,16 +15,16 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import { isProviderSessionNotFoundError } from "./Errors.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
|
||||
return Layer.mergeAll(
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const initialThreadId = ThreadId.make("thread-1");
|
||||
@@ -77,20 +77,9 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
}));
|
||||
|
||||
it("reports a missing provider binding as a domain not-found error", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const error = yield* directory.getProvider(threadId).pipe(Effect.flip);
|
||||
|
||||
assert(isProviderSessionNotFoundError(error));
|
||||
assert.equal(error.threadId, threadId);
|
||||
}));
|
||||
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const threadId = ThreadId.make("thread-runtime");
|
||||
@@ -135,7 +124,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const olderThreadId = ThreadId.make("thread-runtime-older");
|
||||
@@ -209,7 +198,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
|
||||
@@ -247,7 +236,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
const threadId = ThreadId.make("thread-restart");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
@@ -255,7 +244,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
assert.equal(provider, "codex");
|
||||
@@ -0,0 +1,201 @@
|
||||
import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
type ProviderRuntimeBindingWithMetadata,
|
||||
type ProviderSessionDirectoryShape,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
|
||||
|
||||
function toPersistenceError(operation: string) {
|
||||
return (cause: unknown) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Failed to execute ${operation}.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeProviderDriverKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKindValue(providerName).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function mergeRuntimePayload(
|
||||
existing: unknown | null,
|
||||
next: unknown | null | undefined,
|
||||
): unknown | null {
|
||||
if (next === undefined) {
|
||||
return existing ?? null;
|
||||
}
|
||||
if (isRecord(existing) && isRecord(next)) {
|
||||
return { ...existing, ...next };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function toRuntimeBinding(
|
||||
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
|
||||
Effect.map(
|
||||
(provider) =>
|
||||
({
|
||||
threadId: runtime.threadId,
|
||||
provider,
|
||||
// Migration boundary only: rows written before the instance split
|
||||
// have a null provider_instance_id. Promote them as they leave
|
||||
// persistence so hot routing code never has to infer an instance
|
||||
// from a driver kind.
|
||||
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
|
||||
adapterKey: runtime.adapterKey,
|
||||
runtimeMode: runtime.runtimeMode,
|
||||
status: runtime.status,
|
||||
resumeCursor: runtime.resumeCursor,
|
||||
runtimePayload: runtime.runtimePayload,
|
||||
lastSeenAt: runtime.lastSeenAt,
|
||||
}) satisfies ProviderRuntimeBindingWithMetadata,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding = (threadId: ThreadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
|
||||
Effect.flatMap((runtime) =>
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((binding) => Option.some(binding)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
|
||||
const existing = yield* repository
|
||||
.getByThreadId({ threadId: binding.threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
|
||||
|
||||
const existingRuntime = Option.getOrUndefined(existing);
|
||||
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
|
||||
if (!resolvedThreadId) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "threadId must be a non-empty string.",
|
||||
});
|
||||
}
|
||||
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const providerChanged =
|
||||
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
|
||||
const providerInstanceId =
|
||||
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
|
||||
if (providerInstanceId === null || providerInstanceId === undefined) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "providerInstanceId is required for provider session runtime bindings.",
|
||||
});
|
||||
}
|
||||
yield* repository
|
||||
.upsert({
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
providerInstanceId,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
binding.resumeCursor !== undefined
|
||||
? binding.resumeCursor
|
||||
: (existingRuntime?.resumeCursor ?? null),
|
||||
runtimePayload: mergeRuntimePayload(
|
||||
existingRuntime?.runtimePayload ?? null,
|
||||
binding.runtimePayload,
|
||||
),
|
||||
})
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
|
||||
});
|
||||
|
||||
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
|
||||
getBinding(threadId).pipe(
|
||||
Effect.flatMap((binding) =>
|
||||
Option.match(binding, {
|
||||
onSome: (value) => Effect.succeed(value.provider),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getProvider",
|
||||
detail: `No persisted provider binding found for thread '${threadId}'.`,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
} satisfies ProviderSessionDirectoryShape;
|
||||
});
|
||||
|
||||
export const ProviderSessionDirectoryLive = Layer.effect(
|
||||
ProviderSessionDirectory,
|
||||
makeProviderSessionDirectory,
|
||||
);
|
||||
|
||||
export function makeProviderSessionDirectoryLive() {
|
||||
return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);
|
||||
}
|
||||
+26
-41
@@ -17,13 +17,14 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderValidationError } from "./Errors.ts";
|
||||
import * as ProviderSessionReaper from "./ProviderSessionReaper.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
|
||||
|
||||
const defaultModelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
@@ -116,8 +117,7 @@ function makeReadModel(
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
| ProviderSessionReaper.ProviderSessionReaper
|
||||
| ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -137,19 +137,19 @@ describe("ProviderSessionReaper", () => {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderService.ProviderService["Service"]["stopSession"]>(
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>,
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const providerService: ProviderService.ProviderService["Service"] = {
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -178,21 +178,18 @@ describe("ProviderSessionReaper", () => {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = Layer.effect(
|
||||
ProviderSessionReaper.ProviderSessionReaper,
|
||||
ProviderSessionReaper.make({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}),
|
||||
).pipe(
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, providerService)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
@@ -260,9 +257,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -312,9 +307,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
@@ -363,9 +356,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
@@ -414,9 +405,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
@@ -502,9 +491,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -587,9 +574,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
+25
-22
@@ -1,37 +1,31 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
|
||||
export class ProviderSessionReaper extends Context.Service<
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
{
|
||||
/** Start the background provider session reaper within the provided scope. */
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/provider/ProviderSessionReaper") {}
|
||||
type ProviderSessionReaperShape,
|
||||
} from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService } from "../Services/ProviderService.ts";
|
||||
|
||||
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface ProviderSessionReaperOptions {
|
||||
export interface ProviderSessionReaperLiveOptions {
|
||||
readonly inactivityThresholdMs?: number;
|
||||
readonly sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
@@ -109,15 +103,19 @@ export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
}
|
||||
});
|
||||
|
||||
const start: ProviderSessionReaper["Service"]["start"] = () =>
|
||||
const start: ProviderSessionReaperShape["start"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
sweep.pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", { error }),
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.catchDefect((defect: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", { defect }),
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", {
|
||||
defect,
|
||||
}),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
||||
),
|
||||
@@ -129,7 +127,12 @@ export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
});
|
||||
});
|
||||
|
||||
return ProviderSessionReaper.of({ start });
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderSessionReaperShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderSessionReaper, make());
|
||||
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
|
||||
|
||||
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
|
||||
@@ -1,167 +0,0 @@
|
||||
/**
|
||||
* ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.
|
||||
*
|
||||
* Maps a `ProviderInstanceId` (the new per-instance routing key) or a
|
||||
* `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete
|
||||
* adapter service (Codex, Claude, etc). It does not own session lifecycle
|
||||
* or routing rules; `ProviderService` uses this registry together with
|
||||
* `ProviderSessionDirectory`.
|
||||
*
|
||||
* During the driver/instance migration this tag exposes both flavours:
|
||||
*
|
||||
* - `getByInstance` / `listInstances` — new per-instance routing. Callers
|
||||
* that already know an `instanceId` (threads, sessions, events)
|
||||
* should prefer these.
|
||||
* - `listProviders` — legacy kind-keyed routing for default instances
|
||||
* (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D
|
||||
* behaviour. New code should not grow additional callers of the kind-keyed
|
||||
* methods; they exist so the settings UI, WS refresh RPC, and a handful
|
||||
* of legacy persisted rows can still be routed during the rollout.
|
||||
*
|
||||
* Adapter lookups are resolved dynamically through `ProviderInstanceRegistry`.
|
||||
* Settings-driven hot reload is therefore visible immediately without
|
||||
* rebuilding this facade.
|
||||
*
|
||||
* @module ProviderAdapterRegistry
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as PubSub from "effect/PubSub";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderUnsupportedError, type ProviderAdapterError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ProviderContinuationIdentity } from "./ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
|
||||
export interface ProviderInstanceRoutingInfo {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
}
|
||||
|
||||
export class ProviderAdapterRegistry extends Context.Service<
|
||||
ProviderAdapterRegistry,
|
||||
{
|
||||
/**
|
||||
* Resolve the adapter for a specific instance id. Returns
|
||||
* `ProviderUnsupportedError` if no such instance is currently registered
|
||||
* (which covers "never configured" and "configured but the driver is
|
||||
* unavailable in this build"; both surface the same failure to callers
|
||||
* that expect a working adapter).
|
||||
*/
|
||||
readonly getByInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;
|
||||
|
||||
/** Resolve routing metadata for a specific live provider instance. */
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
|
||||
|
||||
/**
|
||||
* List all live instance ids. Excludes unavailable/shadow instances because
|
||||
* callers of this method want something they can pass to `getByInstance`.
|
||||
*/
|
||||
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||
|
||||
/**
|
||||
* List provider kinds whose default instance is currently registered.
|
||||
*
|
||||
* @deprecated Prefer `listInstances`. Retained for migration-era call sites
|
||||
* that iterate providers to build UI or metrics.
|
||||
*/
|
||||
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
|
||||
|
||||
/**
|
||||
* Change notification stream mirroring
|
||||
* `ProviderInstanceRegistry.streamChanges`. Emits one `void` tick whenever
|
||||
* the set of live instances changes. Consumers that fan out
|
||||
* `adapter.streamEvents` per instance re-pull `listInstances` on each tick
|
||||
* and fork subscriptions for instances they have not seen yet.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
|
||||
/**
|
||||
* Acquire a change subscription synchronously in the caller's current
|
||||
* fiber. Consumers that must avoid missing a publish between initial
|
||||
* reconciliation and watcher startup should use this, then fork
|
||||
* `Stream.fromSubscription`.
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/provider/ProviderAdapterRegistry") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
|
||||
|
||||
const getByInstance: ProviderAdapterRegistry["Service"]["getByInstance"] = (instanceId) =>
|
||||
registry
|
||||
.getInstance(instanceId)
|
||||
.pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(new ProviderUnsupportedError({ provider: instanceId }))
|
||||
: Effect.succeed(instance.adapter),
|
||||
),
|
||||
);
|
||||
|
||||
const getInstanceInfo: ProviderAdapterRegistry["Service"]["getInstanceInfo"] = (instanceId) =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(new ProviderUnsupportedError({ provider: instanceId }))
|
||||
: Effect.succeed({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
displayName: instance.displayName,
|
||||
accentColor: instance.accentColor,
|
||||
enabled: instance.enabled,
|
||||
continuationIdentity: instance.continuationIdentity,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listInstances: ProviderAdapterRegistry["Service"]["listInstances"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
|
||||
);
|
||||
|
||||
const listProviders: ProviderAdapterRegistry["Service"]["listProviders"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => {
|
||||
const kinds = new Set<ProviderDriverKind>();
|
||||
for (const instance of instances) {
|
||||
if (instance.instanceId === defaultInstanceIdForDriver(instance.driverKind)) {
|
||||
// Only default instances appear through this legacy view; custom
|
||||
// instances such as `codex_personal` have no driver-kind identity.
|
||||
kinds.add(instance.driverKind);
|
||||
}
|
||||
}
|
||||
return Array.from(kinds);
|
||||
}),
|
||||
);
|
||||
|
||||
return ProviderAdapterRegistry.of({
|
||||
getByInstance,
|
||||
getInstanceInfo,
|
||||
listInstances,
|
||||
listProviders,
|
||||
// The facade owns no state; the instance registry already coalesces
|
||||
// add, remove, and rebuild notifications into a single change channel.
|
||||
streamChanges: registry.streamChanges,
|
||||
subscribeChanges: registry.subscribeChanges,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderAdapterRegistry, make);
|
||||
@@ -1,769 +0,0 @@
|
||||
/**
|
||||
* ProviderRegistry aggregates per-instance snapshot streams into a
|
||||
* single materialized list.
|
||||
*
|
||||
* Historically this Layer composed four per-kind Live Layers
|
||||
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
|
||||
* `ServerProviderShape`. Those Lives were deleted during the driver /
|
||||
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
|
||||
* bundled onto the `ProviderInstance` the registry produces.
|
||||
*
|
||||
* Each configured instance (including multi-instance setups like
|
||||
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
|
||||
* keyed by `instanceId`. Instances whose driver is unavailable or whose
|
||||
* config failed to decode are merged from `instanceRegistry.listUnavailable`
|
||||
* as shadow snapshots so the UI can render their exact unavailable reason.
|
||||
*
|
||||
* Cache paths on disk are now keyed by `instanceId`. Because
|
||||
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
|
||||
* `<kind>.json` files remain the on-disk location for that driver's default
|
||||
* instance. Identity-less legacy cache contents are ignored and replaced by
|
||||
* the first live refresh.
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
isCachedProviderCorrelated,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import {
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export class ProviderSnapshotCorrelationError extends Schema.TaggedErrorClass<ProviderSnapshotCorrelationError>()(
|
||||
"ProviderSnapshotCorrelationError",
|
||||
{
|
||||
sourceInstanceId: ProviderInstanceId,
|
||||
snapshotInstanceId: ProviderInstanceId,
|
||||
sourceDriver: ProviderDriverKind,
|
||||
snapshotDriver: ProviderDriverKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider snapshot correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceDriver}) and emitted instance '${this.snapshotInstanceId}' (${this.snapshotDriver}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderRegistry extends Context.Service<
|
||||
ProviderRegistry,
|
||||
{
|
||||
/**
|
||||
* Read the latest provider snapshots for every configured instance.
|
||||
* Multiple snapshots may share the same driver kind and disambiguate via
|
||||
* `instanceId`.
|
||||
*/
|
||||
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh all providers, or the default instance of the specified kind
|
||||
* when supplied.
|
||||
*
|
||||
* Retained for compatibility with legacy call sites such as the WS refresh
|
||||
* RPC and orchestration metrics.
|
||||
*
|
||||
* @deprecated Prefer `refreshInstance` for new call sites.
|
||||
*/
|
||||
readonly refresh: (
|
||||
provider?: ProviderDriverKind,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh one configured instance. Unknown ids resolve to the current
|
||||
* cached list, matching the legacy `refresh` behavior so transport layers
|
||||
* do not have to special-case unknown ids.
|
||||
*/
|
||||
readonly refreshInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve maintenance capabilities for one live provider instance,
|
||||
* falling back to manual-only capabilities when it is unavailable.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance. This
|
||||
* state is never persisted. Today only update actions are projected onto
|
||||
* `ServerProvider.updateState`; install/auth actions can extend this map
|
||||
* without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates, one emission per aggregated change.
|
||||
* The array contains the full current state.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
|
||||
}
|
||||
>()("t3/provider/ProviderRegistry") {}
|
||||
|
||||
const loadProviders = (
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
|
||||
Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) =>
|
||||
providerSource.getSnapshot.pipe(
|
||||
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
|
||||
const mergedModels = nextModels.map((model) => {
|
||||
const previousModel = previousBySlug.get(model.slug);
|
||||
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
capabilities: previousModel.capabilities,
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
previousProvider: ServerProvider | undefined,
|
||||
nextProvider: ServerProvider,
|
||||
): ServerProvider =>
|
||||
!previousProvider
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
const correlateSnapshotWithSource = (
|
||||
source: ProviderSnapshotSource,
|
||||
snapshot: ServerProvider,
|
||||
): Effect.Effect<ServerProvider> => {
|
||||
if (snapshot.instanceId !== source.instanceId || snapshot.driver !== source.driverKind) {
|
||||
return Effect.die(
|
||||
new ProviderSnapshotCorrelationError({
|
||||
sourceInstanceId: source.instanceId,
|
||||
snapshotInstanceId: snapshot.instanceId,
|
||||
sourceDriver: source.driverKind,
|
||||
snapshotDriver: snapshot.driver,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(snapshot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Key a snapshot for aggregation and persistence. Snapshot sources
|
||||
* must be correlated by instance id before reaching this map; missing
|
||||
* identities are defects, not runtime routing fallbacks.
|
||||
*/
|
||||
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
|
||||
return provider.instanceId;
|
||||
};
|
||||
|
||||
// Project a live `ProviderInstance` into the aggregator's consumption
|
||||
// shape. Each call re-captures the instance's `snapshot` closures, so
|
||||
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
|
||||
// its settings changed), a fresh source rides the new PubSub instead
|
||||
// of a closed one.
|
||||
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
getSnapshot: instance.snapshot.getSnapshot,
|
||||
...(instance.snapshot.isInitialSnapshot === undefined
|
||||
? {}
|
||||
: { isInitialSnapshot: instance.snapshot.isInitialSnapshot }),
|
||||
refresh: instance.snapshot.refresh,
|
||||
streamChanges: instance.snapshot.streamChanges,
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
|
||||
const config = yield* Config.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
|
||||
// coalesced updates across every instance.
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
|
||||
// Boot-only: hydrate `providersRef` from the on-disk per-instance
|
||||
// cache so the UI has something to render during the first refresh.
|
||||
// Instances added post-boot skip this path; their first entry in
|
||||
// `providersRef` comes from the reactive `syncLiveSources` pass
|
||||
// below.
|
||||
const bootInstances = yield* instanceRegistry.listInstances;
|
||||
const bootSources = bootInstances.map(buildSnapshotSource);
|
||||
const fallbackProviders = yield* loadProviders(bootSources);
|
||||
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
|
||||
for (let index = 0; index < fallbackProviders.length; index++) {
|
||||
const provider = fallbackProviders[index];
|
||||
const source = bootSources[index];
|
||||
if (provider === undefined || source === undefined) {
|
||||
continue;
|
||||
}
|
||||
fallbackByInstance.set(source.instanceId, provider);
|
||||
}
|
||||
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
bootSources,
|
||||
(source) =>
|
||||
Effect.gen(function* () {
|
||||
// One cache file per configured instance. For the default
|
||||
// instance of a built-in kind the path equals `<kind>.json` —
|
||||
// identical to the legacy filename. We still require the cache
|
||||
// payload to carry matching instance id + driver kind; old
|
||||
// identity-less payloads are discarded and the awaited refresh
|
||||
// below repopulates the cache.
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: source.instanceId,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
const fallbackProvider = fallbackByInstance.get(source.instanceId);
|
||||
if (fallbackProvider === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return yield* readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.flatMap((cachedProvider) => {
|
||||
if (cachedProvider === undefined) {
|
||||
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cachedInstanceIds = new Set(cachedProviders.map(snapshotInstanceKey));
|
||||
const bootInstancesById = new Map(
|
||||
bootInstances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
// reference is used for identity equality so "no-op" reconciles
|
||||
// (settings unchanged) skip re-subscribing + re-probing.
|
||||
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(new Map());
|
||||
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
|
||||
// interleave two passes clobbering each other's fiber bookkeeping.
|
||||
const syncSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
|
||||
liveSubsRef,
|
||||
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
|
||||
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
Effect.gen(function* () {
|
||||
// Persist every instance — the file name is the instance id, so
|
||||
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
|
||||
// get their own cache. We resolve the path fresh so snapshots
|
||||
// produced by newly-added instances post-boot still land on disk
|
||||
// without the aggregator holding a stale `cachePathByInstance`
|
||||
// entry.
|
||||
const key = snapshotInstanceKey(provider);
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: key,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
yield* writeProviderStatusCache({ filePath, provider }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
readonly persist?: boolean;
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
? provider
|
||||
: mergeProviderSnapshot(mergedProviders.get(key), provider),
|
||||
);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
return yield* providerSource.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) =>
|
||||
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshAll = Effect.fn("refreshAll")(function* () {
|
||||
const sources = yield* getLiveSources;
|
||||
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
|
||||
if (provider === undefined) {
|
||||
return yield* refreshAll();
|
||||
}
|
||||
// Kind-scoped refreshes target the default instance for that driver.
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(provider);
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === defaultInstanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const refreshInstance = Effect.fn("refreshInstance")(function* (instanceId: ProviderInstanceId) {
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
* down and our `Stream.runForEach` fiber exits naturally.
|
||||
*/
|
||||
const syncLiveSources = syncSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const instances = yield* instanceRegistry.listInstances;
|
||||
const unavailableProviders = yield* instanceRegistry.listUnavailable;
|
||||
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
|
||||
instances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
|
||||
for (const provider of unavailableProviders) {
|
||||
knownInstanceIds.add(snapshotInstanceKey(provider));
|
||||
}
|
||||
const previousSubs = yield* Ref.get(liveSubsRef);
|
||||
|
||||
// Carry over subscriptions for instances whose identity is
|
||||
// unchanged (reconcile treated them as no-op). Instances that
|
||||
// disappeared, or were rebuilt with a different reference,
|
||||
// fall through to the "newly-added" branch below.
|
||||
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
|
||||
for (const [instanceId, previousInstance] of previousSubs) {
|
||||
const nextInstance = nextByInstance.get(instanceId);
|
||||
if (nextInstance !== undefined && nextInstance === previousInstance) {
|
||||
carriedOver.set(instanceId, previousInstance);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect new/rebuilt instances in `nextByInstance` insertion
|
||||
// order (which preserves settings-author order).
|
||||
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
|
||||
for (const [instanceId, instance] of nextByInstance) {
|
||||
if (carriedOver.has(instanceId)) {
|
||||
continue;
|
||||
}
|
||||
newlyAdded.push([instanceId, instance] as const);
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([instanceId, instance]) =>
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
// Keep hydrated cache state only while the original boot instance
|
||||
// still exposes its explicitly-marked initial snapshot. Comparing
|
||||
// snapshot values is insufficient: the first probe may have
|
||||
// completed before registry construction, making the boot-time
|
||||
// fallback a real live result that must replace stale disk state.
|
||||
if (
|
||||
cachedInstanceIds.has(instanceId) &&
|
||||
bootInstancesById.get(instanceId) === instance &&
|
||||
source.isInitialSnapshot?.(provider) === true
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider));
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
persist: false,
|
||||
replace: true,
|
||||
});
|
||||
|
||||
const nextSubs = new Map(carriedOver);
|
||||
for (const [instanceId, instance] of newlyAdded) {
|
||||
nextSubs.set(instanceId, instance);
|
||||
}
|
||||
yield* Ref.set(liveSubsRef, nextSubs);
|
||||
|
||||
// Drop aggregator state for instances that have disappeared —
|
||||
// otherwise the UI would keep rendering ghosts.
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const providers = orderProviderSnapshots(
|
||||
previousProviders.filter((provider) =>
|
||||
knownInstanceIds.has(snapshotInstanceKey(provider)),
|
||||
),
|
||||
);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.logError("provider registry instance sync failed; keeping subscription alive", {
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Cached snapshots are already in `providersRef`; only seed instances
|
||||
// without cache entries so pending fallbacks cannot overwrite hydrated
|
||||
// status while the managed provider's first probe is still running.
|
||||
yield* upsertProviders(
|
||||
fallbackProviders.filter((provider) => !cachedInstanceIds.has(snapshotInstanceKey(provider))),
|
||||
{ publish: false },
|
||||
);
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the `PubSub.Subscription` synchronously
|
||||
// in this fibre; the subscription is registered with the PubSub the
|
||||
// instant this `yield*` returns, so any subsequent publish is
|
||||
// buffered in the subscription regardless of when the consumer
|
||||
// fibre below actually starts running.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
|
||||
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
|
||||
// schedules the consumer fibre — so a reconcile that published
|
||||
// between "fibre scheduled" and "fibre starts running + subscribes"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
// subscription rather than subscribing on stream start, which is
|
||||
// what closes the race.
|
||||
yield* Stream.runForEach(
|
||||
Stream.fromSubscription(instanceChanges),
|
||||
() => syncLiveSourcesAndContinue,
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
|
||||
cause: Cause.Cause<unknown>,
|
||||
) {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
|
||||
cause,
|
||||
});
|
||||
return yield* Ref.get(providersRef);
|
||||
});
|
||||
|
||||
return ProviderRegistry.of({
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderDriverKind) =>
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderRegistry, make);
|
||||
@@ -1,283 +0,0 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderSessionRuntimeStatus,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderSessionNotFoundError,
|
||||
ProviderValidationError,
|
||||
} from "./Errors.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
|
||||
export interface ProviderRuntimeBinding {
|
||||
readonly threadId: ThreadId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
/**
|
||||
* Routing key for the configured provider instance that owns this
|
||||
* session. The persistence layer promotes legacy null rows before
|
||||
* exposing bindings; runtime callers must not infer this from `provider`.
|
||||
*/
|
||||
readonly providerInstanceId?: ProviderInstanceId;
|
||||
readonly adapterKey?: string;
|
||||
readonly status?: ProviderSessionRuntimeStatus;
|
||||
readonly resumeCursor?: unknown | null;
|
||||
readonly runtimePayload?: unknown | null;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
|
||||
readonly lastSeenAt: string;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError =
|
||||
| ProviderSessionDirectoryPersistenceError
|
||||
| ProviderSessionNotFoundError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
ProviderSessionDirectory,
|
||||
{
|
||||
readonly upsert: (
|
||||
binding: ProviderRuntimeBinding,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
|
||||
readonly getProvider: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
|
||||
readonly getBinding: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<
|
||||
Option.Option<ProviderRuntimeBinding>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
>()("t3/provider/ProviderSessionDirectory") {}
|
||||
|
||||
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
|
||||
|
||||
function decodeProviderDriverKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKindValue(providerName).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function mergeRuntimePayload(
|
||||
existing: unknown | null,
|
||||
next: unknown | null | undefined,
|
||||
): unknown | null {
|
||||
if (next === undefined) {
|
||||
return existing ?? null;
|
||||
}
|
||||
if (isRecord(existing) && isRecord(next)) {
|
||||
return { ...existing, ...next };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function toRuntimeBinding(
|
||||
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
|
||||
Effect.map(
|
||||
(provider) =>
|
||||
({
|
||||
threadId: runtime.threadId,
|
||||
provider,
|
||||
// Migration boundary: rows written before provider instances had a
|
||||
// nullable id. Promote them here so runtime routing never has to
|
||||
// infer an instance from its driver kind.
|
||||
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
|
||||
adapterKey: runtime.adapterKey,
|
||||
runtimeMode: runtime.runtimeMode,
|
||||
status: runtime.status,
|
||||
resumeCursor: runtime.resumeCursor,
|
||||
runtimePayload: runtime.runtimePayload,
|
||||
lastSeenAt: runtime.lastSeenAt,
|
||||
}) satisfies ProviderRuntimeBindingWithMetadata,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding: ProviderSessionDirectory["Service"]["getBinding"] = (threadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getBinding:getByThreadId",
|
||||
detail: "Failed to read the persisted provider session binding.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((runtime) =>
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map(Option.some),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsert: ProviderSessionDirectory["Service"]["upsert"] = Effect.fn(
|
||||
"ProviderSessionDirectory.upsert",
|
||||
)(function* (binding) {
|
||||
const existing = yield* repository.getByThreadId({ threadId: binding.threadId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.upsert:getByThreadId",
|
||||
detail: "Failed to read the existing provider session binding before upsert.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const existingRuntime = Option.getOrUndefined(existing);
|
||||
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
|
||||
if (!resolvedThreadId) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "threadId must be a non-empty string.",
|
||||
});
|
||||
}
|
||||
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const providerChanged =
|
||||
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
|
||||
const providerInstanceId =
|
||||
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
|
||||
if (providerInstanceId === null || providerInstanceId === undefined) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "providerInstanceId is required for provider session runtime bindings.",
|
||||
});
|
||||
}
|
||||
yield* repository
|
||||
.upsert({
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
providerInstanceId,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
binding.resumeCursor !== undefined
|
||||
? binding.resumeCursor
|
||||
: (existingRuntime?.resumeCursor ?? null),
|
||||
runtimePayload: mergeRuntimePayload(
|
||||
existingRuntime?.runtimePayload ?? null,
|
||||
binding.runtimePayload,
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.upsert:upsert",
|
||||
detail: "Failed to persist the provider session binding.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getProvider: ProviderSessionDirectory["Service"]["getProvider"] = (threadId) =>
|
||||
getBinding(threadId).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: (value) => Effect.succeed(value.provider),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProviderSessionNotFoundError({
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectory["Service"]["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.listThreadIds:list",
|
||||
detail: "Failed to list persisted provider session bindings.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const listBindings: ProviderSessionDirectory["Service"]["listBindings"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.listBindings:list",
|
||||
detail: "Failed to list persisted provider session bindings.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return ProviderSessionDirectory.of({
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderSessionDirectory, make);
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.
|
||||
*
|
||||
* Maps a `ProviderInstanceId` (the new per-instance routing key) or a
|
||||
* `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete
|
||||
* adapter service (Codex, Claude, etc). It does not own session lifecycle
|
||||
* or routing rules; `ProviderService` uses this registry together with
|
||||
* `ProviderSessionDirectory`.
|
||||
*
|
||||
* During the driver/instance migration this tag exposes both flavours:
|
||||
*
|
||||
* - `getByInstance` / `listInstances` — new per-instance routing. Callers
|
||||
* that already know an `instanceId` (threads, sessions, events)
|
||||
* should prefer these.
|
||||
* (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D
|
||||
* behaviour. New code should not grow additional callers of the kind-keyed
|
||||
* methods; they exist so the settings UI, WS refresh RPC, and a handful
|
||||
* of legacy persisted rows can still be routed during the rollout.
|
||||
*
|
||||
* @module ProviderAdapterRegistry
|
||||
*/
|
||||
import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as PubSub from "effect/PubSub";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
import type { ProviderContinuationIdentity } from "../ProviderDriver.ts";
|
||||
|
||||
export interface ProviderInstanceRoutingInfo {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterRegistryShape - Service API for adapter lookup.
|
||||
*/
|
||||
export interface ProviderAdapterRegistryShape {
|
||||
/**
|
||||
* Resolve the adapter for a specific instance id. Returns
|
||||
* `ProviderUnsupportedError` if no such instance is currently registered
|
||||
* (which covers "never configured" *and* "configured but the driver is
|
||||
* unavailable in this build" — both surface the same failure to callers
|
||||
* that expect a working adapter).
|
||||
*/
|
||||
readonly getByInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;
|
||||
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
|
||||
|
||||
/**
|
||||
* List all live instance ids. Excludes unavailable/shadow instances —
|
||||
* callers of this method want something they can pass to `getByInstance`.
|
||||
*/
|
||||
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||
|
||||
/**
|
||||
* Legacy: list provider kinds whose default instance is currently
|
||||
* registered.
|
||||
*
|
||||
* @deprecated Prefer `listInstances`. Retained for migration-era call
|
||||
* sites that iterate providers to build UI/metrics.
|
||||
*/
|
||||
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
|
||||
|
||||
/**
|
||||
* Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.
|
||||
* Emits one `void` tick whenever the set of live instances changes
|
||||
* (instance added, removed, or rebuilt after a settings edit). Consumers
|
||||
* that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s
|
||||
* runtime event bus — re-pull `listInstances` on each tick and fork new
|
||||
* subscriptions for instances they haven't seen yet.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
|
||||
/**
|
||||
* Acquire a change subscription synchronously in the caller's current fiber.
|
||||
* Consumers that must avoid missing a publish between initial reconciliation
|
||||
* and watcher startup should use this, then fork `Stream.fromSubscription`.
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterRegistry - Service tag for provider adapter lookup.
|
||||
*/
|
||||
export class ProviderAdapterRegistry extends Context.Service<
|
||||
ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistryShape
|
||||
>()("t3/provider/Services/ProviderAdapterRegistry") {}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* ProviderInstanceRegistry — the single Effect service in the new model.
|
||||
*
|
||||
* Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running
|
||||
* registered driver factories against `ServerSettings.providerInstances`.
|
||||
* The registry watches settings; when an instance's config changes (or
|
||||
* the entry disappears), the registry tears down the affected instance's
|
||||
* scope and rebuilds — that's the entire hot-reload story.
|
||||
*
|
||||
* What rest-of-server reads from here:
|
||||
* - `getInstance(instanceId)` — for routing turn/session calls.
|
||||
* - `listInstances` — for snapshot aggregation in `ProviderRegistry`.
|
||||
* - `listUnavailable` — `ServerProvider` shadows for instances whose
|
||||
* driver is not registered in this build (rollback / fork tolerance).
|
||||
* - `streamChanges` — coalesced "registry mutated" pings so consumers
|
||||
* can re-pull lists or re-broadcast.
|
||||
*
|
||||
* @module provider/Services/ProviderInstanceRegistry
|
||||
*/
|
||||
import type { ProviderInstanceId, ServerProvider } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as PubSub from "effect/PubSub";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
|
||||
export interface ProviderInstanceRegistryShape {
|
||||
/**
|
||||
* Look up one instance by id. Returns `undefined` (not Option) when the
|
||||
* id is unknown — callers branch on falsy and emit
|
||||
* `ProviderInstanceNotFoundError`.
|
||||
*/
|
||||
readonly getInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstance | undefined>;
|
||||
/**
|
||||
* Every available (driver-registered, successfully created) instance,
|
||||
* in stable settings-author order.
|
||||
*/
|
||||
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
|
||||
/**
|
||||
* Wire-shape shadow snapshots for instances whose driver is unknown to
|
||||
* this build (or whose config failed to decode). Suitable for merging
|
||||
* directly into `ProviderRegistry` output.
|
||||
*/
|
||||
readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
/**
|
||||
* Push notification stream emitted whenever the registry's contents
|
||||
* change — instance added, removed, or rebuilt. The payload is `void`
|
||||
* because consumers always want to re-pull `listInstances` /
|
||||
* `listUnavailable` together.
|
||||
*
|
||||
* NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the
|
||||
* stream starts running, forking a consumer via
|
||||
* `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next
|
||||
* publish — the forked fiber may not have subscribed yet when the
|
||||
* publish lands. Hot-reload consumers that must not miss a publish
|
||||
* should use `subscribeChanges` below instead, which acquires the
|
||||
* subscription synchronously in the caller's fiber before the consumer
|
||||
* loop is forked.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
/**
|
||||
* Acquire a subscription to the registry's change channel synchronously
|
||||
* in the caller's fiber. Returns a `PubSub.Subscription<void>` whose
|
||||
* lifetime is scoped to the provided `Scope` (the subscription is
|
||||
* released when the scope closes). Consumers typically `yield*` this
|
||||
* in the same fiber that forks their consumer loop, then drain with
|
||||
* `PubSub.take(subscription)` inside `Effect.forever`. Because the
|
||||
* subscription is registered with the PubSub before this `yield*`
|
||||
* returns, no subsequent publish can land in a gap.
|
||||
*
|
||||
* This exists because the `ProviderInstanceRegistry` publishes on a
|
||||
* PubSub and `Stream.fromPubSub` defers subscription until the stream
|
||||
* starts executing — a consumer that `forkScoped`s the stream
|
||||
* consumption can miss a publish that lands in the narrow window
|
||||
* between "fiber scheduled" and "fiber starts running".
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ProviderInstanceRegistry extends Context.Service<
|
||||
ProviderInstanceRegistry,
|
||||
ProviderInstanceRegistryShape
|
||||
>()("t3/provider/Services/ProviderInstanceRegistry") {}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* ProviderInstanceRegistryMutator — internal handle used by the hydration
|
||||
* layer to reconcile the live registry with a fresh
|
||||
* `ProviderInstanceConfigMap`.
|
||||
*
|
||||
* Kept separate from the public `ProviderInstanceRegistry` service tag so
|
||||
* downstream consumers (drivers, reactors, `ProviderService`) can only read
|
||||
* from the registry. Only the hydration layer — which watches
|
||||
* `ServerSettingsService.streamChanges` and applies diffs — imports this
|
||||
* tag.
|
||||
*
|
||||
* The mutator exposes a single entry point, `reconcile(configMap)`, which:
|
||||
*
|
||||
* 1. Diffs the incoming map against the live one keyed by instance id.
|
||||
* 2. Closes the per-instance `Scope` of every removed or replaced entry
|
||||
* (tearing down adapter processes, refresh fibres, temp files) BEFORE
|
||||
* creating the replacement — `reconcile` guarantees "at most one live
|
||||
* instance per id" at all times.
|
||||
* 3. Opens a fresh child `Scope` for every added or replaced entry, runs
|
||||
* the driver's `create`, and stores the resulting `ProviderInstance`
|
||||
* plus its scope.
|
||||
* 4. Publishes one `void` tick on the registry's `streamChanges` PubSub at
|
||||
* the end of the batch — consumers re-pull `listInstances` /
|
||||
* `listUnavailable`.
|
||||
*
|
||||
* `reconcile` is idempotent: calling it with an unchanged config map is a
|
||||
* no-op (no scope churn, no pubsub emission).
|
||||
*
|
||||
* @module provider/Services/ProviderInstanceRegistryMutator
|
||||
*/
|
||||
import type { ProviderInstanceConfigMap } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export interface ProviderInstanceRegistryMutatorShape {
|
||||
/**
|
||||
* Bring the live registry in line with the supplied config map. See
|
||||
* module docs for the add / remove / replace semantics.
|
||||
*
|
||||
* The effect never fails: individual driver `create` failures are
|
||||
* captured as "unavailable" shadow snapshots inside the registry, the
|
||||
* same way boot-time failures are handled by
|
||||
* `makeProviderInstanceRegistry`. This keeps settings-watcher loops from
|
||||
* erroring out on a single bad entry.
|
||||
*/
|
||||
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class ProviderInstanceRegistryMutator extends Context.Service<
|
||||
ProviderInstanceRegistryMutator,
|
||||
ProviderInstanceRegistryMutatorShape
|
||||
>()("t3/provider/Services/ProviderInstanceRegistryMutator") {}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* ProviderRegistry - Provider snapshot service.
|
||||
*
|
||||
* Owns provider install/auth/version/model snapshots and exposes the latest
|
||||
* provider state to transport layers.
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
* Read the latest provider snapshots for every configured instance.
|
||||
* Multiple snapshots may share the same `provider` kind (multiple
|
||||
* instances of the same driver) and disambiguate via `instanceId`.
|
||||
*/
|
||||
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh all providers, or the default instance of the specified
|
||||
* kind when supplied.
|
||||
*
|
||||
* Retained for back-compat with legacy call sites (WS refresh RPC,
|
||||
* orchestration metrics). New code should prefer `refreshInstance`.
|
||||
*
|
||||
* @deprecated prefer `refreshInstance` for new call sites.
|
||||
*/
|
||||
readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh the specific configured instance. Returns the updated snapshot
|
||||
* list. When the instance id is unknown the call resolves with the
|
||||
* currently cached list (no error) — matching the legacy `refresh` shim
|
||||
* behaviour so transport layers don't have to special-case unknowns.
|
||||
*/
|
||||
readonly refreshInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
|
||||
}
|
||||
|
||||
export class ProviderRegistry extends Context.Service<ProviderRegistry, ProviderRegistryShape>()(
|
||||
"t3/provider/Services/ProviderRegistry",
|
||||
) {}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* ProviderService - Service interface for provider sessions, turns, and checkpoints.
|
||||
*
|
||||
* Acts as the cross-provider facade used by transports (WebSocket/RPC). It
|
||||
* resolves provider adapters through `ProviderAdapterRegistry`, routes
|
||||
* session-scoped calls via `ProviderSessionDirectory`, and exposes one unified
|
||||
* provider event stream to callers.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and returns typed
|
||||
* domain errors for validation, session, codex, and checkpoint workflows.
|
||||
*
|
||||
* @module ProviderService
|
||||
*/
|
||||
import type {
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderInstanceId,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderRespondToUserInputInput,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ThreadId,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import type { ProviderServiceError } from "../Errors.ts";
|
||||
import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";
|
||||
import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts";
|
||||
|
||||
/**
|
||||
* ProviderServiceShape - Service API for provider session and turn orchestration.
|
||||
*/
|
||||
export interface ProviderServiceShape {
|
||||
/**
|
||||
* Start a provider session.
|
||||
*/
|
||||
readonly startSession: (
|
||||
threadId: ThreadId,
|
||||
input: ProviderSessionStartInput,
|
||||
) => Effect.Effect<ProviderSession, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Send a provider turn.
|
||||
*/
|
||||
readonly sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Interrupt a running provider turn.
|
||||
*/
|
||||
readonly interruptTurn: (
|
||||
input: ProviderInterruptTurnInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Respond to a provider approval request.
|
||||
*/
|
||||
readonly respondToRequest: (
|
||||
input: ProviderRespondToRequestInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Respond to a provider structured user-input request.
|
||||
*/
|
||||
readonly respondToUserInput: (
|
||||
input: ProviderRespondToUserInputInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Stop a provider session.
|
||||
*/
|
||||
readonly stopSession: (
|
||||
input: ProviderStopSessionInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* List active provider sessions.
|
||||
*
|
||||
* Aggregates runtime session lists from all registered adapters.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
|
||||
|
||||
/**
|
||||
* Read capabilities for the adapter bound to a configured provider instance.
|
||||
*/
|
||||
readonly getCapabilities: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;
|
||||
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Roll back provider conversation state by a number of turns.
|
||||
*/
|
||||
readonly rollbackConversation: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly numTurns: number;
|
||||
}) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Canonical provider runtime event stream.
|
||||
*
|
||||
* Fan-out is owned by ProviderService (not by a standalone event-bus service).
|
||||
*/
|
||||
readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderService - Service tag for provider orchestration.
|
||||
*/
|
||||
export class ProviderService extends Context.Service<ProviderService, ProviderServiceShape>()(
|
||||
"t3/provider/Services/ProviderService",
|
||||
) {}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderValidationError,
|
||||
} from "../Errors.ts";
|
||||
|
||||
export interface ProviderRuntimeBinding {
|
||||
readonly threadId: ThreadId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
/**
|
||||
* Routing key for the configured provider instance that owns this
|
||||
* session. The persistence layer promotes legacy null rows before
|
||||
* exposing bindings; runtime callers must not infer this from `provider`.
|
||||
*/
|
||||
readonly providerInstanceId?: ProviderInstanceId;
|
||||
readonly adapterKey?: string;
|
||||
readonly status?: ProviderSessionRuntimeStatus;
|
||||
readonly resumeCursor?: unknown | null;
|
||||
readonly runtimePayload?: unknown | null;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
|
||||
readonly lastSeenAt: string;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export interface ProviderSessionDirectoryShape {
|
||||
readonly upsert: (
|
||||
binding: ProviderRuntimeBinding,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
|
||||
|
||||
readonly getProvider: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
|
||||
|
||||
readonly getBinding: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
|
||||
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
ProviderSessionDirectory,
|
||||
ProviderSessionDirectoryShape
|
||||
>()("t3/provider/Services/ProviderSessionDirectory") {}
|
||||
@@ -0,0 +1,15 @@
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
export interface ProviderSessionReaperShape {
|
||||
/**
|
||||
* Start the background provider session reaper within the provided scope.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ProviderSessionReaper extends Context.Service<
|
||||
ProviderSessionReaper,
|
||||
ProviderSessionReaperShape
|
||||
>()("t3/provider/Services/ProviderSessionReaper") {}
|
||||
@@ -6,15 +6,6 @@ import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts"
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
/**
|
||||
* Identifies the driver's unprobed startup snapshot. Registries use this to
|
||||
* keep a hydrated disk snapshot only until the first live probe completes.
|
||||
*
|
||||
* Optional for compatibility with static/test snapshot sources. A source
|
||||
* that does not expose lifecycle state is treated as live rather than
|
||||
* allowing a stale cache entry to mask it.
|
||||
*/
|
||||
readonly isInitialSnapshot?: (snapshot: ServerProvider) => boolean;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
}
|
||||
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user