Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58340604f0 | ||
|
|
8e2d5d326a | ||
|
|
b239fa9c6d | ||
|
|
a03b7bce5a | ||
|
|
041f875ae5 | ||
|
|
1732212b43 | ||
|
|
1115b14e4d |
No files matched your search
@@ -22,6 +22,9 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -31,6 +34,9 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -55,12 +61,18 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -272,21 +272,29 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -306,6 +314,11 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -533,6 +546,19 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -540,6 +566,13 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -594,6 +627,24 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
const envEntries = [
|
||||
["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],
|
||||
["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],
|
||||
["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,
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -302,12 +286,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
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' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("DesktopBackendOutputLog", () => {
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
yield* outputLog.beginSession({ details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
@@ -102,7 +102,8 @@ describe("DesktopBackendOutputLog", () => {
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
yield* outputLog.beginSession({ details: "test" });
|
||||
yield* outputLog.persistFailure({ details: "failed" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
|
||||
@@ -17,6 +17,8 @@ export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
@@ -93,14 +95,13 @@ export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<Des
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
@@ -122,10 +123,76 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [...session.chunks, { streamName, chunk: retainedChunk }];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) break;
|
||||
if (first.chunk.byteLength <= overflow) {
|
||||
overflow -= first.chunk.byteLength;
|
||||
byteLength -= first.chunk.byteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
chunk: first.chunk.slice(overflow),
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
@@ -338,44 +405,78 @@ export const make = Effect.gen(function* () {
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [
|
||||
current,
|
||||
Option.map(current, (value) => ({ ...value, chunks: [], byteLength: 0 })),
|
||||
]);
|
||||
if (Option.isNone(session)) return;
|
||||
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "START",
|
||||
details: session.value.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.value.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
runId: session.value.runId,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
|
||||
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -112,41 +112,56 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk(
|
||||
"stderr",
|
||||
new TextEncoder().encode("normal shutdown\n"),
|
||||
);
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -154,6 +169,98 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -12,7 +12,7 @@ import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ function makeEnvironmentLayer(
|
||||
options?: {
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
@@ -57,7 +58,7 @@ function makeEnvironmentLayer(
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: "/missing/resources",
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -254,4 +255,39 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("passes the packaged resource monitor path to the backend", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -75,6 +75,42 @@ const logBackendObservabilitySettingsReadFailure = (
|
||||
);
|
||||
};
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -104,6 +140,7 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -130,6 +167,12 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
@@ -169,9 +212,14 @@ export const make = Effect.gen(function* () {
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resourceMonitorPath,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -26,12 +27,16 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -47,6 +52,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
@@ -63,6 +70,7 @@ function makeProcess(options?: {
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -74,7 +82,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -111,6 +119,9 @@ function makeManagerLayer(input: {
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -124,12 +135,21 @@ function makeManagerLayer(input: {
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
: DesktopState.layer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -205,8 +225,7 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -229,6 +248,8 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
@@ -288,6 +309,7 @@ describe("DesktopBackendManager", () => {
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
@@ -327,7 +349,10 @@ describe("DesktopBackendManager", () => {
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
@@ -368,7 +393,10 @@ describe("DesktopBackendManager", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
@@ -412,6 +440,7 @@ describe("DesktopBackendManager", () => {
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
@@ -451,6 +480,7 @@ describe("DesktopBackendManager", () => {
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutput: () => Effect.fail(outputCause),
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
@@ -476,6 +506,88 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
|
||||
const outputDrainStarted = yield* Deferred.make<void>();
|
||||
const outputChunks = yield* Ref.make<Array<string>>([]);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.succeed(outputDrainStarted, void 0).pipe(
|
||||
Effect.andThen(Effect.sleep(Duration.millis(50))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
writeOutputChunk: (_streamName, chunk) =>
|
||||
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
|
||||
persistFailure: () =>
|
||||
Ref.get(outputChunks).pipe(
|
||||
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
@@ -513,8 +625,7 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -547,6 +658,8 @@ describe("DesktopBackendManager", () => {
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReady = yield* Ref.make(false);
|
||||
const quitting = yield* Ref.make(false);
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -578,6 +691,15 @@ describe("DesktopBackendManager", () => {
|
||||
desktopWindow: {
|
||||
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -597,6 +719,8 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.stop();
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
|
||||
const stoppedSnapshot = yield* manager.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReady));
|
||||
@@ -610,6 +734,7 @@ describe("DesktopBackendManager", () => {
|
||||
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -629,6 +754,9 @@ describe("DesktopBackendManager", () => {
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -636,6 +764,7 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(499));
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
@@ -692,6 +821,13 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* manager.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* manager.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -21,11 +22,14 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
@@ -34,6 +38,7 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
|
||||
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.millis(250);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
@@ -172,6 +177,10 @@ export const BackendProcessError = Schema.Union([
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
@@ -327,6 +336,7 @@ function drainBackendOutput(
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
@@ -345,6 +355,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
@@ -359,12 +386,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
additionalFds,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -380,8 +402,35 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
|
||||
Stream.runForEach(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
@@ -391,20 +440,22 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
outputFibers.push(
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
);
|
||||
}
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
@@ -420,7 +471,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
const exit = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
@@ -432,7 +483,16 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
|
||||
if (Exit.isFailure(exit)) {
|
||||
return yield* Effect.failCause(exit.cause);
|
||||
}
|
||||
const exitCode = exit.value;
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
@@ -445,6 +505,7 @@ export const make = Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -581,10 +642,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
if (isCurrentRun) {
|
||||
if (Option.isSome(pid)) {
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
if (nextState.desiredRunning) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
@@ -598,13 +662,14 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
}));
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
yield* backendOutputLog.beginSession({
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
@@ -637,10 +702,16 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
});
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
@@ -761,7 +832,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options),
|
||||
onSome: (run) => closeRun(run, options).pipe(Effect.andThen(backendOutputLog.discardSession)),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ export class ElectronApp extends Context.Service<
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -150,6 +151,7 @@ export const make = ElectronApp.of({
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export interface ElectronPowerMonitorShape {
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
ElectronPowerMonitorShape
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -43,16 +43,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
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",
|
||||
},
|
||||
}),
|
||||
),
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -79,11 +70,6 @@ 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)),
|
||||
);
|
||||
@@ -113,34 +99,6 @@ 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,7 +1,6 @@
|
||||
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";
|
||||
@@ -115,60 +114,18 @@ 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,
|
||||
headers: request.headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response = 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);
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -46,6 +47,7 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
@@ -105,6 +107,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -146,6 +149,7 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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";
|
||||
@@ -19,25 +18,16 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
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(),
|
||||
}));
|
||||
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(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -54,7 +44,6 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -92,7 +81,6 @@ 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);
|
||||
|
||||
@@ -109,8 +97,6 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -264,197 +250,6 @@ 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* () {
|
||||
@@ -716,178 +511,6 @@ 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* () {
|
||||
|
||||
+115
-280
@@ -25,7 +25,6 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -63,7 +62,6 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -380,7 +378,6 @@ 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>();
|
||||
@@ -537,9 +534,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
),
|
||||
);
|
||||
|
||||
const tabIdForWebContents = Effect.fn("PreviewManager.tabIdForWebContents")(function* (
|
||||
webContentsId: number,
|
||||
) {
|
||||
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
return (
|
||||
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
|
||||
@@ -549,7 +544,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
|
||||
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
|
||||
|
||||
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
|
||||
const captureDiagnosticMessage = Effect.fnUntraced(function* (
|
||||
webContentsId: number,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -727,47 +722,46 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
|
||||
function* (method: string, params: Record<string, unknown>) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width:
|
||||
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
const handleDebuggerMessage = Effect.fnUntraced(function* (
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width: typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
});
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
runFork(handleDebuggerMessage(method, params));
|
||||
};
|
||||
@@ -857,24 +851,11 @@ 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, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -915,22 +896,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
// 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);
|
||||
return yield* use(send);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1122,62 +1088,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
if (wc.isDestroyed()) return;
|
||||
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;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
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;
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: validatedUrl || wc.getURL(),
|
||||
url: wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1232,8 +1158,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1244,8 +1170,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", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1351,40 +1277,21 @@ 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;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
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;
|
||||
@@ -1403,7 +1310,6 @@ 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 [
|
||||
@@ -1421,6 +1327,11 @@ 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),
|
||||
);
|
||||
@@ -2032,7 +1943,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* prepareAutomationInput(send, true);
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2094,7 +2008,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2104,15 +2018,8 @@ 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 }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2120,54 +2027,12 @@ 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 (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);
|
||||
}
|
||||
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" }));
|
||||
}
|
||||
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) };
|
||||
@@ -2191,12 +2056,6 @@ 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* (
|
||||
@@ -2204,10 +2063,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
// 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);
|
||||
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,
|
||||
);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2222,54 +2094,32 @@ 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,
|
||||
) {
|
||||
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);
|
||||
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* 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));
|
||||
}, 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 });
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2277,8 +2127,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2676,20 +2526,6 @@ 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",
|
||||
{
|
||||
@@ -2792,7 +2628,6 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -1,203 +0,0 @@
|
||||
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 },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
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";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly suspended: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
DesktopTelemetryPublisherShape
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return { ...state, locked: booleanState(event.value) };
|
||||
case "suspended":
|
||||
return { ...state, suspended: event.value };
|
||||
case "onBattery":
|
||||
return { ...state, onBattery: booleanState(event.value) };
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
idleSeconds,
|
||||
locked,
|
||||
suspended: currentPower.suspended,
|
||||
onBattery: booleanState(onBattery),
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: currentPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: currentPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: metric.creationTime,
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
Ref.get(latest).pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.fromPubSub(changes),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -40,6 +40,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -4,7 +4,6 @@ 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";
|
||||
@@ -48,14 +47,12 @@ 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(),
|
||||
@@ -82,7 +79,6 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -241,73 +237,6 @@ 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,6 +1,5 @@
|
||||
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";
|
||||
@@ -23,16 +22,6 @@ 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,
|
||||
@@ -97,22 +86,6 @@ 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,
|
||||
@@ -179,7 +152,6 @@ 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<
|
||||
@@ -305,61 +277,7 @@ 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(
|
||||
@@ -368,22 +286,11 @@ 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 }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -405,13 +312,14 @@ 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": "^7.0.3"
|
||||
"astro": "^6.0.4"
|
||||
},
|
||||
"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.2.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@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.7",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -92,7 +91,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -448,7 +447,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage();
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
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,
|
||||
@@ -16,8 +13,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, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } 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";
|
||||
@@ -28,7 +25,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 { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -76,7 +73,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -209,33 +206,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const composerRef = useRef<ComposerEditorHandle>(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 + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
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)
|
||||
@@ -265,67 +254,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
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 handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerEditorRef.current?.blur();
|
||||
composerRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -378,13 +315,10 @@ 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={estimatedOverlayHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -398,7 +332,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -427,7 +361,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
editorRef={composerRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -446,7 +380,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -25,6 +15,8 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -37,7 +29,6 @@ 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 {
|
||||
@@ -73,11 +64,14 @@ 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",
|
||||
@@ -99,13 +93,10 @@ 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>;
|
||||
}
|
||||
|
||||
@@ -821,6 +812,30 @@ 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}
|
||||
@@ -1107,12 +1122,17 @@ 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>;
|
||||
@@ -1194,16 +1214,6 @@ 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) {
|
||||
@@ -1219,6 +1229,54 @@ 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;
|
||||
@@ -1250,6 +1308,9 @@ 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);
|
||||
}
|
||||
@@ -1297,7 +1358,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
setFoldToggleSettling(true);
|
||||
suppressAutoFollowRef.current = true;
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1315,7 +1376,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
suppressAutoFollowRef.current = false;
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
@@ -1397,60 +1458,59 @@ 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 }}>
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
foldToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
keyExtractor={(entry) => `${entry.type}:${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
|
||||
|
||||
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -209,7 +209,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -271,7 +271,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
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);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
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);
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -9,6 +10,7 @@ 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";
|
||||
|
||||
@@ -86,6 +88,13 @@ 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;
|
||||
@@ -95,7 +104,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -1246,6 +1255,8 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1262,6 +1273,13 @@ 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) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
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;
|
||||
}
|
||||
@@ -40,6 +40,7 @@ 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;
|
||||
@@ -76,6 +77,7 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,9 +91,17 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
@@ -115,6 +125,7 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -124,9 +135,14 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
queuedSendStartedAt,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
@@ -134,7 +150,7 @@ export function useThreadComposerState() {
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
@@ -143,16 +159,15 @@ export function useThreadComposerState() {
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
@@ -162,12 +177,10 @@ export function useThreadComposerState() {
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
|
||||
@@ -19,23 +19,6 @@ 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;
|
||||
@@ -53,21 +36,8 @@ 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;
|
||||
@@ -75,10 +45,6 @@ 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);
|
||||
@@ -318,66 +284,22 @@ 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) =>
|
||||
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,
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -434,152 +356,19 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
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" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
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";
|
||||
|
||||
@@ -810,42 +599,6 @@ 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: {
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
AuthSessionId,
|
||||
RpcClientId,
|
||||
type HostPowerSnapshot,
|
||||
type ClientActivityReportInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
|
||||
|
||||
const nominalHostPower: HostPowerSnapshot = {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_NOW,
|
||||
};
|
||||
|
||||
const constrainedHostPower: HostPowerSnapshot = {
|
||||
...nominalHostPower,
|
||||
lowPowerMode: "true",
|
||||
stale: false,
|
||||
};
|
||||
|
||||
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
|
||||
return {
|
||||
clientId: "client-1",
|
||||
clientKind: "web",
|
||||
visible: true,
|
||||
focused: true,
|
||||
recentlyInteracted: true,
|
||||
scopes: [{ type: "vcs-status", cwd: "/repo" }],
|
||||
ttlMs: 45_000,
|
||||
observedAt: TEST_NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
|
||||
) {
|
||||
const hostLayer = Layer.effect(
|
||||
HostPowerMonitor.HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
let snapshot = hostPower;
|
||||
return HostPowerMonitor.HostPowerMonitor.of({
|
||||
snapshot: Effect.sync(() => snapshot),
|
||||
report: (next) =>
|
||||
Effect.sync(() => {
|
||||
snapshot = next;
|
||||
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
|
||||
);
|
||||
}
|
||||
|
||||
describe("BackgroundPolicy", () => {
|
||||
it.effect("records foreground scoped client demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("removes all leases for a disconnected websocket connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
yield* policy.removeRpcClient(RpcClientId.make(1));
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
|
||||
);
|
||||
|
||||
it.effect("keeps background demand visible while preventing scoped work", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"performance profile allows background scoped work while a scoped lease is active",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("battery saver profile pauses scoped work on battery", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
onBattery: "true",
|
||||
stale: false,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not gate work on stale host power values", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
locked: "true",
|
||||
onBattery: "true",
|
||||
lowPowerMode: "true",
|
||||
thermalState: "critical",
|
||||
stale: true,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
type AuthSessionId,
|
||||
type BackgroundPolicySnapshot,
|
||||
type BackgroundScope,
|
||||
type ClientActivityLease,
|
||||
type ClientActivityReportInput,
|
||||
type HostPowerSnapshot,
|
||||
type RpcClientId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
type ResolvedBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
export interface BackgroundPolicyShape {
|
||||
readonly reportClientActivity: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
input: ClientActivityReportInput,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
|
||||
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
|
||||
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
|
||||
"t3/background/BackgroundPolicy",
|
||||
) {}
|
||||
|
||||
const DEFAULT_LEASE_TTL_MS = 45_000;
|
||||
const MAX_LEASE_TTL_MS = 120_000;
|
||||
|
||||
function scopeKey(scope: BackgroundScope): string {
|
||||
switch (scope.type) {
|
||||
case "server-config":
|
||||
case "diagnostics":
|
||||
return scope.type;
|
||||
case "provider-status":
|
||||
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
|
||||
case "vcs-status":
|
||||
case "git-refs":
|
||||
return `${scope.type}:${scope.cwd}`;
|
||||
case "thread":
|
||||
return `${scope.type}:${scope.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return DateTime.isGreaterThan(lease.expiresAt, now);
|
||||
}
|
||||
|
||||
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return isLeaseActive(lease, now) && lease.visible && lease.focused;
|
||||
}
|
||||
|
||||
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
|
||||
const key = scopeKey(scope);
|
||||
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
|
||||
}
|
||||
|
||||
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
|
||||
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
|
||||
}
|
||||
|
||||
function isHostConstrained(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (hostPower.stale) return false;
|
||||
if (
|
||||
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
|
||||
hasThermalPressure(hostPower)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
|
||||
}
|
||||
|
||||
function isClientConstrained(
|
||||
lease: ClientActivityLease,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
|
||||
}
|
||||
|
||||
function leaseMayRunScopedWork(
|
||||
lease: ClientActivityLease,
|
||||
scope: BackgroundScope,
|
||||
now: DateTime.Utc,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
|
||||
if (!activeWithScope || isClientConstrained(lease, settings)) {
|
||||
return false;
|
||||
}
|
||||
if (settings.profile === "performance") {
|
||||
return true;
|
||||
}
|
||||
return isForegroundLease(lease, now);
|
||||
}
|
||||
|
||||
function computeSnapshot(input: {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly leases: ReadonlyMap<string, ClientActivityLease>;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly settings: ResolvedBackgroundActivitySettings;
|
||||
readonly updatedAt: DateTime.Utc;
|
||||
}): BackgroundPolicySnapshot {
|
||||
const activeLeases = [...input.leases.values()].filter((lease) =>
|
||||
isLeaseActive(lease, input.now),
|
||||
);
|
||||
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
|
||||
const activeScopeKeys = new Set<string>();
|
||||
for (const lease of activeLeases) {
|
||||
for (const scope of lease.scopes) {
|
||||
activeScopeKeys.add(scopeKey(scope));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hostPower: input.hostPower,
|
||||
leases: activeLeases,
|
||||
activeForegroundLeaseCount: foregroundLeases.length,
|
||||
activeScopeKeys: [...activeScopeKeys].toSorted(),
|
||||
shouldRunOpportunisticWork:
|
||||
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
|
||||
!isHostConstrained(input.hostPower, input.settings),
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.policy.make")(function* () {
|
||||
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
|
||||
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
|
||||
|
||||
const backgroundActivitySettings = serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
|
||||
);
|
||||
|
||||
const snapshot = Effect.gen(function* () {
|
||||
const [hostPower, leases, now, settings] = yield* Effect.all([
|
||||
hostPowerMonitor.snapshot,
|
||||
Ref.get(leasesRef),
|
||||
DateTime.now,
|
||||
backgroundActivitySettings,
|
||||
]);
|
||||
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
|
||||
});
|
||||
|
||||
const publishSnapshot = snapshot.pipe(Effect.flatMap((next) => PubSub.publish(changes, next)));
|
||||
|
||||
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ttlMs = Math.min(
|
||||
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
|
||||
MAX_LEASE_TTL_MS,
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
|
||||
const lease: ClientActivityLease = {
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
clientId: input.clientId,
|
||||
clientKind: input.clientKind,
|
||||
visible: input.visible,
|
||||
focused: input.focused,
|
||||
recentlyInteracted: input.recentlyInteracted,
|
||||
...(input.appState !== undefined ? { appState: input.appState } : {}),
|
||||
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
|
||||
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
|
||||
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
|
||||
scopes: input.scopes,
|
||||
updatedAt: now,
|
||||
expiresAt,
|
||||
};
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
next.set(`${rpcClientId}:${input.clientId}`, lease);
|
||||
return next;
|
||||
});
|
||||
yield* publishSnapshot;
|
||||
});
|
||||
|
||||
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
|
||||
Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(`${rpcClientId}:`)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
|
||||
|
||||
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
|
||||
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
|
||||
|
||||
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
|
||||
Effect.gen(function* () {
|
||||
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
|
||||
if (isHostConstrained(current.hostPower, settings)) {
|
||||
return false;
|
||||
}
|
||||
return current.leases.some((lease) =>
|
||||
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
|
||||
);
|
||||
});
|
||||
|
||||
const shouldRunOpportunisticWork = Effect.map(
|
||||
snapshot,
|
||||
(current) => current.shouldRunOpportunisticWork,
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep("15 seconds").pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const [key, lease] of next) {
|
||||
if (!isLeaseActive(lease, now)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.andThen(publishSnapshot),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return BackgroundPolicy.of({
|
||||
reportClientActivity,
|
||||
removeRpcClient,
|
||||
reportHostPowerState: hostPowerMonitor.report,
|
||||
snapshot,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
hasDemand,
|
||||
shouldRunScopeWork,
|
||||
shouldRunOpportunisticWork,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BackgroundPolicy, make());
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
describe("HostPowerMonitor", () => {
|
||||
it.effect("publishes semantic power changes without idle-time heartbeat churn", () =>
|
||||
Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.make();
|
||||
const initial = {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
|
||||
} as const;
|
||||
yield* monitor.report(initial);
|
||||
|
||||
const nextChange = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
idleSeconds: 1,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
|
||||
});
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
locked: "true",
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:02.000Z"),
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextChange)).locked).toBe("true");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("consumes desktop power directly without retaining diagnostics telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
|
||||
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
|
||||
const diagnosticsDemandWrites = yield* Ref.make(0);
|
||||
const receiverLayer = DesktopTelemetryReceiver.layerTest({
|
||||
changes: Stream.fromPubSub(desktopChanges),
|
||||
setDiagnosticsDemand: () => Ref.update(diagnosticsDemandWrites, (count) => count + 1),
|
||||
});
|
||||
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const nextPower = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* PubSub.publish(desktopChanges, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(sampledAt),
|
||||
electronPid: 100,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "true",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [],
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextPower)).onBattery).toBe("true");
|
||||
expect(yield* Ref.get(diagnosticsDemandWrites)).toBe(0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { HostPowerSnapshot } 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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
|
||||
"t3/background/HostPowerMonitor",
|
||||
) {}
|
||||
|
||||
export const makeUnknownSnapshot = (
|
||||
source: HostPowerSnapshot["source"],
|
||||
updatedAt: HostPowerSnapshot["updatedAt"],
|
||||
): HostPowerSnapshot => ({
|
||||
source,
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
function samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {
|
||||
return (
|
||||
left.source === right.source &&
|
||||
left.idle === right.idle &&
|
||||
left.locked === right.locked &&
|
||||
left.suspended === right.suspended &&
|
||||
left.onBattery === right.onBattery &&
|
||||
left.lowPowerMode === right.lowPowerMode &&
|
||||
left.thermalState === right.thermalState &&
|
||||
left.stale === right.stale
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
initialSource: HostPowerSnapshot["source"] = "unknown",
|
||||
) {
|
||||
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
|
||||
const latestRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitorShape["report"] = (snapshot) =>
|
||||
Ref.modify(latestRef, (current) => [!samePowerState(current, snapshot), snapshot]).pipe(
|
||||
Effect.flatMap((changed) => (changed ? PubSub.publish(changes, snapshot) : Effect.void)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const initial = yield* desktopTelemetry.latest;
|
||||
const monitor = yield* make(
|
||||
Option.match(initial, {
|
||||
onNone: () => "unknown" as const,
|
||||
onSome: (snapshot) => snapshot.power.source,
|
||||
}),
|
||||
);
|
||||
if (Option.isSome(initial)) {
|
||||
yield* monitor.report(initial.value.power);
|
||||
}
|
||||
yield* desktopTelemetry.changes.pipe(
|
||||
Stream.map((snapshot) => snapshot.power),
|
||||
Stream.runForEach(monitor.report),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
return monitor;
|
||||
}),
|
||||
);
|
||||
@@ -38,7 +38,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
@@ -268,6 +268,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: baseDir,
|
||||
noBrowser: true,
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
@@ -323,12 +325,17 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
resourceMonitorPath: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
assert.equal(resolved.desktopTelemetryFd, 4);
|
||||
assert.equal(resolved.desktopTelemetryControlFd, 5);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ const EnvServerConfig = Config.all({
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -290,6 +290,9 @@ export const resolveServerConfig = (
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
|
||||
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
|
||||
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
@@ -362,6 +365,9 @@ export const resolveServerConfig = (
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
desktopTelemetryFd,
|
||||
desktopTelemetryControlFd,
|
||||
resourceMonitorPath,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
|
||||
@@ -71,6 +71,9 @@ export class ServerConfig extends Context.Service<
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly desktopTelemetryFd?: number | undefined;
|
||||
readonly desktopTelemetryControlFd?: number | undefined;
|
||||
readonly resourceMonitorPath?: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
@@ -177,6 +180,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
desktopTelemetryFd: undefined,
|
||||
desktopTelemetryControlFd: undefined,
|
||||
resourceMonitorPath: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
|
||||
@@ -1,282 +1,133 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
} 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 Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
function makeNativeSnapshot(
|
||||
processes: ResourceMonitorSnapshotEvent["processes"],
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
function makeTelemetryLayer(
|
||||
snapshot: ResourceMonitorSnapshotEvent,
|
||||
desktopSnapshot?: DesktopHostTelemetrySnapshot,
|
||||
) {
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
sampleNow: Effect.succeed(snapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = desktopSnapshot
|
||||
? DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(desktopSnapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
})
|
||||
: DesktopTelemetryReceiver.layerTest();
|
||||
return ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
it.effect("projects live process data from resource telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 10,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
startTimeMs: 1_000,
|
||||
runTimeMs: 60_000,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
cpuTimeMs: 100,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 100,
|
||||
ioWriteBytes: 200,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
pid: 4_242,
|
||||
ppid: process.pid,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "agent",
|
||||
command: "codex app-server",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provideMerge(telemetryLayer));
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
const diagnostics = yield* Effect.gen(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
yield* telemetry.refresh;
|
||||
return yield* processDiagnostics.read;
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
expect(diagnostics.processes[0]?.startTimeMs).toBe(2_000);
|
||||
expect(diagnostics.processes[0]?.cpuPercent).toBe(1.5);
|
||||
expect(diagnostics.processes[0]?.rssBytes).toBe(2_048);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
|
||||
it.effect("rejects stale process identities before signaling", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
code: 17,
|
||||
stdout: "partial process output",
|
||||
stderr: "process access denied",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ProcessDiagnosticsQueryFailedError",
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: process.cwd(),
|
||||
exitCode: 17,
|
||||
stdoutBytes: 22,
|
||||
stderrBytes: 21,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
const snapshot = makeNativeSnapshot([]);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGINT",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
@@ -284,7 +135,85 @@ describe("ProcessDiagnostics", () => {
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
message: Option.some("Process 4242 no longer matches the selected process identity."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects Electron processes as signal targets", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(
|
||||
DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
);
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 4_242,
|
||||
ppid: 1,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 4_242,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: 4_242,
|
||||
creationTimeMs: 2_000,
|
||||
type: "Browser",
|
||||
name: "electron",
|
||||
cpuPercent: 1.5,
|
||||
idleWakeupsPerSecond: 0,
|
||||
workingSetBytes: 2_048,
|
||||
peakWorkingSetBytes: 2_048,
|
||||
},
|
||||
],
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGKILL",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4_242,
|
||||
signal: "SIGKILL",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a signalable T3 backend descendant."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,105 +1,46 @@
|
||||
import type {
|
||||
ResourceTelemetryProcessCategory,
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
export interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly startTimeMs: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
{
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
|
||||
"ProcessDiagnosticsQueryTimeoutError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
|
||||
"ProcessDiagnosticsQueryFailedError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutBytes: Schema.optional(Schema.Number),
|
||||
stderrBytes: Schema.optional(Schema.Number),
|
||||
stdoutTruncated: Schema.optional(Schema.Boolean),
|
||||
stderrTruncated: Schema.optional(Schema.Boolean),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
|
||||
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
|
||||
"ProcessDiagnosticsServerProcessSignalError",
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to signal the T3 server process.";
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
|
||||
"ProcessDiagnosticsNotDescendantError",
|
||||
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
|
||||
"ProcessIdentityChanged",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
serverPid: Schema.Number,
|
||||
startTimeMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
|
||||
"ProcessDiagnosticsSignalFailedError",
|
||||
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
|
||||
"ProcessSignalFailed",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
signal: Schema.String,
|
||||
@@ -111,465 +52,140 @@ class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<Proces
|
||||
}
|
||||
}
|
||||
|
||||
const ProcessDiagnosticsError = Schema.Union([
|
||||
ProcessDiagnosticsQueryTimeoutError,
|
||||
ProcessDiagnosticsQueryFailedError,
|
||||
ProcessDiagnosticsServerProcessSignalError,
|
||||
ProcessDiagnosticsNotDescendantError,
|
||||
ProcessDiagnosticsSignalFailedError,
|
||||
]);
|
||||
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
function formatElapsed(runTimeMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
|
||||
const hours = Math.floor(totalSeconds / 3_600);
|
||||
const minutes = Math.floor((totalSeconds % 3_600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
|
||||
: `${minutes}:${String(seconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = parsePositiveInt(pidText);
|
||||
const ppid = parseNonNegativeInt(ppidText);
|
||||
const pgid = Number.parseInt(pgidText, 10);
|
||||
const cpuPercent = parseNumber(cpuText);
|
||||
const rssKiB = parseNonNegativeInt(rssText);
|
||||
if (
|
||||
pid === null ||
|
||||
ppid === null ||
|
||||
!Number.isInteger(pgid) ||
|
||||
cpuPercent === null ||
|
||||
rssKiB === null ||
|
||||
!status ||
|
||||
!elapsed ||
|
||||
!command
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
pid,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
category === "server-child" || category === "provider-root" || category === "terminal-root"
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly cwd: string;
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stdoutBytes: number;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderr: string;
|
||||
readonly stderrBytes: number;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const cwd = process.cwd();
|
||||
return yield* Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
// contains pipes) before PowerShell ever sees it.
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd,
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
cwd,
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stdoutBytes: stdout.bytes,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderr: stderr.text,
|
||||
stderrBytes: stderr.bytes,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProcessOutput;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const read: ProcessDiagnosticsShape["read"] = telemetry.latest.pipe(
|
||||
Effect.map((snapshot) => {
|
||||
const processes = snapshot.processes
|
||||
.filter((entry) => entry.identity.pid !== process.pid)
|
||||
.map(
|
||||
(entry): ServerProcessDiagnosticsEntry => ({
|
||||
pid: entry.identity.pid,
|
||||
startTimeMs: entry.identity.startTimeMs,
|
||||
ppid: entry.ppid,
|
||||
pgid: Option.none(),
|
||||
status: entry.status || "Unknown",
|
||||
cpuPercent: entry.cpuPercent,
|
||||
rssBytes: entry.residentBytes,
|
||||
elapsed: formatElapsed(entry.runTimeMs),
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: Math.max(0, entry.depth - 1),
|
||||
childPids: entry.childPids,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "powershell.exe",
|
||||
argCount: 4,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const readProcessRows = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
});
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(
|
||||
new ProcessDiagnosticsServerProcessSignalError({
|
||||
pid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows.pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessDiagnosticsNotDescendantError({
|
||||
pid,
|
||||
serverPid: process.pid,
|
||||
}),
|
||||
);
|
||||
);
|
||||
return {
|
||||
serverPid: process.pid,
|
||||
readAt: snapshot.readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
|
||||
totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
|
||||
processes,
|
||||
error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessDiagnosticsSignalFailedError({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
if (input.pid === process.pid) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some("Refusing to signal the T3 server process."),
|
||||
};
|
||||
}
|
||||
const current = yield* telemetry.latest;
|
||||
const selected = current.processes.find(
|
||||
(entry) =>
|
||||
entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
|
||||
);
|
||||
if (!selected) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
`Process ${input.pid} no longer matches the selected process identity.`,
|
||||
),
|
||||
};
|
||||
}
|
||||
if (!canSignalCategory(selected.category)) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
|
||||
};
|
||||
}
|
||||
return yield* telemetry
|
||||
.validateProcessIdentity({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((valid) =>
|
||||
valid
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessIdentityChanged({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessSignalFailed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
error instanceof Error ? error.message : "Failed to signal process.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make);
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,255 +1,137 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type { ResourceTelemetryHistory } 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 Stream from "effect/Stream";
|
||||
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
|
||||
|
||||
describe("ProcessResourceMonitor", () => {
|
||||
it.effect("samples the server root process and descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 50,
|
||||
rssBytes: 3_000,
|
||||
elapsed: "00:05",
|
||||
command: "rg needle",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "R",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:05",
|
||||
command: "unrelated",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
|
||||
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
|
||||
expect(samples[0]?.isServerRoot).toBe(true);
|
||||
expect(samples[1]?.isServerRoot).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls samples up by process and CPU time", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 30,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:05",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(Option.isNone(result.error)).toBe(true);
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
|
||||
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
|
||||
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
|
||||
expect(result.totalCpuSecondsApprox).toBe(2);
|
||||
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:06",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
|
||||
expect(result.topProcesses[0]?.sampleCount).toBe(2);
|
||||
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns all process summaries in the selected window", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
...Array.from({ length: 35 }, (_, index) => ({
|
||||
pid: 200 + index,
|
||||
ppid: index === 0 ? 100 : 199 + index,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 35 - index,
|
||||
rssBytes: 2_000 + index,
|
||||
elapsed: "00:10",
|
||||
command: `worker ${index}`,
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
|
||||
Effect.sync(() => {
|
||||
it.effect("projects resource telemetry history into the legacy diagnostics contract", () =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const cause = new Error("stderr included credential=secret-value");
|
||||
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
cause,
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples: [],
|
||||
const history: ResourceTelemetryHistory = {
|
||||
readAt,
|
||||
readAtMs: DateTime.toEpochMillis(readAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: failure,
|
||||
});
|
||||
sampleIntervalMs: 1_000,
|
||||
retainedSampleCount: 2,
|
||||
buckets: [
|
||||
{
|
||||
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
|
||||
endedAt: readAt,
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
maxProcessCount: 2,
|
||||
},
|
||||
],
|
||||
topProcesses: [
|
||||
{
|
||||
identity: { pid: process.pid, startTimeMs: 100 },
|
||||
ppid: 1,
|
||||
depth: 0,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
category: "server",
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuTimeMs: 1_500,
|
||||
currentRssBytes: 2_048,
|
||||
peakRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
ioSemantics: "storage",
|
||||
sampleCount: 2,
|
||||
},
|
||||
],
|
||||
health: {
|
||||
native: {
|
||||
status: "degraded",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.some("collector stalled"),
|
||||
},
|
||||
desktop: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
sidecarVersion: Option.some("0.1.0"),
|
||||
sidecarPid: Option.some(9_000),
|
||||
restartCount: 1,
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: 80,
|
||||
retainedProcessCount: 2,
|
||||
inaccessibleProcessCount: 0,
|
||||
},
|
||||
};
|
||||
const telemetry: ResourceTelemetry.ResourceTelemetryShape = {
|
||||
latest: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
readHistory: () => Effect.succeed(history),
|
||||
refresh: Effect.die("unused"),
|
||||
validateProcessIdentity: () => Effect.die("unused"),
|
||||
retry: Effect.die("unused"),
|
||||
};
|
||||
const layer = ProcessResourceMonitor.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ResourceTelemetry.ResourceTelemetry,
|
||||
ResourceTelemetry.ResourceTelemetry.of(telemetry),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(failure.cause).toBe(cause);
|
||||
expect(Option.getOrThrow(result.error)).toEqual({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
|
||||
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
|
||||
Effect.flatMap((monitor) =>
|
||||
monitor.readHistory({
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result.totalCpuSecondsApprox).toBe(1.5);
|
||||
expect(result.topProcesses).toEqual([
|
||||
{
|
||||
processKey: `${process.pid}:100`,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
command: "t3 server",
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuSecondsApprox: 1.5,
|
||||
currentRssBytes: 2_048,
|
||||
maxRssBytes: 4_096,
|
||||
sampleCount: 2,
|
||||
},
|
||||
]);
|
||||
expect(result.buckets[0]).toMatchObject({
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
maxProcessCount: 2,
|
||||
});
|
||||
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
|
||||
expect(result.error).toEqual(
|
||||
Option.some({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "collector stalled",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,329 +1,77 @@
|
||||
import {
|
||||
ServerProcessResourceHistoryFailureTag,
|
||||
type ServerProcessResourceHistoryBucket,
|
||||
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
|
||||
type ServerProcessResourceHistoryInput,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProcessResourceHistorySummary,
|
||||
import type {
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
} 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 Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
const MAX_RETAINED_SAMPLES = 20_000;
|
||||
|
||||
export interface ProcessResourceSample {
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
readonly processKey: string;
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly command: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly depth: number;
|
||||
readonly isServerRoot: boolean;
|
||||
}
|
||||
|
||||
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
|
||||
"ProcessResourceSamplingError",
|
||||
{
|
||||
failureTag: ServerProcessResourceHistoryFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sample process resources (${this.failureTag}).`;
|
||||
}
|
||||
}
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
export interface ProcessResourceMonitorShape {
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
{
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
ProcessResourceMonitorShape
|
||||
>()("t3/diagnostics/ProcessResourceMonitor") {}
|
||||
|
||||
function dateTimeFromMillis(ms: number): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(ms);
|
||||
}
|
||||
|
||||
function sampleKey(row: Pick<ProcessDiagnostics.ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(
|
||||
rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>,
|
||||
serverPid: number,
|
||||
): ProcessDiagnostics.ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
readonly rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>;
|
||||
readonly serverPid: number;
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
}): ReadonlyArray<ProcessResourceSample> {
|
||||
const rows = input.rows.filter(
|
||||
(row) => !ProcessDiagnostics.isDiagnosticsQueryProcess(row, input.serverPid),
|
||||
);
|
||||
const root = findServerRootRow(rows, input.serverPid);
|
||||
const descendants = ProcessDiagnostics.buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(root),
|
||||
pid: root.pid,
|
||||
ppid: root.ppid,
|
||||
command: root.command,
|
||||
cpuPercent: root.cpuPercent,
|
||||
rssBytes: root.rssBytes,
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const process of descendants) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(process),
|
||||
pid: process.pid,
|
||||
ppid: process.ppid,
|
||||
command: process.command,
|
||||
cpuPercent: process.cpuPercent,
|
||||
rssBytes: process.rssBytes,
|
||||
depth: process.depth + 1,
|
||||
isServerRoot: false,
|
||||
});
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
function trimSamples(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
nowMs: number,
|
||||
): ReadonlyArray<ProcessResourceSample> {
|
||||
const minSampledAtMs = nowMs - RETENTION_MS;
|
||||
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
return retained.length <= MAX_RETAINED_SAMPLES
|
||||
? retained
|
||||
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
): ReadonlyArray<ServerProcessResourceHistorySummary> {
|
||||
const groups = new Map<string, ProcessResourceSample[]>();
|
||||
for (const sample of samples) {
|
||||
const processSamples = groups.get(sample.processKey) ?? [];
|
||||
processSamples.push(sample);
|
||||
groups.set(sample.processKey, processSamples);
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([processKey, processSamples]) => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
|
||||
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
|
||||
const cpuSecondsApprox = sorted.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
processKey,
|
||||
pid: latest.pid,
|
||||
ppid: latest.ppid,
|
||||
command: latest.command,
|
||||
depth: latest.depth,
|
||||
isServerRoot: latest.isServerRoot,
|
||||
firstSeenAt: first.sampledAt,
|
||||
lastSeenAt: latest.sampledAt,
|
||||
currentCpuPercent: latest.cpuPercent,
|
||||
avgCpuPercent: cpuPercentTotal / sorted.length,
|
||||
maxCpuPercent,
|
||||
cpuSecondsApprox,
|
||||
currentRssBytes: latest.rssBytes,
|
||||
maxRssBytes,
|
||||
sampleCount: sorted.length,
|
||||
} satisfies ServerProcessResourceHistorySummary;
|
||||
})
|
||||
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ServerProcessResourceHistoryBucket[] = [];
|
||||
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
|
||||
const bucketSamples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const samplesByRead = new Map<number, ProcessResourceSample[]>();
|
||||
for (const sample of bucketSamples) {
|
||||
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
|
||||
samplesAtTime.push(sample);
|
||||
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
|
||||
}
|
||||
|
||||
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
|
||||
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
|
||||
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
|
||||
processCount: samplesAtTime.length,
|
||||
}));
|
||||
const avgCpuPercent =
|
||||
readTotals.length === 0
|
||||
? 0
|
||||
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
|
||||
|
||||
buckets.push({
|
||||
startedAt: dateTimeFromMillis(startedAtMs),
|
||||
endedAt: dateTimeFromMillis(endedAtMs),
|
||||
avgCpuPercent,
|
||||
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
|
||||
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
|
||||
maxProcessCount: readTotals.length
|
||||
? Math.max(...readTotals.map((read) => read.processCount))
|
||||
: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function aggregateProcessResourceHistory(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const minSampledAtMs = input.readAtMs - windowMs;
|
||||
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
const topProcesses = summarizeProcesses(samples);
|
||||
const totalCpuSecondsApprox = samples.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
retainedSampleCount: input.samples.length,
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
topProcesses,
|
||||
error: input.lastFailure
|
||||
? Option.some({
|
||||
failureTag: input.lastFailure.failureTag,
|
||||
message: input.lastFailure.message,
|
||||
})
|
||||
: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
|
||||
|
||||
const recordSamplingFailure = (cause: {
|
||||
readonly _tag: ServerProcessResourceHistoryFailureTagType;
|
||||
}) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastFailure: new ProcessResourceSamplingError({
|
||||
failureTag: cause._tag,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
telemetry.readHistory(input).pipe(
|
||||
Effect.map((history) => {
|
||||
const topProcesses = history.topProcesses.map((entry) => ({
|
||||
processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
|
||||
pid: entry.identity.pid,
|
||||
ppid: entry.ppid,
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: entry.depth,
|
||||
isServerRoot: entry.category === "server",
|
||||
firstSeenAt: entry.firstSeenAt,
|
||||
lastSeenAt: entry.lastSeenAt,
|
||||
currentCpuPercent: entry.currentCpuPercent,
|
||||
avgCpuPercent: entry.avgCpuPercent,
|
||||
maxCpuPercent: entry.maxCpuPercent,
|
||||
cpuSecondsApprox: entry.cpuTimeMs / 1_000,
|
||||
currentRssBytes: entry.currentRssBytes,
|
||||
maxRssBytes: entry.peakRssBytes,
|
||||
sampleCount: entry.sampleCount,
|
||||
}));
|
||||
return {
|
||||
readAt: history.readAt,
|
||||
windowMs: history.windowMs,
|
||||
bucketMs: history.bucketMs,
|
||||
sampleIntervalMs: history.sampleIntervalMs,
|
||||
retainedSampleCount: history.retainedSampleCount,
|
||||
totalCpuSecondsApprox: topProcesses.reduce(
|
||||
(total, entry) => total + entry.cpuSecondsApprox,
|
||||
0,
|
||||
),
|
||||
buckets: history.buckets.map((bucket) => ({
|
||||
startedAt: bucket.startedAt,
|
||||
endedAt: bucket.endedAt,
|
||||
avgCpuPercent: bucket.avgCpuPercent,
|
||||
maxCpuPercent: bucket.maxCpuPercent,
|
||||
maxRssBytes: bucket.maxRssBytes,
|
||||
maxProcessCount: bucket.maxProcessCount,
|
||||
})),
|
||||
topProcesses,
|
||||
error: history.health.native.lastError.pipe(
|
||||
Option.map((message) => ({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError" as const,
|
||||
message,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
rows,
|
||||
serverPid: process.pid,
|
||||
sampledAt,
|
||||
sampledAtMs,
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastFailure: null,
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
|
||||
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
|
||||
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
|
||||
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
|
||||
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
const current = yield* Ref.get(state);
|
||||
return aggregateProcessResourceHistory({
|
||||
samples: current.samples,
|
||||
readAt,
|
||||
readAtMs,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
lastFailure: current.lastFailure,
|
||||
});
|
||||
});
|
||||
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make);
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
@@ -114,6 +114,33 @@ describe("GitWorkflowService", () => {
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("routes explicit upstream refreshes through the Git driver", () => {
|
||||
const refreshStatusUpstream = vi.fn(() => Effect.void);
|
||||
const testLayer = GitWorkflowService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
detect: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
} as VcsDriverRegistry.VcsDriverHandle),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitVcsDriver.GitVcsDriver)({
|
||||
refreshStatusUpstream,
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitManager.GitManager)({})),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
yield* workflow.refreshStatusUpstream("/repo");
|
||||
|
||||
assert.deepStrictEqual(refreshStatusUpstream.mock.calls, [["/repo"]]);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("returns an empty ref list when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
|
||||
@@ -45,6 +45,7 @@ export class GitWorkflowService extends Context.Service<
|
||||
input: VcsStatusInput,
|
||||
options?: GitVcsDriver.GitRemoteStatusOptions,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
@@ -270,6 +271,12 @@ export const make = Effect.gen(function* () {
|
||||
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
|
||||
),
|
||||
),
|
||||
refreshStatusUpstream: (cwd) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void,
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
|
||||
@@ -44,18 +44,13 @@ 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, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
@@ -35,7 +34,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -55,26 +54,36 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
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" },
|
||||
},
|
||||
}),
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: 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: {} })
|
||||
@@ -154,50 +163,60 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
const requests = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
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,
|
||||
},
|
||||
}),
|
||||
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,
|
||||
},
|
||||
}),
|
||||
).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,4 +214,7 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
@@ -1,28 +1,20 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewTabId,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewAutomationOwner,
|
||||
} 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"),
|
||||
@@ -30,42 +22,27 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
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", () =>
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
result: { available: true },
|
||||
@@ -84,39 +61,6 @@ it.effect("atomically registers a connected host 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.";
|
||||
@@ -128,12 +72,10 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: remoteError,
|
||||
@@ -146,7 +88,6 @@ 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);
|
||||
@@ -180,61 +121,13 @@ 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* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
}),
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -257,14 +150,13 @@ it.effect("distinguishes malformed remote failures", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no connected host exists", () =>
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
@@ -275,425 +167,32 @@ it.effect("rejects calls when no connected host exists", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
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", () =>
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
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);
|
||||
|
||||
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
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;
|
||||
yield* Fiber.interrupt(consumer);
|
||||
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes requests for background threads through an environment-level host", () =>
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
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()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
});
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -704,55 +203,61 @@ it.effect("lets the browser host resolve an active tab locally", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let replacementConnectionId = "";
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
});
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
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;
|
||||
|
||||
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.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
|
||||
expect(replacementConnectionId).not.toBe(firstConnectionId);
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("replacement");
|
||||
expect(routedTabId).toBe("tab-current");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
).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: {} });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
@@ -770,40 +275,25 @@ it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("accepts responses only from the host that received the request", () =>
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
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",
|
||||
});
|
||||
}),
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
).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("owner");
|
||||
|
||||
expect(result).toBe("connected");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,29 +1,26 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
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";
|
||||
@@ -46,9 +43,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -60,12 +60,7 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -74,13 +69,6 @@ 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"];
|
||||
@@ -88,7 +76,6 @@ 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;
|
||||
@@ -98,36 +85,11 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
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"> => {
|
||||
@@ -141,14 +103,6 @@ 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 {
|
||||
@@ -177,8 +131,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -208,36 +162,6 @@ 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;
|
||||
@@ -269,21 +193,36 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
assignments: new Map(),
|
||||
owners: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
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(
|
||||
disconnected,
|
||||
toFail,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -291,89 +230,54 @@ 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",
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
)(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)));
|
||||
});
|
||||
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
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);
|
||||
if (
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
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 };
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -382,13 +286,7 @@ 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 ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
if (!entry) return [undefined, current] as const;
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -409,83 +307,29 @@ 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 timeoutMs = input.timeoutMs ?? 15_000;
|
||||
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
|
||||
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;
|
||||
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,
|
||||
});
|
||||
}
|
||||
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,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
@@ -493,7 +337,42 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext } = route;
|
||||
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 selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
|
||||
const context: PreviewAutomationRequestErrorContext = {
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -502,16 +381,12 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -529,7 +404,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -40,8 +39,6 @@ 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,8 +7,6 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
@@ -37,7 +35,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, loading state, viewport mode, and measured CSS-pixel size.",
|
||||
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -71,19 +69,6 @@ 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:
|
||||
@@ -183,7 +168,6 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -199,7 +183,6 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as OtlpSerialization from "effect/unstable/observability/OtlpSerializat
|
||||
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import { ServerLoggerLive } from "../../serverLogger.ts";
|
||||
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
|
||||
|
||||
@@ -17,6 +18,7 @@ const otlpSerializationLayer = OtlpSerialization.layerJson;
|
||||
export const ObservabilityLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
@@ -31,6 +33,14 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
onFlush: (stats) =>
|
||||
attribution.record({
|
||||
component: "server-trace",
|
||||
operation: "append",
|
||||
logicalWriteBytes: stats.logicalWriteBytes,
|
||||
count: stats.count,
|
||||
durationMs: stats.durationMs,
|
||||
}),
|
||||
});
|
||||
const delegate =
|
||||
config.otlpTracesUrl === undefined
|
||||
|
||||
@@ -151,61 +151,6 @@ 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,8 +20,6 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -47,9 +45,6 @@ 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>;
|
||||
@@ -119,7 +114,6 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -133,7 +127,6 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -244,7 +237,6 @@ 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 {
|
||||
@@ -277,7 +269,6 @@ 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 =
|
||||
@@ -308,34 +299,6 @@ 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
|
||||
@@ -397,7 +360,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -24,6 +24,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -57,7 +58,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
@@ -82,6 +82,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -186,7 +187,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
* @module provider/Drivers/CodexDriver
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -32,6 +31,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
@@ -74,6 +73,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
* registered driver and the runtime satisfies them once.
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -186,7 +186,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
* @module provider/Drivers/CursorDriver
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -21,6 +20,7 @@ import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
@@ -53,7 +53,6 @@ import {
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -65,6 +64,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -157,8 +157,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -8,6 +7,7 @@ import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -49,6 +48,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type GrokDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -134,7 +134,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
publishSnapshot,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
* @module provider/Drivers/OpenCodeDriver
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -23,6 +22,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
@@ -55,7 +55,6 @@ import {
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
@@ -78,6 +77,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -166,7 +166,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
},
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -1354,6 +1354,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
|
||||
const createQuery =
|
||||
options?.createQuery ??
|
||||
@@ -1387,7 +1389,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
|
||||
|
||||
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
|
||||
const logNativeSdkMessage = Effect.fnUntraced(function* (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
) {
|
||||
@@ -3843,6 +3845,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
|
||||
),
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1637,7 +1637,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
),
|
||||
);
|
||||
|
||||
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
|
||||
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -113,23 +113,6 @@ 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
|
||||
@@ -1021,10 +1004,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
|
||||
@@ -785,9 +785,6 @@ 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":
|
||||
|
||||
@@ -5,11 +5,14 @@ import * as NodePath from "node:path";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
@@ -148,6 +151,100 @@ describe("EventNdjsonLogger", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares one thread writer across native and canonical streams", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
const threadId = ThreadId.make("thread-shared");
|
||||
|
||||
yield* native.write({ id: "native-event" }, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-shared.log"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "NTIVE", payload: '{"id":"native-event"}' },
|
||||
{
|
||||
stream: "CANON",
|
||||
payload: '{"type":"item.completed","id":"canonical-event"}',
|
||||
},
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("flushes an active batch without a permanent polling loop", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const threadPath = NodePath.join(tempDir, "thread-batched.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
|
||||
yield* store
|
||||
.logger("native")
|
||||
.write({ id: "batched-event" }, ThreadId.make("thread-batched"));
|
||||
|
||||
assert.equal(NodeFS.existsSync(threadPath), false);
|
||||
yield* TestClock.adjust(1_000);
|
||||
assert.equal(NodeFS.existsSync(threadPath), true);
|
||||
yield* store.close();
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops transient canonical events before serialization", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const canonical = store.logger("canonical");
|
||||
const native = store.logger("native");
|
||||
const threadId = ThreadId.make("thread-filtered");
|
||||
const circularDelta: Record<string, unknown> = { type: "content.delta" };
|
||||
circularDelta["self"] = circularDelta;
|
||||
|
||||
yield* canonical.write(circularDelta, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
|
||||
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-filtered.log"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
|
||||
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent first writes for the same segment", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
@@ -196,19 +293,19 @@ describe("EventNdjsonLogger", () => {
|
||||
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxBytes: 120,
|
||||
maxFiles: 2,
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const logger = index % 2 === 0 ? native : canonical;
|
||||
yield* logger.write(
|
||||
{
|
||||
type: "session.started",
|
||||
threadId: "provider-thread-rotate",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(40),
|
||||
@@ -216,7 +313,7 @@ describe("EventNdjsonLogger", () => {
|
||||
ThreadId.make("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
yield* store.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const matchingFiles = NodeFS.readdirSync(tempDir)
|
||||
@@ -240,4 +337,71 @@ describe("EventNdjsonLogger", () => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("enforces aggregate age and byte retention on startup", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const expiredPath = NodePath.join(tempDir, "expired.log");
|
||||
const oldPath = NodePath.join(tempDir, "old.log");
|
||||
const newPath = NodePath.join(tempDir, "new.log");
|
||||
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
|
||||
|
||||
try {
|
||||
yield* TestClock.setTime(1_800_000_000_000);
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
for (const filePath of [expiredPath, oldPath, newPath, ignoredPath]) {
|
||||
NodeFS.writeFileSync(filePath, "x".repeat(40));
|
||||
}
|
||||
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
|
||||
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
|
||||
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
|
||||
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxAgeMs: 10_000,
|
||||
maxTotalBytes: 60,
|
||||
});
|
||||
yield* store.close();
|
||||
|
||||
assert.equal(NodeFS.existsSync(expiredPath), false);
|
||||
assert.equal(NodeFS.existsSync(oldPath), false);
|
||||
assert.equal(NodeFS.existsSync(newPath), true);
|
||||
assert.equal(NodeFS.existsSync(ignoredPath), true);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports logical provider log writes to resource attribution", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const attribution = yield* ResourceAttribution.make();
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
batchWindowMs: 0,
|
||||
attribution,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution"));
|
||||
yield* logger.close();
|
||||
|
||||
const snapshot = yield* attribution.snapshot;
|
||||
assert.equal(snapshot.entries.length, 1);
|
||||
assert.equal(snapshot.entries[0]?.component, "provider-event-log");
|
||||
assert.equal(snapshot.entries[0]?.operation, "native.append");
|
||||
assert.equal(snapshot.entries[0]?.count, 1);
|
||||
assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Provider event logger helper.
|
||||
* Best-effort provider event logging with one shared writer per thread.
|
||||
*
|
||||
* Best-effort writer for observability logs. Each record is formatted as a
|
||||
* single effect-style text line in a thread-scoped file. Failures are
|
||||
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||
* Native and canonical views share batching, rotation, and retention state so
|
||||
* they cannot race while appending to the same thread-scoped file.
|
||||
*/
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
@@ -12,45 +11,149 @@ import * as NodePath from "node:path";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { errorTag } from "@t3tools/shared/observability";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
import type { ResourceAttributionShape } from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
|
||||
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const MEBIBYTE = 1024 * 1024;
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
|
||||
const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 1_000;
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
|
||||
const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
|
||||
const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
|
||||
const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
|
||||
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
const PROVIDER_LOG_FILE_PATTERN = /\.log(?:\.\d+)?$/u;
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
const transientCanonicalEventTypes = new Set([
|
||||
"content.delta",
|
||||
"hook.progress",
|
||||
"item.updated",
|
||||
"task.progress",
|
||||
"thread.realtime.audio.delta",
|
||||
"tool.progress",
|
||||
"turn.proposed.delta",
|
||||
]);
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
|
||||
close: () => Effect.Effect<void, never, never>;
|
||||
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLoggerOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
export interface EventNdjsonLogStore {
|
||||
readonly filePath: string;
|
||||
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLogStoreOptions {
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
readonly batchWindowMs?: number;
|
||||
readonly maxTotalBytes?: number;
|
||||
readonly maxAgeMs?: number;
|
||||
readonly retentionCheckIntervalMs?: number;
|
||||
readonly maxBufferedBytes?: number;
|
||||
readonly maxBufferedRecords?: number;
|
||||
readonly attribution?: ResourceAttributionShape;
|
||||
}
|
||||
|
||||
interface ThreadWriter {
|
||||
writeMessage: (message: string) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
}
|
||||
|
||||
interface LoggerState {
|
||||
readonly threadWriters: Map<string, ThreadWriter>;
|
||||
readonly failedSegments: Set<string>;
|
||||
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
|
||||
"EventNdjsonLogConfigurationError",
|
||||
{
|
||||
filePath: Schema.String,
|
||||
option: Schema.String,
|
||||
value: Schema.Number,
|
||||
minimum: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
|
||||
"EventNdjsonLogDirectoryError",
|
||||
{
|
||||
directory: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create provider event log directory '${this.directory}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EventNdjsonLogStoreError =
|
||||
| EventNdjsonLogConfigurationError
|
||||
| EventNdjsonLogDirectoryError;
|
||||
|
||||
interface ResolvedOptions {
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly retentionCheckIntervalMs: number;
|
||||
readonly maxBufferedBytes: number;
|
||||
readonly maxBufferedRecords: number;
|
||||
readonly attribution: ResourceAttributionShape | undefined;
|
||||
}
|
||||
|
||||
interface PendingRecord {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly threadSegment: string;
|
||||
readonly line: string;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface StoreState {
|
||||
readonly pending: ReadonlyArray<PendingRecord>;
|
||||
readonly pendingBytes: number;
|
||||
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
|
||||
readonly failedSegments: ReadonlySet<string>;
|
||||
readonly flushScheduled: boolean;
|
||||
readonly closed: boolean;
|
||||
readonly lastRetentionAt: number;
|
||||
}
|
||||
|
||||
interface AttributionSummary {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly count: number;
|
||||
readonly logicalWriteBytes: number;
|
||||
}
|
||||
|
||||
interface FileOperationFailure {
|
||||
readonly filePath: string;
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
interface RetentionResult {
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
}
|
||||
|
||||
interface DrainResult {
|
||||
readonly attributions: ReadonlyArray<AttributionSummary>;
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
@@ -62,34 +165,249 @@ function resolveThreadSegment(raw: string | null | undefined): string {
|
||||
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||
}
|
||||
|
||||
function formatLoggerMessage(message: unknown): string {
|
||||
if (Array.isArray(message)) {
|
||||
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||
}
|
||||
return typeof message === "string" ? message : String(message);
|
||||
}
|
||||
|
||||
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||
return Logger.make(
|
||||
({ date, message }) =>
|
||||
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
switch (stream) {
|
||||
case "native":
|
||||
return "NTIVE";
|
||||
case "canonical":
|
||||
case "orchestration":
|
||||
default:
|
||||
return "CANON";
|
||||
}
|
||||
return stream === "native" ? "NTIVE" : "CANON";
|
||||
}
|
||||
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
|
||||
if (stream !== "canonical" || typeof event !== "object" || event === null) {
|
||||
return true;
|
||||
}
|
||||
const type = Reflect.get(event, "type");
|
||||
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
|
||||
}
|
||||
|
||||
function writeBatchedMessages(
|
||||
sink: RotatingFileSink,
|
||||
records: ReadonlyArray<PendingRecord>,
|
||||
maxBytes: number,
|
||||
): void {
|
||||
let pendingLines: Array<string> = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (pendingLines.length === 0) return;
|
||||
sink.write(pendingLines.join(""));
|
||||
pendingLines = [];
|
||||
pendingBytes = 0;
|
||||
};
|
||||
|
||||
for (const record of records) {
|
||||
if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
|
||||
flush();
|
||||
}
|
||||
pendingLines.push(record.line);
|
||||
pendingBytes += record.bytes;
|
||||
if (pendingBytes >= maxBytes) {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function enforceRetention(input: {
|
||||
readonly directory: string;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly activeFilePaths: ReadonlySet<string>;
|
||||
readonly now: number;
|
||||
}): RetentionResult {
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
|
||||
|
||||
let entries: ReadonlyArray<NodeFS.Dirent>;
|
||||
try {
|
||||
entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
|
||||
} catch (cause) {
|
||||
return { failures: [{ filePath: input.directory, cause }] };
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue;
|
||||
const filePath = NodePath.join(input.directory, entry.name);
|
||||
try {
|
||||
const stat = NodeFS.statSync(filePath);
|
||||
files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
|
||||
} catch (cause) {
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
let totalBytes = files.reduce((total, file) => total + file.size, 0);
|
||||
const remove = (file: (typeof files)[number]) => {
|
||||
if (input.activeFilePaths.has(file.filePath)) return false;
|
||||
try {
|
||||
NodeFS.rmSync(file.filePath, { force: true });
|
||||
totalBytes -= file.size;
|
||||
return true;
|
||||
} catch (cause) {
|
||||
failures.push({ filePath: file.filePath, cause });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const retained = files.filter((file) => {
|
||||
if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
|
||||
return !remove(file);
|
||||
});
|
||||
|
||||
for (const file of retained.toSorted(
|
||||
(left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
|
||||
)) {
|
||||
if (totalBytes <= input.maxTotalBytes) break;
|
||||
remove(file);
|
||||
}
|
||||
|
||||
return { failures };
|
||||
}
|
||||
|
||||
function validateOption(input: {
|
||||
readonly filePath: string;
|
||||
readonly option: string;
|
||||
readonly value: number;
|
||||
readonly minimum: number;
|
||||
}): EventNdjsonLogConfigurationError | undefined {
|
||||
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
|
||||
return new EventNdjsonLogConfigurationError(input);
|
||||
}
|
||||
|
||||
function resolveOptions(
|
||||
filePath: string,
|
||||
options: EventNdjsonLogStoreOptions,
|
||||
): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
|
||||
const resolved = {
|
||||
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
||||
maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
|
||||
batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
|
||||
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
|
||||
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
|
||||
retentionCheckIntervalMs:
|
||||
options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
|
||||
maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
|
||||
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
|
||||
attribution: options.attribution,
|
||||
} satisfies ResolvedOptions;
|
||||
|
||||
const validations = [
|
||||
["maxBytes", resolved.maxBytes, 1],
|
||||
["maxFiles", resolved.maxFiles, 1],
|
||||
["batchWindowMs", resolved.batchWindowMs, 0],
|
||||
["maxTotalBytes", resolved.maxTotalBytes, 1],
|
||||
["maxAgeMs", resolved.maxAgeMs, 1],
|
||||
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
|
||||
["maxBufferedBytes", resolved.maxBufferedBytes, 1],
|
||||
["maxBufferedRecords", resolved.maxBufferedRecords, 1],
|
||||
] as const;
|
||||
|
||||
for (const [option, value, minimum] of validations) {
|
||||
const error = validateOption({ filePath, option, value, minimum });
|
||||
if (error) return Effect.fail(error);
|
||||
}
|
||||
return Effect.succeed(resolved);
|
||||
}
|
||||
|
||||
function drainPending(input: {
|
||||
readonly directory: string;
|
||||
readonly options: ResolvedOptions;
|
||||
readonly state: StoreState;
|
||||
readonly now: number;
|
||||
readonly timerFired: boolean;
|
||||
readonly close: boolean;
|
||||
}): readonly [DrainResult, StoreState] {
|
||||
if (input.state.closed) {
|
||||
return [{ attributions: [], failures: [] }, input.state];
|
||||
}
|
||||
|
||||
const sinks = new Map(input.state.sinks);
|
||||
const failedSegments = new Set(input.state.failedSegments);
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const attributionByStream = new Map<
|
||||
EventNdjsonStream,
|
||||
{ count: number; logicalWriteBytes: number }
|
||||
>();
|
||||
const recordsBySegment = new Map<string, Array<PendingRecord>>();
|
||||
|
||||
for (const record of input.state.pending) {
|
||||
const records = recordsBySegment.get(record.threadSegment) ?? [];
|
||||
records.push(record);
|
||||
recordsBySegment.set(record.threadSegment, records);
|
||||
}
|
||||
|
||||
for (const [threadSegment, records] of recordsBySegment) {
|
||||
if (failedSegments.has(threadSegment)) continue;
|
||||
const filePath = NodePath.join(input.directory, `${threadSegment}.log`);
|
||||
let sink = sinks.get(threadSegment);
|
||||
if (!sink) {
|
||||
try {
|
||||
sink = new RotatingFileSink({
|
||||
filePath,
|
||||
maxBytes: input.options.maxBytes,
|
||||
maxFiles: input.options.maxFiles,
|
||||
throwOnError: true,
|
||||
});
|
||||
sinks.set(threadSegment, sink);
|
||||
} catch (cause) {
|
||||
failedSegments.add(threadSegment);
|
||||
failures.push({ filePath, cause });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
writeBatchedMessages(sink, records, input.options.maxBytes);
|
||||
for (const record of records) {
|
||||
const current = attributionByStream.get(record.stream) ?? {
|
||||
count: 0,
|
||||
logicalWriteBytes: 0,
|
||||
};
|
||||
attributionByStream.set(record.stream, {
|
||||
count: current.count + 1,
|
||||
logicalWriteBytes: current.logicalWriteBytes + record.bytes,
|
||||
});
|
||||
}
|
||||
} catch (cause) {
|
||||
failedSegments.add(threadSegment);
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
const retentionDue =
|
||||
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
|
||||
const retention = retentionDue
|
||||
? enforceRetention({
|
||||
directory: input.directory,
|
||||
maxTotalBytes: input.options.maxTotalBytes,
|
||||
maxAgeMs: input.options.maxAgeMs,
|
||||
activeFilePaths: new Set(
|
||||
Array.from(sinks.keys(), (threadSegment) =>
|
||||
NodePath.join(input.directory, `${threadSegment}.log`),
|
||||
),
|
||||
),
|
||||
now: input.now,
|
||||
})
|
||||
: { failures: [] };
|
||||
|
||||
return [
|
||||
{
|
||||
attributions: Array.from(attributionByStream, ([stream, value]) => ({
|
||||
stream,
|
||||
...value,
|
||||
})),
|
||||
failures: [...failures, ...retention.failures],
|
||||
},
|
||||
{
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks,
|
||||
failedSegments,
|
||||
flushScheduled: input.timerFired ? false : input.state.flushScheduled,
|
||||
closed: input.close,
|
||||
lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
|
||||
return yield* encodeUnknownJsonString(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning("failed to serialize provider event log record", {
|
||||
@@ -99,188 +417,169 @@ const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(sinkResult.error),
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(flushResult.error),
|
||||
});
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
|
||||
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
options: EventNdjsonLogStoreOptions = {},
|
||||
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
|
||||
const resolved = yield* resolveOptions(filePath, options);
|
||||
const directory = NodePath.dirname(filePath);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
yield* Effect.try({
|
||||
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
|
||||
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
errorTag: errorTag(directoryReady.error),
|
||||
|
||||
const initializedAt = yield* Clock.currentTimeMillis;
|
||||
const initialRetention = yield* Effect.sync(() =>
|
||||
enforceRetention({
|
||||
directory,
|
||||
maxTotalBytes: resolved.maxTotalBytes,
|
||||
maxAgeMs: resolved.maxAgeMs,
|
||||
activeFilePaths: new Set(),
|
||||
now: initializedAt,
|
||||
}),
|
||||
);
|
||||
for (const failure of initialRetention.failures) {
|
||||
yield* logWarning("provider event log retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stateRef = yield* SynchronizedRef.make<LoggerState>({
|
||||
threadWriters: new Map(),
|
||||
const stateRef = yield* SynchronizedRef.make<StoreState>({
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks: new Map(),
|
||||
failedSegments: new Set(),
|
||||
flushScheduled: false,
|
||||
closed: false,
|
||||
lastRetentionAt: initializedAt,
|
||||
});
|
||||
const timerScope = yield* Scope.make();
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
if (state.failedSegments.has(threadSegment)) {
|
||||
return Effect.succeed([undefined, state] as const);
|
||||
}
|
||||
|
||||
const existing = state.threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return Effect.succeed([existing, state] as const);
|
||||
}
|
||||
|
||||
return makeThreadWriter({
|
||||
filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
}).pipe(
|
||||
Effect.map((writer) => {
|
||||
if (!writer) {
|
||||
const nextFailedSegments = new Set(state.failedSegments);
|
||||
nextFailedSegments.add(threadSegment);
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
...state,
|
||||
failedSegments: nextFailedSegments,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
const nextThreadWriters = new Map(state.threadWriters);
|
||||
nextThreadWriters.set(threadSegment, writer);
|
||||
return [
|
||||
writer,
|
||||
{
|
||||
...state,
|
||||
threadWriters: nextThreadWriters,
|
||||
},
|
||||
] as const;
|
||||
const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
|
||||
const startedAt = yield* Clock.currentTimeMillis;
|
||||
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.sync(() =>
|
||||
drainPending({
|
||||
directory,
|
||||
options: resolved,
|
||||
state,
|
||||
now: startedAt,
|
||||
timerFired,
|
||||
close,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
for (const failure of result.failures) {
|
||||
yield* logWarning("provider event log write or retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
}
|
||||
|
||||
if (resolved.attribution && result.attributions.length > 0) {
|
||||
const completedAt = yield* Clock.currentTimeMillis;
|
||||
const durationMs = Math.max(0, completedAt - startedAt);
|
||||
const totalBytes = result.attributions.reduce(
|
||||
(total, entry) => total + entry.logicalWriteBytes,
|
||||
0,
|
||||
);
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
result.attributions,
|
||||
(entry) =>
|
||||
resolved.attribution?.record({
|
||||
component: "provider-event-log",
|
||||
operation: `${entry.stream}.append`,
|
||||
logicalWriteBytes: entry.logicalWriteBytes,
|
||||
count: entry.count,
|
||||
durationMs:
|
||||
totalBytes === 0
|
||||
? 0
|
||||
: Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
|
||||
}) ?? Effect.void,
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
|
||||
const close = Effect.fn("close")(function* () {
|
||||
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.gen(function* () {
|
||||
for (const writer of state.threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
threadWriters: new Map<string, ThreadWriter>(),
|
||||
failedSegments: new Set<string>(),
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
const scheduleFlush = Effect.fnUntraced(function* () {
|
||||
yield* Effect.forkIn(
|
||||
Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
|
||||
timerScope,
|
||||
{ startImmediately: true },
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write,
|
||||
close,
|
||||
} satisfies EventNdjsonLogger;
|
||||
const close = Effect.fnUntraced(function* () {
|
||||
yield* flush(false, true);
|
||||
yield* Scope.close(timerScope, Exit.void);
|
||||
});
|
||||
|
||||
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
|
||||
const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
|
||||
const existing = loggerViews.get(stream);
|
||||
if (existing) return existing;
|
||||
|
||||
const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
|
||||
if (!shouldPersist(stream, event)) return;
|
||||
const payload = yield* serializeEvent(event);
|
||||
if (payload === undefined) return;
|
||||
|
||||
const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
|
||||
const bytes = Buffer.byteLength(line);
|
||||
const action = yield* SynchronizedRef.modify(stateRef, (state) => {
|
||||
if (state.closed) {
|
||||
return [{ flush: false, schedule: false }, state] as const;
|
||||
}
|
||||
const pending = [
|
||||
...state.pending,
|
||||
{ stream, threadSegment: resolveThreadSegment(threadId), line, bytes },
|
||||
];
|
||||
const pendingBytes = state.pendingBytes + bytes;
|
||||
const flush =
|
||||
resolved.batchWindowMs === 0 ||
|
||||
pending.length >= resolved.maxBufferedRecords ||
|
||||
pendingBytes >= resolved.maxBufferedBytes;
|
||||
const schedule = !flush && !state.flushScheduled;
|
||||
return [
|
||||
{ flush, schedule },
|
||||
{
|
||||
...state,
|
||||
pending,
|
||||
pendingBytes,
|
||||
flushScheduled: state.flushScheduled || schedule,
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
|
||||
if (action.flush) {
|
||||
yield* flush(false, false);
|
||||
} else if (action.schedule) {
|
||||
yield* scheduleFlush();
|
||||
}
|
||||
});
|
||||
|
||||
const view = { filePath, write, close } satisfies EventNdjsonLogger;
|
||||
loggerViews.set(stream, view);
|
||||
return view;
|
||||
};
|
||||
|
||||
return { filePath, logger, close } satisfies EventNdjsonLogStore;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning(error.message, { error }).pipe(
|
||||
Effect.as<EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
return store?.logger(options.stream);
|
||||
});
|
||||
@@ -10,23 +10,20 @@ 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,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -48,11 +45,7 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(
|
||||
filePath: string,
|
||||
attempts = 40,
|
||||
expectedContent?: string,
|
||||
): Effect.Effect<string> {
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
@@ -61,10 +54,7 @@ function waitForFileContent(
|
||||
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (
|
||||
raw.trim().length > 0 &&
|
||||
(expectedContent === undefined || raw.includes(expectedContent))
|
||||
) {
|
||||
if (raw.trim().length > 0) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
@@ -89,39 +79,6 @@ 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* () {
|
||||
@@ -218,783 +175,6 @@ 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());
|
||||
@@ -1151,7 +331,6 @@ 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,7 +22,6 @@ 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";
|
||||
@@ -63,7 +62,6 @@ import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
@@ -110,8 +108,6 @@ 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. */
|
||||
@@ -140,38 +136,10 @@ 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;
|
||||
@@ -202,28 +170,6 @@ 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");
|
||||
@@ -294,144 +240,6 @@ 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;
|
||||
@@ -463,8 +271,6 @@ 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<{
|
||||
@@ -476,17 +282,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
@@ -618,14 +424,13 @@ 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,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
@@ -642,7 +447,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
@@ -681,14 +486,13 @@ 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,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
@@ -708,7 +512,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
@@ -774,7 +578,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
@@ -783,39 +586,14 @@ 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,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
@@ -824,44 +602,40 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
stamp,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"session/update",
|
||||
);
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
turnId: ctx.activeTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
@@ -923,15 +697,6 @@ 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 =
|
||||
@@ -1000,27 +765,12 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
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.",
|
||||
});
|
||||
}
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
@@ -1046,27 +796,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
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,
|
||||
});
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
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
|
||||
@@ -1074,18 +810,6 @@ 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),
|
||||
),
|
||||
@@ -1096,88 +820,38 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
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 }] },
|
||||
];
|
||||
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 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);
|
||||
// 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) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -1186,13 +860,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: completedStopReason,
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
ctx.interruptedTurnIds.delete(prepared.turnId);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
} else if (remainingPrompts > 0) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1204,153 +874,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(promptSettled)) {
|
||||
return;
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
}
|
||||
|
||||
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, turnId) =>
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
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,
|
||||
};
|
||||
}
|
||||
}),
|
||||
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),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* ProviderEventLoggers — single observability service that owns the two
|
||||
* shared NDJSON streams the provider runtime writes:
|
||||
* ProviderEventLoggers — single observability service that owns the shared
|
||||
* provider event log store and exposes its two runtime views:
|
||||
*
|
||||
* - `native` — provider-protocol events as the SDK emits them, written
|
||||
* from inside each `<X>Adapter` factory.
|
||||
@@ -13,17 +13,14 @@
|
||||
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
|
||||
* call site where we can hand an `EventNdjsonLogger` in by hand.
|
||||
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
|
||||
* should share one underlying log writer per stream — opening N writers
|
||||
* against the same rotating file would race the rotation logic. Owning
|
||||
* the loggers on a single tag keeps that invariant intact.
|
||||
* must share one underlying log store — opening N writers against the
|
||||
* same rotating file would race the rotation logic. Owning the loggers on
|
||||
* a single tag keeps that invariant intact.
|
||||
* - Tests can swap one (or both) loggers with in-memory recorders by
|
||||
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
|
||||
* juggling per-Layer option threading.
|
||||
*
|
||||
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
|
||||
* the target directory cannot be created; we forward that as `undefined`
|
||||
* rather than failing the boot Layer, matching the previous best-effort
|
||||
* behavior of `server.ts`.
|
||||
* Both fields are optional because observability must not prevent startup.
|
||||
*
|
||||
* @module provider/Layers/ProviderEventLoggers
|
||||
*/
|
||||
@@ -32,11 +29,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as EventNdjsonLogger from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderEventLoggersShape {
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger | undefined;
|
||||
readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,8 +42,8 @@ export interface ProviderEventLoggersShape {
|
||||
*
|
||||
* Service value is intentionally a struct of two optional loggers rather
|
||||
* than two parallel tags. Construction site is one place
|
||||
* (`ProviderEventLoggersLive`); consumers (drivers, `ProviderService`) read
|
||||
* one tag and pluck the field they need.
|
||||
* (`layer`); consumers (drivers, `ProviderService`) read one tag and pluck the
|
||||
* field they need.
|
||||
*/
|
||||
export class ProviderEventLoggers extends Context.Service<
|
||||
ProviderEventLoggers,
|
||||
@@ -63,23 +61,32 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
|
||||
* If the directory create fails for either stream, the corresponding field
|
||||
* is `undefined` and writes from that stream become no-ops downstream.
|
||||
* Builds both stream views over one shared store. Setup failures are logged
|
||||
* and downgraded to the no-op service so diagnostics never block startup.
|
||||
*/
|
||||
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;
|
||||
}),
|
||||
);
|
||||
export const make = Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
const store = yield* EventNdjsonLogger.makeEventNdjsonLogStore(providerEventLogPath, {
|
||||
attribution,
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(error.message, { error }).pipe(
|
||||
Effect.annotateLogs({ scope: "provider-observability" }),
|
||||
Effect.as<EventNdjsonLogger.EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (!store) {
|
||||
return ProviderEventLoggers.of(NoOpProviderEventLoggers);
|
||||
}
|
||||
|
||||
yield* Effect.addFinalizer(() => store.close());
|
||||
return ProviderEventLoggers.of({
|
||||
native: store.logger("native"),
|
||||
canonical: store.logger("canonical"),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderEventLoggers, make);
|
||||
@@ -34,10 +34,13 @@ import {
|
||||
type ProviderInstanceConfigMap,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
@@ -56,6 +59,37 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -108,6 +142,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
@@ -246,6 +281,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -32,6 +33,7 @@ import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
@@ -64,6 +66,7 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -72,6 +75,35 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -812,6 +844,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -909,6 +942,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
prefix: "t3-provider-registry-refresh-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -1016,6 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
prefix: "t3-provider-registry-sync-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -1120,6 +1155,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
// 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
|
||||
@@ -1219,6 +1255,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1334,6 +1371,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1394,6 +1432,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
|
||||
@@ -7,9 +7,6 @@ import * as NodeFS from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Option from "effect/Option";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
@@ -116,122 +113,6 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drops session updates emitted for a child ACP session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(
|
||||
notes
|
||||
.filter((note) => note._tag === "ContentDelta")
|
||||
.map((note) => note.text)
|
||||
.join(""),
|
||||
).toBe("root before child root after child");
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("supports successive standard ACP prompts", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptFiber = yield* runtime
|
||||
.prompt({
|
||||
prompt: [{ type: "text", text: "hang forever" }],
|
||||
})
|
||||
.pipe(Effect.forkChild({ startImmediately: true }));
|
||||
|
||||
yield* TestClock.adjust("500 millis");
|
||||
yield* runtime.cancel;
|
||||
|
||||
const firstPromptResult = yield* Fiber.join(promptFiber);
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
@@ -465,109 +346,6 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails session startup when session/load returns an error", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const error = yield* runtime.start().pipe(Effect.flip);
|
||||
|
||||
expect(error._tag).toBe("AcpRequestError");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_FAIL_LOAD_SESSION: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "stale-session-id",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores session/update replay notifications during session/load", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"PlanUpdated",
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_EMIT_LOAD_REPLAY: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
expect(started.sessionSetupResult._meta).toMatchObject({
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
});
|
||||
|
||||
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
|
||||
Effect.timeoutOption("100 millis"),
|
||||
);
|
||||
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
|
||||
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
resumeSessionId: "mock-session-1",
|
||||
sessionLoadReplayIdleGap: "50 millis",
|
||||
sessionLoadTimeout: "1 second",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
TestClock.withLive,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
|
||||
@@ -8,8 +8,6 @@ import {
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
describe("AcpRuntimeModel", () => {
|
||||
@@ -61,95 +59,6 @@ describe("AcpRuntimeModel", () => {
|
||||
expect(modelConfigId).toBe("model");
|
||||
});
|
||||
|
||||
it("detects Grok session replay updates from _meta.isReplay", () => {
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
_meta: { isReplay: true },
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replayed" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateIsReplay({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "live" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("builds a synthetic load response from initialize model state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.currentModelId).toBe("grok-build");
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("accepts initialize model descriptions with null", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models?.availableModels[0]?.description).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores malformed initialize model state in synthetic load responses", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modelState: {
|
||||
currentModelId: "grok-build",
|
||||
availableModels: [null],
|
||||
},
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [{ id: "code", name: 12 }],
|
||||
},
|
||||
},
|
||||
} as EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.models).toBeUndefined();
|
||||
expect(response.modes).toBeUndefined();
|
||||
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
|
||||
});
|
||||
|
||||
it("builds a synthetic load response with initialize mode state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
_meta: {
|
||||
modeState: {
|
||||
currentModeId: "code",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask" },
|
||||
{ id: "code", name: "Code" },
|
||||
],
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.InitializeResponse);
|
||||
|
||||
expect(response.modes?.currentModeId).toBe("code");
|
||||
expect(response.modes?.availableModes).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("projects typed ACP tool call updates into runtime events", () => {
|
||||
const created = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
@@ -11,40 +6,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
|
||||
if (!isRecord(value) || typeof value.currentModelId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModels)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModels.every(
|
||||
(model) =>
|
||||
isRecord(model) &&
|
||||
typeof model.modelId === "string" &&
|
||||
typeof model.name === "string" &&
|
||||
(model.description === undefined ||
|
||||
model.description === null ||
|
||||
typeof model.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
|
||||
if (!isRecord(value) || typeof value.currentModeId !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(value.availableModes)) {
|
||||
return false;
|
||||
}
|
||||
return value.availableModes.every(
|
||||
(mode) =>
|
||||
isRecord(mode) &&
|
||||
typeof mode.id === "string" &&
|
||||
typeof mode.name === "string" &&
|
||||
(mode.description === undefined || typeof mode.description === "string"),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpSessionMode {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
@@ -453,58 +414,6 @@ export function parsePermissionRequest(
|
||||
};
|
||||
}
|
||||
|
||||
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
|
||||
const meta = params._meta;
|
||||
return isRecord(meta) && meta.isReplay === true;
|
||||
}
|
||||
|
||||
export interface SessionLoadGate {
|
||||
readonly active: boolean;
|
||||
readonly lastActivityAtMillis: number | undefined;
|
||||
readonly idleGap: Duration.Duration;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
}
|
||||
|
||||
export const waitForSessionLoadReplayIdle = (input: {
|
||||
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
|
||||
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
|
||||
Effect.gen(function* () {
|
||||
const pollInterval = Duration.millis(25);
|
||||
while (true) {
|
||||
const gate = yield* Ref.get(input.gateRef);
|
||||
if (
|
||||
Option.isSome(gate) &&
|
||||
gate.value.active &&
|
||||
gate.value.lastActivityAtMillis !== undefined
|
||||
) {
|
||||
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
|
||||
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
|
||||
}
|
||||
}
|
||||
yield* Effect.sleep(pollInterval);
|
||||
}
|
||||
});
|
||||
|
||||
export function syntheticLoadSessionResponseFromInitialize(
|
||||
initializeResult: EffectAcpSchema.InitializeResponse,
|
||||
): EffectAcpSchema.LoadSessionResponse {
|
||||
const meta = initializeResult._meta;
|
||||
const modelState = isRecord(meta) ? meta.modelState : undefined;
|
||||
const modeState = isRecord(meta) ? meta.modeState : undefined;
|
||||
const models = isSessionModelState(modelState) ? modelState : undefined;
|
||||
const modes = isSessionModeState(modeState) ? modeState : undefined;
|
||||
|
||||
return {
|
||||
...(models ? { models } : {}),
|
||||
...(modes ? { modes } : {}),
|
||||
_meta: {
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
|
||||
readonly modeId?: string;
|
||||
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -27,9 +23,6 @@ import {
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
waitForSessionLoadReplayIdle,
|
||||
type SessionLoadGate,
|
||||
type AcpParsedSessionEvent,
|
||||
type AcpSessionModeState,
|
||||
type AcpToolCallState,
|
||||
@@ -39,16 +32,6 @@ function formatConfigOptionValue(value: string | boolean): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export interface AcpSessionEventStreamBarrier {
|
||||
readonly _tag: "EventStreamBarrier";
|
||||
readonly acknowledge: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
|
||||
|
||||
const defaultSessionLoadTimeout = Duration.seconds(90);
|
||||
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -60,8 +43,6 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly sessionLoadTimeout?: Duration.Input;
|
||||
readonly sessionLoadReplayIdleGap?: Duration.Input;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
@@ -179,9 +160,7 @@ export class AcpSessionRuntime extends Context.Service<
|
||||
*/
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
/** Stream of parsed ACP session events emitted after startup. */
|
||||
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
|
||||
/** Waits until the current event consumer has processed every queued event. */
|
||||
readonly drainEvents: Effect.Effect<void>;
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
/** Latest mode state observed from session setup and `session/update` notifications. */
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
/** Latest configuration options observed from session setup and configuration writes. */
|
||||
@@ -275,17 +254,12 @@ export const make = (
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
const promptSerializationSemaphore = yield* Semaphore.make(1);
|
||||
const activePromptFiberRef = yield* Ref.make<
|
||||
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
|
||||
>(Option.none());
|
||||
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
@@ -357,40 +331,15 @@ export const make = (
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
Effect.gen(function* () {
|
||||
const gate = yield* Ref.get(sessionLoadGateRef);
|
||||
if (Option.isSome(gate) && gate.value.active) {
|
||||
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
...gate.value,
|
||||
lastActivityAtMillis,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (sessionUpdateIsReplay(notification)) {
|
||||
return;
|
||||
}
|
||||
const startState = yield* Ref.get(startStateRef);
|
||||
// One runtime projects one root ACP session. Child-session updates need
|
||||
// explicit lineage routing and must never be flattened into this stream.
|
||||
if (
|
||||
startState._tag !== "Started" ||
|
||||
notification.sessionId !== startState.result.sessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
});
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
@@ -550,74 +499,27 @@ export const make = (
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const sessionLoadTimeout = Duration.fromInputUnsafe(
|
||||
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
|
||||
);
|
||||
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
|
||||
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
|
||||
);
|
||||
|
||||
yield* Ref.set(
|
||||
sessionLoadGateRef,
|
||||
Option.some({
|
||||
active: true,
|
||||
lastActivityAtMillis: undefined,
|
||||
idleGap: sessionLoadReplayIdleGap,
|
||||
initializeResult,
|
||||
}),
|
||||
);
|
||||
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = yield* Effect.gen(function* () {
|
||||
yield* logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "started",
|
||||
});
|
||||
|
||||
const idleFiber = yield* waitForSessionLoadReplayIdle({
|
||||
gateRef: sessionLoadGateRef,
|
||||
}).pipe(Effect.forkIn(runtimeScope));
|
||||
const loaded = yield* Effect.raceFirst(
|
||||
acp.agent.loadSession(loadPayload),
|
||||
Fiber.join(idleFiber),
|
||||
).pipe(
|
||||
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
|
||||
Effect.timeoutOption(sessionLoadTimeout),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
operation: "call-rpc",
|
||||
method: "session/load",
|
||||
detail: "session/load timed out waiting for RPC response or replay idle gap",
|
||||
cause: undefined,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method: "session/load",
|
||||
payload: loadPayload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
|
||||
return loaded;
|
||||
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
@@ -694,48 +596,25 @@ export const make = (
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
drainEvents: Effect.gen(function* () {
|
||||
const acknowledge = yield* Deferred.make<void>();
|
||||
yield* Queue.offer(eventQueue, {
|
||||
_tag: "EventStreamBarrier",
|
||||
acknowledge,
|
||||
});
|
||||
yield* Deferred.await(acknowledge);
|
||||
}),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
promptSerializationSemaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const started = yield* getStartedState;
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
const cancelledResponse = {
|
||||
stopReason: "cancelled",
|
||||
} satisfies EffectAcpSchema.PromptResponse;
|
||||
const promptRpcFiber = yield* runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
).pipe(Effect.forkIn(runtimeScope));
|
||||
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
|
||||
return yield* Fiber.join(promptRpcFiber).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.succeed(cancelledResponse)
|
||||
: Effect.failCause(cause),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.gen(function* () {
|
||||
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
|
||||
yield* Ref.set(activePromptFiberRef, Option.none());
|
||||
}),
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
@@ -747,17 +626,7 @@ export const make = (
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) =>
|
||||
Effect.gen(function* () {
|
||||
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
|
||||
if (Option.isSome(activePromptFiber)) {
|
||||
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
|
||||
}
|
||||
yield* acp.agent
|
||||
.cancel({ sessionId: started.sessionId })
|
||||
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
@@ -836,7 +705,7 @@ const handleSessionUpdate = ({
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
@@ -932,7 +801,7 @@ const ensureActiveAssistantSegment = ({
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
@@ -969,7 +838,7 @@ const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
|
||||
@@ -8,7 +8,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
|
||||
|
||||
const GROK_API_KEY_ENV = "XAI_API_KEY";
|
||||
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
|
||||
@@ -69,10 +68,9 @@ export const makeGrokAcpRuntime = (
|
||||
),
|
||||
),
|
||||
);
|
||||
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
|
||||
|
||||
@@ -1,39 +1,12 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.make({
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [mockAgentPath],
|
||||
env,
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
});
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
@@ -274,59 +247,4 @@ describe("XAiAcpExtension", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
const promptId = promptResult._meta?.promptId;
|
||||
|
||||
expect(typeof promptId).toBe("string");
|
||||
expect(promptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
sessionId: "mock-session-1",
|
||||
promptId,
|
||||
requestId: promptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale xAI completion from an already settled prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const firstPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "first" }],
|
||||
});
|
||||
expect(firstPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: { promptId: "mock-stale-xai-prompt-1" },
|
||||
});
|
||||
|
||||
const secondPromptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "second" }],
|
||||
});
|
||||
const secondPromptId = secondPromptResult._meta?.promptId;
|
||||
expect(typeof secondPromptId).toBe("string");
|
||||
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
|
||||
expect(secondPromptResult).toMatchObject({
|
||||
stopReason: "end_turn",
|
||||
_meta: {
|
||||
promptId: secondPromptId,
|
||||
requestId: secondPromptId,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,29 +1,5 @@
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const XAiPromptCompleteNotification = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
promptId: Schema.optional(Schema.String),
|
||||
stopReason: Schema.optional(Schema.String),
|
||||
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
});
|
||||
|
||||
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
|
||||
|
||||
interface PendingXAiPromptCompletion {
|
||||
readonly sessionId: string;
|
||||
readonly promptId: string;
|
||||
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
|
||||
}
|
||||
|
||||
const completedXAiPromptIdLimit = 128;
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
@@ -195,238 +171,3 @@ export function makeXAiAskUserQuestionResponse(
|
||||
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
|
||||
return { outcome: "cancelled" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
|
||||
* The underlying runtime remains unaware of xAI methods and metadata.
|
||||
*/
|
||||
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
|
||||
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
|
||||
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
|
||||
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
|
||||
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
let nextPromptFallbackId = 0;
|
||||
const allocatePromptFallbackId = Effect.sync(() => {
|
||||
nextPromptFallbackId += 1;
|
||||
return `t3-xai-prompt-${nextPromptFallbackId}`;
|
||||
});
|
||||
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/session/prompt_complete",
|
||||
XAiPromptCompleteNotification,
|
||||
(notification) =>
|
||||
resolveXAiPromptCompletionFallback({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
...runtime,
|
||||
start: () =>
|
||||
runtime
|
||||
.start()
|
||||
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
|
||||
prompt: (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = yield* Ref.get(activeSessionIdRef);
|
||||
if (sessionId === undefined) {
|
||||
return yield* runtime.prompt(payload);
|
||||
}
|
||||
|
||||
const promptId = yield* allocatePromptFallbackId;
|
||||
const fallback = yield* registerXAiPromptCompletionFallback(
|
||||
pendingRef,
|
||||
sessionId,
|
||||
promptId,
|
||||
);
|
||||
const requestPayload = {
|
||||
...payload,
|
||||
_meta: {
|
||||
...payload._meta,
|
||||
promptId: fallback.promptId,
|
||||
requestId: fallback.promptId,
|
||||
},
|
||||
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
|
||||
|
||||
return yield* Effect.raceFirst(
|
||||
runtime.prompt(requestPayload),
|
||||
Deferred.await(fallback.deferred),
|
||||
).pipe(
|
||||
Effect.tap((response) =>
|
||||
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
|
||||
),
|
||||
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
|
||||
);
|
||||
}),
|
||||
cancel: Ref.get(activeSessionIdRef).pipe(
|
||||
Effect.flatMap((sessionId) =>
|
||||
sessionId === undefined
|
||||
? runtime.cancel
|
||||
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
|
||||
Effect.andThen(runtime.cancel),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
},
|
||||
);
|
||||
|
||||
const registerXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
promptId: string,
|
||||
) =>
|
||||
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
|
||||
Effect.tap((deferred) =>
|
||||
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
|
||||
),
|
||||
Effect.map((deferred) => ({ deferred, promptId })),
|
||||
);
|
||||
|
||||
const unregisterXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
|
||||
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
|
||||
|
||||
const abortPendingPromptCompletions = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
sessionId: string,
|
||||
) =>
|
||||
Ref.modify(pendingRef, (pending) => {
|
||||
const [toAbort, remaining] = pending.reduce<
|
||||
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
|
||||
>(
|
||||
([aborting, kept], entry) =>
|
||||
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
|
||||
[[], []],
|
||||
);
|
||||
if (toAbort.length === 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Effect.forEach(
|
||||
toAbort,
|
||||
(entry) =>
|
||||
Deferred.succeed(
|
||||
entry.deferred,
|
||||
promptResponseFromXAi({
|
||||
sessionId: entry.sessionId,
|
||||
promptId: entry.promptId,
|
||||
stopReason: "cancelled",
|
||||
agentResult: null,
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.asVoid),
|
||||
remaining,
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
|
||||
const resolveXAiPromptCompletionFallback = ({
|
||||
pendingRef,
|
||||
completedPromptIdsRef,
|
||||
notification,
|
||||
}: {
|
||||
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
|
||||
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
|
||||
readonly notification: XAiPromptCompleteNotification;
|
||||
}) =>
|
||||
Ref.get(completedPromptIdsRef).pipe(
|
||||
Effect.flatMap((completedPromptIds) => {
|
||||
if (
|
||||
notification.promptId !== undefined &&
|
||||
completedPromptIds.includes(notification.promptId)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.modify(pendingRef, (pending) => {
|
||||
const index =
|
||||
notification.promptId !== undefined
|
||||
? pending.findIndex(
|
||||
(entry) =>
|
||||
entry.sessionId === notification.sessionId &&
|
||||
entry.promptId === notification.promptId,
|
||||
)
|
||||
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
|
||||
if (index < 0) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
const entry = pending[index];
|
||||
if (!entry) {
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
|
||||
[...pending.slice(0, index), ...pending.slice(index + 1)],
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
}),
|
||||
);
|
||||
|
||||
const rememberCompletedXAiPromptId = (
|
||||
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
fallbackPromptId: string,
|
||||
) => {
|
||||
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
|
||||
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
|
||||
if (completedPromptIds.includes(promptId)) {
|
||||
return completedPromptIds;
|
||||
}
|
||||
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
|
||||
});
|
||||
};
|
||||
|
||||
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
|
||||
const meta = response._meta;
|
||||
if (meta === null || typeof meta !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const promptId = meta.promptId ?? meta.requestId;
|
||||
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
|
||||
}
|
||||
|
||||
export function promptResponseHasMissingXAiStopReason(
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
): boolean {
|
||||
const meta = response._meta;
|
||||
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
|
||||
}
|
||||
|
||||
function promptResponseFromXAi(
|
||||
notification: XAiPromptCompleteNotification,
|
||||
): EffectAcpSchema.PromptResponse {
|
||||
const stopReason = normalizeXAiStopReason(notification.stopReason);
|
||||
const meta: Record<string, unknown> = {
|
||||
sessionId: notification.sessionId,
|
||||
};
|
||||
if (notification.stopReason === undefined) {
|
||||
meta[xAiStopReasonMissingMetaKey] = true;
|
||||
}
|
||||
if (notification.promptId !== undefined) {
|
||||
meta.promptId = notification.promptId;
|
||||
meta.requestId = notification.promptId;
|
||||
}
|
||||
if (notification.agentResult !== undefined) {
|
||||
meta.agentResult = notification.agentResult;
|
||||
}
|
||||
return {
|
||||
stopReason,
|
||||
_meta: meta,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
|
||||
switch (value) {
|
||||
case "cancelled":
|
||||
case "end_turn":
|
||||
case "max_tokens":
|
||||
case "max_turn_requests":
|
||||
case "refusal":
|
||||
return value;
|
||||
default:
|
||||
return "end_turn";
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,22 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
const fastModeCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
@@ -87,6 +93,43 @@ const refreshedSnapshotSecond: ServerProvider = {
|
||||
message: "Refreshed provider availability again.",
|
||||
};
|
||||
|
||||
function makeBackgroundPolicyLayer(shouldRunScopeWork: boolean) {
|
||||
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunScopeWork: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunOpportunisticWork: Effect.succeed(shouldRunScopeWork),
|
||||
});
|
||||
}
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = makeBackgroundPolicyLayer(true);
|
||||
const BackgroundPolicyNeverRunLayer = makeBackgroundPolicyLayer(false);
|
||||
const ServerSettingsTestLayer = ServerSettingsService.layerTest();
|
||||
const AlwaysRunTestLayer = Layer.merge(BackgroundPolicyAlwaysRunLayer, ServerSettingsTestLayer);
|
||||
const NeverRunTestLayer = Layer.merge(BackgroundPolicyNeverRunLayer, ServerSettingsTestLayer);
|
||||
|
||||
const enrichedSnapshotSecond: ServerProvider = {
|
||||
...refreshedSnapshotSecond,
|
||||
checkedAt: "2026-04-10T00:00:04.000Z",
|
||||
@@ -140,7 +183,38 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshot);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips periodic provider refreshes without foreground provider-status demand", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => Effect.succeed(initialSnapshot),
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.tap((count) =>
|
||||
count === 1
|
||||
? Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: "1 second",
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(NeverRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("reruns the provider check when streamed settings change", () =>
|
||||
@@ -185,7 +259,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
|
||||
@@ -223,7 +297,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshot);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
|
||||
@@ -284,6 +358,6 @@ describe("makeManagedServerProvider", () => {
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
type ServerProvider,
|
||||
ServerSettingsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -9,8 +14,9 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
interface ProviderSnapshotState {
|
||||
readonly snapshot: ServerProvider;
|
||||
@@ -33,7 +39,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
}): Effect.fn.Return<
|
||||
ServerProviderShape,
|
||||
ServerSettingsError,
|
||||
Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
|
||||
> {
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
@@ -134,13 +146,45 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
|
||||
const hasProviderStatusDemand = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(snapshotStateRef);
|
||||
const instanceId = state.snapshot.instanceId;
|
||||
const [genericDemand, instanceDemand] = yield* Effect.all([
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
|
||||
]);
|
||||
return genericDemand || instanceDemand;
|
||||
});
|
||||
|
||||
const getRefreshInterval = input.refreshInterval
|
||||
? Effect.succeed(input.refreshInterval)
|
||||
: serverSettings.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) =>
|
||||
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
|
||||
),
|
||||
Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot()),
|
||||
getRefreshInterval.pipe(
|
||||
Effect.flatMap((refreshInterval) =>
|
||||
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
|
||||
? Effect.sleep("60 seconds")
|
||||
: Effect.sleep(refreshInterval).pipe(
|
||||
Effect.flatMap(() =>
|
||||
hasProviderStatusDemand.pipe(
|
||||
Effect.flatMap((shouldRefresh) =>
|
||||
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
|
||||
import * as NodeStream from "@effect/platform-node/NodeStream";
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
DesktopTelemetryControlMessage,
|
||||
type ResourceTelemetrySourceStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 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 Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
const STALE_AFTER_MS = 90_000;
|
||||
const STALE_CHECK_INTERVAL = Duration.seconds(30);
|
||||
|
||||
export class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedErrorClass<DesktopTelemetryDescriptorUnavailable>()(
|
||||
"DesktopTelemetryDescriptorUnavailable",
|
||||
{
|
||||
mode: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryProtocolMismatch extends Schema.TaggedErrorClass<DesktopTelemetryProtocolMismatch>()(
|
||||
"DesktopTelemetryProtocolMismatch",
|
||||
{
|
||||
expectedVersion: Schema.Number,
|
||||
receivedVersion: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryDecodeFailed extends Schema.TaggedErrorClass<DesktopTelemetryDecodeFailed>()(
|
||||
"DesktopTelemetryDecodeFailed",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to decode desktop telemetry.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryStreamFailed extends Schema.TaggedErrorClass<DesktopTelemetryStreamFailed>()(
|
||||
"DesktopTelemetryStreamFailed",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry stream on fd ${this.fd} failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryStreamClosed extends Schema.TaggedErrorClass<DesktopTelemetryStreamClosed>()(
|
||||
"DesktopTelemetryStreamClosed",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry stream on fd ${this.fd} closed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopTelemetryStale extends Schema.TaggedErrorClass<DesktopTelemetryStale>()(
|
||||
"DesktopTelemetryStale",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
staleAfterMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopTelemetryReceiverError =
|
||||
| DesktopTelemetryDescriptorUnavailable
|
||||
| DesktopTelemetryProtocolMismatch
|
||||
| DesktopTelemetryDecodeFailed
|
||||
| DesktopTelemetryStreamFailed
|
||||
| DesktopTelemetryStreamClosed;
|
||||
|
||||
export class DesktopTelemetryControlFailed extends Schema.TaggedErrorClass<DesktopTelemetryControlFailed>()(
|
||||
"DesktopTelemetryControlFailed",
|
||||
{
|
||||
fd: Schema.Number,
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryReceiverHealth {
|
||||
readonly status: ResourceTelemetrySourceStatus;
|
||||
readonly lastSampleAt: Option.Option<DateTime.Utc>;
|
||||
readonly lastError: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryReceiverShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;
|
||||
readonly healthChanges: Stream.Stream<DesktopTelemetryReceiverHealth>;
|
||||
readonly setDiagnosticsDemand: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<void, DesktopTelemetryControlFailed>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryReceiver extends Context.Service<
|
||||
DesktopTelemetryReceiver,
|
||||
DesktopTelemetryReceiverShape
|
||||
>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
|
||||
|
||||
const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
|
||||
const encodeControlMessage = Schema.encodeEffect(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
const isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);
|
||||
const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);
|
||||
const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);
|
||||
const isStreamFailed = Schema.is(DesktopTelemetryStreamFailed);
|
||||
|
||||
function normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError {
|
||||
if (
|
||||
isDescriptorUnavailable(error) ||
|
||||
isProtocolMismatch(error) ||
|
||||
isDecodeFailed(error) ||
|
||||
isStreamFailed(error)
|
||||
) {
|
||||
return error;
|
||||
}
|
||||
return new DesktopTelemetryDecodeFailed({ cause: error });
|
||||
}
|
||||
|
||||
function messageVersion(value: unknown): number | undefined {
|
||||
if (typeof value !== "object" || value === null) return undefined;
|
||||
const version = Reflect.get(value, "version");
|
||||
return typeof version === "number" ? version : undefined;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
|
||||
const controlMutex = yield* Semaphore.make(1);
|
||||
const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
|
||||
status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError:
|
||||
config.desktopTelemetryFd === undefined
|
||||
? Option.some(
|
||||
new DesktopTelemetryDescriptorUnavailable({
|
||||
mode: config.mode,
|
||||
}).message,
|
||||
)
|
||||
: Option.none(),
|
||||
});
|
||||
const updateHealth = (
|
||||
update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,
|
||||
) =>
|
||||
Ref.modify(health, (current) => {
|
||||
const next = update(current);
|
||||
return [next, next];
|
||||
}).pipe(
|
||||
Effect.flatMap((next) => PubSub.publish(healthChanges, next)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
const updateSampleHealth = (sampledAt: DateTime.Utc) =>
|
||||
Ref.modify(health, (current) => {
|
||||
const next: DesktopTelemetryReceiverHealth = {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(sampledAt),
|
||||
lastError: Option.none(),
|
||||
};
|
||||
return [
|
||||
current.status !== "healthy" || Option.isSome(current.lastError)
|
||||
? Option.some(next)
|
||||
: Option.none(),
|
||||
next,
|
||||
] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.void,
|
||||
onSome: (next) => PubSub.publish(healthChanges, next),
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const setDiagnosticsDemand: DesktopTelemetryReceiverShape["setDiagnosticsDemand"] = (enabled) =>
|
||||
controlMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const fd = config.desktopTelemetryControlFd;
|
||||
if (fd === undefined) return;
|
||||
const encoded = yield* encodeControlMessage({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopTelemetryControlFailed({
|
||||
fd,
|
||||
operation: "encode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
const payload = Buffer.from(`${encoded}\n`);
|
||||
let offset = 0;
|
||||
while (offset < payload.byteLength) {
|
||||
const written = NodeFS.writeSync(fd, payload, offset);
|
||||
if (written <= 0) throw new Error("desktop telemetry control pipe accepted no bytes");
|
||||
offset += written;
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new DesktopTelemetryControlFailed({
|
||||
fd,
|
||||
operation: "write",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.tapError((error) =>
|
||||
updateHealth((current) => ({
|
||||
...current,
|
||||
status: "degraded",
|
||||
lastError: Option.some(error.message),
|
||||
})),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
if (config.desktopTelemetryFd !== undefined) {
|
||||
const fd = config.desktopTelemetryFd;
|
||||
const readable = yield* Effect.acquireRelease(
|
||||
Effect.try({
|
||||
try: () =>
|
||||
NodeFS.createReadStream("", {
|
||||
fd,
|
||||
autoClose: true,
|
||||
}),
|
||||
catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
|
||||
}),
|
||||
(stream) =>
|
||||
Effect.sync(() => {
|
||||
stream.destroy();
|
||||
}),
|
||||
);
|
||||
|
||||
const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =
|
||||
NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({
|
||||
evaluate: () => readable,
|
||||
closeOnDone: true,
|
||||
onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
|
||||
}).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect(
|
||||
(
|
||||
value,
|
||||
): Effect.Effect<
|
||||
DesktopHostTelemetryMessageValue,
|
||||
DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed
|
||||
> => {
|
||||
const version = messageVersion(value);
|
||||
if (version !== undefined && version !== 1) {
|
||||
return Effect.fail(
|
||||
new DesktopTelemetryProtocolMismatch({
|
||||
expectedVersion: 1,
|
||||
receivedVersion: version,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return decodeMessage(value).pipe(
|
||||
Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),
|
||||
);
|
||||
},
|
||||
),
|
||||
Stream.mapError(normalizeReceiverError),
|
||||
);
|
||||
|
||||
yield* messages.pipe(
|
||||
Stream.runForEach((message) => {
|
||||
if (message.type === "desktopTelemetryHello") {
|
||||
return updateHealth(
|
||||
(current): DesktopTelemetryReceiverHealth => ({
|
||||
...current,
|
||||
status: "healthy",
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
|
||||
return Ref.set(latest, Option.some(message)).pipe(
|
||||
Effect.andThen(updateSampleHealth(sampledAt)),
|
||||
Effect.andThen(PubSub.publish(changes, message)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
}),
|
||||
Effect.andThen(
|
||||
updateHealth(
|
||||
(current): DesktopTelemetryReceiverHealth => ({
|
||||
...current,
|
||||
status: "stopped",
|
||||
lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
updateHealth(
|
||||
(current): DesktopTelemetryReceiverHealth => ({
|
||||
...current,
|
||||
status: "degraded",
|
||||
lastError: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(STALE_CHECK_INTERVAL).pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(latest);
|
||||
if (Option.isNone(current) || current.value.power.stale) return;
|
||||
const now = yield* DateTime.now;
|
||||
if (DateTime.toEpochMillis(now) - current.value.sampledAtUnixMs < STALE_AFTER_MS)
|
||||
return;
|
||||
const staleSnapshot: DesktopHostTelemetrySnapshot = {
|
||||
...current.value,
|
||||
power: { ...current.value.power, stale: true },
|
||||
};
|
||||
yield* Ref.set(latest, Option.some(staleSnapshot));
|
||||
yield* updateHealth((currentHealth) => ({
|
||||
...currentHealth,
|
||||
status: currentHealth.status === "stopped" ? "stopped" : "degraded",
|
||||
lastError:
|
||||
currentHealth.status === "stopped"
|
||||
? currentHealth.lastError
|
||||
: Option.some(
|
||||
new DesktopTelemetryStale({ fd, staleAfterMs: STALE_AFTER_MS }).message,
|
||||
),
|
||||
}));
|
||||
yield* PubSub.publish(changes, staleSnapshot);
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
|
||||
return DesktopTelemetryReceiver.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
health: Ref.get(health),
|
||||
healthChanges: Stream.fromPubSub(healthChanges),
|
||||
setDiagnosticsDemand,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryReceiver, make());
|
||||
|
||||
export const layerTest = (
|
||||
overrides: Partial<DesktopTelemetryReceiverShape> = {},
|
||||
): Layer.Layer<DesktopTelemetryReceiver> =>
|
||||
Layer.succeed(
|
||||
DesktopTelemetryReceiver,
|
||||
DesktopTelemetryReceiver.of({
|
||||
latest: Effect.succeedNone,
|
||||
changes: Stream.empty,
|
||||
health: Effect.succeed({
|
||||
status: "unavailable",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.some("Desktop telemetry test implementation is unavailable."),
|
||||
}),
|
||||
healthChanges: Stream.empty,
|
||||
setDiagnosticsDemand: () => Effect.void,
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,433 @@
|
||||
import {
|
||||
type DesktopElectronProcessMetric,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type ResourceMonitorProcessSample,
|
||||
type ResourceMonitorSnapshotEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { emptyTelemetryCounters, mergeProcesses, type MergeProcessesResult } from "./Model.ts";
|
||||
|
||||
const SERVER_PID = 100;
|
||||
const BASE_TIME_MS = DateTime.toEpochMillis(DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"));
|
||||
|
||||
function processSample(
|
||||
input: Partial<ResourceMonitorProcessSample> &
|
||||
Pick<ResourceMonitorProcessSample, "pid" | "ppid" | "startTimeMs">,
|
||||
): ResourceMonitorProcessSample {
|
||||
return {
|
||||
runTimeMs: 1_000,
|
||||
name: `process-${input.pid}`,
|
||||
command: `process-${input.pid}`,
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
cpuTimeMs: 0,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
ioSemantics: "storage",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function nativeSnapshot(
|
||||
sampledAtUnixMs: number,
|
||||
processes: ReadonlyArray<ResourceMonitorProcessSample>,
|
||||
sequence = 1,
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence,
|
||||
sampledAtUnixMs,
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes: [...processes],
|
||||
};
|
||||
}
|
||||
|
||||
function electronMetric(
|
||||
input: Partial<DesktopElectronProcessMetric> &
|
||||
Pick<DesktopElectronProcessMetric, "pid" | "creationTimeMs" | "type">,
|
||||
): DesktopElectronProcessMetric {
|
||||
return {
|
||||
cpuPercent: 0,
|
||||
idleWakeupsPerSecond: 0,
|
||||
workingSetBytes: 1_024,
|
||||
peakWorkingSetBytes: 2_048,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function desktopSnapshot(
|
||||
sampledAtUnixMs: number,
|
||||
electronProcesses: ReadonlyArray<DesktopElectronProcessMetric>,
|
||||
): DesktopHostTelemetrySnapshot {
|
||||
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
|
||||
return {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: electronProcesses[0]?.pid ?? 10_000,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [...electronProcesses],
|
||||
};
|
||||
}
|
||||
|
||||
function merge(input: {
|
||||
readonly native: ResourceMonitorSnapshotEvent;
|
||||
readonly desktop?: DesktopHostTelemetrySnapshot;
|
||||
readonly previous?: MergeProcessesResult;
|
||||
readonly sidecarPid?: number;
|
||||
}): MergeProcessesResult {
|
||||
return mergeProcesses({
|
||||
serverPid: SERVER_PID,
|
||||
sidecarPid: Option.fromUndefinedOr(input.sidecarPid),
|
||||
fallbackSampledAtMs: input.native.sampledAtUnixMs,
|
||||
nativeSnapshot: Option.some(input.native),
|
||||
desktopSnapshot: Option.fromUndefinedOr(input.desktop),
|
||||
previous: input.previous?.previous ?? new Map(),
|
||||
counters: input.previous?.counters ?? emptyTelemetryCounters(),
|
||||
updatePrevious: true,
|
||||
});
|
||||
}
|
||||
|
||||
describe("resource telemetry process model", () => {
|
||||
it("builds complete descendant depths and isolates monitor overhead", () => {
|
||||
const result = merge({
|
||||
sidecarPid: 900,
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 1_000 }),
|
||||
processSample({ pid: 200, ppid: SERVER_PID, startTimeMs: 2_000 }),
|
||||
processSample({ pid: 201, ppid: 200, startTimeMs: 3_000 }),
|
||||
processSample({ pid: 202, ppid: 201, startTimeMs: 4_000 }),
|
||||
processSample({ pid: 900, ppid: SERVER_PID, startTimeMs: 5_000 }),
|
||||
]),
|
||||
});
|
||||
|
||||
expect(result.processes.map((process) => [process.identity.pid, process.depth])).toEqual([
|
||||
[100, 0],
|
||||
[200, 1],
|
||||
[201, 2],
|
||||
[202, 3],
|
||||
[900, 1],
|
||||
]);
|
||||
expect(result.processes.find((process) => process.identity.pid === 900)?.category).toBe(
|
||||
"resource-monitor",
|
||||
);
|
||||
expect(result.groups.backend.processCount).toBe(4);
|
||||
expect(result.groups.monitor.processCount).toBe(1);
|
||||
expect(result.groups.monitor.processStarts).toBe(1);
|
||||
expect(result.groups.allT3.processStarts).toBe(5);
|
||||
});
|
||||
|
||||
it("deduplicates Electron metrics and classifies Electron descendants", () => {
|
||||
const electronStart = 10_000;
|
||||
const result = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 1_000 }),
|
||||
processSample({ pid: 300, ppid: 1, startTimeMs: electronStart }),
|
||||
processSample({ pid: 301, ppid: 300, startTimeMs: electronStart + 1 }),
|
||||
]),
|
||||
desktop: desktopSnapshot(BASE_TIME_MS, [
|
||||
electronMetric({
|
||||
pid: 300,
|
||||
creationTimeMs: electronStart + 500,
|
||||
type: "Browser",
|
||||
name: "electron",
|
||||
}),
|
||||
electronMetric({
|
||||
pid: 301,
|
||||
creationTimeMs: electronStart + 500,
|
||||
type: "Utility",
|
||||
name: "network-service",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
expect(result.processes.filter((process) => process.identity.pid === 300)).toHaveLength(1);
|
||||
expect(result.processes.find((process) => process.identity.pid === 300)?.category).toBe(
|
||||
"electron-main",
|
||||
);
|
||||
expect(result.processes.find((process) => process.identity.pid === 301)?.category).toBe(
|
||||
"electron-utility",
|
||||
);
|
||||
expect(result.processes.find((process) => process.identity.pid === 301)?.depth).toBe(1);
|
||||
expect(result.groups.electron.processCount).toBe(2);
|
||||
});
|
||||
|
||||
it("ignores stale Electron metrics after PID reuse", () => {
|
||||
const result = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 1_000 }),
|
||||
processSample({ pid: 300, ppid: SERVER_PID, startTimeMs: 50_000 }),
|
||||
]),
|
||||
desktop: desktopSnapshot(BASE_TIME_MS, [
|
||||
electronMetric({
|
||||
pid: 300,
|
||||
creationTimeMs: 10_000,
|
||||
type: "Browser",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
expect(result.processes.find((process) => process.identity.pid === 300)?.category).toBe(
|
||||
"server-child",
|
||||
);
|
||||
expect(result.groups.electron.processCount).toBe(0);
|
||||
});
|
||||
|
||||
it("derives rates from cumulative counters and preserves I/O semantics", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_000,
|
||||
ioReadBytes: 10_000,
|
||||
ioWriteBytes: 20_000,
|
||||
ioSemantics: "all-io",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const second = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 1_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_250,
|
||||
ioReadBytes: 12_000,
|
||||
ioWriteBytes: 23_000,
|
||||
ioSemantics: "all-io",
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
const server = second.processes[0]!;
|
||||
|
||||
expect(server.cpuPercent).toBe(25);
|
||||
expect(server.ioReadBytesPerSecond).toBe(2_000);
|
||||
expect(server.ioWriteBytesPerSecond).toBe(3_000);
|
||||
expect(server.ioSemantics).toBe("all-io");
|
||||
expect(second.groups.backend.cpuTimeMs).toBe(250);
|
||||
expect(second.groups.backend.ioReadBytes).toBe(2_000);
|
||||
expect(second.groups.backend.ioWriteBytes).toBe(3_000);
|
||||
});
|
||||
|
||||
it("derives deltas at the constrained 15-second sampling cadence", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_000,
|
||||
ioReadBytes: 10_000,
|
||||
ioWriteBytes: 20_000,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const second = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 15_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 2_500,
|
||||
ioReadBytes: 25_000,
|
||||
ioWriteBytes: 50_000,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
|
||||
expect(second.processes[0]?.cpuPercent).toBe(10);
|
||||
expect(second.processes[0]?.ioReadBytesPerSecond).toBe(1_000);
|
||||
expect(second.processes[0]?.ioWriteBytesPerSecond).toBe(2_000);
|
||||
expect(second.groups.backend.cpuTimeMs).toBe(1_500);
|
||||
expect(second.groups.backend.ioReadBytes).toBe(15_000);
|
||||
expect(second.groups.backend.ioWriteBytes).toBe(30_000);
|
||||
});
|
||||
|
||||
it("preserves native rates while applying a desktop-only update", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_000,
|
||||
ioReadBytes: 10_000,
|
||||
ioWriteBytes: 20_000,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const second = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 1_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_250,
|
||||
ioReadBytes: 12_000,
|
||||
ioWriteBytes: 23_000,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
const desktopOnly = mergeProcesses({
|
||||
serverPid: SERVER_PID,
|
||||
sidecarPid: Option.none(),
|
||||
fallbackSampledAtMs: BASE_TIME_MS + 1_000,
|
||||
nativeSnapshot: Option.some(
|
||||
nativeSnapshot(
|
||||
BASE_TIME_MS + 1_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_250,
|
||||
ioReadBytes: 12_000,
|
||||
ioWriteBytes: 23_000,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
),
|
||||
desktopSnapshot: Option.some(desktopSnapshot(BASE_TIME_MS + 1_500, [])),
|
||||
previous: second.previous,
|
||||
counters: second.counters,
|
||||
updatePrevious: false,
|
||||
});
|
||||
|
||||
expect(desktopOnly.processes[0]?.cpuPercent).toBe(25);
|
||||
expect(desktopOnly.processes[0]?.ioReadBytesPerSecond).toBe(2_000);
|
||||
expect(desktopOnly.processes[0]?.ioWriteBytesPerSecond).toBe(3_000);
|
||||
});
|
||||
|
||||
it("resets deltas when counters decrease or the sampling gap is unsafe", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 1_000,
|
||||
ioReadBytes: 10_000,
|
||||
ioWriteBytes: 20_000,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
const decreased = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 1_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 100,
|
||||
ioReadBytes: 100,
|
||||
ioWriteBytes: 200,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
const delayed = merge({
|
||||
previous: decreased,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 90_000,
|
||||
[
|
||||
processSample({
|
||||
pid: SERVER_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 1_000,
|
||||
cpuTimeMs: 10_000,
|
||||
ioReadBytes: 100_000,
|
||||
ioWriteBytes: 200_000,
|
||||
}),
|
||||
],
|
||||
3,
|
||||
),
|
||||
});
|
||||
|
||||
expect(decreased.processes[0]?.cpuPercent).toBe(0);
|
||||
expect(decreased.processes[0]?.ioReadBytesPerSecond).toBe(0);
|
||||
expect(decreased.processes[0]?.ioWriteBytesPerSecond).toBe(0);
|
||||
expect(delayed.processes[0]?.cpuPercent).toBe(0);
|
||||
expect(delayed.processes[0]?.ioReadBytesPerSecond).toBe(0);
|
||||
expect(delayed.processes[0]?.ioWriteBytesPerSecond).toBe(0);
|
||||
expect(delayed.groups.backend.cpuTimeMs).toBe(0);
|
||||
expect(delayed.groups.backend.ioReadBytes).toBe(0);
|
||||
expect(delayed.groups.backend.ioWriteBytes).toBe(0);
|
||||
});
|
||||
|
||||
it("treats reused PIDs as an exit plus a new process", () => {
|
||||
const first = merge({
|
||||
native: nativeSnapshot(BASE_TIME_MS, [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 1_000 }),
|
||||
processSample({ pid: 200, ppid: SERVER_PID, startTimeMs: 2_000 }),
|
||||
]),
|
||||
});
|
||||
const second = merge({
|
||||
previous: first,
|
||||
native: nativeSnapshot(
|
||||
BASE_TIME_MS + 1_000,
|
||||
[
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 1_000 }),
|
||||
processSample({
|
||||
pid: 200,
|
||||
ppid: SERVER_PID,
|
||||
startTimeMs: 9_000,
|
||||
cpuTimeMs: 999,
|
||||
ioReadBytes: 999,
|
||||
ioWriteBytes: 999,
|
||||
}),
|
||||
],
|
||||
2,
|
||||
),
|
||||
});
|
||||
const reused = second.processes.find((process) => process.identity.pid === 200)!;
|
||||
|
||||
expect(reused.identity.startTimeMs).toBe(9_000);
|
||||
expect(reused.cpuPercent).toBe(0);
|
||||
expect(reused.ioReadBytesPerSecond).toBe(0);
|
||||
expect(second.groups.backend.processStarts).toBe(3);
|
||||
expect(second.groups.backend.processExits).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,559 @@
|
||||
import type {
|
||||
DesktopElectronProcessMetric,
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorProcessSample,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryAggregate,
|
||||
ResourceTelemetryProcess,
|
||||
ResourceTelemetryProcessCategory,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const MAX_DELTA_INTERVAL_MS = 30_000;
|
||||
const ELECTRON_IDENTITY_TOLERANCE_MS = 2_000;
|
||||
|
||||
export interface ProcessState {
|
||||
readonly process: ResourceTelemetryProcess;
|
||||
readonly sampledAtMs: number;
|
||||
}
|
||||
|
||||
export interface GroupCounters {
|
||||
readonly cpuTimeMs: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
readonly processStarts: number;
|
||||
readonly processExits: number;
|
||||
}
|
||||
|
||||
export interface TelemetryCounters {
|
||||
readonly backend: GroupCounters;
|
||||
readonly electron: GroupCounters;
|
||||
readonly monitor: GroupCounters;
|
||||
readonly allT3: GroupCounters;
|
||||
}
|
||||
|
||||
export interface ProcessDelta {
|
||||
readonly identityKey: string;
|
||||
readonly category: ResourceTelemetryProcessCategory;
|
||||
readonly cpuTimeMs: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
export interface MergeProcessesInput {
|
||||
readonly serverPid: number;
|
||||
readonly sidecarPid: Option.Option<number>;
|
||||
readonly fallbackSampledAtMs: number;
|
||||
readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
|
||||
readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
|
||||
readonly electronRootPids?: ReadonlySet<number>;
|
||||
readonly previous: ReadonlyMap<string, ProcessState>;
|
||||
readonly counters: TelemetryCounters;
|
||||
readonly updatePrevious: boolean;
|
||||
}
|
||||
|
||||
export interface MergeProcessesResult {
|
||||
readonly sampledAtMs: number;
|
||||
readonly processes: ReadonlyArray<ResourceTelemetryProcess>;
|
||||
readonly previous: ReadonlyMap<string, ProcessState>;
|
||||
readonly counters: TelemetryCounters;
|
||||
readonly groups: {
|
||||
readonly backend: ResourceTelemetryAggregate;
|
||||
readonly electron: ResourceTelemetryAggregate;
|
||||
readonly monitor: ResourceTelemetryAggregate;
|
||||
readonly allT3: ResourceTelemetryAggregate;
|
||||
};
|
||||
readonly deltas: ReadonlyArray<ProcessDelta>;
|
||||
}
|
||||
|
||||
export const emptyGroupCounters = (): GroupCounters => ({
|
||||
cpuTimeMs: 0,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
processStarts: 0,
|
||||
processExits: 0,
|
||||
});
|
||||
|
||||
export const emptyTelemetryCounters = (): TelemetryCounters => ({
|
||||
backend: emptyGroupCounters(),
|
||||
electron: emptyGroupCounters(),
|
||||
monitor: emptyGroupCounters(),
|
||||
allT3: emptyGroupCounters(),
|
||||
});
|
||||
|
||||
export function processIdentityKey(pid: number, startTimeMs: number): string {
|
||||
return `${pid}:${startTimeMs}`;
|
||||
}
|
||||
|
||||
function finiteNonNegative(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(0, value) : 0;
|
||||
}
|
||||
|
||||
function categoryGroup(
|
||||
category: ResourceTelemetryProcessCategory,
|
||||
): "backend" | "electron" | "monitor" {
|
||||
if (category === "resource-monitor") return "monitor";
|
||||
if (category.startsWith("electron-")) return "electron";
|
||||
return "backend";
|
||||
}
|
||||
|
||||
function electronCategory(metric: DesktopElectronProcessMetric): ResourceTelemetryProcessCategory {
|
||||
switch (metric.type) {
|
||||
case "Browser":
|
||||
return "electron-main";
|
||||
case "Tab":
|
||||
return "electron-renderer";
|
||||
case "GPU":
|
||||
return "electron-gpu";
|
||||
default:
|
||||
return "electron-utility";
|
||||
}
|
||||
}
|
||||
|
||||
function inferredElectronCategory(
|
||||
process: ResourceMonitorProcessSample,
|
||||
): ResourceTelemetryProcessCategory {
|
||||
const command = process.command.toLowerCase();
|
||||
if (command.includes("--type=renderer")) return "electron-renderer";
|
||||
if (command.includes("--type=gpu-process")) return "electron-gpu";
|
||||
return "electron-utility";
|
||||
}
|
||||
|
||||
function matchElectronMetric(
|
||||
process: ResourceMonitorProcessSample,
|
||||
metricsByPid: ReadonlyMap<number, DesktopElectronProcessMetric>,
|
||||
): DesktopElectronProcessMetric | undefined {
|
||||
const metric = metricsByPid.get(process.pid);
|
||||
if (!metric) return undefined;
|
||||
return Math.abs(metric.creationTimeMs - process.startTimeMs) <= ELECTRON_IDENTITY_TOLERANCE_MS
|
||||
? metric
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function syntheticNativeSample(
|
||||
metric: DesktopElectronProcessMetric,
|
||||
sampledAtMs: number,
|
||||
): ResourceMonitorProcessSample {
|
||||
return {
|
||||
pid: metric.pid,
|
||||
ppid: 0,
|
||||
startTimeMs: metric.creationTimeMs,
|
||||
runTimeMs: Math.max(0, sampledAtMs - metric.creationTimeMs),
|
||||
name: metric.name ?? metric.serviceName ?? metric.type,
|
||||
command: metric.name ?? metric.serviceName ?? metric.type,
|
||||
status: "Running",
|
||||
cpuPercent: metric.cpuPercent,
|
||||
cpuTimeMs: Math.max(0, Math.round((metric.cumulativeCpuSeconds ?? 0) * 1_000)),
|
||||
residentBytes: metric.workingSetBytes,
|
||||
virtualBytes: 0,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
ioSemantics: "storage",
|
||||
};
|
||||
}
|
||||
|
||||
function processDepths(
|
||||
processes: ReadonlyArray<ResourceMonitorProcessSample>,
|
||||
roots: ReadonlySet<number>,
|
||||
): ReadonlyMap<number, number> {
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const process of processes) {
|
||||
const children = childrenByParent.get(process.ppid) ?? [];
|
||||
children.push(process.pid);
|
||||
childrenByParent.set(process.ppid, children);
|
||||
}
|
||||
|
||||
const depths = new Map<number, number>();
|
||||
const queue = [...roots].map((pid) => ({ pid, depth: 0 }));
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift();
|
||||
if (!current || depths.has(current.pid)) continue;
|
||||
depths.set(current.pid, current.depth);
|
||||
for (const childPid of childrenByParent.get(current.pid) ?? []) {
|
||||
queue.push({ pid: childPid, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return depths;
|
||||
}
|
||||
|
||||
function isElectronDescendant(
|
||||
pid: number,
|
||||
processesByPid: ReadonlyMap<number, ResourceMonitorProcessSample>,
|
||||
electronPids: ReadonlySet<number>,
|
||||
): boolean {
|
||||
const visited = new Set<number>();
|
||||
let currentPid = pid;
|
||||
while (!visited.has(currentPid)) {
|
||||
visited.add(currentPid);
|
||||
if (electronPids.has(currentPid)) return true;
|
||||
const current = processesByPid.get(currentPid);
|
||||
if (!current || current.ppid <= 0 || current.ppid === currentPid) return false;
|
||||
currentPid = current.ppid;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasElectronAncestor(
|
||||
process: ResourceMonitorProcessSample,
|
||||
processesByPid: ReadonlyMap<number, ResourceMonitorProcessSample>,
|
||||
electronPids: ReadonlySet<number>,
|
||||
): boolean {
|
||||
const visited = new Set<number>();
|
||||
let currentPid = process.ppid;
|
||||
while (currentPid > 0 && !visited.has(currentPid)) {
|
||||
visited.add(currentPid);
|
||||
if (electronPids.has(currentPid)) return true;
|
||||
const current = processesByPid.get(currentPid);
|
||||
if (!current || current.ppid === currentPid) return false;
|
||||
currentPid = current.ppid;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function orderProcessTree(
|
||||
processes: ReadonlyArray<ResourceTelemetryProcess>,
|
||||
rootPids: ReadonlyArray<number>,
|
||||
): ReadonlyArray<ResourceTelemetryProcess> {
|
||||
const processesByPid = new Map(processes.map((process) => [process.identity.pid, process]));
|
||||
const childrenByParent = new Map<number, ResourceTelemetryProcess[]>();
|
||||
for (const process of processes) {
|
||||
const children = childrenByParent.get(process.ppid) ?? [];
|
||||
children.push(process);
|
||||
childrenByParent.set(process.ppid, children);
|
||||
}
|
||||
for (const children of childrenByParent.values()) {
|
||||
children.sort((left, right) => left.identity.pid - right.identity.pid);
|
||||
}
|
||||
|
||||
const ordered: ResourceTelemetryProcess[] = [];
|
||||
const visited = new Set<number>();
|
||||
const visit = (process: ResourceTelemetryProcess): void => {
|
||||
if (visited.has(process.identity.pid)) return;
|
||||
visited.add(process.identity.pid);
|
||||
ordered.push(process);
|
||||
for (const child of childrenByParent.get(process.identity.pid) ?? []) {
|
||||
visit(child);
|
||||
}
|
||||
};
|
||||
|
||||
for (const rootPid of rootPids) {
|
||||
const root = processesByPid.get(rootPid);
|
||||
if (root) visit(root);
|
||||
}
|
||||
for (const process of processes.toSorted(
|
||||
(left, right) => left.depth - right.depth || left.identity.pid - right.identity.pid,
|
||||
)) {
|
||||
visit(process);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function delta(input: {
|
||||
readonly current: number;
|
||||
readonly previous: number;
|
||||
readonly elapsedMs: number;
|
||||
}): number {
|
||||
if (
|
||||
input.elapsedMs <= 0 ||
|
||||
input.elapsedMs > MAX_DELTA_INTERVAL_MS ||
|
||||
input.current < input.previous
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
return input.current - input.previous;
|
||||
}
|
||||
|
||||
function incrementCounters(counters: GroupCounters, update: Partial<GroupCounters>): GroupCounters {
|
||||
return {
|
||||
cpuTimeMs: counters.cpuTimeMs + (update.cpuTimeMs ?? 0),
|
||||
ioReadBytes: counters.ioReadBytes + (update.ioReadBytes ?? 0),
|
||||
ioWriteBytes: counters.ioWriteBytes + (update.ioWriteBytes ?? 0),
|
||||
processStarts: counters.processStarts + (update.processStarts ?? 0),
|
||||
processExits: counters.processExits + (update.processExits ?? 0),
|
||||
};
|
||||
}
|
||||
|
||||
function applyLifecycleCounters(input: {
|
||||
readonly counters: TelemetryCounters;
|
||||
readonly deltas: ReadonlyArray<ProcessDelta>;
|
||||
readonly current: ReadonlyMap<string, ProcessState>;
|
||||
readonly previous: ReadonlyMap<string, ProcessState>;
|
||||
}): TelemetryCounters {
|
||||
let backend = input.counters.backend;
|
||||
let electron = input.counters.electron;
|
||||
let monitor = input.counters.monitor;
|
||||
let allT3 = input.counters.allT3;
|
||||
for (const processDelta of input.deltas) {
|
||||
const group = categoryGroup(processDelta.category);
|
||||
switch (group) {
|
||||
case "backend":
|
||||
backend = incrementCounters(backend, processDelta);
|
||||
break;
|
||||
case "electron":
|
||||
electron = incrementCounters(electron, processDelta);
|
||||
break;
|
||||
case "monitor":
|
||||
monitor = incrementCounters(monitor, processDelta);
|
||||
break;
|
||||
}
|
||||
allT3 = incrementCounters(allT3, processDelta);
|
||||
}
|
||||
|
||||
for (const [identityKey, current] of input.current) {
|
||||
if (input.previous.has(identityKey)) continue;
|
||||
const group = categoryGroup(current.process.category);
|
||||
switch (group) {
|
||||
case "backend":
|
||||
backend = incrementCounters(backend, { processStarts: 1 });
|
||||
break;
|
||||
case "electron":
|
||||
electron = incrementCounters(electron, { processStarts: 1 });
|
||||
break;
|
||||
case "monitor":
|
||||
monitor = incrementCounters(monitor, { processStarts: 1 });
|
||||
break;
|
||||
}
|
||||
allT3 = incrementCounters(allT3, { processStarts: 1 });
|
||||
}
|
||||
|
||||
for (const [identityKey, previous] of input.previous) {
|
||||
if (input.current.has(identityKey)) continue;
|
||||
const group = categoryGroup(previous.process.category);
|
||||
switch (group) {
|
||||
case "backend":
|
||||
backend = incrementCounters(backend, { processExits: 1 });
|
||||
break;
|
||||
case "electron":
|
||||
electron = incrementCounters(electron, { processExits: 1 });
|
||||
break;
|
||||
case "monitor":
|
||||
monitor = incrementCounters(monitor, { processExits: 1 });
|
||||
break;
|
||||
}
|
||||
allT3 = incrementCounters(allT3, { processExits: 1 });
|
||||
}
|
||||
|
||||
return { backend, electron, monitor, allT3 };
|
||||
}
|
||||
|
||||
function aggregate(
|
||||
processes: ReadonlyArray<ResourceTelemetryProcess>,
|
||||
counters: GroupCounters,
|
||||
): ResourceTelemetryAggregate {
|
||||
return {
|
||||
processCount: processes.length,
|
||||
currentCpuPercent: processes.reduce((total, process) => total + process.cpuPercent, 0),
|
||||
cpuTimeMs: counters.cpuTimeMs,
|
||||
currentRssBytes: processes.reduce((total, process) => total + process.residentBytes, 0),
|
||||
peakRssBytes: processes.reduce((total, process) => total + process.peakResidentBytes, 0),
|
||||
ioReadBytes: counters.ioReadBytes,
|
||||
ioWriteBytes: counters.ioWriteBytes,
|
||||
ioReadBytesPerSecond: processes.reduce(
|
||||
(total, process) => total + process.ioReadBytesPerSecond,
|
||||
0,
|
||||
),
|
||||
ioWriteBytesPerSecond: processes.reduce(
|
||||
(total, process) => total + process.ioWriteBytesPerSecond,
|
||||
0,
|
||||
),
|
||||
processStarts: counters.processStarts,
|
||||
processExits: counters.processExits,
|
||||
};
|
||||
}
|
||||
|
||||
export function mergeProcesses(input: MergeProcessesInput): MergeProcessesResult {
|
||||
const nativeProcesses = Option.match(input.nativeSnapshot, {
|
||||
onNone: () => [] as ReadonlyArray<ResourceMonitorProcessSample>,
|
||||
onSome: (snapshot) => snapshot.processes,
|
||||
});
|
||||
const electronMetrics = Option.match(input.desktopSnapshot, {
|
||||
onNone: () => [] as ReadonlyArray<DesktopElectronProcessMetric>,
|
||||
onSome: (snapshot) => snapshot.electronProcesses,
|
||||
});
|
||||
const sampledAtMs = Option.match(input.nativeSnapshot, {
|
||||
onNone: () =>
|
||||
Option.match(input.desktopSnapshot, {
|
||||
onNone: () => input.fallbackSampledAtMs,
|
||||
onSome: (snapshot) => snapshot.sampledAtUnixMs,
|
||||
}),
|
||||
onSome: (snapshot) => snapshot.sampledAtUnixMs,
|
||||
});
|
||||
const nativeByPid = new Map(nativeProcesses.map((process) => [process.pid, process]));
|
||||
const metricsByPid = new Map<number, DesktopElectronProcessMetric>();
|
||||
for (const metric of electronMetrics) {
|
||||
const nativeProcess = nativeByPid.get(metric.pid);
|
||||
if (!nativeProcess) {
|
||||
nativeByPid.set(metric.pid, syntheticNativeSample(metric, sampledAtMs));
|
||||
metricsByPid.set(metric.pid, metric);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
Math.abs(metric.creationTimeMs - nativeProcess.startTimeMs) <= ELECTRON_IDENTITY_TOLERANCE_MS
|
||||
) {
|
||||
metricsByPid.set(metric.pid, metric);
|
||||
}
|
||||
}
|
||||
const processes = [...nativeByPid.values()];
|
||||
const processesByPid = new Map(processes.map((process) => [process.pid, process]));
|
||||
const explicitElectronRootPids = input.electronRootPids ?? new Set<number>();
|
||||
const electronPids = new Set([...metricsByPid.keys(), ...explicitElectronRootPids]);
|
||||
const electronRootPids = [
|
||||
...explicitElectronRootPids,
|
||||
...[...electronPids]
|
||||
.filter((pid) => {
|
||||
if (explicitElectronRootPids.has(pid)) return false;
|
||||
const process = processesByPid.get(pid);
|
||||
return process === undefined
|
||||
? true
|
||||
: !hasElectronAncestor(process, processesByPid, electronPids);
|
||||
})
|
||||
.toSorted((left, right) => left - right),
|
||||
].filter((pid, index, values) => values.indexOf(pid) === index);
|
||||
const rootPids = [input.serverPid, ...electronRootPids];
|
||||
const roots = new Set(rootPids);
|
||||
const depths = processDepths(processes, roots);
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const process of processes) {
|
||||
const children = childrenByParent.get(process.ppid) ?? [];
|
||||
children.push(process.pid);
|
||||
childrenByParent.set(process.ppid, children);
|
||||
}
|
||||
|
||||
const nextPrevious = new Map<string, ProcessState>();
|
||||
const processDeltas: ProcessDelta[] = [];
|
||||
const normalized = processes.map((process): ResourceTelemetryProcess => {
|
||||
const identityKey = processIdentityKey(process.pid, process.startTimeMs);
|
||||
const previous = input.previous.get(identityKey);
|
||||
const elapsedMs = previous ? sampledAtMs - previous.sampledAtMs : 0;
|
||||
const cpuTimeDelta = previous
|
||||
? delta({
|
||||
current: process.cpuTimeMs,
|
||||
previous: previous.process.cpuTimeMs,
|
||||
elapsedMs,
|
||||
})
|
||||
: 0;
|
||||
const ioReadDelta = previous
|
||||
? delta({
|
||||
current: process.ioReadBytes,
|
||||
previous: previous.process.ioReadBytes,
|
||||
elapsedMs,
|
||||
})
|
||||
: 0;
|
||||
const ioWriteDelta = previous
|
||||
? delta({
|
||||
current: process.ioWriteBytes,
|
||||
previous: previous.process.ioWriteBytes,
|
||||
elapsedMs,
|
||||
})
|
||||
: 0;
|
||||
const electronMetric = matchElectronMetric(process, metricsByPid);
|
||||
const category: ResourceTelemetryProcessCategory =
|
||||
process.pid === input.serverPid
|
||||
? "server"
|
||||
: Option.contains(input.sidecarPid, process.pid)
|
||||
? "resource-monitor"
|
||||
: explicitElectronRootPids.has(process.pid)
|
||||
? "electron-main"
|
||||
: electronMetric
|
||||
? electronCategory(electronMetric)
|
||||
: isElectronDescendant(process.pid, processesByPid, electronPids)
|
||||
? inferredElectronCategory(process)
|
||||
: "server-child";
|
||||
const firstSeenAt = previous?.process.firstSeenAt ?? DateTime.makeUnsafe(sampledAtMs);
|
||||
const preservePreviousRates = !input.updatePrevious && previous !== undefined;
|
||||
const cpuPercent = preservePreviousRates
|
||||
? previous.process.cpuPercent
|
||||
: previous && elapsedMs > 0 && elapsedMs <= MAX_DELTA_INTERVAL_MS
|
||||
? (cpuTimeDelta / elapsedMs) * 100
|
||||
: finiteNonNegative(process.cpuPercent);
|
||||
const normalizedProcess: ResourceTelemetryProcess = {
|
||||
identity: {
|
||||
pid: process.pid,
|
||||
startTimeMs: process.startTimeMs,
|
||||
},
|
||||
ppid: process.ppid,
|
||||
childPids: [...(childrenByParent.get(process.pid) ?? [])].toSorted(
|
||||
(left, right) => left - right,
|
||||
),
|
||||
depth: depths.get(process.pid) ?? 0,
|
||||
name: process.name,
|
||||
command: process.command,
|
||||
status: process.status,
|
||||
category,
|
||||
...(electronMetric ? { electronType: electronMetric.type } : {}),
|
||||
...(electronMetric?.serviceName ? { electronServiceName: electronMetric.serviceName } : {}),
|
||||
cpuPercent: finiteNonNegative(cpuPercent),
|
||||
cpuTimeMs: process.cpuTimeMs,
|
||||
residentBytes: process.residentBytes,
|
||||
peakResidentBytes: Math.max(
|
||||
process.residentBytes,
|
||||
electronMetric?.peakWorkingSetBytes ?? 0,
|
||||
previous?.process.peakResidentBytes ?? 0,
|
||||
),
|
||||
virtualBytes: process.virtualBytes,
|
||||
ioReadBytes: process.ioReadBytes,
|
||||
ioWriteBytes: process.ioWriteBytes,
|
||||
ioReadBytesPerSecond: preservePreviousRates
|
||||
? previous.process.ioReadBytesPerSecond
|
||||
: elapsedMs > 0
|
||||
? finiteNonNegative((ioReadDelta * 1_000) / elapsedMs)
|
||||
: 0,
|
||||
ioWriteBytesPerSecond: preservePreviousRates
|
||||
? previous.process.ioWriteBytesPerSecond
|
||||
: elapsedMs > 0
|
||||
? finiteNonNegative((ioWriteDelta * 1_000) / elapsedMs)
|
||||
: 0,
|
||||
ioSemantics: process.ioSemantics,
|
||||
...(electronMetric ? { idleWakeupsPerSecond: electronMetric.idleWakeupsPerSecond } : {}),
|
||||
runTimeMs: process.runTimeMs,
|
||||
firstSeenAt,
|
||||
lastSeenAt: DateTime.makeUnsafe(sampledAtMs),
|
||||
};
|
||||
nextPrevious.set(identityKey, {
|
||||
process: normalizedProcess,
|
||||
sampledAtMs,
|
||||
});
|
||||
processDeltas.push({
|
||||
identityKey,
|
||||
category,
|
||||
cpuTimeMs: cpuTimeDelta,
|
||||
ioReadBytes: ioReadDelta,
|
||||
ioWriteBytes: ioWriteDelta,
|
||||
});
|
||||
return normalizedProcess;
|
||||
});
|
||||
const ordered = orderProcessTree(normalized, rootPids);
|
||||
|
||||
const counters = input.updatePrevious
|
||||
? applyLifecycleCounters({
|
||||
counters: input.counters,
|
||||
deltas: processDeltas,
|
||||
current: nextPrevious,
|
||||
previous: input.previous,
|
||||
})
|
||||
: input.counters;
|
||||
const backendProcesses = ordered.filter(
|
||||
(process) => categoryGroup(process.category) === "backend",
|
||||
);
|
||||
const electronProcesses = ordered.filter(
|
||||
(process) => categoryGroup(process.category) === "electron",
|
||||
);
|
||||
const monitorProcesses = ordered.filter(
|
||||
(process) => categoryGroup(process.category) === "monitor",
|
||||
);
|
||||
|
||||
return {
|
||||
sampledAtMs,
|
||||
processes: ordered,
|
||||
previous: input.updatePrevious ? nextPrevious : input.previous,
|
||||
counters,
|
||||
groups: {
|
||||
backend: aggregate(backendProcesses, counters.backend),
|
||||
electron: aggregate(electronProcesses, counters.electron),
|
||||
monitor: aggregate(monitorProcesses, counters.monitor),
|
||||
allT3: aggregate(ordered, counters.allT3),
|
||||
},
|
||||
deltas: processDeltas,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { HostPowerSnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { resolveNativeSampleIntervalMs } from "./NativeTelemetryClient.ts";
|
||||
|
||||
const basePower: HostPowerSnapshot = {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "false",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
|
||||
};
|
||||
|
||||
describe("resolveNativeSampleIntervalMs", () => {
|
||||
it("pauses while suspended and backs off under host constraints", () => {
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, suspended: true }, 1)).toBe(0);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 1)).toBe(15_000);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, lowPowerMode: "true" }, 1)).toBe(15_000);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, thermalState: "critical" }, 1)).toBe(
|
||||
15_000,
|
||||
);
|
||||
expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000);
|
||||
});
|
||||
|
||||
it("keeps unknown background telemetry cheap but serves live diagnostics at 1Hz", () => {
|
||||
const unknown: HostPowerSnapshot = {
|
||||
...basePower,
|
||||
source: "unknown",
|
||||
stale: true,
|
||||
};
|
||||
expect(resolveNativeSampleIntervalMs(unknown, 0)).toBe(5_000);
|
||||
expect(resolveNativeSampleIntervalMs(unknown, 1)).toBe(1_000);
|
||||
expect(
|
||||
resolveNativeSampleIntervalMs(
|
||||
{ ...basePower, stale: true, locked: "true", suspended: true },
|
||||
0,
|
||||
),
|
||||
).toBe(5_000);
|
||||
expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(1_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,922 @@
|
||||
import type {
|
||||
HostPowerSnapshot,
|
||||
ResourceMonitorCapabilities,
|
||||
ResourceMonitorCommand,
|
||||
ResourceMonitorEvent,
|
||||
ResourceMonitorExternalProcess,
|
||||
ResourceMonitorHelloEvent,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetrySourceStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
ResourceMonitorCommand as ResourceMonitorCommandSchema,
|
||||
ResourceMonitorEvent as ResourceMonitorEventSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 1_000;
|
||||
const UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS = 5_000;
|
||||
const BATTERY_SAMPLE_INTERVAL_MS = 5_000;
|
||||
const CONSTRAINED_SAMPLE_INTERVAL_MS = 15_000;
|
||||
const HANDSHAKE_TIMEOUT = Duration.seconds(5);
|
||||
const SAMPLE_REQUEST_TIMEOUT = Duration.seconds(5);
|
||||
const HISTORY_REQUEST_TIMEOUT = Duration.seconds(15);
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
const FAILURE_WINDOW_MS = 60_000;
|
||||
const MAX_FAILURES_PER_WINDOW = 5;
|
||||
|
||||
export class NativeTelemetrySpawnFailed extends Schema.TaggedErrorClass<NativeTelemetrySpawnFailed>()(
|
||||
"NativeTelemetrySpawnFailed",
|
||||
{
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to start resource monitor '${this.path}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryHandshakeTimedOut extends Schema.TaggedErrorClass<NativeTelemetryHandshakeTimedOut>()(
|
||||
"NativeTelemetryHandshakeTimedOut",
|
||||
{
|
||||
timeoutMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor handshake timed out after ${this.timeoutMs}ms.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryProtocolMismatch extends Schema.TaggedErrorClass<NativeTelemetryProtocolMismatch>()(
|
||||
"NativeTelemetryProtocolMismatch",
|
||||
{
|
||||
expectedVersion: Schema.Number,
|
||||
receivedVersion: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryDecodeFailed extends Schema.TaggedErrorClass<NativeTelemetryDecodeFailed>()(
|
||||
"NativeTelemetryDecodeFailed",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to decode resource monitor output.";
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryCommandFailed extends Schema.TaggedErrorClass<NativeTelemetryCommandFailed>()(
|
||||
"NativeTelemetryCommandFailed",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor command '${this.operation}' failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryExited extends Schema.TaggedErrorClass<NativeTelemetryExited>()(
|
||||
"NativeTelemetryExited",
|
||||
{
|
||||
exitCode: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor exited with code ${this.exitCode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class NativeTelemetryUnavailable extends Schema.TaggedErrorClass<NativeTelemetryUnavailable>()(
|
||||
"NativeTelemetryUnavailable",
|
||||
{
|
||||
reason: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor is unavailable: ${this.reason}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type NativeTelemetryClientError =
|
||||
| NativeTelemetrySpawnFailed
|
||||
| NativeTelemetryHandshakeTimedOut
|
||||
| NativeTelemetryProtocolMismatch
|
||||
| NativeTelemetryDecodeFailed
|
||||
| NativeTelemetryCommandFailed
|
||||
| NativeTelemetryExited
|
||||
| NativeTelemetryUnavailable;
|
||||
|
||||
export interface NativeTelemetryClientHealth {
|
||||
readonly status: ResourceTelemetrySourceStatus;
|
||||
readonly hello: Option.Option<ResourceMonitorHelloEvent>;
|
||||
readonly lastSampleAt: Option.Option<DateTime.Utc>;
|
||||
readonly lastError: Option.Option<string>;
|
||||
readonly restartCount: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
}
|
||||
|
||||
export interface NativeTelemetryClientShape {
|
||||
readonly capabilities: Effect.Effect<ResourceMonitorCapabilities, NativeTelemetryClientError>;
|
||||
readonly snapshots: Stream.Stream<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>;
|
||||
readonly readHistory: (
|
||||
windowMs: number,
|
||||
) => Effect.Effect<ReadonlyArray<ResourceMonitorSnapshotEvent>, NativeTelemetryClientError>;
|
||||
readonly setExternalProcesses: (
|
||||
processes: ReadonlyArray<ResourceMonitorExternalProcess>,
|
||||
) => Effect.Effect<void, NativeTelemetryClientError>;
|
||||
readonly setHostPowerState: (
|
||||
snapshot: HostPowerSnapshot,
|
||||
) => Effect.Effect<void, NativeTelemetryClientError>;
|
||||
readonly sampleNow: Effect.Effect<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>;
|
||||
readonly retry: Effect.Effect<boolean>;
|
||||
readonly health: Effect.Effect<NativeTelemetryClientHealth>;
|
||||
readonly healthChanges: Stream.Stream<NativeTelemetryClientHealth>;
|
||||
}
|
||||
|
||||
export class NativeTelemetryClient extends Context.Service<
|
||||
NativeTelemetryClient,
|
||||
NativeTelemetryClientShape
|
||||
>()("t3/resourceTelemetry/NativeTelemetryClient") {}
|
||||
|
||||
interface ClientState {
|
||||
readonly status: ResourceTelemetrySourceStatus;
|
||||
readonly handle: Option.Option<ChildProcessSpawner.ChildProcessHandle>;
|
||||
readonly hello: Option.Option<ResourceMonitorHelloEvent>;
|
||||
readonly lastSampleAt: Option.Option<DateTime.Utc>;
|
||||
readonly lastError: Option.Option<string>;
|
||||
readonly restartCount: number;
|
||||
}
|
||||
|
||||
interface CollectionControl {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly liveSubscriberCount: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
}
|
||||
|
||||
interface PendingHistoryRequest {
|
||||
readonly deferred: Deferred.Deferred<
|
||||
ReadonlyArray<ResourceMonitorSnapshotEvent>,
|
||||
NativeTelemetryClientError
|
||||
>;
|
||||
readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
|
||||
}
|
||||
|
||||
const initialState: ClientState = {
|
||||
status: "starting",
|
||||
handle: Option.none(),
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
};
|
||||
|
||||
function toHealth(state: ClientState, sampleIntervalMs: number): NativeTelemetryClientHealth {
|
||||
return {
|
||||
status: state.status,
|
||||
hello: state.hello,
|
||||
lastSampleAt: state.lastSampleAt,
|
||||
lastError: state.lastError,
|
||||
restartCount: state.restartCount,
|
||||
sampleIntervalMs,
|
||||
};
|
||||
}
|
||||
|
||||
function isThermallyConstrained(snapshot: HostPowerSnapshot): boolean {
|
||||
return snapshot.thermalState === "serious" || snapshot.thermalState === "critical";
|
||||
}
|
||||
|
||||
export function resolveNativeSampleIntervalMs(
|
||||
snapshot: HostPowerSnapshot,
|
||||
liveSubscriberCount: number,
|
||||
): number {
|
||||
if (snapshot.stale || snapshot.source === "unknown") {
|
||||
return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
if (snapshot.suspended) return 0;
|
||||
if (
|
||||
snapshot.locked === "true" ||
|
||||
snapshot.lowPowerMode === "true" ||
|
||||
isThermallyConstrained(snapshot)
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
if (snapshot.onBattery === "true") return BATTERY_SAMPLE_INTERVAL_MS;
|
||||
return SAMPLE_INTERVAL_MS;
|
||||
}
|
||||
|
||||
const decodeMonitorEvent: (
|
||||
value: unknown,
|
||||
) => Effect.Effect<ResourceMonitorEvent, Schema.SchemaError> = Schema.decodeUnknownEffect(
|
||||
ResourceMonitorEventSchema,
|
||||
);
|
||||
const encodeMonitorCommand = Schema.encodeEffect(
|
||||
Schema.fromJsonString(ResourceMonitorCommandSchema),
|
||||
);
|
||||
const isProtocolMismatch = Schema.is(NativeTelemetryProtocolMismatch);
|
||||
const isDecodeFailed = Schema.is(NativeTelemetryDecodeFailed);
|
||||
const isCommandFailed = Schema.is(NativeTelemetryCommandFailed);
|
||||
|
||||
function eventVersion(value: unknown): number | undefined {
|
||||
if (typeof value !== "object" || value === null) return undefined;
|
||||
const version = Reflect.get(value, "version");
|
||||
return typeof version === "number" ? version : undefined;
|
||||
}
|
||||
|
||||
function restartDelay(attempt: number): Duration.Duration {
|
||||
return Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
|
||||
}
|
||||
|
||||
function errorMessage(error: NativeTelemetryClientError): string {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () {
|
||||
const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const config = yield* ServerConfig;
|
||||
const initializedAt = yield* DateTime.now;
|
||||
const state = yield* Ref.make(initialState);
|
||||
const collectionControl = yield* Ref.make<CollectionControl>({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: initializedAt,
|
||||
},
|
||||
liveSubscriberCount: 0,
|
||||
sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
|
||||
});
|
||||
const externalProcesses = yield* Ref.make<ReadonlyArray<ResourceMonitorExternalProcess>>([]);
|
||||
const pendingSamples = yield* Ref.make(
|
||||
new Map<string, Deferred.Deferred<ResourceMonitorSnapshotEvent, NativeTelemetryClientError>>(),
|
||||
);
|
||||
const pendingHistories = yield* Ref.make(new Map<string, PendingHistoryRequest>());
|
||||
const snapshots = yield* PubSub.sliding<ResourceMonitorSnapshotEvent>(8);
|
||||
const healthChanges = yield* PubSub.sliding<NativeTelemetryClientHealth>(4);
|
||||
const retryQueue = yield* Queue.sliding<void>(1);
|
||||
const commandMutex = yield* Semaphore.make(1);
|
||||
const currentHealth = Effect.all([Ref.get(state), Ref.get(collectionControl)]).pipe(
|
||||
Effect.map(([current, control]) => toHealth(current, control.sampleIntervalMs)),
|
||||
);
|
||||
const publishHealth = currentHealth.pipe(
|
||||
Effect.flatMap((health) => PubSub.publish(healthChanges, health)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const failPending = (error: NativeTelemetryClientError) =>
|
||||
Effect.gen(function* () {
|
||||
const samples = yield* Ref.getAndSet(pendingSamples, new Map());
|
||||
const histories = yield* Ref.getAndSet(pendingHistories, new Map());
|
||||
yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
|
||||
discard: true,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
histories.values(),
|
||||
(request) => Deferred.fail(request.deferred, error),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const writeCommand = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
command: ResourceMonitorCommand,
|
||||
): Effect.Effect<void, NativeTelemetryClientError> =>
|
||||
commandMutex.withPermits(1)(
|
||||
encodeMonitorCommand(command).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((encoded) =>
|
||||
Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const processEvent = (
|
||||
event: ResourceMonitorEvent,
|
||||
helloDeferred: Deferred.Deferred<ResourceMonitorHelloEvent>,
|
||||
): Effect.Effect<void, NativeTelemetryClientError> => {
|
||||
switch (event.type) {
|
||||
case "hello":
|
||||
return Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "starting" as const,
|
||||
hello: Option.some(event),
|
||||
lastError: Option.none(),
|
||||
})).pipe(
|
||||
Effect.andThen(publishHealth),
|
||||
Effect.andThen(Deferred.succeed(helloDeferred, event)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
case "snapshot":
|
||||
return Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
lastSampleAt: Option.some(sampledAt),
|
||||
lastError: Option.none(),
|
||||
}));
|
||||
yield* PubSub.publish(snapshots, event);
|
||||
if (event.requestId) {
|
||||
const deferred = yield* Ref.modify(pendingSamples, (pending) => {
|
||||
const next = new Map(pending);
|
||||
const current = next.get(event.requestId!);
|
||||
next.delete(event.requestId!);
|
||||
return [Option.fromUndefinedOr(current), next];
|
||||
});
|
||||
if (Option.isSome(deferred)) {
|
||||
yield* Deferred.succeed(deferred.value, event);
|
||||
}
|
||||
}
|
||||
});
|
||||
case "historyChunk":
|
||||
return Effect.gen(function* () {
|
||||
const latestSnapshot = event.snapshots.at(-1);
|
||||
if (latestSnapshot) {
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
}));
|
||||
}
|
||||
const completed = yield* Ref.modify(pendingHistories, (pending) => {
|
||||
const request = pending.get(event.requestId);
|
||||
if (!request) return [Option.none(), pending] as const;
|
||||
const snapshots = [...request.snapshots, ...event.snapshots];
|
||||
const next = new Map(pending);
|
||||
if (event.done) {
|
||||
next.delete(event.requestId);
|
||||
return [Option.some({ deferred: request.deferred, snapshots }), next] as const;
|
||||
}
|
||||
next.set(event.requestId, { deferred: request.deferred, snapshots });
|
||||
return [Option.none(), next] as const;
|
||||
});
|
||||
if (Option.isSome(completed)) {
|
||||
yield* Deferred.succeed(completed.value.deferred, completed.value.snapshots);
|
||||
}
|
||||
});
|
||||
case "error":
|
||||
return Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "degraded" as const,
|
||||
lastError: Option.some(event.message),
|
||||
})).pipe(
|
||||
Effect.andThen(publishHealth),
|
||||
Effect.andThen(
|
||||
event.recoverable
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: event.code,
|
||||
cause: event.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const runAttempt: Effect.Effect<void, NativeTelemetryClientError> = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const executablePath = yield* binary.resolve.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const command = ChildProcess.make(executablePath, [], {
|
||||
cwd: config.cwd,
|
||||
stdin: {
|
||||
stream: "pipe",
|
||||
endOnDone: false,
|
||||
},
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: Duration.seconds(2),
|
||||
});
|
||||
const handle = yield* Effect.acquireRelease(
|
||||
spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new NativeTelemetrySpawnFailed({ path: executablePath, cause }),
|
||||
),
|
||||
),
|
||||
(child) => child.kill().pipe(Effect.ignore),
|
||||
);
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "starting" as const,
|
||||
handle: Option.some(handle),
|
||||
hello: Option.none(),
|
||||
}));
|
||||
yield* publishHealth;
|
||||
|
||||
const helloDeferred = yield* Deferred.make<ResourceMonitorHelloEvent>();
|
||||
const eventFiber = yield* handle.stdout.pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect(
|
||||
(
|
||||
value,
|
||||
): Effect.Effect<
|
||||
ResourceMonitorEvent,
|
||||
NativeTelemetryProtocolMismatch | NativeTelemetryDecodeFailed
|
||||
> => {
|
||||
const version = eventVersion(value);
|
||||
if (version !== undefined && version !== RESOURCE_MONITOR_PROTOCOL_VERSION) {
|
||||
return Effect.fail(
|
||||
new NativeTelemetryProtocolMismatch({
|
||||
expectedVersion: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
receivedVersion: version,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return decodeMonitorEvent(value).pipe(
|
||||
Effect.mapError((cause) => new NativeTelemetryDecodeFailed({ cause })),
|
||||
);
|
||||
},
|
||||
),
|
||||
Stream.runForEach((event) => processEvent(event, helloDeferred)),
|
||||
Effect.mapError((cause) =>
|
||||
isProtocolMismatch(cause) || isDecodeFailed(cause) || isCommandFailed(cause)
|
||||
? cause
|
||||
: new NativeTelemetryDecodeFailed({ cause }),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* handle.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);
|
||||
|
||||
const hello = yield* Deferred.await(helloDeferred).pipe(
|
||||
Effect.timeoutOption(HANDSHAKE_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryHandshakeTimedOut({
|
||||
timeoutMs: Duration.toMillis(HANDSHAKE_TIMEOUT),
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const control = yield* Ref.get(collectionControl);
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "configure",
|
||||
rootPid: process.pid,
|
||||
sampleIntervalMs: control.sampleIntervalMs,
|
||||
externalProcesses: [...(yield* Ref.get(externalProcesses))],
|
||||
});
|
||||
if (control.liveSubscriberCount > 0) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "healthy" as const,
|
||||
hello: Option.some(hello),
|
||||
}));
|
||||
yield* publishHealth;
|
||||
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setExternalProcesses",
|
||||
processes: [...(yield* Ref.get(externalProcesses))],
|
||||
});
|
||||
const latestControl = yield* Ref.get(collectionControl);
|
||||
if (latestControl.sampleIntervalMs !== control.sampleIntervalMs) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setSampleInterval",
|
||||
sampleIntervalMs: latestControl.sampleIntervalMs,
|
||||
});
|
||||
}
|
||||
if (latestControl.liveSubscriberCount > 0 !== control.liveSubscriberCount > 0) {
|
||||
yield* writeCommand(handle, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: latestControl.liveSubscriberCount > 0,
|
||||
});
|
||||
}
|
||||
|
||||
const exitEffect = handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "waitForExit",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((exitCode) =>
|
||||
Effect.fail(new NativeTelemetryExited({ exitCode: Number(exitCode) })),
|
||||
),
|
||||
);
|
||||
const decoderEffect = Fiber.join(eventFiber).pipe(
|
||||
Effect.andThen(Effect.fail(new NativeTelemetryExited({ exitCode: -1 }))),
|
||||
);
|
||||
return yield* Effect.raceFirst(exitEffect, decoderEffect);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
handle: Option.none(),
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
let failures: ReadonlyArray<number> = [];
|
||||
let restartAttempt = 0;
|
||||
|
||||
while (true) {
|
||||
const result = yield* Effect.result(runAttempt);
|
||||
if (Result.isSuccess(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const error = result.failure;
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
failures = [...failures.filter((failedAt) => now - failedAt <= FAILURE_WINDOW_MS), now];
|
||||
const exhausted = failures.length >= MAX_FAILURES_PER_WINDOW;
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: exhausted ? ("unavailable" as const) : ("degraded" as const),
|
||||
hello: Option.none(),
|
||||
lastError: Option.some(errorMessage(error)),
|
||||
restartCount: current.restartCount + 1,
|
||||
}));
|
||||
yield* publishHealth;
|
||||
yield* failPending(error);
|
||||
|
||||
if (exhausted) {
|
||||
yield* Queue.take(retryQueue);
|
||||
failures = [];
|
||||
restartAttempt = 0;
|
||||
yield* Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "starting" as const,
|
||||
hello: Option.none(),
|
||||
lastError: Option.none(),
|
||||
}));
|
||||
yield* publishHealth;
|
||||
continue;
|
||||
}
|
||||
|
||||
const manuallyRetried = yield* Effect.raceFirst(
|
||||
Effect.sleep(restartDelay(restartAttempt)).pipe(Effect.as(false)),
|
||||
Queue.take(retryQueue).pipe(Effect.as(true)),
|
||||
);
|
||||
restartAttempt = manuallyRetried ? 0 : restartAttempt + 1;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
: Ref.update(state, (current) => ({
|
||||
...current,
|
||||
status: "unavailable" as const,
|
||||
hello: Option.none(),
|
||||
lastError: Option.some(Cause.pretty(cause)),
|
||||
})).pipe(
|
||||
Effect.andThen(publishHealth),
|
||||
Effect.andThen(
|
||||
Effect.logWarning("Resource monitor supervisor failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const applyCollectionControl = Effect.fn(
|
||||
"resourceTelemetry.nativeTelemetryClient.applyCollectionControl",
|
||||
)(function* (previous: CollectionControl, next: CollectionControl) {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isSome(current.handle) && current.status === "healthy") {
|
||||
if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setSampleInterval",
|
||||
sampleIntervalMs: next.sampleIntervalMs,
|
||||
});
|
||||
}
|
||||
const wasStreaming = previous.liveSubscriberCount > 0;
|
||||
const isStreaming = next.liveSubscriberCount > 0;
|
||||
if (wasStreaming !== isStreaming) {
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setStreaming",
|
||||
enabled: isStreaming,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
|
||||
yield* publishHealth;
|
||||
}
|
||||
});
|
||||
|
||||
const setHostPowerState: NativeTelemetryClientShape["setHostPowerState"] = (hostPower) =>
|
||||
Effect.gen(function* () {
|
||||
const [previous, next] = yield* Ref.modify(collectionControl, (current) => {
|
||||
const updated: CollectionControl = {
|
||||
...current,
|
||||
hostPower,
|
||||
sampleIntervalMs: resolveNativeSampleIntervalMs(hostPower, current.liveSubscriberCount),
|
||||
};
|
||||
return [[current, updated] as const, updated];
|
||||
});
|
||||
yield* applyCollectionControl(previous, next);
|
||||
});
|
||||
|
||||
const changeLiveSubscriberCount = Effect.fn(
|
||||
"resourceTelemetry.nativeTelemetryClient.changeLiveSubscriberCount",
|
||||
)(function* (delta: 1 | -1) {
|
||||
const [previous, next] = yield* Ref.modify(collectionControl, (current) => {
|
||||
const liveSubscriberCount = Math.max(0, current.liveSubscriberCount + delta);
|
||||
const updated: CollectionControl = {
|
||||
...current,
|
||||
liveSubscriberCount,
|
||||
sampleIntervalMs: resolveNativeSampleIntervalMs(current.hostPower, liveSubscriberCount),
|
||||
};
|
||||
return [[current, updated] as const, updated];
|
||||
});
|
||||
yield* applyCollectionControl(previous, next);
|
||||
});
|
||||
|
||||
const liveSnapshots = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(snapshots);
|
||||
yield* Effect.acquireRelease(changeLiveSubscriberCount(1), () =>
|
||||
changeLiveSubscriberCount(-1).pipe(Effect.ignore),
|
||||
);
|
||||
return Stream.fromSubscription(subscription);
|
||||
}),
|
||||
);
|
||||
|
||||
const setExternalProcesses: NativeTelemetryClientShape["setExternalProcesses"] = (processes) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(externalProcesses, [...processes]);
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") return;
|
||||
yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "setExternalProcesses",
|
||||
processes: [...processes],
|
||||
});
|
||||
});
|
||||
|
||||
const readHistory: NativeTelemetryClientShape["readHistory"] = (windowMs) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") {
|
||||
return yield* new NativeTelemetryUnavailable({
|
||||
reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
|
||||
});
|
||||
}
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "createHistoryRequestId",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const deferred = yield* Deferred.make<
|
||||
ReadonlyArray<ResourceMonitorSnapshotEvent>,
|
||||
NativeTelemetryClientError
|
||||
>();
|
||||
yield* Ref.update(pendingHistories, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.set(requestId, { deferred, snapshots: [] });
|
||||
return next;
|
||||
});
|
||||
return yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "readHistory",
|
||||
requestId,
|
||||
windowMs: Math.max(0, Math.round(windowMs)),
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "readHistory",
|
||||
cause: "history request timed out",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Ref.update(pendingHistories, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.delete(requestId);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const sampleNow: NativeTelemetryClientShape["sampleNow"] = Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isNone(current.handle) || current.status !== "healthy") {
|
||||
return yield* new NativeTelemetryUnavailable({
|
||||
reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
|
||||
});
|
||||
}
|
||||
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "createRequestId",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const deferred = yield* Deferred.make<
|
||||
ResourceMonitorSnapshotEvent,
|
||||
NativeTelemetryClientError
|
||||
>();
|
||||
yield* Ref.update(pendingSamples, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.set(requestId, deferred);
|
||||
return next;
|
||||
});
|
||||
return yield* writeCommand(current.handle.value, {
|
||||
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
|
||||
type: "sampleNow",
|
||||
requestId,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Deferred.await(deferred).pipe(
|
||||
Effect.timeoutOption(SAMPLE_REQUEST_TIMEOUT),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryCommandFailed({
|
||||
operation: "sampleNow",
|
||||
cause: "sample request timed out",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Ref.update(pendingSamples, (pending) => {
|
||||
const next = new Map(pending);
|
||||
next.delete(requestId);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const health = currentHealth;
|
||||
|
||||
return NativeTelemetryClient.of({
|
||||
capabilities: Ref.get(state).pipe(
|
||||
Effect.flatMap((current) =>
|
||||
Option.match(current.hello, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: Option.getOrElse(current.lastError, () => "handshake is incomplete"),
|
||||
}),
|
||||
),
|
||||
onSome: (hello) => Effect.succeed(hello.capabilities),
|
||||
}),
|
||||
),
|
||||
),
|
||||
snapshots: liveSnapshots,
|
||||
readHistory,
|
||||
setExternalProcesses,
|
||||
setHostPowerState,
|
||||
sampleNow,
|
||||
retry: Ref.get(state).pipe(
|
||||
Effect.flatMap((current) =>
|
||||
current.status === "healthy" || current.status === "starting"
|
||||
? Effect.succeed(false)
|
||||
: Queue.offer(retryQueue, undefined).pipe(Effect.as(true)),
|
||||
),
|
||||
),
|
||||
health,
|
||||
healthChanges: Stream.fromPubSub(healthChanges),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(NativeTelemetryClient, make());
|
||||
|
||||
export const layerTest = (
|
||||
overrides: Partial<NativeTelemetryClientShape> = {},
|
||||
): Layer.Layer<NativeTelemetryClient> =>
|
||||
Layer.succeed(
|
||||
NativeTelemetryClient,
|
||||
NativeTelemetryClient.of({
|
||||
capabilities: Effect.succeed({
|
||||
cumulativeCpuTime: true,
|
||||
currentCpuPercent: true,
|
||||
residentMemory: true,
|
||||
virtualMemory: true,
|
||||
ioBytes: true,
|
||||
processStartTime: true,
|
||||
processTree: true,
|
||||
}),
|
||||
snapshots: Stream.empty,
|
||||
readHistory: () =>
|
||||
Effect.fail(
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: "No resource monitor history was configured for this test.",
|
||||
}),
|
||||
),
|
||||
setExternalProcesses: () => Effect.void,
|
||||
setHostPowerState: () => Effect.void,
|
||||
sampleNow: Effect.fail(
|
||||
new NativeTelemetryUnavailable({
|
||||
reason: "No resource monitor sample was configured for this test.",
|
||||
}),
|
||||
),
|
||||
retry: Effect.succeed(false),
|
||||
health: Effect.succeed({
|
||||
status: "unavailable",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.some("Resource monitor test implementation is unavailable."),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
|
||||
}),
|
||||
healthChanges: Stream.empty,
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ResourceAttributionEntry, ResourceAttributionSnapshot } 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 Ref from "effect/Ref";
|
||||
|
||||
export interface ResourceAttributionRecord {
|
||||
readonly component: string;
|
||||
readonly operation: string;
|
||||
readonly logicalReadBytes?: number;
|
||||
readonly logicalWriteBytes?: number;
|
||||
readonly count?: number;
|
||||
readonly durationMs?: number;
|
||||
}
|
||||
|
||||
export interface ResourceAttributionShape {
|
||||
readonly record: (input: ResourceAttributionRecord) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<ResourceAttributionSnapshot>;
|
||||
}
|
||||
|
||||
export class ResourceAttribution extends Context.Service<
|
||||
ResourceAttribution,
|
||||
ResourceAttributionShape
|
||||
>()("t3/resourceTelemetry/ResourceAttribution") {}
|
||||
|
||||
function key(input: Pick<ResourceAttributionRecord, "component" | "operation">): string {
|
||||
return `${input.component}\u0000${input.operation}`;
|
||||
}
|
||||
|
||||
function nonNegativeInteger(value: number | undefined, fallback: number): number {
|
||||
if (value === undefined) return fallback;
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.resourceAttribution.make")(function* () {
|
||||
const entries = yield* Ref.make(new Map<string, ResourceAttributionEntry>());
|
||||
|
||||
const record: ResourceAttributionShape["record"] = (input) =>
|
||||
Ref.update(entries, (current) => {
|
||||
const next = new Map(current);
|
||||
const entryKey = key(input);
|
||||
const existing = next.get(entryKey);
|
||||
next.set(entryKey, {
|
||||
component: input.component,
|
||||
operation: input.operation,
|
||||
logicalReadBytes:
|
||||
(existing?.logicalReadBytes ?? 0) + nonNegativeInteger(input.logicalReadBytes, 0),
|
||||
logicalWriteBytes:
|
||||
(existing?.logicalWriteBytes ?? 0) + nonNegativeInteger(input.logicalWriteBytes, 0),
|
||||
count: (existing?.count ?? 0) + nonNegativeInteger(input.count, 1),
|
||||
durationMs: (existing?.durationMs ?? 0) + nonNegativeInteger(input.durationMs, 0),
|
||||
});
|
||||
return next;
|
||||
});
|
||||
|
||||
return ResourceAttribution.of({
|
||||
record,
|
||||
snapshot: Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const current = yield* Ref.get(entries);
|
||||
return {
|
||||
readAt,
|
||||
entries: [...current.values()].toSorted(
|
||||
(left, right) => right.logicalWriteBytes - left.logicalWriteBytes,
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ResourceAttribution, make());
|
||||
@@ -0,0 +1,80 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
HostProcessArchitecture,
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
|
||||
|
||||
describe("ResourceMonitorBinary", () => {
|
||||
it.effect("resolves an executable override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-resource-monitor-binary-",
|
||||
});
|
||||
const binaryPath = `${baseDir}/t3-resource-monitor`;
|
||||
yield* fileSystem.writeFileString(binaryPath, "binary");
|
||||
yield* fileSystem.chmod(binaryPath, 0o755);
|
||||
|
||||
const service = yield* ResourceMonitorBinary.make().pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.provideService(HostProcessArchitecture, "x64"),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
T3CODE_RESOURCE_MONITOR_PATH: binaryPath,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* service.resolve, binaryPath);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rejects a non-executable POSIX override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-resource-monitor-binary-",
|
||||
});
|
||||
const binaryPath = `${baseDir}/t3-resource-monitor`;
|
||||
yield* fileSystem.writeFileString(binaryPath, "binary");
|
||||
yield* fileSystem.chmod(binaryPath, 0o644);
|
||||
|
||||
const service = yield* ResourceMonitorBinary.make().pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.provideService(HostProcessArchitecture, "x64"),
|
||||
Effect.provideService(HostProcessEnvironment, {
|
||||
T3CODE_RESOURCE_MONITOR_PATH: binaryPath,
|
||||
}),
|
||||
);
|
||||
const error = yield* Effect.flip(service.resolve);
|
||||
|
||||
assert.instanceOf(error, ResourceMonitorBinary.ResourceMonitorBinaryNotExecutable);
|
||||
assert.equal(error.path, binaryPath);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rejects unsupported platform and architecture pairs", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-resource-monitor-binary-",
|
||||
});
|
||||
const service = yield* ResourceMonitorBinary.make().pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Effect.provideService(HostProcessPlatform, "freebsd"),
|
||||
Effect.provideService(HostProcessArchitecture, "ia32"),
|
||||
Effect.provideService(HostProcessEnvironment, {}),
|
||||
);
|
||||
const error = yield* Effect.flip(service.resolve);
|
||||
|
||||
assert.instanceOf(error, ResourceMonitorBinary.ResourceMonitorBinaryUnsupported);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import {
|
||||
HostProcessArchitecture,
|
||||
HostProcessEnvironment,
|
||||
HostProcessPlatform,
|
||||
} from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
export class ResourceMonitorBinaryUnsupported extends Schema.TaggedErrorClass<ResourceMonitorBinaryUnsupported>()(
|
||||
"ResourceMonitorBinaryUnsupported",
|
||||
{
|
||||
platform: Schema.String,
|
||||
architecture: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitoring is unsupported on ${this.platform}/${this.architecture}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ResourceMonitorBinaryNotFound extends Schema.TaggedErrorClass<ResourceMonitorBinaryNotFound>()(
|
||||
"ResourceMonitorBinaryNotFound",
|
||||
{
|
||||
platform: Schema.String,
|
||||
architecture: Schema.String,
|
||||
candidates: Schema.Array(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor binary was not found for ${this.platform}/${this.architecture}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ResourceMonitorBinaryNotExecutable extends Schema.TaggedErrorClass<ResourceMonitorBinaryNotExecutable>()(
|
||||
"ResourceMonitorBinaryNotExecutable",
|
||||
{
|
||||
path: Schema.String,
|
||||
mode: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource monitor binary at '${this.path}' is not executable.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ResourceMonitorBinaryError =
|
||||
| ResourceMonitorBinaryUnsupported
|
||||
| ResourceMonitorBinaryNotFound
|
||||
| ResourceMonitorBinaryNotExecutable;
|
||||
|
||||
export interface ResourceMonitorBinaryShape {
|
||||
readonly resolve: Effect.Effect<string, ResourceMonitorBinaryError>;
|
||||
}
|
||||
|
||||
export class ResourceMonitorBinary extends Context.Service<
|
||||
ResourceMonitorBinary,
|
||||
ResourceMonitorBinaryShape
|
||||
>()("t3/resourceTelemetry/ResourceMonitorBinary") {}
|
||||
|
||||
function binaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
export function resourceMonitorPlatformKey(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: NodeJS.Architecture,
|
||||
): string | undefined {
|
||||
if (
|
||||
(platform !== "darwin" && platform !== "linux" && platform !== "win32") ||
|
||||
(architecture !== "arm64" && architecture !== "x64")
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return `${platform}-${architecture}`;
|
||||
}
|
||||
|
||||
function resourceMonitorRustTarget(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: NodeJS.Architecture,
|
||||
): string | undefined {
|
||||
if (platform === "darwin") {
|
||||
return architecture === "arm64"
|
||||
? "aarch64-apple-darwin"
|
||||
: architecture === "x64"
|
||||
? "x86_64-apple-darwin"
|
||||
: undefined;
|
||||
}
|
||||
if (platform === "linux") {
|
||||
return architecture === "arm64"
|
||||
? "aarch64-unknown-linux-gnu"
|
||||
: architecture === "x64"
|
||||
? "x86_64-unknown-linux-gnu"
|
||||
: undefined;
|
||||
}
|
||||
if (platform === "win32") {
|
||||
return architecture === "arm64"
|
||||
? "aarch64-pc-windows-msvc"
|
||||
: architecture === "x64"
|
||||
? "x86_64-pc-windows-msvc"
|
||||
: undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const architecture = yield* HostProcessArchitecture;
|
||||
const environment = yield* HostProcessEnvironment;
|
||||
const executableName = binaryName(platform);
|
||||
const platformKey = resourceMonitorPlatformKey(platform, architecture);
|
||||
const rustTarget = resourceMonitorRustTarget(platform, architecture);
|
||||
if (platformKey === undefined || rustTarget === undefined) {
|
||||
return ResourceMonitorBinary.of({
|
||||
resolve: Effect.fail(
|
||||
new ResourceMonitorBinaryUnsupported({
|
||||
platform,
|
||||
architecture,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
environment.T3CODE_RESOURCE_MONITOR_PATH,
|
||||
config.resourceMonitorPath,
|
||||
path.resolve(import.meta.dirname, "resource-monitor", platformKey, executableName),
|
||||
path.resolve(import.meta.dirname, "resource-monitor", executableName),
|
||||
path.resolve(import.meta.dirname, "../resource-monitor", executableName),
|
||||
path.resolve(
|
||||
import.meta.dirname,
|
||||
"../../../../native/resource-monitor/target",
|
||||
rustTarget,
|
||||
"release",
|
||||
executableName,
|
||||
),
|
||||
path.resolve(
|
||||
import.meta.dirname,
|
||||
"../../../native/resource-monitor/target",
|
||||
rustTarget,
|
||||
"release",
|
||||
executableName,
|
||||
),
|
||||
path.resolve(
|
||||
import.meta.dirname,
|
||||
"../../../../native/resource-monitor/target/release",
|
||||
executableName,
|
||||
),
|
||||
path.resolve(
|
||||
import.meta.dirname,
|
||||
"../../../../native/resource-monitor/target/debug",
|
||||
executableName,
|
||||
),
|
||||
].filter((candidate): candidate is string => Boolean(candidate));
|
||||
|
||||
const resolve: ResourceMonitorBinaryShape["resolve"] = Effect.gen(function* () {
|
||||
for (const candidate of candidates) {
|
||||
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) continue;
|
||||
|
||||
if (platform !== "win32") {
|
||||
const stat = yield* fileSystem.stat(candidate).pipe(Effect.option);
|
||||
if (Option.isSome(stat) && (stat.value.mode & 0o111) === 0) {
|
||||
return yield* new ResourceMonitorBinaryNotExecutable({
|
||||
path: candidate,
|
||||
mode: stat.value.mode,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
return yield* new ResourceMonitorBinaryNotFound({
|
||||
platform,
|
||||
architecture,
|
||||
candidates,
|
||||
});
|
||||
});
|
||||
|
||||
return ResourceMonitorBinary.of({ resolve });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ResourceMonitorBinary, make());
|
||||
@@ -0,0 +1,345 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorProcessSample,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "./DesktopTelemetryReceiver.ts";
|
||||
import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "./ResourceAttribution.ts";
|
||||
import * as ResourceTelemetry from "./ResourceTelemetry.ts";
|
||||
|
||||
function processSample(
|
||||
input: Partial<ResourceMonitorProcessSample> &
|
||||
Pick<ResourceMonitorProcessSample, "pid" | "ppid" | "startTimeMs">,
|
||||
): ResourceMonitorProcessSample {
|
||||
return {
|
||||
runTimeMs: 1_000,
|
||||
name: `process-${input.pid}`,
|
||||
command: `process-${input.pid}`,
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
cpuTimeMs: 0,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
ioSemantics: "storage",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function nativeSnapshot(input: {
|
||||
readonly sequence: number;
|
||||
readonly sampledAtUnixMs: number;
|
||||
readonly childCpuTimeMs: number;
|
||||
readonly childWriteBytes: number;
|
||||
}): ResourceMonitorSnapshotEvent {
|
||||
const processes = [
|
||||
processSample({
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
startTimeMs: 100,
|
||||
cpuTimeMs: input.sequence * 10,
|
||||
}),
|
||||
processSample({
|
||||
pid: 4_242,
|
||||
ppid: process.pid,
|
||||
startTimeMs: 200,
|
||||
name: "codex",
|
||||
command: "codex app-server",
|
||||
cpuTimeMs: input.childCpuTimeMs,
|
||||
ioWriteBytes: input.childWriteBytes,
|
||||
}),
|
||||
processSample({
|
||||
pid: 5_000,
|
||||
ppid: 1,
|
||||
startTimeMs: 300,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
cpuTimeMs: input.sequence * 20,
|
||||
}),
|
||||
processSample({
|
||||
pid: 9_000,
|
||||
ppid: process.pid,
|
||||
startTimeMs: 400,
|
||||
name: "t3-resource-monitor",
|
||||
command: "t3-resource-monitor",
|
||||
cpuTimeMs: input.sequence * 5,
|
||||
}),
|
||||
];
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: input.sequence,
|
||||
sampledAtUnixMs: input.sampledAtUnixMs,
|
||||
collectionDurationMicros: 300,
|
||||
scannedProcessCount: 80,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 1,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot {
|
||||
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
|
||||
return {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 5_000,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 2,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "true",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "fair",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.some(90),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: 5_000,
|
||||
creationTimeMs: 300,
|
||||
type: "Browser",
|
||||
name: "electron",
|
||||
cpuPercent: 2,
|
||||
cumulativeCpuSeconds: 0.02,
|
||||
idleWakeupsPerSecond: 3,
|
||||
workingSetBytes: 4_096,
|
||||
peakWorkingSetBytes: 8_192,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("ResourceTelemetry", () => {
|
||||
it.effect("enables live native and Electron collection only while changes are retained", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
const sample = nativeSnapshot({
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
childCpuTimeMs: 100,
|
||||
childWriteBytes: 1_000,
|
||||
});
|
||||
const demandChanges = yield* Ref.make<ReadonlyArray<boolean>>([]);
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
sampleNow: Effect.succeed(sample),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot(sampledAtUnixMs)),
|
||||
setDiagnosticsDemand: (enabled) =>
|
||||
Ref.update(demandChanges, (changes) => [...changes, enabled]),
|
||||
});
|
||||
const telemetryLayer = ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
|
||||
);
|
||||
|
||||
const live = yield* Stream.runHead(
|
||||
Effect.gen(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
return telemetry.changes;
|
||||
}).pipe(Stream.unwrap),
|
||||
).pipe(Effect.provide(telemetryLayer));
|
||||
|
||||
expect(Option.isSome(live)).toBe(true);
|
||||
expect(yield* Ref.get(demandChanges)).toEqual([true, false]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("combines native, Electron, attribution, retry, and history data", () =>
|
||||
Effect.gen(function* () {
|
||||
const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
const samples = [
|
||||
nativeSnapshot({
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: startedAt,
|
||||
childCpuTimeMs: 100,
|
||||
childWriteBytes: 1_000,
|
||||
}),
|
||||
nativeSnapshot({
|
||||
sequence: 2,
|
||||
sampledAtUnixMs: startedAt + 1_000,
|
||||
childCpuTimeMs: 350,
|
||||
childWriteBytes: 5_000,
|
||||
}),
|
||||
nativeSnapshot({
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: startedAt + 2_000,
|
||||
childCpuTimeMs: 500,
|
||||
childWriteBytes: 7_000,
|
||||
}),
|
||||
] as const;
|
||||
const sampleIndex = yield* Ref.make(0);
|
||||
const externalProcesses = yield* Ref.make<
|
||||
ReadonlyArray<{ readonly pid: number; readonly startTimeMs?: number }>
|
||||
>([]);
|
||||
const retryCount = yield* Ref.make(0);
|
||||
const nativeHealth = yield* Ref.make<NativeTelemetryClient.NativeTelemetryClientHealth>({
|
||||
status: "healthy",
|
||||
hello: Option.some({
|
||||
version: 2,
|
||||
type: "hello",
|
||||
sidecarVersion: "0.1.0",
|
||||
sidecarPid: 9_000,
|
||||
platform: "test",
|
||||
arch: "test",
|
||||
capabilities: {
|
||||
cumulativeCpuTime: true,
|
||||
currentCpuPercent: true,
|
||||
residentMemory: true,
|
||||
virtualMemory: true,
|
||||
ioBytes: true,
|
||||
processStartTime: true,
|
||||
processTree: true,
|
||||
},
|
||||
}),
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(startedAt)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 2,
|
||||
sampleIntervalMs: 1_000,
|
||||
});
|
||||
const nativeHealthChanges =
|
||||
yield* PubSub.sliding<NativeTelemetryClient.NativeTelemetryClientHealth>(4);
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
setExternalProcesses: (processes) => Ref.set(externalProcesses, processes),
|
||||
readHistory: () => Effect.succeed(samples.slice(0, 2)),
|
||||
sampleNow: Ref.modify(sampleIndex, (index) => [
|
||||
samples[Math.min(index, samples.length - 1)]!,
|
||||
index + 1,
|
||||
]),
|
||||
retry: Ref.updateAndGet(retryCount, (count) => count + 1).pipe(Effect.as(true)),
|
||||
health: Ref.get(nativeHealth),
|
||||
healthChanges: Stream.fromPubSub(nativeHealthChanges),
|
||||
});
|
||||
const desktopLayer = DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot(startedAt)),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(startedAt)),
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
});
|
||||
const attributionLayer = ResourceAttribution.layer;
|
||||
const dependencies = Layer.mergeAll(nativeLayer, desktopLayer, attributionLayer);
|
||||
const telemetryLayer = ResourceTelemetry.layer.pipe(Layer.provide(dependencies));
|
||||
const layer = Layer.mergeAll(dependencies, telemetryLayer);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
|
||||
expect(yield* Ref.get(externalProcesses)).toEqual([{ pid: 5_000 }]);
|
||||
|
||||
yield* attribution.record({
|
||||
component: "provider-event-log",
|
||||
operation: "append",
|
||||
logicalWriteBytes: 512,
|
||||
count: 2,
|
||||
durationMs: 4,
|
||||
});
|
||||
const first = yield* telemetry.refresh;
|
||||
expect(first.groups.backend.processCount).toBe(2);
|
||||
expect(first.groups.electron.processCount).toBe(1);
|
||||
expect(first.groups.monitor.processCount).toBe(1);
|
||||
expect(first.power.onBattery).toBe("true");
|
||||
expect(Option.getOrNull(first.speedLimitPercent)).toBe(90);
|
||||
expect(first.attribution.entries).toEqual([
|
||||
{
|
||||
component: "provider-event-log",
|
||||
operation: "append",
|
||||
logicalReadBytes: 0,
|
||||
logicalWriteBytes: 512,
|
||||
count: 2,
|
||||
durationMs: 4,
|
||||
},
|
||||
]);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
const second = yield* telemetry.refresh;
|
||||
const codex = second.processes.find((entry) => entry.identity.pid === 4_242);
|
||||
expect(codex?.cpuPercent).toBe(25);
|
||||
expect(codex?.ioWriteBytesPerSecond).toBe(4_000);
|
||||
expect(second.groups.backend.ioWriteBytes).toBe(4_000);
|
||||
expect(second.health.collectionDurationMicros).toBe(300);
|
||||
expect(second.health.scannedProcessCount).toBe(80);
|
||||
expect(second.health.inaccessibleProcessCount).toBe(1);
|
||||
|
||||
const history = yield* telemetry.readHistory({
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
});
|
||||
expect(history.retainedSampleCount).toBeGreaterThan(0);
|
||||
expect(
|
||||
history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.sampleCount,
|
||||
).toBe(2);
|
||||
expect(history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.cpuTimeMs).toBe(
|
||||
250,
|
||||
);
|
||||
expect(
|
||||
history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.ioWriteBytes,
|
||||
).toBe(4_000);
|
||||
expect(history.buckets.reduce((total, bucket) => total + bucket.ioWriteBytes, 0)).toBe(
|
||||
4_000,
|
||||
);
|
||||
|
||||
const retry = yield* telemetry.retry;
|
||||
expect(retry.accepted).toBe(true);
|
||||
expect(yield* Ref.get(retryCount)).toBe(1);
|
||||
|
||||
yield* Ref.update(nativeHealth, (current) => ({
|
||||
...current,
|
||||
hello: Option.map(current.hello, (hello) => ({
|
||||
...hello,
|
||||
sidecarPid: 9_001,
|
||||
})),
|
||||
restartCount: 3,
|
||||
}));
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
const restarted = yield* telemetry.refresh;
|
||||
expect(DateTime.toEpochMillis(restarted.readAt)).toBe(startedAt + 2_000);
|
||||
expect(Option.getOrNull(restarted.health.sidecarPid)).toBe(9_001);
|
||||
|
||||
yield* Ref.update(nativeHealth, (current) => ({
|
||||
...current,
|
||||
status: "degraded" as const,
|
||||
lastError: Option.some("collector exited"),
|
||||
}));
|
||||
yield* PubSub.publish(nativeHealthChanges, yield* Ref.get(nativeHealth));
|
||||
yield* Effect.yieldNow;
|
||||
const healthUpdate = yield* telemetry.latest;
|
||||
expect(healthUpdate.health.native.status).toBe("degraded");
|
||||
expect(Option.getOrNull(healthUpdate.health.native.lastError)).toBe("collector exited");
|
||||
const degradedHistory = yield* telemetry.readHistory({
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
});
|
||||
expect(degradedHistory.health.native.status).toBe("degraded");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,453 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
HostPowerSnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryHealth,
|
||||
ResourceTelemetryHistory,
|
||||
ResourceTelemetryHistoryInput,
|
||||
ResourceTelemetryProcessIdentity,
|
||||
ResourceTelemetryRetryResult,
|
||||
ResourceTelemetrySnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
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 Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "./DesktopTelemetryReceiver.ts";
|
||||
import {
|
||||
emptyTelemetryCounters,
|
||||
mergeProcesses,
|
||||
type ProcessState,
|
||||
type TelemetryCounters,
|
||||
} from "./Model.ts";
|
||||
import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "./ResourceAttribution.ts";
|
||||
import {
|
||||
buildResourceTelemetryHistory,
|
||||
normalizeResourceTelemetryHistoryInput,
|
||||
} from "./ResourceTelemetryHistory.ts";
|
||||
|
||||
export class ResourceTelemetryRefreshFailed extends Schema.TaggedErrorClass<ResourceTelemetryRefreshFailed>()(
|
||||
"ResourceTelemetryRefreshFailed",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Resource telemetry operation '${this.operation}' failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ResourceTelemetryShape {
|
||||
readonly latest: Effect.Effect<ResourceTelemetrySnapshot>;
|
||||
readonly changes: Stream.Stream<ResourceTelemetrySnapshot>;
|
||||
readonly readHistory: (
|
||||
input: ResourceTelemetryHistoryInput,
|
||||
) => Effect.Effect<ResourceTelemetryHistory>;
|
||||
readonly refresh: Effect.Effect<ResourceTelemetrySnapshot, ResourceTelemetryRefreshFailed>;
|
||||
readonly validateProcessIdentity: (
|
||||
identity: ResourceTelemetryProcessIdentity,
|
||||
) => Effect.Effect<boolean, ResourceTelemetryRefreshFailed>;
|
||||
readonly retry: Effect.Effect<ResourceTelemetryRetryResult>;
|
||||
}
|
||||
|
||||
export class ResourceTelemetry extends Context.Service<ResourceTelemetry, ResourceTelemetryShape>()(
|
||||
"t3/resourceTelemetry/ResourceTelemetry",
|
||||
) {}
|
||||
|
||||
interface TelemetryState {
|
||||
readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
|
||||
readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
|
||||
readonly previous: ReadonlyMap<string, ProcessState>;
|
||||
readonly counters: TelemetryCounters;
|
||||
readonly latest: ResourceTelemetrySnapshot;
|
||||
readonly lastNativeSequence: number;
|
||||
readonly lastNativeRestartCount: number;
|
||||
}
|
||||
|
||||
interface LiveTelemetryState {
|
||||
readonly retainCount: number;
|
||||
readonly scope: Option.Option<Scope.Closeable>;
|
||||
}
|
||||
|
||||
function unknownPower(updatedAt: DateTime.Utc): HostPowerSnapshot {
|
||||
return {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function buildHealth(input: {
|
||||
readonly native: NativeTelemetryClient.NativeTelemetryClientHealth;
|
||||
readonly desktop: DesktopTelemetryReceiver.DesktopTelemetryReceiverHealth;
|
||||
readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
|
||||
}): ResourceTelemetryHealth {
|
||||
return {
|
||||
native: {
|
||||
status: input.native.status,
|
||||
lastSampleAt: input.native.lastSampleAt,
|
||||
lastError: input.native.lastError,
|
||||
},
|
||||
desktop: {
|
||||
status: input.desktop.status,
|
||||
lastSampleAt: input.desktop.lastSampleAt,
|
||||
lastError: input.desktop.lastError,
|
||||
},
|
||||
sidecarVersion: Option.map(input.native.hello, (hello) => hello.sidecarVersion),
|
||||
sidecarPid: Option.map(input.native.hello, (hello) => hello.sidecarPid),
|
||||
restartCount: input.native.restartCount,
|
||||
collectionDurationMicros: Option.match(input.nativeSnapshot, {
|
||||
onNone: () => 0,
|
||||
onSome: (snapshot) => snapshot.collectionDurationMicros,
|
||||
}),
|
||||
scannedProcessCount: Option.match(input.nativeSnapshot, {
|
||||
onNone: () => 0,
|
||||
onSome: (snapshot) => snapshot.scannedProcessCount,
|
||||
}),
|
||||
retainedProcessCount: Option.match(input.nativeSnapshot, {
|
||||
onNone: () => 0,
|
||||
onSome: (snapshot) => snapshot.retainedProcessCount,
|
||||
}),
|
||||
inaccessibleProcessCount: Option.match(input.nativeSnapshot, {
|
||||
onNone: () => 0,
|
||||
onSome: (snapshot) => snapshot.inaccessibleProcessCount,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(function* () {
|
||||
const nativeClient = yield* NativeTelemetryClient.NativeTelemetryClient;
|
||||
const desktopReceiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
const changes = yield* PubSub.sliding<ResourceTelemetrySnapshot>(8);
|
||||
const initialReadAt = yield* DateTime.now;
|
||||
const initialDesktop = yield* desktopReceiver.latest;
|
||||
if (Option.isSome(initialDesktop)) {
|
||||
yield* nativeClient
|
||||
.setExternalProcesses([{ pid: initialDesktop.value.electronPid }])
|
||||
.pipe(Effect.ignore);
|
||||
yield* nativeClient.setHostPowerState(initialDesktop.value.power).pipe(Effect.ignore);
|
||||
}
|
||||
const [initialNativeHealth, initialDesktopHealth, initialAttribution] = yield* Effect.all([
|
||||
nativeClient.health,
|
||||
desktopReceiver.health,
|
||||
attribution.snapshot,
|
||||
]);
|
||||
const initialMerge = mergeProcesses({
|
||||
serverPid: process.pid,
|
||||
sidecarPid: Option.map(initialNativeHealth.hello, (hello) => hello.sidecarPid),
|
||||
fallbackSampledAtMs: DateTime.toEpochMillis(initialReadAt),
|
||||
nativeSnapshot: Option.none(),
|
||||
desktopSnapshot: initialDesktop,
|
||||
previous: new Map(),
|
||||
counters: emptyTelemetryCounters(),
|
||||
updatePrevious: false,
|
||||
});
|
||||
const initialSnapshot: ResourceTelemetrySnapshot = {
|
||||
readAt: initialReadAt,
|
||||
sampleIntervalMs: initialNativeHealth.sampleIntervalMs,
|
||||
processes: initialMerge.processes,
|
||||
groups: initialMerge.groups,
|
||||
power: Option.match(initialDesktop, {
|
||||
onNone: () => unknownPower(initialReadAt),
|
||||
onSome: (desktop) => desktop.power,
|
||||
}),
|
||||
speedLimitPercent: Option.flatMap(initialDesktop, (desktop) => desktop.speedLimitPercent),
|
||||
attribution: initialAttribution,
|
||||
health: buildHealth({
|
||||
native: initialNativeHealth,
|
||||
desktop: initialDesktopHealth,
|
||||
nativeSnapshot: Option.none(),
|
||||
}),
|
||||
};
|
||||
const state = yield* Ref.make<TelemetryState>({
|
||||
nativeSnapshot: Option.none(),
|
||||
desktopSnapshot: initialDesktop,
|
||||
previous: new Map(),
|
||||
counters: emptyTelemetryCounters(),
|
||||
latest: initialSnapshot,
|
||||
lastNativeSequence: 0,
|
||||
lastNativeRestartCount: initialNativeHealth.restartCount,
|
||||
});
|
||||
const liveState = yield* Ref.make<LiveTelemetryState>({
|
||||
retainCount: 0,
|
||||
scope: Option.none(),
|
||||
});
|
||||
const liveMutex = yield* Semaphore.make(1);
|
||||
const refreshHealth = mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
const [nativeHealth, desktopHealth] = yield* Effect.all([
|
||||
nativeClient.health,
|
||||
desktopReceiver.health,
|
||||
]);
|
||||
const snapshot: ResourceTelemetrySnapshot = {
|
||||
...current.latest,
|
||||
health: buildHealth({
|
||||
native: nativeHealth,
|
||||
desktop: desktopHealth,
|
||||
nativeSnapshot: current.nativeSnapshot,
|
||||
}),
|
||||
};
|
||||
yield* Ref.set(state, {
|
||||
...current,
|
||||
latest: snapshot,
|
||||
});
|
||||
if ((yield* Ref.get(liveState)).retainCount > 0) {
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const rebuild = (input: {
|
||||
readonly nativeSnapshot?: ResourceMonitorSnapshotEvent;
|
||||
readonly desktopSnapshot?: DesktopHostTelemetrySnapshot;
|
||||
readonly updatePrevious: boolean;
|
||||
readonly publish?: boolean;
|
||||
}): Effect.Effect<ResourceTelemetrySnapshot> =>
|
||||
mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
const nativeHealth = yield* nativeClient.health;
|
||||
const nativeGenerationChanged =
|
||||
nativeHealth.restartCount !== current.lastNativeRestartCount;
|
||||
if (
|
||||
input.nativeSnapshot &&
|
||||
!nativeGenerationChanged &&
|
||||
input.nativeSnapshot.sequence <= current.lastNativeSequence
|
||||
) {
|
||||
return current.latest;
|
||||
}
|
||||
const nativeSnapshot = input.nativeSnapshot
|
||||
? Option.some(input.nativeSnapshot)
|
||||
: current.nativeSnapshot;
|
||||
const desktopSnapshot = input.desktopSnapshot
|
||||
? Option.some(input.desktopSnapshot)
|
||||
: current.desktopSnapshot;
|
||||
const [desktopHealth, attributionSnapshot] = yield* Effect.all([
|
||||
desktopReceiver.health,
|
||||
attribution.snapshot,
|
||||
]);
|
||||
const merged = mergeProcesses({
|
||||
serverPid: process.pid,
|
||||
sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
|
||||
fallbackSampledAtMs: DateTime.toEpochMillis(current.latest.readAt),
|
||||
nativeSnapshot,
|
||||
desktopSnapshot,
|
||||
electronRootPids: Option.match(desktopSnapshot, {
|
||||
onNone: () => new Set<number>(),
|
||||
onSome: (desktop) => new Set([desktop.electronPid]),
|
||||
}),
|
||||
previous: current.previous,
|
||||
counters: current.counters,
|
||||
updatePrevious: input.updatePrevious,
|
||||
});
|
||||
const readAt = DateTime.makeUnsafe(merged.sampledAtMs);
|
||||
const snapshot: ResourceTelemetrySnapshot = {
|
||||
readAt,
|
||||
sampleIntervalMs: nativeHealth.sampleIntervalMs,
|
||||
processes: merged.processes,
|
||||
groups: merged.groups,
|
||||
power: Option.match(desktopSnapshot, {
|
||||
onNone: () => unknownPower(readAt),
|
||||
onSome: (desktop) => desktop.power,
|
||||
}),
|
||||
speedLimitPercent: Option.match(desktopSnapshot, {
|
||||
onNone: () => Option.none(),
|
||||
onSome: (desktop) => desktop.speedLimitPercent,
|
||||
}),
|
||||
attribution: attributionSnapshot,
|
||||
health: buildHealth({
|
||||
native: nativeHealth,
|
||||
desktop: desktopHealth,
|
||||
nativeSnapshot,
|
||||
}),
|
||||
};
|
||||
yield* Ref.set(state, {
|
||||
nativeSnapshot,
|
||||
desktopSnapshot,
|
||||
previous: merged.previous,
|
||||
counters: merged.counters,
|
||||
latest: snapshot,
|
||||
lastNativeSequence: input.nativeSnapshot?.sequence ?? current.lastNativeSequence,
|
||||
lastNativeRestartCount: input.nativeSnapshot
|
||||
? nativeHealth.restartCount
|
||||
: current.lastNativeRestartCount,
|
||||
});
|
||||
if (input.publish !== false) {
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}
|
||||
return snapshot;
|
||||
}),
|
||||
);
|
||||
|
||||
const ingestNative = (snapshot: ResourceMonitorSnapshotEvent) =>
|
||||
rebuild({ nativeSnapshot: snapshot, updatePrevious: true });
|
||||
const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>
|
||||
Effect.gen(function* () {
|
||||
yield* nativeClient.setExternalProcesses([{ pid: snapshot.electronPid }]).pipe(Effect.ignore);
|
||||
yield* nativeClient.setHostPowerState(snapshot.power).pipe(Effect.ignore);
|
||||
const live = (yield* Ref.get(liveState)).retainCount > 0;
|
||||
return yield* rebuild({ desktopSnapshot: snapshot, updatePrevious: false, publish: live });
|
||||
});
|
||||
|
||||
yield* desktopReceiver.changes.pipe(
|
||||
Stream.runForEach((snapshot) => ingestDesktop(snapshot)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const acquireLive = liveMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(liveState);
|
||||
if (current.retainCount > 0) {
|
||||
yield* Ref.set(liveState, { ...current, retainCount: current.retainCount + 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
const scope = yield* Scope.make();
|
||||
yield* Ref.set(liveState, { retainCount: 1, scope: Option.some(scope) });
|
||||
yield* desktopReceiver.setDiagnosticsDemand(true).pipe(Effect.ignore);
|
||||
yield* nativeClient.snapshots.pipe(
|
||||
Stream.runForEach(ingestNative),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Native resource telemetry stream stopped", {
|
||||
cause: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.forkIn(scope),
|
||||
);
|
||||
yield* nativeClient.sampleNow.pipe(Effect.flatMap(ingestNative), Effect.ignore);
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseLive = liveMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(liveState);
|
||||
if (current.retainCount <= 1) {
|
||||
yield* Ref.set(liveState, { retainCount: 0, scope: Option.none() });
|
||||
if (Option.isSome(current.scope)) {
|
||||
yield* Scope.close(current.scope.value, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
yield* desktopReceiver.setDiagnosticsDemand(false).pipe(Effect.ignore);
|
||||
return;
|
||||
}
|
||||
yield* Ref.set(liveState, { ...current, retainCount: current.retainCount - 1 });
|
||||
}),
|
||||
);
|
||||
|
||||
const liveChanges = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(changes);
|
||||
yield* Effect.acquireRelease(acquireLive, () => releaseLive);
|
||||
return Stream.fromSubscription(subscription);
|
||||
}),
|
||||
);
|
||||
|
||||
const readHistory: ResourceTelemetryShape["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const normalizedInput = normalizeResourceTelemetryHistoryInput(input);
|
||||
const historyResult = yield* Effect.result(
|
||||
nativeClient.readHistory(normalizedInput.windowMs),
|
||||
);
|
||||
if (Result.isFailure(historyResult)) {
|
||||
yield* Effect.logWarning("Failed to read native resource telemetry history", {
|
||||
cause: historyResult.failure.message,
|
||||
});
|
||||
}
|
||||
const [nativeHealth, desktopHealth] = yield* Effect.all([
|
||||
nativeClient.health,
|
||||
desktopReceiver.health,
|
||||
]);
|
||||
const current = yield* Ref.get(state);
|
||||
return buildResourceTelemetryHistory({
|
||||
readAt,
|
||||
windowMs: normalizedInput.windowMs,
|
||||
bucketMs: normalizedInput.bucketMs,
|
||||
sampleIntervalMs: nativeHealth.sampleIntervalMs,
|
||||
serverPid: process.pid,
|
||||
sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
|
||||
desktopSnapshot: current.desktopSnapshot,
|
||||
snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],
|
||||
health: buildHealth({
|
||||
native: nativeHealth,
|
||||
desktop: desktopHealth,
|
||||
nativeSnapshot: current.nativeSnapshot,
|
||||
}),
|
||||
});
|
||||
});
|
||||
yield* nativeClient.healthChanges.pipe(
|
||||
Stream.runForEach(() => refreshHealth),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* desktopReceiver.healthChanges.pipe(
|
||||
Stream.runForEach(() => refreshHealth),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const refresh: ResourceTelemetryShape["refresh"] = nativeClient.sampleNow.pipe(
|
||||
Effect.flatMap(ingestNative),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ResourceTelemetryRefreshFailed({
|
||||
operation: "refresh",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const validateProcessIdentity: ResourceTelemetryShape["validateProcessIdentity"] = (identity) =>
|
||||
nativeClient.sampleNow.pipe(
|
||||
Effect.map((snapshot) =>
|
||||
snapshot.processes.some(
|
||||
(process) => process.pid === identity.pid && process.startTimeMs === identity.startTimeMs,
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ResourceTelemetryRefreshFailed({
|
||||
operation: "validateProcessIdentity",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return ResourceTelemetry.of({
|
||||
latest: Ref.get(state).pipe(Effect.map((current) => current.latest)),
|
||||
changes: liveChanges,
|
||||
readHistory,
|
||||
refresh,
|
||||
validateProcessIdentity,
|
||||
retry: nativeClient.retry.pipe(
|
||||
Effect.zip(Ref.get(state)),
|
||||
Effect.map(
|
||||
([accepted, current]): ResourceTelemetryRetryResult => ({
|
||||
accepted,
|
||||
snapshot: current.latest,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ResourceTelemetry, make());
|
||||
@@ -0,0 +1,167 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorProcessSample,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryHealth,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
buildResourceTelemetryHistory,
|
||||
normalizeResourceTelemetryHistoryInput,
|
||||
} from "./ResourceTelemetryHistory.ts";
|
||||
|
||||
const SERVER_PID = 100;
|
||||
const ELECTRON_PID = 200;
|
||||
const CHILD_PID = 300;
|
||||
const STARTED_AT_MS = DateTime.toEpochMillis(DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"));
|
||||
|
||||
function processSample(
|
||||
input: Partial<ResourceMonitorProcessSample> &
|
||||
Pick<ResourceMonitorProcessSample, "pid" | "ppid" | "startTimeMs">,
|
||||
): ResourceMonitorProcessSample {
|
||||
return {
|
||||
runTimeMs: 1_000,
|
||||
name: `process-${input.pid}`,
|
||||
command: `process-${input.pid}`,
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
cpuTimeMs: 0,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 0,
|
||||
ioWriteBytes: 0,
|
||||
ioSemantics: "storage",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(
|
||||
sequence: number,
|
||||
sampledAtUnixMs: number,
|
||||
childCpuTimeMs: number,
|
||||
childWriteBytes: number,
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
const processes = [
|
||||
processSample({ pid: SERVER_PID, ppid: 1, startTimeMs: 10 }),
|
||||
processSample({
|
||||
pid: ELECTRON_PID,
|
||||
ppid: 1,
|
||||
startTimeMs: 20,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
}),
|
||||
processSample({
|
||||
pid: CHILD_PID,
|
||||
ppid: SERVER_PID,
|
||||
startTimeMs: 30,
|
||||
name: "codex",
|
||||
command: "codex app-server",
|
||||
cpuTimeMs: childCpuTimeMs,
|
||||
ioWriteBytes: childWriteBytes,
|
||||
}),
|
||||
];
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence,
|
||||
sampledAtUnixMs,
|
||||
collectionDurationMicros: 100,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
const health: ResourceTelemetryHealth = {
|
||||
native: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
desktop: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.none(),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
sidecarVersion: Option.some("0.1.0"),
|
||||
sidecarPid: Option.some(400),
|
||||
restartCount: 0,
|
||||
collectionDurationMicros: 100,
|
||||
scannedProcessCount: 3,
|
||||
retainedProcessCount: 3,
|
||||
inaccessibleProcessCount: 0,
|
||||
};
|
||||
|
||||
function desktopSnapshot(): DesktopHostTelemetrySnapshot {
|
||||
const sampledAt = DateTime.makeUnsafe(STARTED_AT_MS + 1_000);
|
||||
return {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: STARTED_AT_MS + 1_000,
|
||||
electronPid: ELECTRON_PID,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: ELECTRON_PID,
|
||||
creationTimeMs: 20,
|
||||
type: "Browser",
|
||||
cpuPercent: 999,
|
||||
idleWakeupsPerSecond: 999,
|
||||
workingSetBytes: 999_999,
|
||||
peakWorkingSetBytes: 999_999,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildResourceTelemetryHistory", () => {
|
||||
it("normalizes query bounds before requesting native history", () => {
|
||||
expect(normalizeResourceTelemetryHistoryInput({ windowMs: 0, bucketMs: 0 })).toEqual({
|
||||
windowMs: 1_000,
|
||||
bucketMs: 1_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("replays native snapshots on demand without applying current Electron metrics", () => {
|
||||
const history = buildResourceTelemetryHistory({
|
||||
readAt: DateTime.makeUnsafe(STARTED_AT_MS + 2_000),
|
||||
windowMs: 10_000,
|
||||
bucketMs: 10_000,
|
||||
sampleIntervalMs: 1_000,
|
||||
serverPid: SERVER_PID,
|
||||
sidecarPid: Option.some(400),
|
||||
desktopSnapshot: Option.some(desktopSnapshot()),
|
||||
snapshots: [
|
||||
snapshot(1, STARTED_AT_MS, 100, 1_000),
|
||||
snapshot(2, STARTED_AT_MS + 1_000, 350, 5_000),
|
||||
],
|
||||
health,
|
||||
});
|
||||
|
||||
const child = history.topProcesses.find((process) => process.identity.pid === CHILD_PID);
|
||||
const electron = history.topProcesses.find((process) => process.identity.pid === ELECTRON_PID);
|
||||
expect(child?.sampleCount).toBe(2);
|
||||
expect(child?.cpuTimeMs).toBe(250);
|
||||
expect(child?.ioWriteBytes).toBe(4_000);
|
||||
expect(electron?.category).toBe("electron-main");
|
||||
expect(electron?.currentRssBytes).toBe(1_024);
|
||||
expect(history.buckets.reduce((total, bucket) => total + bucket.ioWriteBytes, 0)).toBe(4_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
ResourceTelemetryHealth,
|
||||
ResourceTelemetryHistory,
|
||||
ResourceTelemetryHistoryBucket,
|
||||
ResourceTelemetryProcess,
|
||||
ResourceTelemetryProcessSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
emptyTelemetryCounters,
|
||||
mergeProcesses,
|
||||
processIdentityKey,
|
||||
type ProcessState,
|
||||
type TelemetryCounters,
|
||||
} from "./Model.ts";
|
||||
|
||||
const MAX_HISTORY_WINDOW_MS = 60 * 60_000;
|
||||
|
||||
export function normalizeResourceTelemetryHistoryInput(input: {
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): { readonly windowMs: number; readonly bucketMs: number } {
|
||||
const windowMs = Math.max(1_000, Math.min(MAX_HISTORY_WINDOW_MS, input.windowMs));
|
||||
return {
|
||||
windowMs,
|
||||
bucketMs: Math.max(1_000, Math.min(windowMs, input.bucketMs)),
|
||||
};
|
||||
}
|
||||
|
||||
interface AggregateSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly processCount: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
interface ProcessSample {
|
||||
readonly sampledAtMs: number;
|
||||
readonly process: ResourceTelemetryProcess;
|
||||
readonly cpuTimeMs: number;
|
||||
readonly ioReadBytes: number;
|
||||
readonly ioWriteBytes: number;
|
||||
}
|
||||
|
||||
export interface BuildResourceTelemetryHistoryInput {
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly sampleIntervalMs: number;
|
||||
readonly serverPid: number;
|
||||
readonly sidecarPid: Option.Option<number>;
|
||||
readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
|
||||
readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
|
||||
readonly health: ResourceTelemetryHealth;
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessSample>,
|
||||
): ReadonlyArray<ResourceTelemetryProcessSummary> {
|
||||
const groups = new Map<string, ProcessSample[]>();
|
||||
for (const sample of samples) {
|
||||
const identityKey = processIdentityKey(
|
||||
sample.process.identity.pid,
|
||||
sample.process.identity.startTimeMs,
|
||||
);
|
||||
const current = groups.get(identityKey) ?? [];
|
||||
current.push(sample);
|
||||
groups.set(identityKey, current);
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((processSamples): ResourceTelemetryProcessSummary => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuTotal = sorted.reduce((total, sample) => total + sample.process.cpuPercent, 0);
|
||||
return {
|
||||
identity: latest.process.identity,
|
||||
ppid: latest.process.ppid,
|
||||
depth: latest.process.depth,
|
||||
name: latest.process.name,
|
||||
command: latest.process.command,
|
||||
category: latest.process.category,
|
||||
firstSeenAt: first.process.firstSeenAt,
|
||||
lastSeenAt: latest.process.lastSeenAt,
|
||||
currentCpuPercent: latest.process.cpuPercent,
|
||||
avgCpuPercent: cpuTotal / sorted.length,
|
||||
maxCpuPercent: Math.max(...sorted.map((sample) => sample.process.cpuPercent)),
|
||||
cpuTimeMs: sorted.reduce((total, sample) => total + sample.cpuTimeMs, 0),
|
||||
currentRssBytes: latest.process.residentBytes,
|
||||
peakRssBytes: Math.max(...sorted.map((sample) => sample.process.peakResidentBytes)),
|
||||
ioReadBytes: sorted.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: sorted.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
ioSemantics: latest.process.ioSemantics,
|
||||
sampleCount: sorted.length,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
(left, right) => right.cpuTimeMs - left.cpuTimeMs || right.peakRssBytes - left.peakRssBytes,
|
||||
);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<AggregateSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ResourceTelemetryHistoryBucket> {
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ResourceTelemetryHistoryBucket[] = [];
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);
|
||||
const samples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
buckets.push({
|
||||
startedAt: DateTime.makeUnsafe(startedAtMs),
|
||||
endedAt: DateTime.makeUnsafe(endedAtMs),
|
||||
avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,
|
||||
maxCpuPercent:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),
|
||||
maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),
|
||||
ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),
|
||||
ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),
|
||||
maxProcessCount:
|
||||
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),
|
||||
});
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function buildResourceTelemetryHistory(
|
||||
input: BuildResourceTelemetryHistoryInput,
|
||||
): ResourceTelemetryHistory {
|
||||
const readAtMs = DateTime.toEpochMillis(input.readAt);
|
||||
const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);
|
||||
const windowStartMs = readAtMs - windowMs;
|
||||
const snapshots = input.snapshots
|
||||
.filter((snapshot) => snapshot.sampledAtUnixMs >= windowStartMs)
|
||||
.toSorted((left, right) => left.sampledAtUnixMs - right.sampledAtUnixMs);
|
||||
const electronRootPids = Option.match(input.desktopSnapshot, {
|
||||
onNone: () => new Set<number>(),
|
||||
onSome: (snapshot) => new Set([snapshot.electronPid]),
|
||||
});
|
||||
const desktopIdentity = Option.map(input.desktopSnapshot, (snapshot) => ({
|
||||
...snapshot,
|
||||
electronProcesses: [],
|
||||
}));
|
||||
const aggregateSamples: AggregateSample[] = [];
|
||||
const processSamples: ProcessSample[] = [];
|
||||
let previous: ReadonlyMap<string, ProcessState> = new Map();
|
||||
let counters: TelemetryCounters = emptyTelemetryCounters();
|
||||
|
||||
for (const snapshot of snapshots) {
|
||||
const merged = mergeProcesses({
|
||||
serverPid: input.serverPid,
|
||||
sidecarPid: input.sidecarPid,
|
||||
fallbackSampledAtMs: snapshot.sampledAtUnixMs,
|
||||
nativeSnapshot: Option.some(snapshot),
|
||||
desktopSnapshot: desktopIdentity,
|
||||
electronRootPids,
|
||||
previous,
|
||||
counters,
|
||||
updatePrevious: true,
|
||||
});
|
||||
previous = merged.previous;
|
||||
counters = merged.counters;
|
||||
const deltasByIdentity = new Map(
|
||||
merged.deltas.map((processDelta) => [processDelta.identityKey, processDelta]),
|
||||
);
|
||||
aggregateSamples.push({
|
||||
sampledAtMs: snapshot.sampledAtUnixMs,
|
||||
cpuPercent: merged.groups.allT3.currentCpuPercent,
|
||||
rssBytes: merged.groups.allT3.currentRssBytes,
|
||||
processCount: merged.groups.allT3.processCount,
|
||||
ioReadBytes: merged.deltas.reduce((total, process) => total + process.ioReadBytes, 0),
|
||||
ioWriteBytes: merged.deltas.reduce((total, process) => total + process.ioWriteBytes, 0),
|
||||
});
|
||||
for (const process of merged.processes) {
|
||||
const processDelta = deltasByIdentity.get(
|
||||
processIdentityKey(process.identity.pid, process.identity.startTimeMs),
|
||||
);
|
||||
processSamples.push({
|
||||
sampledAtMs: snapshot.sampledAtUnixMs,
|
||||
process,
|
||||
cpuTimeMs: processDelta?.cpuTimeMs ?? 0,
|
||||
ioReadBytes: processDelta?.ioReadBytes ?? 0,
|
||||
ioWriteBytes: processDelta?.ioWriteBytes ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: input.sampleIntervalMs,
|
||||
retainedSampleCount: aggregateSamples.length + processSamples.length,
|
||||
buckets: buildBuckets({ samples: aggregateSamples, nowMs: readAtMs, windowMs, bucketMs }),
|
||||
topProcesses: summarizeProcesses(processSamples),
|
||||
health: input.health,
|
||||
};
|
||||
}
|
||||
@@ -70,6 +70,7 @@ import { vi } from "vite-plus/test";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
|
||||
@@ -112,6 +113,10 @@ import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
const defaultProjectId = ProjectId.make("project-default");
|
||||
@@ -347,6 +352,10 @@ const buildAppUnderTest = (options?: {
|
||||
>;
|
||||
relayClient?: Partial<RelayClient.RelayClient["Service"]>;
|
||||
cloudCliTokenManager?: Partial<CloudCliTokenManager.CloudCliTokenManager["Service"]>;
|
||||
nativeTelemetryClient?: Partial<NativeTelemetryClient.NativeTelemetryClient["Service"]>;
|
||||
desktopTelemetryReceiver?: Partial<
|
||||
DesktopTelemetryReceiver.DesktopTelemetryReceiver["Service"]
|
||||
>;
|
||||
};
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -519,6 +528,15 @@ const buildAppUnderTest = (options?: {
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
})
|
||||
: VcsStatusBroadcaster.layer.pipe(Layer.provide(gitWorkflowLayer));
|
||||
const resourceTelemetryLayer = ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NativeTelemetryClient.layerTest(options?.layers?.nativeTelemetryClient),
|
||||
DesktopTelemetryReceiver.layerTest(options?.layers?.desktopTelemetryReceiver),
|
||||
ResourceAttribution.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -653,7 +671,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(PreviewManager.PreviewManager)({
|
||||
open: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
resize: () => Effect.die("PreviewManager not stubbed in this test"),
|
||||
reportStatus: () => Effect.void,
|
||||
refresh: () => Effect.void,
|
||||
close: () => Effect.void,
|
||||
@@ -731,6 +748,7 @@ const buildAppUnderTest = (options?: {
|
||||
);
|
||||
|
||||
const appLayer = servedRoutesLayer.pipe(
|
||||
Layer.provide(resourceTelemetryLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({
|
||||
record: () => Effect.void,
|
||||
@@ -753,6 +771,36 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.serverRuntimeStartup,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: false,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(false),
|
||||
shouldRunScopeWork: () => Effect.succeed(false),
|
||||
shouldRunOpportunisticWork: Effect.succeed(false),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerEnvironment.ServerEnvironment)({
|
||||
getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId),
|
||||
@@ -3234,32 +3282,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
|
||||
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
config: { devUrl: new URL(crossOriginClientOrigin) },
|
||||
});
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* fetchEffect(sessionUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: desktopOrigin,
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsPreflightHeaders(response.headers, {
|
||||
origin: desktopOrigin,
|
||||
credentials: true,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
@@ -4126,46 +4148,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("shares one preview automation broker across websocket sessions", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const firstConnected = yield* Deferred.make<string>();
|
||||
const firstClosed = yield* Deferred.make<void>();
|
||||
const host = {
|
||||
clientId: "shared-preview-host",
|
||||
environmentId: testEnvironmentDescriptor.environmentId,
|
||||
} as const;
|
||||
|
||||
yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(
|
||||
Stream.tap((event) =>
|
||||
event.type === "connected"
|
||||
? Deferred.succeed(firstConnected, event.connectionId)
|
||||
: Effect.void,
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.ensuring(Deferred.succeed(firstClosed, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const firstConnectionId = yield* Deferred.await(firstConnected);
|
||||
const replacementEvent = yield* withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead),
|
||||
).pipe(Effect.map(Option.getOrThrow));
|
||||
const firstStreamClosed = yield* Deferred.await(firstClosed).pipe(
|
||||
Effect.timeoutOption("2 seconds"),
|
||||
);
|
||||
|
||||
assert.equal(replacementEvent.type, "connected");
|
||||
assert.notEqual(replacementEvent.connectionId, firstConnectionId);
|
||||
assert.isTrue(Option.isSome(firstStreamClosed));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -4272,6 +4254,23 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket resource telemetry through the subscription", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const snapshot = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeResourceTelemetry]({}).pipe(Stream.runHead),
|
||||
),
|
||||
);
|
||||
|
||||
assertTrue(Option.isSome(snapshot));
|
||||
assert.equal(snapshot.value.processes.length, 0);
|
||||
assert.equal(snapshot.value.groups.backend.processCount, 0);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const nextProviders = [
|
||||
|
||||
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user