Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c3bf90886 | ||
|
|
2f466ffc9c | ||
|
|
9146ed2f49 | ||
|
|
f0f16e4f6e | ||
|
|
00da6b57a4 | ||
|
|
6ab2f16809 | ||
|
|
6efcf3e10c | ||
|
|
748203ea19 | ||
|
|
b125b76351 | ||
|
|
758decaa56 | ||
|
|
2d9066e089 | ||
|
|
35a684000d | ||
|
|
9e3e9bb4f0 | ||
|
|
a8e05cbb92 | ||
|
|
e6987965f6 | ||
|
|
fc28abf24b | ||
|
|
85a8986870 | ||
|
|
faea70aeba | ||
|
|
d19039aeef | ||
|
|
49c0d96edf | ||
|
|
3137c2b162 | ||
|
|
c3e8fb67d7 | ||
|
|
72b960fa39 | ||
|
|
08e4932f04 | ||
|
|
1b4830ff06 | ||
|
|
694f8d1c6e | ||
|
|
1b61ce1112 | ||
|
|
60af905e70 |
No files matched your search
@@ -22,6 +22,11 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -31,6 +36,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 +63,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
|
||||
|
||||
@@ -326,21 +326,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
|
||||
@@ -360,6 +368,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:
|
||||
@@ -598,6 +611,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:
|
||||
@@ -605,6 +631,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]
|
||||
@@ -659,6 +692,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
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ dist-electron/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
|
||||
@@ -59,7 +59,7 @@ We need to be on the same page with terminology. When communicating, use this la
|
||||
## The three ways to hurt yourself
|
||||
|
||||
1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or `kill` a PID you found by matching a name, path, or worktree string. Your own agent process has this worktree's path in its argv, and this machine runs several other dev servers at once. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc/<pid>/cwd` is your worktree.
|
||||
2. **Touching the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Read-only inspection is fine. Never start a server against it, never open it read-write, never clean it up.
|
||||
2. **Writing to the live install.** `~/.t3/userdata` is the developer's real T3 Code database, in use while you work. Reading it and copying from it are fine, and a good way to get real test data (see Test data). Never start a server against it, never open it read-write, never clean it up.
|
||||
3. **Baking in origins.** Never set `VITE_HTTP_URL` or `VITE_WS_URL` for dev. Dev is single-origin and Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known`. Setting them bakes localhost into the bundle and silently breaks every remote browser.
|
||||
|
||||
## Hit every surface
|
||||
@@ -85,10 +85,19 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
|
||||
## Test data
|
||||
|
||||
An empty database is a bad test. Seed your worktree's `.t3` instead of pointing at live state:
|
||||
An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state:
|
||||
|
||||
- Copy from `~/.t3/userdata` (the developer's real data, the most realistic test set) or `~/.t3/dev`. Worktree state lives at `<worktree>/.t3/userdata`.
|
||||
- Snapshot the database with `VACUUM INTO`, which is safe even while a server has the source open and yields one consistent file:
|
||||
|
||||
```bash
|
||||
mkdir -p .t3/userdata
|
||||
rm -f .t3/userdata/state.sqlite* # VACUUM INTO refuses to overwrite
|
||||
bun -e "new (require('bun:sqlite').Database)(process.env.HOME + '/.t3/userdata/state.sqlite', { readonly: true }).run(\"VACUUM INTO '.t3/userdata/state.sqlite'\")"
|
||||
```
|
||||
|
||||
A plain `cp` is only safe when no server has the source open, and must bring the `-wal` and `-shm` siblings along. A live file copy is a corrupt copy.
|
||||
|
||||
- Copy from `~/.t3/dev`, never from `~/.t3/userdata`.
|
||||
- Copy `state.sqlite` together with its `-wal` and `-shm` siblings, and only while no server has the source open. A live copy is a corrupt copy.
|
||||
- Bring `secrets` and `settings.json` only if the flow under test needs them.
|
||||
- Copy in, never symlink. Data flows one way: into your sandbox, never back out.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app, [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
|
||||
T3 Code is an "agent harness control surface". It enables control of the agents on your machine with a best-in-class mobile app ([iOS](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824), [Android](https://play.google.com/store/apps/details?id=com.t3tools.t3code)), [web app](https://app.t3.codes) and [Electron-based desktop app](https://t3.codes).
|
||||
|
||||
Works with your subscriptions on Claude Code, Codex, Cursor, Grok Build, and OpenCode. If they're set up on your computer, T3 Code can control them.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.29",
|
||||
"version": "0.0.31",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "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,
|
||||
|
||||
@@ -30,6 +30,7 @@ describe("DesktopLifecycle", () => {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -49,20 +49,41 @@ 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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopObservability", () => {
|
||||
it("advances a retained output offset instead of repeatedly copying a full head chunk", () => {
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const initial = DesktopObservability.appendBoundedOutputChunk(
|
||||
{
|
||||
runId: "test-run",
|
||||
startDetails: "pid=123",
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
},
|
||||
"stderr",
|
||||
new Uint8Array(maxBufferedBytes),
|
||||
);
|
||||
const initialBackingBuffer = initial.chunks[0]?.chunk.buffer;
|
||||
|
||||
const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1));
|
||||
|
||||
assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer);
|
||||
assert.equal(next.chunks[0]?.offset, 1);
|
||||
assert.equal(next.byteLength, maxBufferedBytes);
|
||||
});
|
||||
|
||||
it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -112,26 +133,34 @@ 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 factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
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))),
|
||||
@@ -139,16 +168,18 @@ describe("DesktopObservability", () => {
|
||||
|
||||
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.instanceId, "primary");
|
||||
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.instanceId, "primary");
|
||||
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");
|
||||
@@ -157,6 +188,141 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.instanceId, "primary");
|
||||
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.instanceId, "primary");
|
||||
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("keeps buffering output after a non-terminal failure snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-snapshot-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.gen(function* () {
|
||||
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n"));
|
||||
yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" });
|
||||
yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n"));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
);
|
||||
|
||||
const records = yield* Effect.forEach(
|
||||
(yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"),
|
||||
(line) => decodeDesktopBackendChildLogRecord(line),
|
||||
);
|
||||
assert.equal(
|
||||
records.some((record) => record.annotations.text === "after timeout\n"),
|
||||
true,
|
||||
);
|
||||
assert.equal(records.at(-1)?.annotations.details, "code=1");
|
||||
}).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 factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
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 factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const outputLog = yield* factory.forInstance("primary");
|
||||
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)),
|
||||
|
||||
@@ -24,7 +24,9 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
export interface RotatingLogFileWriter {
|
||||
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
|
||||
@@ -32,14 +34,14 @@ export interface RotatingLogFileWriter {
|
||||
}
|
||||
|
||||
export interface DesktopBackendOutputLogShape {
|
||||
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 persistFailureSnapshot: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
// Factory for per-instance backend output logs. `forInstance(id)` returns
|
||||
@@ -127,10 +129,80 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
readonly offset: number;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
export 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, offset: 0 }];
|
||||
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;
|
||||
const retainedByteLength = first.chunk.byteLength - first.offset;
|
||||
if (retainedByteLength <= overflow) {
|
||||
overflow -= retainedByteLength;
|
||||
byteLength -= retainedByteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
offset: first.offset + 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) {
|
||||
const chunk = chunks[index];
|
||||
byteLength -= chunk ? chunk.chunk.byteLength - chunk.offset : 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const currentDesktopRunId = Effect.gen(function* () {
|
||||
const annotations = yield* References.CurrentLogAnnotations;
|
||||
const runId = annotations.runId;
|
||||
@@ -345,47 +417,93 @@ const makeBackendOutputLogShape = (
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
id: string,
|
||||
sink: Option.Option<RotatingLogFileWriter>,
|
||||
): DesktopBackendOutputLogShape =>
|
||||
): Effect.Effect<DesktopBackendOutputLogShape> =>
|
||||
Option.match(sink, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
Effect.gen(function* () {
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
|
||||
function* (session: BackendOutputSession, details: string) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase,
|
||||
phase: "START",
|
||||
details: session.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk.subarray(output.offset)),
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.runId,
|
||||
instanceId: id,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
);
|
||||
return {
|
||||
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);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
instanceId: id,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}) satisfies DesktopBackendOutputLogShape,
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailureSnapshot: Effect.fn(
|
||||
"desktop.observability.backendOutput.persistFailureSnapshot",
|
||||
)(function* ({ details }) {
|
||||
const session = yield* Ref.get(sessionRef);
|
||||
if (Option.isSome(session)) {
|
||||
yield* writeFailure(session.value, details);
|
||||
}
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
|
||||
function* ({ details }) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
|
||||
if (Option.isNone(session)) return;
|
||||
yield* writeFailure(session.value, details);
|
||||
},
|
||||
),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
} satisfies DesktopBackendOutputLogShape;
|
||||
}),
|
||||
});
|
||||
|
||||
const backendOutputLogFactoryLayer = Layer.effect(
|
||||
@@ -412,10 +530,9 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
const cacheKey = backendLogFilePathForInstance(environment, id);
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached !== undefined) {
|
||||
return Effect.succeed([
|
||||
makeBackendOutputLogShape(environment, id, cached),
|
||||
cache,
|
||||
] as const);
|
||||
return makeBackendOutputLogShape(environment, id, cached).pipe(
|
||||
Effect.map((outputLog) => [outputLog, cache] as const),
|
||||
);
|
||||
}
|
||||
return makeBackendOutputSinkForInstance(environment, id).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
@@ -424,11 +541,19 @@ const backendOutputLogFactoryLayer = Layer.effect(
|
||||
Effect.map((sink) => {
|
||||
const next = new Map(cache);
|
||||
next.set(cacheKey, sink);
|
||||
return [
|
||||
makeBackendOutputLogShape(environment, id, sink),
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const;
|
||||
return { sink, next };
|
||||
}),
|
||||
Effect.flatMap(({ sink, next }) =>
|
||||
makeBackendOutputLogShape(environment, id, sink).pipe(
|
||||
Effect.map(
|
||||
(outputLog) =>
|
||||
[
|
||||
outputLog,
|
||||
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
|
||||
] as const,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ function makeEnvironmentLayer(
|
||||
baseDir: string,
|
||||
options?: {
|
||||
readonly appPath?: string;
|
||||
readonly dirname?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
@@ -59,7 +60,7 @@ function makeEnvironmentLayer(
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
dirname: options?.dirname ?? "/repo/apps/desktop/src",
|
||||
homeDirectory: baseDir,
|
||||
platform: options?.platform ?? "darwin",
|
||||
processArch: "x64",
|
||||
@@ -464,6 +465,8 @@ describe("DesktopBackendConfiguration", () => {
|
||||
// both wslhost-forwarded localhost and the distro's eth0 IP.
|
||||
assert.equal(config.bootstrap.host, "0.0.0.0");
|
||||
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
|
||||
assert.notProperty(config.bootstrap, "desktopTelemetryFd");
|
||||
assert.notProperty(config.bootstrap, "resourceMonitorPath");
|
||||
// httpBaseUrl uses the resolved distro IP from the test stub,
|
||||
// not localhost — the renderer reaches the backend directly to
|
||||
// avoid relying on wslhost forwarding.
|
||||
@@ -713,6 +716,97 @@ describe("DesktopBackendConfiguration", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
|
||||
const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(
|
||||
`${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
|
||||
{ recursive: true },
|
||||
);
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
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(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: `${resourcesPath}/app.asar`,
|
||||
dirname,
|
||||
isPackaged: true,
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("prefers the release resource monitor when both development builds exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const dirname = path.join(baseDir, "apps/desktop/src");
|
||||
const releaseMonitorPath = path.join(
|
||||
baseDir,
|
||||
"native/resource-monitor/target/release/t3-resource-monitor",
|
||||
);
|
||||
const debugMonitorPath = path.join(
|
||||
baseDir,
|
||||
"native/resource-monitor/target/debug/t3-resource-monitor",
|
||||
);
|
||||
yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
|
||||
yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(releaseMonitorPath, "release");
|
||||
yield* fileSystem.writeFileString(debugMonitorPath, "debug");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolvePrimary;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
dirname,
|
||||
devServerUrl: "http://127.0.0.1:5733",
|
||||
isPackaged: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -141,6 +141,44 @@ 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/release",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.isPackaged
|
||||
? [environment.path.join(environment.resourcesPath, "resource-monitor", 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;
|
||||
@@ -326,7 +364,9 @@ const buildObservabilityFragment = (observabilitySettings: BackendObservabilityS
|
||||
|
||||
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
|
||||
function* (
|
||||
input: SharedBootstrapInput,
|
||||
input: SharedBootstrapInput & {
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
},
|
||||
): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -345,6 +385,12 @@ const resolvePrimaryStartConfig = 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 }),
|
||||
}),
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
@@ -411,6 +457,10 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
// inert.
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
// The packaged sidecar is a Windows executable and cannot run inside the
|
||||
// Linux WSL backend. Keep the field absent instead of passing an unusable
|
||||
// `/mnt/.../*.exe` path; WSL resource telemetry is reported unavailable.
|
||||
// See docs/architecture/resource-telemetry.md.
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
@@ -621,7 +671,11 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const buildWindowsPrimaryConfig = Effect.gen(function* () {
|
||||
const shared = yield* sharedInputs;
|
||||
return yield* resolvePrimaryStartConfig(shared).pipe(
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
);
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -21,10 +24,15 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.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",
|
||||
@@ -41,6 +49,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
bootstrapDelivery: "fd3",
|
||||
extendEnv: true,
|
||||
@@ -52,14 +62,16 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
const configWithObservability: DesktopBackendBootstrapValue = {
|
||||
...baseConfig.bootstrap,
|
||||
tailscaleServeEnabled: true,
|
||||
desktopTelemetryFd: 4,
|
||||
otlpTracesUrl: "http://127.0.0.1:4318/v1/traces",
|
||||
};
|
||||
|
||||
function makeProcess(options?: {
|
||||
readonly stdout?: Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: Stream.Stream<Uint8Array>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
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),
|
||||
@@ -71,7 +83,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),
|
||||
});
|
||||
}
|
||||
@@ -112,7 +124,14 @@ interface MakeInstanceInput {
|
||||
failure: DesktopBackendManager.PreflightFailure,
|
||||
) => Effect.Effect<boolean>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
readonly configResolve?: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
readonly desktopTelemetryStream?: Stream.Stream<Uint8Array>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
}
|
||||
|
||||
// Helper that constructs a primary backend instance using the factory
|
||||
@@ -122,8 +141,11 @@ interface MakeInstanceInput {
|
||||
// to drive the instance's lifecycle.
|
||||
function makeTestInstance(input: MakeInstanceInput) {
|
||||
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
};
|
||||
const servicesLayer = Layer.mergeAll(
|
||||
@@ -135,6 +157,16 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () => Effect.succeed(stubLog),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: input.desktopTelemetryStream ?? Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
|
||||
const instance = DesktopBackendManager.makeBackendInstance({
|
||||
@@ -150,11 +182,12 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
}
|
||||
|
||||
describe("DesktopBackendManager", () => {
|
||||
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
|
||||
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.Command | undefined;
|
||||
let bootstrapJson = "";
|
||||
let telemetryJson = "";
|
||||
let readyCount = 0;
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const exited = yield* Queue.unbounded<void>();
|
||||
@@ -169,6 +202,10 @@ describe("DesktopBackendManager", () => {
|
||||
if (fd3?.type === "input" && fd3.stream) {
|
||||
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
}
|
||||
const fd4 = command.options.additionalFds?.fd4;
|
||||
if (fd4?.type === "input" && fd4.stream) {
|
||||
telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
|
||||
}
|
||||
}
|
||||
|
||||
return makeProcess({
|
||||
@@ -184,12 +221,14 @@ describe("DesktopBackendManager", () => {
|
||||
bootstrap: configWithObservability,
|
||||
},
|
||||
spawnerLayer,
|
||||
desktopTelemetryStream: Stream.encodeText(
|
||||
Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
|
||||
),
|
||||
onReady: Effect.sync(() => {
|
||||
readyCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -210,16 +249,400 @@ 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,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
|
||||
assert.equal(
|
||||
telemetryJson,
|
||||
'{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves the readiness timeout cause and process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
|
||||
const layer = Layer.merge(
|
||||
TestClock.layer(),
|
||||
httpClientLayer((request) =>
|
||||
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const readiness = yield* DesktopBackendManager.waitForHttpReady({
|
||||
executablePath: baseConfig.executablePath,
|
||||
entryPath: baseConfig.entryPath,
|
||||
cwd: baseConfig.cwd,
|
||||
httpBaseUrl: baseConfig.httpBaseUrl,
|
||||
timeout: Duration.millis(50),
|
||||
}).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
const request = yield* Deferred.await(requested);
|
||||
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(readiness);
|
||||
|
||||
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
|
||||
assert.equal(error.timeoutMs, 50);
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports bootstrap encoding failures with stable process context", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessBootstrapEncodeError") {
|
||||
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.isDefined(error.cause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
|
||||
);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves spawn failures without deriving their message from the cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcessSpawner",
|
||||
method: "spawn",
|
||||
pathOrDescriptor: baseConfig.executablePath,
|
||||
description: "low-level detail that must not become the public message",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessSpawnError") {
|
||||
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, spawnCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
|
||||
);
|
||||
assert.notInclude(error.message, spawnCause.message);
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves exit-status failures without copying their detail into the message", () =>
|
||||
Effect.gen(function* () {
|
||||
const exitCause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "ChildProcess",
|
||||
method: "exitCode",
|
||||
description: "exit-status-secret-sentinel",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Effect.fail(exitCause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
);
|
||||
|
||||
if (error._tag !== "BackendProcessExitStatusError") {
|
||||
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.strictEqual(error.cause, exitCause);
|
||||
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
|
||||
assert.notInclude(error.message, "exit-status-secret-sentinel");
|
||||
assert.isTrue(isBackendProcessError(error));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output stream failures with process and stream context", () =>
|
||||
Effect.gen(function* () {
|
||||
const outputCause = PlatformError.systemError({
|
||||
_tag: "BadResource",
|
||||
module: "ChildProcess",
|
||||
method: "stdout",
|
||||
description: "output-stream-secret-sentinel",
|
||||
});
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fail(outputCause),
|
||||
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputReadError") {
|
||||
return assert.fail(`Expected output read error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
|
||||
assert.notInclude(error.message, "output-stream-secret-sentinel");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports output handler failures separately from stream read failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const chunk = new TextEncoder().encode("backend output");
|
||||
const nextChunk = new TextEncoder().encode("still draining");
|
||||
const outputCause = new Error("output-handler-secret-sentinel");
|
||||
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
|
||||
const drained = yield* Deferred.make<void>();
|
||||
let outputCount = 0;
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.make(chunk, nextChunk),
|
||||
exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutput: () => {
|
||||
outputCount += 1;
|
||||
return outputCount === 1
|
||||
? Effect.fail(outputCause)
|
||||
: Deferred.succeed(drained, void 0).pipe(Effect.asVoid);
|
||||
},
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
|
||||
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
|
||||
if (error._tag !== "BackendProcessOutputHandlingError") {
|
||||
return assert.fail(`Expected output handling error, received ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.executablePath, "/electron");
|
||||
assert.equal(error.entryPath, "/server/bin.mjs");
|
||||
assert.equal(error.cwd, "/server");
|
||||
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
|
||||
assert.equal(error.pid, 123);
|
||||
assert.equal(error.streamName, "stdout");
|
||||
assert.equal(error.chunkByteLength, chunk.byteLength);
|
||||
assert.strictEqual(error.cause, outputCause);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
|
||||
);
|
||||
assert.notInclude(error.message, "output-handler-secret-sentinel");
|
||||
assert.equal(outputCount, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports child exit before waiting for trailing output to drain", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const exitObserved = yield* Deferred.make<void>();
|
||||
const finishOutputDrain = yield* Deferred.make<void>();
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.await(finishOutputDrain).pipe(
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runFiber = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
|
||||
}).pipe(
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* Deferred.await(exitObserved);
|
||||
assert.isUndefined(runFiber.pollUnsafe());
|
||||
|
||||
yield* Deferred.succeed(finishOutputDrain, void 0);
|
||||
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
|
||||
Effect.scoped(
|
||||
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(`not-json\n${controlMessage}\n`))
|
||||
: Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
message.type === "setDiagnosticsDemand"
|
||||
? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
},
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.scoped(
|
||||
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.seconds(1))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
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* instance.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -256,8 +679,7 @@ describe("DesktopBackendManager", () => {
|
||||
readyCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -285,9 +707,15 @@ describe("DesktopBackendManager", () => {
|
||||
let startCount = 0;
|
||||
let closedCount = 0;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
const startedPids = yield* Queue.unbounded<number>();
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReadyFlag = yield* Ref.make(false);
|
||||
let shutdownCount = 0;
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
let removedTelemetrySources = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -296,9 +724,16 @@ describe("DesktopBackendManager", () => {
|
||||
const scope = yield* Scope.Scope;
|
||||
startCount += 1;
|
||||
yield* Queue.offer(startedPids, 123);
|
||||
const close = Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
|
||||
const close = Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
closedCount += 1;
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Deferred.succeed(closed, void 0)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
yield* Scope.addFinalizer(scope, close);
|
||||
|
||||
@@ -316,7 +751,28 @@ describe("DesktopBackendManager", () => {
|
||||
Effect.andThen(Deferred.succeed(ready, void 0)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
onShutdown: Ref.set(backendReadyFlag, false),
|
||||
onShutdown: Ref.set(backendReadyFlag, false).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
shutdownCount += 1;
|
||||
}),
|
||||
),
|
||||
),
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
desktopTelemetryPublisher: {
|
||||
removeControlSource: () =>
|
||||
Effect.sync(() => {
|
||||
removedTelemetrySources += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
assert.isTrue(Option.isNone(yield* instance.currentConfig));
|
||||
|
||||
@@ -330,12 +786,21 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(runningSnapshot.ready, true);
|
||||
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
|
||||
|
||||
yield* instance.stop();
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
assert.isFalse(yield* Ref.get(backendReadyFlag));
|
||||
assert.equal(shutdownCount, 1);
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
assert.equal(removedTelemetrySources, 1);
|
||||
|
||||
const stoppedSnapshot = yield* instance.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReadyFlag));
|
||||
assert.equal(shutdownCount, 1);
|
||||
assert.equal(stoppedSnapshot.desiredRunning, false);
|
||||
assert.equal(stoppedSnapshot.ready, false);
|
||||
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
|
||||
@@ -343,6 +808,213 @@ describe("DesktopBackendManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("restarts when start is requested during stop teardown", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
assert.equal((yield* instance.snapshot).desiredRunning, true);
|
||||
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
const restarted = yield* instance.snapshot;
|
||||
assert.equal(restarted.desiredRunning, true);
|
||||
assert.deepEqual(restarted.activePid, Option.some(123));
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retries config resolution after a start request during stop teardown", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
const configAttempts = yield* Ref.make(0);
|
||||
let startCount = 0;
|
||||
|
||||
const configFailure = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "DesktopBackendManager",
|
||||
method: "configResolve",
|
||||
description: "transient configuration failure",
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe(
|
||||
Effect.flatMap((attempt) =>
|
||||
attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig),
|
||||
),
|
||||
);
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
configResolve,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
|
||||
const pendingRestart = yield* instance.snapshot;
|
||||
assert.equal(pendingRestart.desiredRunning, true);
|
||||
assert.equal(pendingRestart.restartScheduled, true);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
assert.equal(yield* Ref.get(configAttempts), 3);
|
||||
assert.equal((yield* instance.snapshot).desiredRunning, true);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps a timed-out run active until its process exits", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const teardownStarted = yield* Deferred.make<void>();
|
||||
const finishTeardown = yield* Deferred.make<void>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope;
|
||||
const closed = yield* Deferred.make<void>();
|
||||
startCount += 1;
|
||||
yield* Queue.offer(starts, startCount);
|
||||
if (startCount === 1) {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(teardownStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(finishTeardown)),
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
return makeProcess({
|
||||
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
});
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
|
||||
const stopFiber = yield* instance
|
||||
.stop({ timeout: Duration.millis(100) })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
|
||||
yield* instance.start;
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
|
||||
|
||||
assert.equal(startCount, 1);
|
||||
const timedOut = yield* instance.snapshot;
|
||||
assert.equal(timedOut.desiredRunning, true);
|
||||
assert.deepEqual(timedOut.activePid, Option.some(123));
|
||||
|
||||
yield* Deferred.succeed(finishTeardown, undefined);
|
||||
yield* TestClock.adjust(Duration.millis(500));
|
||||
|
||||
assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not notify shutdown before the first start has prior state", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -383,6 +1055,7 @@ describe("DesktopBackendManager", () => {
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -402,11 +1075,15 @@ describe("DesktopBackendManager", () => {
|
||||
const instance = yield* makeTestInstance({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* instance.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);
|
||||
@@ -657,6 +1334,13 @@ describe("DesktopBackendManager", () => {
|
||||
yield* instance.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* instance.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* instance.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -33,7 +33,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -46,10 +45,13 @@ import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
const MAX_RESTART_DELAY = Duration.seconds(10);
|
||||
@@ -62,7 +64,10 @@ 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.seconds(5);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
const { logWarning: logBackendProcessWarning } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-process");
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
|
||||
@@ -70,13 +75,17 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
|
||||
|
||||
export type BackendProcessOutputStream = "stdout" | "stderr";
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig {
|
||||
export interface BackendProcessContext {
|
||||
readonly executablePath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly entryPath: string;
|
||||
readonly cwd: string;
|
||||
readonly httpBaseUrl: URL;
|
||||
}
|
||||
|
||||
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
|
||||
|
||||
export interface DesktopBackendStartConfig extends BackendProcessContext {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env: Record<string, string | undefined>;
|
||||
// When true the spawner merges the desktop process.env on top of `env`;
|
||||
// when false `env` is passed verbatim. WSL mode opts out so a leaking
|
||||
@@ -106,55 +115,122 @@ export interface PreflightFailure {
|
||||
interface BackendProcessExit {
|
||||
readonly code: Option.Option<number>;
|
||||
readonly reason: string;
|
||||
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
}
|
||||
|
||||
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
|
||||
"BackendTimeoutError",
|
||||
{
|
||||
url: Schema.instanceOf(URL),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Timed out waiting for backend readiness at ${this.url.href}.`;
|
||||
}
|
||||
}
|
||||
const backendProcessContextSchema = {
|
||||
executablePath: Schema.String,
|
||||
entryPath: Schema.String,
|
||||
cwd: Schema.String,
|
||||
httpBaseUrl: Schema.URL,
|
||||
};
|
||||
|
||||
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
|
||||
"BackendReadinessTimeoutError",
|
||||
{
|
||||
entryPath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
readinessUrl: Schema.URL,
|
||||
timeoutMs: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
override get message(): string {
|
||||
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
|
||||
"BackendProcessBootstrapEncodeError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
|
||||
"BackendProcessSpawnError",
|
||||
{
|
||||
executablePath: Schema.String,
|
||||
...backendProcessContextSchema,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
|
||||
override get message(): string {
|
||||
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
|
||||
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
|
||||
"BackendProcessOutputReadError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
|
||||
"BackendProcessOutputHandlingError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
streamName: Schema.Literals(["stdout", "stderr"]),
|
||||
chunkByteLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type BackendProcessOutputError =
|
||||
| BackendProcessOutputReadError
|
||||
| BackendProcessOutputHandlingError;
|
||||
|
||||
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
|
||||
"BackendProcessExitStatusError",
|
||||
{
|
||||
...backendProcessContextSchema,
|
||||
pid: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const BackendProcessError = Schema.Union([
|
||||
BackendProcessBootstrapEncodeError,
|
||||
BackendProcessSpawnError,
|
||||
BackendProcessExitStatusError,
|
||||
]);
|
||||
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 outputDrainTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onExitObserved?: () => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
|
||||
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
|
||||
readonly onOutput?: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
) => Effect.Effect<void, Error>;
|
||||
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface DesktopBackendSnapshot {
|
||||
@@ -225,6 +301,8 @@ interface ActiveBackendRun {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
|
||||
readonly pid: Option.Option<number>;
|
||||
readonly exitObserved: boolean;
|
||||
readonly stopRequested: boolean;
|
||||
}
|
||||
|
||||
interface BackendManagerState {
|
||||
@@ -266,76 +344,130 @@ const calculateRestartDelay = (attempt: number): Duration.Duration =>
|
||||
|
||||
const closeRun = (
|
||||
run: ActiveBackendRun,
|
||||
parentScope: Scope.Scope,
|
||||
options?: { readonly timeout?: Duration.Duration },
|
||||
): Effect.Effect<void> => {
|
||||
): Effect.Effect<boolean> => {
|
||||
const waitForFiber = Option.match(run.fiber, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
|
||||
});
|
||||
const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
|
||||
const timeout = options?.timeout;
|
||||
|
||||
return (
|
||||
options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
|
||||
).pipe(Effect.ignore);
|
||||
if (!timeout) {
|
||||
return close.pipe(Effect.as(true));
|
||||
}
|
||||
|
||||
return Effect.forkIn(close, parentScope).pipe(
|
||||
Effect.flatMap((closeFiber) =>
|
||||
Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
export const waitForHttpReady = (
|
||||
options: BackendProcessContext & { readonly timeout: Duration.Duration },
|
||||
): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
baseUrl: options.httpBaseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
makeError: ({ cause }) =>
|
||||
new BackendReadinessTimeoutError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
readinessUrl,
|
||||
timeoutMs: Duration.toMillis(options.timeout),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
): BackendProcessExit {
|
||||
if (Result.isSuccess(result)) {
|
||||
return {
|
||||
code: Option.some(result.success),
|
||||
reason: `code=${result.success}`,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: Option.none(),
|
||||
reason: result.failure.message,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
function drainBackendOutput(
|
||||
context: BackendProcessContext & { readonly pid: number },
|
||||
streamName: BackendProcessOutputStream,
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
|
||||
onOutput: (
|
||||
streamName: BackendProcessOutputStream,
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void, Error>,
|
||||
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
|
||||
): Effect.Effect<void> {
|
||||
return stream.pipe(
|
||||
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
|
||||
Effect.ignore,
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputReadError({
|
||||
...context,
|
||||
streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Stream.runForEach((chunk) =>
|
||||
onOutput(streamName, chunk).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessOutputHandlingError({
|
||||
...context,
|
||||
streamName,
|
||||
chunkByteLength: chunk.byteLength,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
|
||||
),
|
||||
),
|
||||
Effect.catchTags({
|
||||
BackendProcessOutputReadError: onOutputFailure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
|
||||
(cause) =>
|
||||
new BackendProcessBootstrapEncodeError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
|
||||
if (options.bootstrapDelivery === "fd3") {
|
||||
additionalFds.fd3 = {
|
||||
type: "input",
|
||||
stream: bootstrapStream,
|
||||
};
|
||||
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.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
@@ -350,34 +482,131 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
// wsl.exe drops additional file descriptors when forwarding to the Linux
|
||||
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
|
||||
// (`--bootstrap-fd 0`) instead.
|
||||
...(options.bootstrapDelivery === "fd3"
|
||||
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
|
||||
: {}),
|
||||
...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
|
||||
});
|
||||
|
||||
const handle = yield* spawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
|
||||
),
|
||||
);
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessSpawnError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (options.captureOutput) {
|
||||
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.splitLines,
|
||||
Stream.filter((line) => line.trim().length > 0),
|
||||
Stream.runForEach((line) =>
|
||||
decodeDesktopTelemetryControlLine(line).pipe(
|
||||
Effect.flatMap(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendProcessWarning("ignored invalid desktop telemetry control message", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendProcessWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
yield* waitForHttpReady(
|
||||
options.httpBaseUrl,
|
||||
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
).pipe(
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
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,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return describeProcessExit(yield* Effect.result(handle.exitCode));
|
||||
const exit = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
pid: Number(handle.pid),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
yield* options.onExitObserved?.() ?? Effect.void;
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(
|
||||
Effect.timeout(options.outputDrainTimeout ?? 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}`,
|
||||
} satisfies BackendProcessExit;
|
||||
});
|
||||
|
||||
// Factory for one pooled backend instance. The returned instance owns
|
||||
@@ -394,12 +623,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| DesktopTelemetryPublisher.DesktopTelemetryPublisher
|
||||
| Scope.Scope
|
||||
> {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const state = yield* Ref.make(initialState);
|
||||
@@ -444,6 +675,12 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.get(state);
|
||||
if (Option.isSome(current.active)) {
|
||||
if (!current.desiredRunning) {
|
||||
yield* Ref.update(state, (latest) => ({
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -462,6 +699,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
Effect.option,
|
||||
);
|
||||
if (Option.isNone(config)) {
|
||||
if (current.desiredRunning) {
|
||||
yield* scheduleRestart("failed to generate desktop backend configuration");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const entryExists = yield* fileSystem
|
||||
@@ -561,6 +801,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
scope: runScope,
|
||||
fiber: Option.none(),
|
||||
pid: Option.none(),
|
||||
exitObserved: false,
|
||||
stopRequested: false,
|
||||
} satisfies ActiveBackendRun),
|
||||
nextRunId: latest.nextRunId + 1,
|
||||
},
|
||||
@@ -571,54 +813,70 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
) {
|
||||
yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const { isCurrentRun, nextState, pid } = yield* Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly isCurrentRun: boolean;
|
||||
readonly nextState: BackendManagerState;
|
||||
readonly pid: Option.Option<number>;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const currentRun = Option.getOrUndefined(latest.active);
|
||||
if (currentRun?.id !== runId) {
|
||||
const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
|
||||
yield* Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly isCurrentRun: boolean;
|
||||
readonly nextState: BackendManagerState;
|
||||
readonly pid: Option.Option<number>;
|
||||
readonly exitObserved: boolean;
|
||||
readonly stopRequested: boolean;
|
||||
readonly wasReady: boolean;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const currentRun = Option.getOrUndefined(latest.active);
|
||||
if (currentRun?.id !== runId) {
|
||||
return [
|
||||
{
|
||||
isCurrentRun: false,
|
||||
nextState: latest,
|
||||
pid: Option.none<number>(),
|
||||
exitObserved: false,
|
||||
stopRequested: false,
|
||||
wasReady: false,
|
||||
},
|
||||
latest,
|
||||
] as const;
|
||||
}
|
||||
|
||||
const next = {
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
ready: false,
|
||||
};
|
||||
return [
|
||||
{
|
||||
isCurrentRun: false,
|
||||
nextState: latest,
|
||||
pid: Option.none<number>(),
|
||||
isCurrentRun: true,
|
||||
nextState: next,
|
||||
pid: currentRun.pid,
|
||||
exitObserved: currentRun.exitObserved,
|
||||
stopRequested: currentRun.stopRequested,
|
||||
wasReady: latest.ready,
|
||||
},
|
||||
latest,
|
||||
next,
|
||||
] as const;
|
||||
}
|
||||
|
||||
const next = {
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
ready: false,
|
||||
};
|
||||
return [
|
||||
{
|
||||
isCurrentRun: true,
|
||||
nextState: next,
|
||||
pid: currentRun.pid,
|
||||
},
|
||||
next,
|
||||
] as const;
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (isCurrentRun) {
|
||||
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
|
||||
if (Option.isSome(pid)) {
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
if (exitObserved && !stopRequested) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
}
|
||||
if (wasReady) {
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
yield* spec.onShutdown?.() ?? Effect.void;
|
||||
}
|
||||
|
||||
if (isCurrentRun && nextState.desiredRunning) {
|
||||
@@ -630,16 +888,23 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: (message) =>
|
||||
desktopTelemetryPublisher.handleControlForSource(spec.id, message),
|
||||
onStarted: Effect.fn("desktop.backendInstance.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}`,
|
||||
});
|
||||
}),
|
||||
onExitObserved: () =>
|
||||
updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
exitObserved: true,
|
||||
})),
|
||||
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
|
||||
const isCurrentRun = yield* Ref.modify(state, (latest) => {
|
||||
const activeRun = Option.getOrUndefined(latest.active);
|
||||
@@ -662,10 +927,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
|
||||
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logInstanceWarning("backend readiness check failed during bootstrap", {
|
||||
error: error.message,
|
||||
});
|
||||
yield* backendOutputLog.persistFailureSnapshot({
|
||||
details: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
@@ -750,41 +1021,92 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
|
||||
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
|
||||
readonly timeout?: Duration.Duration;
|
||||
}) {
|
||||
const { active, restartFiber } = yield* mutex.withPermits(1)(
|
||||
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Ref.modify(state, (latest) => [
|
||||
{
|
||||
active: latest.active,
|
||||
restartFiber: latest.restartFiber,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
]);
|
||||
// Ignore failures from spec.onShutdown so a downstream throw
|
||||
// can't abort the rest of stop(). Ref.modify above already
|
||||
// flipped state to "no active run / no restart fiber", and the
|
||||
// physical cleanup (Fiber.interrupt + closeRun) runs after the
|
||||
// mutex releases. If onShutdown were allowed to propagate, both
|
||||
// would be skipped and the child process + restart fiber would
|
||||
// be orphaned while state claimed nothing was running — the
|
||||
// next start() would then spawn a second backend on top.
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
const result = yield* Ref.modify(state, (latest) => {
|
||||
const active = Option.map(latest.active, (run) =>
|
||||
run.exitObserved ? run : { ...run, stopRequested: true },
|
||||
);
|
||||
return [
|
||||
{
|
||||
active,
|
||||
restartFiber: latest.restartFiber,
|
||||
notifyShutdown: latest.ready,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
active,
|
||||
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
|
||||
if (notifyShutdown) {
|
||||
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
|
||||
}
|
||||
yield* Option.match(restartFiber, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options),
|
||||
onSome: (run) =>
|
||||
Effect.gen(function* () {
|
||||
const closed = yield* closeRun(run, parentScope, options);
|
||||
if (!closed) {
|
||||
return;
|
||||
}
|
||||
const cleanup = yield* mutex.withPermits(1)(
|
||||
Ref.modify(
|
||||
state,
|
||||
(
|
||||
latest,
|
||||
): readonly [
|
||||
{
|
||||
readonly needsCleanup: boolean;
|
||||
readonly shouldStart: boolean;
|
||||
},
|
||||
BackendManagerState,
|
||||
] => {
|
||||
const current = Option.getOrUndefined(latest.active);
|
||||
if (current?.id !== run.id) {
|
||||
return [
|
||||
{
|
||||
needsCleanup: false,
|
||||
shouldStart:
|
||||
latest.desiredRunning &&
|
||||
Option.isNone(latest.active) &&
|
||||
Option.isNone(latest.restartFiber),
|
||||
},
|
||||
latest,
|
||||
];
|
||||
}
|
||||
return [
|
||||
{
|
||||
needsCleanup: true,
|
||||
shouldStart: latest.desiredRunning,
|
||||
},
|
||||
{
|
||||
...latest,
|
||||
active: Option.none<ActiveBackendRun>(),
|
||||
},
|
||||
];
|
||||
},
|
||||
),
|
||||
);
|
||||
if (cleanup.needsCleanup) {
|
||||
yield* desktopTelemetryPublisher.removeControlSource(spec.id);
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
if (cleanup.shouldStart) {
|
||||
yield* start;
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,11 +5,13 @@ import * as FileSystem from "effect/FileSystem";
|
||||
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 { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
@@ -56,10 +58,21 @@ function makePoolLayer(
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
|
||||
forInstance: () =>
|
||||
Effect.succeed({
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailureSnapshot: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
resolvePrimaryLabel: Ref.get(labelRef),
|
||||
|
||||
@@ -97,6 +97,7 @@ import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
|
||||
@@ -176,7 +177,8 @@ export type BackendInstanceFactoryRequirements =
|
||||
| FileSystem.FileSystem
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| HttpClient.HttpClient
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory;
|
||||
| DesktopObservability.DesktopBackendOutputLogFactory
|
||||
| DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
interface ActiveRegisteredInstance {
|
||||
readonly _tag: "Active";
|
||||
|
||||
@@ -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,
|
||||
@@ -153,6 +154,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 class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
{
|
||||
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>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitor["Service"]["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: ElectronPowerMonitor["Service"]["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: ElectronPowerMonitor["Service"]["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);
|
||||
@@ -24,6 +24,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";
|
||||
@@ -52,6 +53,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";
|
||||
@@ -113,6 +115,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -160,6 +163,7 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -982,6 +982,92 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("emits debugger screencast frames only while recording is active", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let debuggerMessage:
|
||||
| ((event: unknown, method: string, params: Record<string, unknown>) => void)
|
||||
| undefined;
|
||||
const capturePage = vi.fn(async () => ({
|
||||
toJPEG: () => Buffer.from("scheduled-recording-frame"),
|
||||
getSize: () => ({ width: 1280, height: 720 }),
|
||||
}));
|
||||
const sendCommand = vi.fn(async (method: string) =>
|
||||
method === "Runtime.evaluate" ? { result: { value: null } } : undefined,
|
||||
);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
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,
|
||||
on: vi.fn(
|
||||
(
|
||||
event: string,
|
||||
listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
|
||||
) => {
|
||||
if (event === "message") debuggerMessage = listener;
|
||||
},
|
||||
),
|
||||
off: vi.fn(),
|
||||
},
|
||||
capturePage,
|
||||
} as never);
|
||||
const recordingFrames: DesktopPreviewRecordingFrame[] = [];
|
||||
|
||||
yield* manager.subscribeRecordingFrames((frame) =>
|
||||
Effect.sync(() => {
|
||||
recordingFrames.push(frame);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_screencast_guard");
|
||||
yield* manager.registerWebview("tab_screencast_guard", 42);
|
||||
yield* manager.automationEvaluate("tab_screencast_guard", { expression: "null" });
|
||||
|
||||
debuggerMessage?.({}, "Page.screencastFrame", {
|
||||
sessionId: 1,
|
||||
data: "inactive-frame",
|
||||
metadata: { deviceWidth: 1280, deviceHeight: 720 },
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
expect(recordingFrames).toHaveLength(0);
|
||||
|
||||
yield* manager.startRecording("tab_screencast_guard");
|
||||
recordingFrames.length = 0;
|
||||
debuggerMessage?.({}, "Page.screencastFrame", {
|
||||
sessionId: 2,
|
||||
data: "active-frame",
|
||||
metadata: { deviceWidth: 1280, deviceHeight: 720 },
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(recordingFrames).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "tab_screencast_guard",
|
||||
data: "active-frame",
|
||||
width: 1280,
|
||||
height: 720,
|
||||
}),
|
||||
]);
|
||||
yield* manager.stopRecording("tab_screencast_guard");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares background frame capture between recording and picture-in-picture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -671,10 +671,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
),
|
||||
);
|
||||
|
||||
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
|
||||
);
|
||||
});
|
||||
|
||||
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>,
|
||||
@@ -852,11 +859,53 @@ 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>) {
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
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);
|
||||
}
|
||||
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 captureSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(
|
||||
tabId,
|
||||
);
|
||||
if (captureSession?.consumers.has("recording")) {
|
||||
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));
|
||||
};
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
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 Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
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,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("stops when its scope closes during an Electron telemetry sample", () =>
|
||||
Effect.gen(function* () {
|
||||
const pollStarted = yield* Deferred.make<void>();
|
||||
const blockPoll = yield* Deferred.make<void>();
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(blockPoll)),
|
||||
Effect.as(0),
|
||||
),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: () => Effect.void,
|
||||
onThermalStateChange: () => Effect.void,
|
||||
onSpeedLimitChange: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
|
||||
yield* Layer.buildWithScope(layer, scope);
|
||||
yield* Deferred.await(pollStarted);
|
||||
|
||||
const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.isDefined(closeFiber.pollUnsafe());
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
const systemIdleState = yield* Ref.make<ElectronPowerMonitor.ElectronIdleState>("active");
|
||||
let beforeSystemIdleState: Effect.Effect<void> = Effect.void;
|
||||
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.75,
|
||||
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: () =>
|
||||
beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))),
|
||||
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 decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const messages = yield* Effect.forEach(encoded, (bytes) =>
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
}
|
||||
assert.deepEqual(initialSnapshot.electronProcesses, []);
|
||||
assert.equal(initialSnapshot.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]?.creationTimeMs, 1_001);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
yield* publisher.handleControlForSource("secondary-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
yield* publisher.handleControlForSource("old-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* publisher.handleControlForSource("secondary-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
yield* Effect.all(
|
||||
[
|
||||
publisher.removeControlSource("old-backend"),
|
||||
publisher.handleControlForSource("replacement-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
}),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
yield* Ref.set(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);
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true");
|
||||
|
||||
yield* Ref.set(onBattery, false);
|
||||
const metricsBeforePolledAc = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.seconds(5));
|
||||
assert.equal(metricsReadCount, metricsBeforePolledAc + 1);
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false");
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(metricsReadCount, metricsBeforePolledAc + 2);
|
||||
|
||||
const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
simpleListeners.get("suspend")?.();
|
||||
const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber));
|
||||
assert.isTrue(suspendedSnapshot.power.suspended);
|
||||
|
||||
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");
|
||||
assert.isTrue(constrainedSnapshot.power.suspended);
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber));
|
||||
assert.isFalse(recoveredSnapshot.power.suspended);
|
||||
|
||||
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 encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim());
|
||||
if (decodedSpeedLimit.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the encoded telemetry message to be a snapshot.");
|
||||
}
|
||||
assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65);
|
||||
assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001);
|
||||
|
||||
const metricsBeforeSecondaryOnlySample = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.seconds(15));
|
||||
assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1);
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid,
|
||||
4_242,
|
||||
);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("replacement-backend", {
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setHostPowerIntervals",
|
||||
activeIntervalMs: 7_000,
|
||||
idleIntervalMs: 11_000,
|
||||
});
|
||||
const configuredSequence = Option.getOrThrow(
|
||||
yield* Fiber.join(configuredSnapshotFiber),
|
||||
).sequence;
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(6_999));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
configuredSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
configuredSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
|
||||
yield* Ref.set(systemIdleState, "locked");
|
||||
yield* TestClock.adjust(Duration.seconds(7));
|
||||
const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence;
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true");
|
||||
yield* TestClock.adjust(Duration.millis(10_999));
|
||||
assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
lockedSequence + 1,
|
||||
);
|
||||
|
||||
yield* Ref.set(systemIdleState, "active");
|
||||
yield* TestClock.adjust(Duration.seconds(11));
|
||||
const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow);
|
||||
assert.equal(unlockedSnapshot.power.locked, "false");
|
||||
assert.equal(unlockedSnapshot.power.idle, "false");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(6_999));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
unlockedSnapshot.sequence,
|
||||
);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
unlockedSnapshot.sequence + 1,
|
||||
);
|
||||
|
||||
const pollStarted = yield* Deferred.make<void>();
|
||||
const releasePoll = yield* Deferred.make<void>();
|
||||
beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releasePoll)),
|
||||
);
|
||||
const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
yield* Deferred.await(pollStarted);
|
||||
simpleListeners.get("lock-screen")?.();
|
||||
thermalListener?.("critical");
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Deferred.succeed(releasePoll, undefined);
|
||||
|
||||
const concurrentEventSnapshot = Option.getOrThrow(
|
||||
yield* Fiber.join(concurrentEventSnapshotFiber),
|
||||
);
|
||||
assert.equal(concurrentEventSnapshot.power.locked, "true");
|
||||
assert.equal(concurrentEventSnapshot.power.thermalState, "critical");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
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 DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
|
||||
const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
|
||||
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 idle: HostPowerSnapshot["idle"];
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly lockedEventPending: boolean;
|
||||
readonly suspended: boolean;
|
||||
readonly suspendedEventPending: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly onBatteryEventPending: boolean;
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
interface HostPowerIntervals {
|
||||
readonly active: Duration.Duration;
|
||||
readonly idle: Duration.Duration;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
{
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
readonly handleControlForSource: (
|
||||
sourceId: string,
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
}
|
||||
>()("@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),
|
||||
lockedEventPending: true,
|
||||
};
|
||||
case "suspended":
|
||||
return {
|
||||
...state,
|
||||
suspended: event.value,
|
||||
suspendedEventPending: event.value,
|
||||
};
|
||||
case "onBattery":
|
||||
return {
|
||||
...state,
|
||||
onBattery: booleanState(event.value),
|
||||
onBatteryEventPending: true,
|
||||
};
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(
|
||||
power: PowerState,
|
||||
diagnosticsDemand: boolean,
|
||||
hostPowerIntervals: HostPowerIntervals,
|
||||
): Duration.Duration {
|
||||
if (!diagnosticsDemand) {
|
||||
return power.suspended || power.locked === "true" || power.idle === "true"
|
||||
? hostPowerIntervals.idle
|
||||
: hostPowerIntervals.active;
|
||||
}
|
||||
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 = {
|
||||
idle: "unknown",
|
||||
locked: "unknown",
|
||||
lockedEventPending: false,
|
||||
suspended: false,
|
||||
suspendedEventPending: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
onBatteryEventPending: false,
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
|
||||
active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
|
||||
idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
|
||||
});
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
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 = (allowSuspendRecovery: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
|
||||
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 polledLocked =
|
||||
systemIdleState === "unknown"
|
||||
? currentPower.locked
|
||||
: booleanState(systemIdleState === "locked");
|
||||
const polledOnBattery = booleanState(onBattery);
|
||||
const observedPower = yield* Ref.modify(powerState, (latestPower) => {
|
||||
const preserveEventLocked =
|
||||
latestPower.lockedEventPending ||
|
||||
latestPower.locked !== currentPower.locked ||
|
||||
latestPower.lockedEventPending !== currentPower.lockedEventPending;
|
||||
const preserveEventOnBattery =
|
||||
latestPower.onBatteryEventPending ||
|
||||
latestPower.onBattery !== currentPower.onBattery ||
|
||||
latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
|
||||
const preserveEventSuspended =
|
||||
latestPower.suspendedEventPending ||
|
||||
latestPower.suspended !== currentPower.suspended ||
|
||||
latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
|
||||
const next: PowerState = {
|
||||
...latestPower,
|
||||
idle: idleState(systemIdleState),
|
||||
locked: preserveEventLocked ? latestPower.locked : polledLocked,
|
||||
lockedEventPending:
|
||||
latestPower.lockedEventPending &&
|
||||
(systemIdleState === "unknown" || polledLocked !== latestPower.locked),
|
||||
suspended:
|
||||
allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
|
||||
suspendedEventPending: false,
|
||||
onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
|
||||
onBatteryEventPending:
|
||||
latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
|
||||
};
|
||||
return [next, next] as const;
|
||||
});
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: observedPower.idle,
|
||||
idleSeconds,
|
||||
locked: observedPower.locked,
|
||||
suspended: observedPower.suspended,
|
||||
onBattery: observedPower.onBattery,
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: observedPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: observedPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: Math.max(0, Math.round(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) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce(false);
|
||||
while (true) {
|
||||
const [currentPower, demand, intervals] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
|
||||
Ref.get(hostPowerIntervals),
|
||||
]);
|
||||
const allowSuspendRecovery = yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers).pipe(Effect.as(false)),
|
||||
Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
|
||||
);
|
||||
yield* sampleOnce(allowSuspendRecovery);
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
|
||||
sourceId,
|
||||
message,
|
||||
) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.modify(diagnosticsDemandSources, (sources) => {
|
||||
const previous = sources.size > 0;
|
||||
const next = new Set(sources);
|
||||
if (message.enabled) {
|
||||
next.add(sourceId);
|
||||
} else {
|
||||
next.delete(sourceId);
|
||||
}
|
||||
return [[previous, next.size > 0] as const, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(([previous, enabled]) =>
|
||||
previous === enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
case "setHostPowerIntervals":
|
||||
return Ref.set(hostPowerIntervals, {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
sourceId,
|
||||
) =>
|
||||
Ref.modify(diagnosticsDemandSources, (sources) => {
|
||||
const previous = sources.size > 0;
|
||||
const next = new Set(sources);
|
||||
next.delete(sourceId);
|
||||
return [[previous, next.size > 0] as const, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(([previous, enabled]) =>
|
||||
previous === enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
|
||||
handleControlForSource("legacy", message);
|
||||
|
||||
const snapshots = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(changes);
|
||||
const initial = yield* Ref.get(latest);
|
||||
return Stream.concat(
|
||||
Option.match(initial, {
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
Stream.fromSubscription(subscription),
|
||||
);
|
||||
}),
|
||||
);
|
||||
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,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
---
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
@@ -69,6 +74,8 @@ const {
|
||||
<a href={GITHUB_REPOSITORY_URL} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
|
||||
<a href="/download">Download</a>
|
||||
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS app</a>
|
||||
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android app</a>
|
||||
<a href="/terms-of-service">Terms</a>
|
||||
<a href="/privacy-policy">Privacy</a>
|
||||
<a href="/security-policy">Security</a>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
|
||||
|
||||
export const IOS_APP_STORE_URL =
|
||||
"https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824";
|
||||
|
||||
export const ANDROID_PLAY_STORE_URL =
|
||||
"https://play.google.com/store/apps/details?id=com.t3tools.t3code";
|
||||
|
||||
export const MARKETING_STATS = {
|
||||
githubStars: "14k+",
|
||||
users: "100,000",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -57,6 +58,24 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Mobile -->
|
||||
<section class="platform-section">
|
||||
<div class="platform-header">
|
||||
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="7" y="2" width="10" height="20" rx="2.5"/><path d="M11 18.5h2"/></svg>
|
||||
<h2 class="platform-name">Mobile</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">
|
||||
<span class="card-arch">iPhone & iPad</span>
|
||||
<span class="card-format">App Store</span>
|
||||
</a>
|
||||
<a class="download-card" href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">
|
||||
<span class="card-arch">Android</span>
|
||||
<span class="card-format">Google Play</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
@@ -73,7 +92,8 @@ import { RELEASES_URL } from "../lib/releases";
|
||||
|
||||
async function init() {
|
||||
const versionLabel = document.getElementById("version-label");
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
|
||||
// Only release-asset cards; mobile store cards have no data-asset and keep their href.
|
||||
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card[data-asset]");
|
||||
|
||||
try {
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { GITHUB_REPOSITORY_URL, MARKETING_STATS } from "../lib/site";
|
||||
import {
|
||||
ANDROID_PLAY_STORE_URL,
|
||||
GITHUB_REPOSITORY_URL,
|
||||
IOS_APP_STORE_URL,
|
||||
MARKETING_STATS,
|
||||
} from "../lib/site";
|
||||
import { tweets } from "../lib/tweets";
|
||||
|
||||
const desktopEndorsementRows = [
|
||||
@@ -66,6 +71,12 @@ const mobileEndorsementRows = [
|
||||
<span>Steal our code (legally)</span>
|
||||
<svg class="hero-source-arrow" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17L17 7M8 7h9v9"/></svg>
|
||||
</a>
|
||||
<p class="hero-mobile-line">
|
||||
Also on your phone:
|
||||
<a href={IOS_APP_STORE_URL} target="_blank" rel="noopener noreferrer">iOS</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<a href={ANDROID_PLAY_STORE_URL} target="_blank" rel="noopener noreferrer">Android</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="hero-preview">
|
||||
@@ -578,6 +589,28 @@ const mobileEndorsementRows = [
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.hero-mobile-line {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--fg-dim);
|
||||
font-size: 13px;
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
|
||||
.hero-mobile-line a {
|
||||
color: var(--fg-muted);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: rgba(161, 161, 170, 0.4);
|
||||
text-underline-offset: 3px;
|
||||
transition: color 0.18s ease, text-decoration-color 0.18s ease;
|
||||
}
|
||||
|
||||
.hero-mobile-line a:hover {
|
||||
color: var(--fg);
|
||||
text-decoration-color: var(--fg);
|
||||
}
|
||||
|
||||
/* Download button icons (platform-aware) */
|
||||
.dl-icon {
|
||||
display: none;
|
||||
|
||||
@@ -47,7 +47,6 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
SettingsLegalDocumentCloseHeaderButton,
|
||||
@@ -190,10 +189,11 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
screen: SettingsWaitlistRouteScreen,
|
||||
// Keep the old deep link working after the Connect GA launch.
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Join the waitlist",
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
},
|
||||
@@ -284,6 +284,15 @@ function workspacePathFromState(state: NavigationState): string {
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
// The drain hook subscribes to the outbox, all thread shells, projects, and
|
||||
// connection statuses. Hosting it in a null-rendering leaf keeps those
|
||||
// updates from re-rendering RootStackLayout (and with it every screen) on
|
||||
// each enqueue, shell change, or reconnect.
|
||||
function ThreadOutboxDrainWorker() {
|
||||
useThreadOutboxDrain();
|
||||
return null;
|
||||
}
|
||||
|
||||
function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
@@ -292,7 +301,6 @@ function RootStackLayout(props: {
|
||||
const { pendingShare } = useIncomingShare();
|
||||
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
|
||||
useConnectOnboardingNavigation();
|
||||
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
|
||||
@@ -320,6 +328,7 @@ function RootStackLayout(props: {
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ThreadOutboxDrainWorker />
|
||||
<ShowcaseCaptureCoordinator pathname={pathname} />
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { EnvironmentRpcSubscriptionObservation } from "@t3tools/client-runtime/rpc";
|
||||
import { type BackgroundScope, type EnvironmentId, WS_METHODS } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
interface RetainedScope {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly scope: BackgroundScope;
|
||||
refCount: number;
|
||||
}
|
||||
|
||||
const retainedScopes = new Map<string, RetainedScope>();
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function notify(): void {
|
||||
for (const listener of listeners) {
|
||||
try {
|
||||
listener();
|
||||
} catch {
|
||||
// A failing observer must not corrupt retained-scope lifetime.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stableScopeKey(environmentId: EnvironmentId, scope: BackgroundScope): string {
|
||||
switch (scope.type) {
|
||||
case "server-config":
|
||||
case "diagnostics":
|
||||
return JSON.stringify([environmentId, scope.type]);
|
||||
case "provider-status":
|
||||
return JSON.stringify([environmentId, scope.type, scope.instanceId ?? null]);
|
||||
case "vcs-status":
|
||||
case "git-refs":
|
||||
return JSON.stringify([environmentId, scope.type, scope.cwd]);
|
||||
case "thread":
|
||||
return JSON.stringify([environmentId, scope.type, scope.threadId]);
|
||||
}
|
||||
}
|
||||
|
||||
function scopeForSubscription(
|
||||
observation: EnvironmentRpcSubscriptionObservation,
|
||||
): BackgroundScope | null {
|
||||
if (observation.method === WS_METHODS.subscribeResourceTelemetry) {
|
||||
return { type: "diagnostics" };
|
||||
}
|
||||
if (observation.method !== WS_METHODS.subscribeVcsStatus) {
|
||||
return null;
|
||||
}
|
||||
const input = observation.input as { readonly cwd?: unknown };
|
||||
return typeof input.cwd === "string" ? { type: "vcs-status", cwd: input.cwd } : null;
|
||||
}
|
||||
|
||||
export function retainedMobileBackgroundScopes(
|
||||
environmentId: EnvironmentId,
|
||||
): ReadonlyArray<BackgroundScope> {
|
||||
return Array.from(retainedScopes.values(), (entry) =>
|
||||
entry.environmentId === environmentId ? entry.scope : null,
|
||||
).filter((scope): scope is BackgroundScope => scope !== null);
|
||||
}
|
||||
|
||||
export function observeMobileBackgroundActivitySubscription(
|
||||
observation: EnvironmentRpcSubscriptionObservation,
|
||||
): Effect.Effect<Effect.Effect<void>> {
|
||||
const scope = scopeForSubscription(observation);
|
||||
if (scope === null) return Effect.succeed(Effect.void);
|
||||
return Effect.sync(() => {
|
||||
const environmentId = observation.environmentId as EnvironmentId;
|
||||
const key = stableScopeKey(environmentId, scope);
|
||||
const current = retainedScopes.get(key);
|
||||
if (current) {
|
||||
current.refCount += 1;
|
||||
} else {
|
||||
retainedScopes.set(key, { environmentId, scope, refCount: 1 });
|
||||
notify();
|
||||
}
|
||||
return Effect.sync(() => {
|
||||
const retained = retainedScopes.get(key);
|
||||
if (!retained) return;
|
||||
retained.refCount -= 1;
|
||||
if (retained.refCount <= 0) {
|
||||
retainedScopes.delete(key);
|
||||
notify();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function onRetainedMobileBackgroundScopesChange(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { EnvironmentId, WS_METHODS } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import {
|
||||
onRetainedMobileBackgroundScopesChange,
|
||||
observeMobileBackgroundActivitySubscription,
|
||||
retainedMobileBackgroundScopes,
|
||||
} from "./background-activity-scopes";
|
||||
|
||||
describe("mobile background activity", () => {
|
||||
it.effect("retains VCS demand only while the mobile subscription is active", () =>
|
||||
Effect.gen(function* () {
|
||||
const environmentId = EnvironmentId.make("mobile-environment");
|
||||
const release = yield* observeMobileBackgroundActivitySubscription({
|
||||
environmentId,
|
||||
method: WS_METHODS.subscribeVcsStatus,
|
||||
input: { cwd: "/workspace" },
|
||||
});
|
||||
|
||||
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([
|
||||
{ type: "vcs-status", cwd: "/workspace" },
|
||||
]);
|
||||
|
||||
yield* release;
|
||||
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps delimiter-containing environment and scope values distinct", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstEnvironmentId = EnvironmentId.make("a");
|
||||
const secondEnvironmentId = EnvironmentId.make("a:vcs-status:b");
|
||||
const releaseFirst = yield* observeMobileBackgroundActivitySubscription({
|
||||
environmentId: firstEnvironmentId,
|
||||
method: WS_METHODS.subscribeVcsStatus,
|
||||
input: { cwd: "b:vcs-status:c" },
|
||||
});
|
||||
const releaseSecond = yield* observeMobileBackgroundActivitySubscription({
|
||||
environmentId: secondEnvironmentId,
|
||||
method: WS_METHODS.subscribeVcsStatus,
|
||||
input: { cwd: "c" },
|
||||
});
|
||||
|
||||
expect(retainedMobileBackgroundScopes(firstEnvironmentId)).toEqual([
|
||||
{ type: "vcs-status", cwd: "b:vcs-status:c" },
|
||||
]);
|
||||
expect(retainedMobileBackgroundScopes(secondEnvironmentId)).toEqual([
|
||||
{ type: "vcs-status", cwd: "c" },
|
||||
]);
|
||||
|
||||
yield* Effect.all([releaseFirst, releaseSecond]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a release handle when a retained-scope listener throws", () =>
|
||||
Effect.gen(function* () {
|
||||
const environmentId = EnvironmentId.make("throwing-listener-environment");
|
||||
const removeListener = onRetainedMobileBackgroundScopesChange(() => {
|
||||
throw new Error("listener failed");
|
||||
});
|
||||
|
||||
const release = yield* observeMobileBackgroundActivitySubscription({
|
||||
environmentId,
|
||||
method: WS_METHODS.subscribeVcsStatus,
|
||||
input: { cwd: "/workspace" },
|
||||
});
|
||||
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([
|
||||
{ type: "vcs-status", cwd: "/workspace" },
|
||||
]);
|
||||
|
||||
yield* release;
|
||||
expect(retainedMobileBackgroundScopes(environmentId)).toEqual([]);
|
||||
removeListener();
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
|
||||
import {
|
||||
type BackgroundScope,
|
||||
type ClientActivityReportInput,
|
||||
type EnvironmentId,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import { AppState, type AppStateStatus } from "react-native";
|
||||
|
||||
import * as MobileStorage from "../persistence/mobile-storage";
|
||||
import {
|
||||
observeMobileBackgroundActivitySubscription,
|
||||
onRetainedMobileBackgroundScopesChange,
|
||||
retainedMobileBackgroundScopes,
|
||||
} from "./background-activity-scopes";
|
||||
|
||||
const REPORT_INTERVAL_MS = 25_000;
|
||||
const LEASE_TTL_MS = 45_000;
|
||||
const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
|
||||
|
||||
function normalizeAppState(
|
||||
state: AppStateStatus,
|
||||
): NonNullable<ClientActivityReportInput["appState"]> {
|
||||
if (state === "active" || state === "inactive" || state === "background") return state;
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export const mobileBackgroundActivityObserverLayer = Layer.succeed(
|
||||
EnvironmentRpcSubscriptionObserver,
|
||||
EnvironmentRpcSubscriptionObserver.of({
|
||||
observe: observeMobileBackgroundActivitySubscription,
|
||||
}),
|
||||
);
|
||||
|
||||
export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* EnvironmentRegistry;
|
||||
const storage = yield* MobileStorage.MobileStorage;
|
||||
const clientId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
|
||||
Effect.map((deviceId) => `mobile-${deviceId}`),
|
||||
Effect.orElseSucceed(() => "ephemeral-mobile-client"),
|
||||
);
|
||||
const reportRequests = yield* Queue.sliding<void>(1);
|
||||
const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
|
||||
let appState = AppState.currentState;
|
||||
|
||||
const report = Effect.gen(function* () {
|
||||
const observedAtMs = yield* Clock.currentTimeMillis;
|
||||
const active = appState === "active";
|
||||
const entries = yield* SubscriptionRef.get(registry.entries);
|
||||
yield* Effect.forEach(
|
||||
entries.keys(),
|
||||
(environmentId) =>
|
||||
registry
|
||||
.run(
|
||||
environmentId,
|
||||
request(WS_METHODS.serverReportClientActivity, {
|
||||
environmentId: environmentId as EnvironmentId,
|
||||
clientId,
|
||||
clientKind: "mobile",
|
||||
visible: active,
|
||||
focused: active,
|
||||
recentlyInteracted: active,
|
||||
appState: normalizeAppState(appState),
|
||||
scopes: [
|
||||
...BASELINE_SCOPES,
|
||||
...retainedMobileBackgroundScopes(environmentId as EnvironmentId),
|
||||
],
|
||||
ttlMs: LEASE_TTL_MS,
|
||||
observedAt: DateTime.makeUnsafe(observedAtMs),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.ignore),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
}).pipe(Effect.withSpan("mobile.backgroundActivity.report"));
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const removeScopeListener = onRetainedMobileBackgroundScopesChange(requestReport);
|
||||
const subscription = AppState.addEventListener("change", (nextState) => {
|
||||
appState = nextState;
|
||||
requestReport();
|
||||
});
|
||||
return { removeScopeListener, subscription };
|
||||
}),
|
||||
({ removeScopeListener, subscription }) =>
|
||||
Effect.sync(() => {
|
||||
removeScopeListener();
|
||||
subscription.remove();
|
||||
}),
|
||||
);
|
||||
yield* SubscriptionRef.changes(registry.entries).pipe(
|
||||
Stream.runForEach(() => Effect.sync(requestReport)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.fromQueue(reportRequests).pipe(
|
||||
Stream.debounce("250 millis"),
|
||||
Stream.runForEach(() => report),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.sync(requestReport).pipe(
|
||||
Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -5,6 +5,10 @@ import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { runtimeContextLayer } from "../lib/runtime";
|
||||
import {
|
||||
mobileBackgroundActivityObserverLayer,
|
||||
mobileBackgroundActivityReporterLayer,
|
||||
} from "./background-activity";
|
||||
import { connectionPlatformLayer } from "./platform";
|
||||
|
||||
const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
@@ -17,10 +21,22 @@ type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
| typeof connectionPlatformLayer
|
||||
| typeof mobileBackgroundActivityObserverLayer
|
||||
| typeof mobileBackgroundActivityReporterLayer;
|
||||
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
const providedClientConnectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
runtimeContextLayer,
|
||||
providedConnectionPlatformLayer,
|
||||
mobileBackgroundActivityObserverLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectionLayer = mobileBackgroundActivityReporterLayer.pipe(
|
||||
Layer.provideMerge(providedClientConnectionLayer),
|
||||
);
|
||||
|
||||
export const connectionAtomRuntime: Atom.AtomRuntime<
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import { useWaitlist } from "@clerk/expo";
|
||||
import { ActivityIndicator, Pressable, Text, TextInput, View } from "react-native";
|
||||
import { useState } from "react";
|
||||
|
||||
import { cn } from "../../lib/cn";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
|
||||
const { errors, fetchStatus, waitlist } = useWaitlist();
|
||||
const [emailAddress, setEmailAddress] = useState("");
|
||||
const [requestError, setRequestError] = useState<string | null>(null);
|
||||
const isSubmitting = fetchStatus === "fetching";
|
||||
const fieldError = errors.fields.emailAddress?.longMessage;
|
||||
|
||||
const joinWaitlist = async () => {
|
||||
const normalizedEmailAddress = emailAddress.trim();
|
||||
if (!normalizedEmailAddress || isSubmitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRequestError(null);
|
||||
try {
|
||||
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setRequestError(
|
||||
error instanceof CloudWaitlistJoinRejectedError
|
||||
? "Could not join the waitlist. Check your email address and try again."
|
||||
: "Could not join the waitlist. Check your connection and try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (waitlist.id) {
|
||||
return (
|
||||
<View className="gap-[18px]">
|
||||
<Text className="text-center font-t3-bold text-xl text-foreground">
|
||||
You are on the waitlist
|
||||
</Text>
|
||||
<Text className="text-center font-sans text-base text-foreground-secondary">
|
||||
We will email you when your T3 Connect access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="gap-[18px]">
|
||||
<Text className="font-sans text-base text-foreground-secondary">
|
||||
Enter your email and we will let you know when access is ready.
|
||||
</Text>
|
||||
|
||||
<View className="gap-2">
|
||||
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Email address"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect={false}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-4 py-3.5 font-sans text-lg text-foreground border-continuous",
|
||||
(fieldError || requestError) && "border-danger-foreground",
|
||||
)}
|
||||
keyboardType="email-address"
|
||||
onChangeText={(value) => {
|
||||
setEmailAddress(value);
|
||||
setRequestError(null);
|
||||
}}
|
||||
onSubmitEditing={() => void joinWaitlist()}
|
||||
placeholder="Enter your email address"
|
||||
placeholderTextColorClassName="accent-placeholder"
|
||||
returnKeyType="join"
|
||||
textContentType="emailAddress"
|
||||
value={emailAddress}
|
||||
/>
|
||||
{fieldError || requestError ? (
|
||||
<Text
|
||||
accessibilityLiveRegion="polite"
|
||||
className="font-sans text-sm text-danger-foreground"
|
||||
selectable
|
||||
>
|
||||
{fieldError ?? requestError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{
|
||||
busy: isSubmitting,
|
||||
disabled: isSubmitting || emailAddress.trim().length === 0,
|
||||
}}
|
||||
disabled={isSubmitting || emailAddress.trim().length === 0}
|
||||
onPress={() => void joinWaitlist()}
|
||||
className="min-h-[54px] flex-row items-center justify-center gap-2 rounded-full bg-primary px-5 py-3 disabled:opacity-[0.45]"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<ActivityIndicator colorClassName="accent-primary-foreground" size="small" />
|
||||
) : null}
|
||||
<Text className="font-t3-bold text-base text-primary-foreground">
|
||||
{isSubmitting ? "Joining" : "Join the waitlist"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SignInAction(props: { readonly onPress: () => void }) {
|
||||
return (
|
||||
<View className="flex-row items-center justify-center gap-1 pt-1">
|
||||
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
|
||||
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
|
||||
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
CloudWaitlistJoinRejectedError,
|
||||
CloudWaitlistJoinRequestError,
|
||||
joinCloudWaitlist,
|
||||
} from "./cloudWaitlistJoin";
|
||||
|
||||
describe("joinCloudWaitlist", () => {
|
||||
it("submits the provided email address", async () => {
|
||||
const join = vi.fn().mockResolvedValue({ error: null });
|
||||
|
||||
await joinCloudWaitlist({ join }, "[email protected]");
|
||||
|
||||
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
|
||||
});
|
||||
|
||||
it("preserves Clerk rejection details without exposing the email address", async () => {
|
||||
const cause = Object.assign(new Error("The enrollment was rejected."), {
|
||||
code: "form_identifier_invalid",
|
||||
});
|
||||
const join = vi.fn().mockResolvedValue({ error: cause });
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
expect(failure).toMatchObject({
|
||||
code: "form_identifier_invalid",
|
||||
cause,
|
||||
});
|
||||
expect(String(failure)).not.toContain("[email protected]");
|
||||
});
|
||||
|
||||
it("distinguishes request failures from rejected enrollments", async () => {
|
||||
const cause = new Error("network unavailable");
|
||||
const join = vi.fn().mockRejectedValue(cause);
|
||||
|
||||
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
|
||||
expect(failure).toMatchObject({ cause });
|
||||
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface CloudWaitlistJoiner {
|
||||
readonly join: (input: { emailAddress: string }) => Promise<{
|
||||
readonly error: { readonly code: string } | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
|
||||
"CloudWaitlistJoinRejectedError",
|
||||
{
|
||||
code: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
|
||||
}
|
||||
}
|
||||
|
||||
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
|
||||
"CloudWaitlistJoinRequestError",
|
||||
{
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cloud waitlist enrollment request failed.";
|
||||
}
|
||||
}
|
||||
|
||||
export async function joinCloudWaitlist(
|
||||
waitlist: CloudWaitlistJoiner,
|
||||
emailAddress: string,
|
||||
): Promise<void> {
|
||||
const result = await waitlist.join({ emailAddress }).catch((cause) => {
|
||||
throw new CloudWaitlistJoinRequestError({ cause });
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new CloudWaitlistJoinRejectedError({
|
||||
code: result.error.code,
|
||||
cause: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -665,6 +665,26 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
);
|
||||
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
|
||||
|
||||
// FlatList treats a changed extraData identity as "re-render every visible
|
||||
// row", so an inline object literal would invalidate all rows on every
|
||||
// HomeScreen render.
|
||||
const v2ExtraData = useMemo(
|
||||
() => ({
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}),
|
||||
[
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.savedConnectionsById,
|
||||
serverConfigs,
|
||||
v2ProjectTitleByProjectKey,
|
||||
],
|
||||
);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
@@ -900,13 +920,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={{
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
|
||||
serverConfigs,
|
||||
savedConnectionsById: props.savedConnectionsById,
|
||||
}}
|
||||
extraData={v2ExtraData}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListFooterComponent={
|
||||
threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
|
||||
|
||||
const ENVIRONMENT_A = EnvironmentId.make("environment-a");
|
||||
const ENVIRONMENT_B = EnvironmentId.make("environment-b");
|
||||
|
||||
function environment(environmentId: EnvironmentId, connectionState: EnvironmentConnectionPhase) {
|
||||
return { environmentId, connectionState };
|
||||
}
|
||||
|
||||
describe("resolveAddProjectEnvironment", () => {
|
||||
it("does not redirect an explicit unavailable environment to another environment", () => {
|
||||
expect(
|
||||
resolveAddProjectEnvironment(
|
||||
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
|
||||
ENVIRONMENT_A,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves an explicit connected environment", () => {
|
||||
expect(
|
||||
resolveAddProjectEnvironment(
|
||||
[environment(ENVIRONMENT_A, "connected"), environment(ENVIRONMENT_B, "connected")],
|
||||
ENVIRONMENT_A,
|
||||
)?.environmentId,
|
||||
).toBe(ENVIRONMENT_A);
|
||||
});
|
||||
|
||||
it("defaults to the first connected environment when no environment is requested", () => {
|
||||
expect(
|
||||
resolveAddProjectEnvironment(
|
||||
[environment(ENVIRONMENT_A, "offline"), environment(ENVIRONMENT_B, "connected")],
|
||||
null,
|
||||
)?.environmentId,
|
||||
).toBe(ENVIRONMENT_B);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
export function resolveAddProjectEnvironment<
|
||||
T extends {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
},
|
||||
>(environmentOptions: ReadonlyArray<T>, requestedEnvironmentId: EnvironmentId | null): T | null {
|
||||
if (requestedEnvironmentId !== null) {
|
||||
return (
|
||||
environmentOptions.find(
|
||||
(environment) =>
|
||||
environment.environmentId === requestedEnvironmentId &&
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
environmentOptions.find((environment) =>
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,17 @@ import {
|
||||
addProjectRemoteSourceProvider,
|
||||
buildAddProjectRemoteSourceReadiness,
|
||||
buildProjectCreateCommand,
|
||||
canCreateProjectInEnvironment,
|
||||
findExistingAddProject,
|
||||
getAddProjectInitialQuery,
|
||||
resolveAddProjectPath,
|
||||
sortAddProjectProviderSources,
|
||||
type AddProjectRemoteSource,
|
||||
} from "@t3tools/client-runtime/operations/projects";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPhase,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
canPreloadBrowsePath,
|
||||
createBrowseNavigationCoordinator,
|
||||
@@ -24,7 +29,7 @@ import {
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import * as Arr from "effect/Array";
|
||||
@@ -46,15 +51,20 @@ import { uuidv4 } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
|
||||
import {
|
||||
useRemoteConnectionStatus,
|
||||
useRemoteEnvironmentRuntime,
|
||||
useSavedRemoteConnections,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
|
||||
|
||||
interface EnvironmentOption {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly platform: string;
|
||||
readonly baseDirectory: string | null;
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
readonly connectionError: string | null;
|
||||
readonly connectionErrorTraceId: string | null;
|
||||
}
|
||||
|
||||
const environmentOptionOrder = Order.mapInput(
|
||||
@@ -227,10 +237,13 @@ function ProjectPathInput(props: {
|
||||
}
|
||||
|
||||
function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
const environmentId = environment?.environmentId ?? null;
|
||||
const environmentBaseDirectory = environment?.baseDirectory ?? null;
|
||||
const [pathInput, commitPathInput] = useState(() =>
|
||||
getAddProjectInitialQuery(environment?.baseDirectory),
|
||||
getAddProjectInitialQuery(environmentBaseDirectory),
|
||||
);
|
||||
const environmentRuntime = useRemoteEnvironmentRuntime(environment?.environmentId ?? null);
|
||||
const previousEnvironmentIdRef = useRef(environmentId);
|
||||
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
|
||||
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
|
||||
reportFailure: false,
|
||||
reportDefect: false,
|
||||
@@ -268,10 +281,11 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (environment) {
|
||||
setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
|
||||
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
|
||||
previousEnvironmentIdRef.current = environmentId;
|
||||
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
|
||||
}
|
||||
}, [environment, setPathInput]);
|
||||
}, [environmentBaseDirectory, environmentId, setPathInput]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -286,19 +300,27 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
|
||||
const serverConfigByEnvironmentId = useServerConfigs();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
|
||||
return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
|
||||
const runtimeByEnvironmentId = new Map(
|
||||
connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
|
||||
);
|
||||
const options = Object.values(savedConnectionsById).map((connection) => {
|
||||
const config = serverConfigByEnvironmentId.get(connection.environmentId);
|
||||
const runtime = runtimeByEnvironmentId.get(connection.environmentId);
|
||||
return {
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
platform: platformFromOs(config?.environment.platform.os ?? null),
|
||||
baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
|
||||
connectionState: runtime?.connectionState ?? "available",
|
||||
connectionError: runtime?.connectionError ?? null,
|
||||
connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
|
||||
};
|
||||
});
|
||||
return Arr.sort(options, environmentOptionOrder);
|
||||
}, [savedConnectionsById, serverConfigByEnvironmentId]);
|
||||
}, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
|
||||
}
|
||||
|
||||
function useSelectedEnvironment(): {
|
||||
@@ -309,8 +331,14 @@ function useSelectedEnvironment(): {
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const selectedEnvironment =
|
||||
environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
|
||||
environmentOptions[0] ??
|
||||
environmentOptions.find(
|
||||
(environment) =>
|
||||
environment.environmentId === selectedEnvironmentId &&
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ??
|
||||
environmentOptions.find((environment) =>
|
||||
canCreateProjectInEnvironment(environment.connectionState),
|
||||
) ??
|
||||
null;
|
||||
|
||||
return {
|
||||
@@ -325,9 +353,9 @@ function EmptyEnvironmentState() {
|
||||
|
||||
return (
|
||||
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
|
||||
<Text className="text-center text-lg font-t3-bold">No environments connected</Text>
|
||||
<Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Add an environment before adding a project.
|
||||
Start or reconnect an environment before adding a project.
|
||||
</Text>
|
||||
<Pressable
|
||||
onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
|
||||
@@ -407,17 +435,25 @@ export function AddProjectSourceScreen() {
|
||||
|
||||
return (
|
||||
<AddProjectShell>
|
||||
{environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
|
||||
{selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
|
||||
|
||||
{environmentOptions.length > 1 ? (
|
||||
<>
|
||||
<SectionTitle>Connected environments</SectionTitle>
|
||||
<SectionTitle>Environments</SectionTitle>
|
||||
<ListSection>
|
||||
{environmentOptions.map((environment, index) => (
|
||||
<ListRow
|
||||
key={environment.environmentId}
|
||||
title={environment.label}
|
||||
subtitle={environment.environmentId}
|
||||
subtitle={
|
||||
canCreateProjectInEnvironment(environment.connectionState)
|
||||
? environment.environmentId
|
||||
: connectionStatusText({
|
||||
phase: environment.connectionState,
|
||||
error: environment.connectionError,
|
||||
traceId: environment.connectionErrorTraceId,
|
||||
})
|
||||
}
|
||||
icon={
|
||||
<SymbolView
|
||||
name="server.rack"
|
||||
@@ -427,6 +463,7 @@ export function AddProjectSourceScreen() {
|
||||
/>
|
||||
}
|
||||
selected={environment.environmentId === selectedEnvironment?.environmentId}
|
||||
disabled={!canCreateProjectInEnvironment(environment.connectionState)}
|
||||
isFirst={index === 0}
|
||||
right={
|
||||
environment.environmentId === selectedEnvironment?.environmentId ? (
|
||||
@@ -500,7 +537,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
|
||||
return useCallback(
|
||||
async (workspaceRoot: string) => {
|
||||
if (!environment) return;
|
||||
if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
|
||||
|
||||
const existing = findExistingAddProject({
|
||||
projects,
|
||||
@@ -551,11 +588,7 @@ function useEnvironmentFromParam(
|
||||
): EnvironmentOption | null {
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
|
||||
return (
|
||||
environmentOptions.find((environment) => environment.environmentId === environmentId) ??
|
||||
environmentOptions[0] ??
|
||||
null
|
||||
);
|
||||
return resolveAddProjectEnvironment(environmentOptions, environmentId);
|
||||
}
|
||||
|
||||
export function AddProjectRepositoryScreen(props: {
|
||||
@@ -619,26 +652,32 @@ export function AddProjectRepositoryScreen(props: {
|
||||
return (
|
||||
<AddProjectShell>
|
||||
{error ? <ErrorBanner message={error} /> : null}
|
||||
<TextInput
|
||||
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
|
||||
value={repositoryInput}
|
||||
onChangeText={setRepositoryInput}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
placeholder={
|
||||
source === "url"
|
||||
? "https://github.com/org/repo.git"
|
||||
: addProjectRemoteSourcePathHint(source)
|
||||
}
|
||||
returnKeyType="next"
|
||||
onSubmitEditing={() => void lookupRepository()}
|
||||
/>
|
||||
<PrimaryActionButton
|
||||
label={source === "url" ? "Continue" : "Lookup repository"}
|
||||
disabled={isSubmitting || repositoryInput.trim().length === 0}
|
||||
onPress={() => void lookupRepository()}
|
||||
loading={isSubmitting}
|
||||
/>
|
||||
{environment ? (
|
||||
<>
|
||||
<TextInput
|
||||
className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
|
||||
value={repositoryInput}
|
||||
onChangeText={setRepositoryInput}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
placeholder={
|
||||
source === "url"
|
||||
? "https://github.com/org/repo.git"
|
||||
: addProjectRemoteSourcePathHint(source)
|
||||
}
|
||||
returnKeyType="next"
|
||||
onSubmitEditing={() => void lookupRepository()}
|
||||
/>
|
||||
<PrimaryActionButton
|
||||
label={source === "url" ? "Continue" : "Lookup repository"}
|
||||
disabled={isSubmitting || repositoryInput.trim().length === 0}
|
||||
onPress={() => void lookupRepository()}
|
||||
loading={isSubmitting}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<EmptyEnvironmentState />
|
||||
)}
|
||||
</AddProjectShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const environmentCount = connections.length;
|
||||
const accountLabel = useMemo(() => {
|
||||
if (!isLoaded) return "Checking";
|
||||
if (!isSignedIn) return "Request access";
|
||||
if (!isSignedIn) return "Sign in";
|
||||
return user?.primaryEmailAddress?.emailAddress ?? "Signed in";
|
||||
}, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);
|
||||
|
||||
@@ -273,13 +273,13 @@ function ConfiguredSettingsRouteScreen() {
|
||||
|
||||
const promptSignIn = useCallback(() => {
|
||||
Alert.alert(
|
||||
"Request T3 Connect access",
|
||||
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
|
||||
"Sign in to T3 Connect",
|
||||
"Live Activity updates require T3 Connect so relay can deliver updates to this device.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Continue",
|
||||
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" }),
|
||||
onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
|
||||
},
|
||||
],
|
||||
);
|
||||
@@ -441,7 +441,8 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const openAccount = useCallback(() => {
|
||||
if (!isLoaded) return;
|
||||
if (!isSignedIn) {
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsWaitlist" });
|
||||
expandClerkSheet();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
return;
|
||||
}
|
||||
expandClerkSheet();
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback } from "react";
|
||||
import { ScrollView } from "react-native";
|
||||
|
||||
import { CloudWaitlistEnrollment } from "../cloud/CloudWaitlistEnrollment";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
|
||||
export function SettingsWaitlistRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!hasCloudPublicConfig()) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [navigation]),
|
||||
);
|
||||
|
||||
return hasCloudPublicConfig() ? <ConfiguredSettingsWaitlistRouteScreen /> : null;
|
||||
}
|
||||
|
||||
function ConfiguredSettingsWaitlistRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const navigation = useNavigation();
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (isLoaded && isSignedIn) {
|
||||
navigation.dispatch(StackActions.replace("Settings"));
|
||||
}
|
||||
}, [isLoaded, isSignedIn, navigation]),
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ScrollView
|
||||
automaticallyAdjustKeyboardInsets
|
||||
contentContainerStyle={{
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 12,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="interactive"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<CloudWaitlistEnrollment
|
||||
onSignIn={() => {
|
||||
expand();
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
|
||||
}}
|
||||
/>
|
||||
</ScrollView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
import { createIncomingSharePayloadReader } from "./incoming-share-native";
|
||||
import { IncomingShareInbox } from "./incoming-share-inbox";
|
||||
import {
|
||||
loadIncomingShareDrafts,
|
||||
@@ -48,6 +49,11 @@ function receiveSharingEnabled(): boolean {
|
||||
return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;
|
||||
}
|
||||
|
||||
const getIncomingSharePayloads = createIncomingSharePayloadReader({
|
||||
platform: Platform.OS,
|
||||
readPayloads: getSharedPayloads,
|
||||
});
|
||||
|
||||
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
|
||||
try {
|
||||
return await getResolvedSharedPayloadsAsync();
|
||||
@@ -121,7 +127,7 @@ const incomingShareInbox = new IncomingShareInbox({
|
||||
loadDrafts: loadIncomingShareDrafts,
|
||||
writeDraft: writeIncomingShareDraft,
|
||||
removeDraft: removeIncomingShareDraft,
|
||||
getPayloads: getSharedPayloads,
|
||||
getPayloads: getIncomingSharePayloads,
|
||||
clearPayloads: clearSharedPayloads,
|
||||
buildDraft: async ({ payloads, id, createdAt }) => {
|
||||
const cleanupUris = new Set<string>();
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
import { createIncomingSharePayloadReader } from "./incoming-share-native";
|
||||
|
||||
const PAYLOAD: SharePayload = {
|
||||
shareType: "text",
|
||||
mimeType: "text/plain",
|
||||
value: "Fix this",
|
||||
};
|
||||
|
||||
describe("createIncomingSharePayloadReader", () => {
|
||||
it("treats a missing iOS App Group as an unavailable inbox", () => {
|
||||
const readPayloads = vi.fn((): ReadonlyArray<SharePayload> => {
|
||||
throw Object.assign(new Error("Expo-sharing has failed to fetch the app group id"), {
|
||||
code: "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID",
|
||||
});
|
||||
});
|
||||
const read = createIncomingSharePayloadReader({ platform: "ios", readPayloads });
|
||||
|
||||
expect(read()).toEqual([]);
|
||||
expect(read()).toEqual([]);
|
||||
expect(readPayloads).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns native payloads when receiving is available", () => {
|
||||
const read = createIncomingSharePayloadReader({
|
||||
platform: "ios",
|
||||
readPayloads: () => [PAYLOAD],
|
||||
});
|
||||
|
||||
expect(read()).toEqual([PAYLOAD]);
|
||||
});
|
||||
|
||||
it("preserves other native errors", () => {
|
||||
const error = new Error("native failure");
|
||||
const read = createIncomingSharePayloadReader({
|
||||
platform: "ios",
|
||||
readPayloads: () => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
|
||||
expect(read).toThrow(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { SharePayload } from "expo-sharing";
|
||||
|
||||
const IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE = "ERR_FAILED_TO_RESOLVE_APP_GROUP_ID";
|
||||
|
||||
function errorCode(error: unknown): string | null {
|
||||
if (typeof error !== "object" || error === null || !("code" in error)) {
|
||||
return null;
|
||||
}
|
||||
return typeof error.code === "string" ? error.code : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the native "share into" capability to an empty inbox. Personal
|
||||
* Team builds cannot include the App Group that expo-sharing reads from.
|
||||
*/
|
||||
export function createIncomingSharePayloadReader(input: {
|
||||
readonly platform: string;
|
||||
readonly readPayloads: () => ReadonlyArray<SharePayload>;
|
||||
}): () => ReadonlyArray<SharePayload> {
|
||||
let isUnavailable = false;
|
||||
|
||||
return () => {
|
||||
if (isUnavailable) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return input.readPayloads();
|
||||
} catch (error) {
|
||||
if (input.platform === "ios" && errorCode(error) === IOS_APP_GROUP_UNAVAILABLE_ERROR_CODE) {
|
||||
isUnavailable = true;
|
||||
return [];
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -54,7 +54,14 @@ function useShortcutNavigation(): void {
|
||||
}
|
||||
|
||||
function useRecentThreadShortcutSync(state: NavigationState): void {
|
||||
const threadRef = useMemo(() => activeThreadRef(state), [state]);
|
||||
// Launcher shortcuts are Android-only. A null ref on iOS keeps this hook
|
||||
// (mounted in the root stack layout) from subscribing the root to the
|
||||
// active thread's shell, which would re-render every screen on each
|
||||
// title/status/session change.
|
||||
const threadRef = useMemo(
|
||||
() => (Platform.OS === "android" ? activeThreadRef(state) : null),
|
||||
[state],
|
||||
);
|
||||
const threadShell = useThreadShell(threadRef);
|
||||
// null until the persisted list loads; recording waits on it so the first
|
||||
// thread opened after a cold start cannot clobber older entries.
|
||||
|
||||
@@ -946,7 +946,11 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
autoFocus={!isAndroid}
|
||||
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
|
||||
// forces the iOS keyboard bring-up during the formSheet present
|
||||
// animation and stalls it. The runAfterInteractions effect above focuses
|
||||
// the editor once the transition settles instead.
|
||||
autoFocus={false}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
|
||||
@@ -203,13 +203,17 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
title={screenTitle}
|
||||
subtitle={incomingShareSubtitle}
|
||||
onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
|
||||
actions={[
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
},
|
||||
]}
|
||||
actions={
|
||||
catalogState.hasReadyEnvironment
|
||||
? [
|
||||
{
|
||||
accessibilityLabel: "Add project",
|
||||
icon: "plus",
|
||||
onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
|
||||
},
|
||||
]
|
||||
: []
|
||||
}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
@@ -229,11 +233,13 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
{catalogState.hasReadyEnvironment ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
</NativeHeaderToolbar>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -518,14 +518,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
if (inFlightThreadIdsRef.current.has(threadKey)) return;
|
||||
inFlightThreadIdsRef.current.add(threadKey);
|
||||
// Sending a prompt starts agent work: arm the lock-screen card now, while
|
||||
// the app is foregrounded and the activity token can be registered.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
try {
|
||||
await onSendMessage();
|
||||
// Sending a prompt starts agent work: arm the lock-screen card while the
|
||||
// app is foregrounded and the activity token can be registered. Armed
|
||||
// after the send so its preference read and native Activity start don't
|
||||
// contend with the queued-message feedback on the tap frame.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
} finally {
|
||||
inFlightThreadIdsRef.current.delete(threadKey);
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly hasMoreActivities: boolean;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
@@ -356,6 +357,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
hasMoreActivities={props.hasMoreActivities}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
|
||||
@@ -48,7 +48,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInUp,
|
||||
LinearTransition,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type LayoutAnimationsValues,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -80,7 +82,9 @@ import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../.
|
||||
import {
|
||||
resolveMarkdownFontSizes,
|
||||
resolveNativeMarkdownTypography,
|
||||
scaledTypographyLineHeight,
|
||||
} from "../../lib/appearancePreferences";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
|
||||
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
||||
@@ -91,7 +95,12 @@ import {
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
ThreadWorkLog,
|
||||
WORK_GROUP_TOGGLE_HEIGHT,
|
||||
} from "./thread-work-log";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
@@ -109,8 +118,22 @@ function formatMessageTime(input: string): string {
|
||||
}
|
||||
|
||||
// Rows shift when content above them grows (streaming text, work-log folds);
|
||||
// animating the container position turns those jumps into slides.
|
||||
const FEED_ITEM_LAYOUT_TRANSITION = LinearTransition.duration(180);
|
||||
// animating the container position turns those jumps into slides. Applied
|
||||
// conditionally — see the gated transition in ThreadFeed: while browsing
|
||||
// history the animation must NOT run, or every estimate→actual size
|
||||
// correction plays as a visible slide against the instant scroll-offset
|
||||
// compensation from maintainVisibleContentPosition.
|
||||
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
|
||||
|
||||
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
|
||||
// classNames. The fold row's min-h-11 (44px) stays taller than its single
|
||||
// text-sm line at every supported base font size (26px at the 22pt maximum),
|
||||
// so its height is a constant; a drifted value costs one correction on
|
||||
// measure, not a persistent offset.
|
||||
const TURN_FOLD_HEIGHT = 56; // min-h-11 (44) + mb-3 (12)
|
||||
// The working row has no min-height clamp — its height follows the scaled
|
||||
// text-xs line height (see workingRowHeight in ThreadFeed).
|
||||
const WORKING_ROW_VERTICAL_EXTRAS = 24; // py-1 (8) + mb-4 (16)
|
||||
|
||||
// Entering animations must only play for rows born just now — LegendList
|
||||
// remounts rows when they scroll back into view, and replaying an entrance for
|
||||
@@ -126,6 +149,7 @@ export interface ThreadFeedProps {
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly hasMoreActivities?: boolean;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
@@ -1301,6 +1325,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
props.layoutVariant === "split" ? 0 : windowWidth,
|
||||
);
|
||||
@@ -1410,6 +1435,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
},
|
||||
[props.onHeaderMaterialVisibilityChange],
|
||||
);
|
||||
// True while the viewport sits within ~one screen of the list end — the
|
||||
// only region where layout shifts should animate. Starts true because the
|
||||
// list opens pinned to the end.
|
||||
const nearListEnd = useSharedValue(true);
|
||||
|
||||
const handleScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
// anchorTopInset, not topContentInset: under automatic insets the list
|
||||
@@ -1417,9 +1447,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
|
||||
nearListEnd.value =
|
||||
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
|
||||
);
|
||||
|
||||
// Gated variant of the 180ms feed layout slide. Instant while browsing
|
||||
// history: maintainVisibleContentPosition compensates the scroll offset in
|
||||
// the same frame a row's measured size lands, so an instant reposition is
|
||||
// invisible — animating it is exactly what made cold upward scrolls slide
|
||||
// and jump. Near the end the slide stays on: streaming growth and sends
|
||||
// shift rows at rest, where the animation is the thing preventing a hard
|
||||
// visual snap.
|
||||
const feedItemLayoutTransition = useMemo(() => {
|
||||
return (values: LayoutAnimationsValues) => {
|
||||
"worklet";
|
||||
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
|
||||
return {
|
||||
initialValues: {
|
||||
originX: values.currentOriginX,
|
||||
originY: values.currentOriginY,
|
||||
width: values.currentWidth,
|
||||
height: values.currentHeight,
|
||||
},
|
||||
animations: {
|
||||
originX: withTiming(values.targetOriginX, { duration }),
|
||||
originY: withTiming(values.targetOriginY, { duration }),
|
||||
width: withTiming(values.targetWidth, { duration }),
|
||||
height: withTiming(values.targetHeight, { duration }),
|
||||
},
|
||||
};
|
||||
};
|
||||
}, [nearListEnd]);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
@@ -1636,6 +1697,38 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
setExpandedImage({ uri, headers });
|
||||
}, []);
|
||||
|
||||
// Rows whose height is known before they ever render. Without this, every
|
||||
// row above the viewport is assumed to be estimatedItemSize tall, and
|
||||
// scrolling up through unmeasured content corrects each row's height as it
|
||||
// mounts — the feed visibly jumps. Fixed sizes make the small chrome rows
|
||||
// exact; message rows stay undefined and use LegendList's per-type running
|
||||
// average once one of their type has been measured. Text-driven heights
|
||||
// follow the configurable base font size via scaledTypographyLineHeight.
|
||||
const workingRowHeight =
|
||||
WORKING_ROW_VERTICAL_EXTRAS +
|
||||
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.label, appearance.baseFontSize);
|
||||
const getFixedItemSize = useCallback(
|
||||
(entry: ThreadFeedEntry) => {
|
||||
switch (entry.type) {
|
||||
case "turn-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||
case "working":
|
||||
return workingRowHeight;
|
||||
case "activity-group":
|
||||
// Expanded rows append a variable detail block — fall back to
|
||||
// measurement for those groups.
|
||||
return entry.activities.some((activity) => expandedWorkRows[activity.id])
|
||||
? undefined
|
||||
: collapsedWorkLogHeight(entry.activities, appearance.baseFontSize);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
[expandedWorkRows, workingRowHeight, appearance.baseFontSize],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
(info: { item: ThreadFeedEntry; index: number }) =>
|
||||
renderFeedEntry(info, {
|
||||
@@ -1725,7 +1818,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
itemLayoutAnimation={FEED_ITEM_LAYOUT_TRANSITION}
|
||||
itemLayoutAnimation={feedItemLayoutTransition}
|
||||
// Patched LegendList prop (patches/@[email protected]):
|
||||
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||
@@ -1769,6 +1862,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
getFixedItemSize={getFixedItemSize}
|
||||
// Measure rows well before they scroll into view so estimate→actual
|
||||
// corrections land offscreen instead of under the user's finger.
|
||||
drawDistance={500}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
@@ -1788,11 +1885,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// user overscroll back to the adjusted rest position.
|
||||
scrollToOverflowEnabled
|
||||
estimatedItemSize={180}
|
||||
// Chat-style bottom alignment: when a thread is shorter than the
|
||||
// viewport, pad above the content so messages rest just above the
|
||||
// composer instead of under the header. No effect on threads that
|
||||
// overflow the viewport (the padding clamps to zero).
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
usesNativeAutomaticInsets && props.hasMoreActivities !== true ? null : (
|
||||
<View>
|
||||
{!usesNativeAutomaticInsets ? <View style={{ height: topContentInset }} /> : null}
|
||||
{props.hasMoreActivities === true ? (
|
||||
<Text className="pb-2 text-center text-xs text-foreground-secondary opacity-60">
|
||||
Earlier work activity not shown
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
@@ -1801,6 +1912,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 &&
|
||||
props.hasMoreActivities !== true &&
|
||||
props.activeWorkStartedAt === null &&
|
||||
props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
|
||||
@@ -755,6 +755,7 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
hasMoreActivities={selectedThreadDetail?.hasMoreActivities === true}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
|
||||
@@ -3,8 +3,10 @@ import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import Animated, { FadeIn } from "react-native-reanimated";
|
||||
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
@@ -77,6 +79,46 @@ function isFreshRow(createdAt: string): boolean {
|
||||
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ROW_WINDOW_MS;
|
||||
}
|
||||
|
||||
// Tool-like activities with a neutral status carry no signal worth a row.
|
||||
export function visibleWorkLogActivities(
|
||||
activities: ReadonlyArray<ThreadFeedActivity>,
|
||||
): ReadonlyArray<ThreadFeedActivity> {
|
||||
return activities.filter((activity) => !(activity.toolLike && activity.status === "neutral"));
|
||||
}
|
||||
|
||||
// Pre-measurement heights for the feed's getFixedItemSize. Collapsed work-log
|
||||
// rows are single-line (numberOfLines={1}) inside a min-height that stays
|
||||
// taller than the text at every supported base font size (text-xs reaches
|
||||
// 23px at the 22pt maximum, under the 32px min-h-8), so row height is
|
||||
// deterministic. The "work log" label has no such clamp — its height follows
|
||||
// the scaled text-2xs line height. Values mirror the classNames below — keep
|
||||
// them in sync; a mismatch only costs a one-time correction on measure.
|
||||
const WORK_ROW_HEIGHT = 32; // min-h-8
|
||||
const WORK_ROW_GAP = 1; // gap-px
|
||||
const WORK_LOG_HEADER_PADDING = 2; // pb-0.5 under the "work log" label
|
||||
const WORK_LOG_BOTTOM_MARGIN = 4; // mb-1
|
||||
|
||||
export const WORK_GROUP_TOGGLE_HEIGHT = 36; // min-h-8 (32) + mb-1 (4)
|
||||
|
||||
export function collapsedWorkLogHeight(
|
||||
activities: ReadonlyArray<ThreadFeedActivity>,
|
||||
baseFontSize: number,
|
||||
): number {
|
||||
const rows = visibleWorkLogActivities(activities);
|
||||
if (rows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
const headerHeight =
|
||||
scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING;
|
||||
return (
|
||||
WORK_LOG_BOTTOM_MARGIN +
|
||||
(onlyToolRows ? 0 : headerHeight) +
|
||||
rows.length * WORK_ROW_HEIGHT +
|
||||
(rows.length - 1) * WORK_ROW_GAP
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
@@ -87,9 +129,10 @@ export function ThreadWorkLog(props: {
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const rows = props.activities
|
||||
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
|
||||
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
|
||||
const rows = visibleWorkLogActivities(props.activities).map((activity) => ({
|
||||
...activity,
|
||||
detail: compactActivityDetail(activity.detail),
|
||||
}));
|
||||
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
|
||||
@@ -198,12 +198,27 @@ export function resolveTextScaleVariables(baseFontSize: number): Record<string,
|
||||
|
||||
for (const [name, role] of Object.entries(TEXT_SCALE_VARIABLE_ROLES)) {
|
||||
variables[name] = Math.max(8, Math.round(role.fontSize * scale));
|
||||
variables[`${name}--line-height`] = Math.max(10, Math.round(role.lineHeight * scale));
|
||||
variables[`${name}--line-height`] = scaledTypographyLineHeight(role, baseFontSize);
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* The line height a MOBILE_TYPOGRAPHY role renders at under the given base
|
||||
* font size — the same value resolveTextScaleVariables injects for the role's
|
||||
* `--text-*--line-height` variable. For layout code that must predict
|
||||
* text-driven heights (e.g. the thread feed's fixed item sizes) instead of
|
||||
* measuring them.
|
||||
*/
|
||||
export function scaledTypographyLineHeight(
|
||||
role: { readonly lineHeight: number },
|
||||
baseFontSize: number,
|
||||
): number {
|
||||
const scale = normalizeBaseFontSize(baseFontSize) / DEFAULT_BASE_FONT_SIZE;
|
||||
return Math.max(10, Math.round(role.lineHeight * scale));
|
||||
}
|
||||
|
||||
export function resolveNativeMarkdownTypography(baseFontSize: number): NativeMarkdownTypography {
|
||||
const fontSizes = resolveMarkdownFontSizes(baseFontSize);
|
||||
return {
|
||||
|
||||
@@ -957,6 +957,11 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
|
||||
|
||||
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
|
||||
const grouped: ThreadFeedEntry[] = [];
|
||||
// Mutable backing array for the trailing group so appending an activity is
|
||||
// O(1) instead of re-copying the group (which made this loop quadratic on
|
||||
// long tool runs). The array is only mutated while it is the trailing group.
|
||||
let openGroupActivities: ThreadFeedActivity[] | null = null;
|
||||
let openGroupTurnId: TurnId | null = null;
|
||||
|
||||
for (const entry of entries) {
|
||||
// Skip empty messages so they don't break activity grouping.
|
||||
@@ -966,24 +971,23 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
|
||||
|
||||
if (entry.type !== "activity") {
|
||||
grouped.push(entry);
|
||||
openGroupActivities = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = grouped.at(-1);
|
||||
if (previous?.type === "activity-group" && previous.turnId === entry.turnId) {
|
||||
grouped[grouped.length - 1] = {
|
||||
...previous,
|
||||
activities: [...previous.activities, entry.activity],
|
||||
};
|
||||
if (openGroupActivities !== null && openGroupTurnId === entry.turnId) {
|
||||
openGroupActivities.push(entry.activity);
|
||||
continue;
|
||||
}
|
||||
|
||||
openGroupActivities = [entry.activity];
|
||||
openGroupTurnId = entry.turnId;
|
||||
grouped.push({
|
||||
type: "activity-group",
|
||||
id: entry.id,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
activities: [entry.activity],
|
||||
activities: openGroupActivities,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1225,13 +1229,24 @@ function appendPresentedFeedEntry(
|
||||
});
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
/**
|
||||
* Sorts activities into lifecycle order. `derivePendingApprovals` and
|
||||
* `derivePendingUserInputs` both expect this ordering; sorting once and
|
||||
* passing the result to both avoids re-sorting the full activity history
|
||||
* per derivation.
|
||||
*/
|
||||
export function sortThreadActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
return Arr.sort(activities, activityOrder);
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of ordered) {
|
||||
for (const activity of sortedActivities) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
@@ -1273,12 +1288,11 @@ export function derivePendingApprovals(
|
||||
}
|
||||
|
||||
export function derivePendingUserInputs(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingUserInput[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
|
||||
for (const activity of ordered) {
|
||||
for (const activity of sortedActivities) {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
|
||||
@@ -88,11 +88,23 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
return loadPromise;
|
||||
};
|
||||
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
|
||||
serialize(async () => {
|
||||
// The queued atom drives the composer's immediate "queued" feedback, so it
|
||||
// is published synchronously; the durable write happens behind it and rolls
|
||||
// the message back out if it fails (durability only matters for crash
|
||||
// recovery, not for the in-session queue).
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> => {
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
return serialize(async () => {
|
||||
try {
|
||||
await options.storage.write(message);
|
||||
} catch (cause) {
|
||||
// Roll back by reference, not messageId: a retry enqueue with the same
|
||||
// id may have optimistically replaced this attempt while the write was
|
||||
// in flight, and its entry must survive this attempt's failure.
|
||||
setMessages(currentMessages().filter((candidate) => candidate !== message));
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
@@ -101,11 +113,15 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
// Resolves once all pending mutations (including any in-flight enqueue
|
||||
// write) have settled, reporting whether the message is still queued. The
|
||||
// drain awaits this before dispatching so a message whose durable write
|
||||
// later fails can never have been delivered first.
|
||||
const confirmQueued = (message: QueuedThreadMessage): Promise<boolean> =>
|
||||
serialize(async () => currentMessages().some((candidate) => candidate === message));
|
||||
|
||||
// Rewrites an already-queued message. A no-op when the message has been
|
||||
// removed in the meantime (e.g. deleted or delivered), so a trailing editor
|
||||
@@ -204,6 +220,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
serialize,
|
||||
load,
|
||||
enqueue,
|
||||
confirmQueued,
|
||||
update,
|
||||
remove,
|
||||
clearEnvironment,
|
||||
|
||||
@@ -294,6 +294,111 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("publishes an enqueued message before the durable write resolves", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
let releaseWrite!: () => void;
|
||||
const writeBlocked = new Promise<void>((resolve) => {
|
||||
releaseWrite = resolve;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => writeBlocked,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
const enqueueing = manager.enqueue(message);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
|
||||
releaseWrite();
|
||||
await enqueueing;
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("rolls an enqueued message back out when the durable write fails", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const writeCause = new Error("disk full");
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => {
|
||||
throw writeCause;
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
await expect(manager.enqueue(message)).rejects.toEqual(
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause: writeCause,
|
||||
}),
|
||||
);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps a same-id retry queued when the first attempt's write fails", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
let failNextWrite = true;
|
||||
let releaseFirstWrite!: () => void;
|
||||
const firstWriteBlocked = new Promise<void>((resolve) => {
|
||||
releaseFirstWrite = resolve;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => {
|
||||
if (failNextWrite) {
|
||||
failNextWrite = false;
|
||||
await firstWriteBlocked;
|
||||
throw new Error("disk full");
|
||||
}
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const retried = { ...message, text: "retried" };
|
||||
|
||||
const first = manager.enqueue(message);
|
||||
const second = manager.enqueue(retried);
|
||||
releaseFirstWrite();
|
||||
await expect(first).rejects.toBeInstanceOf(ThreadOutboxManagerError);
|
||||
await second;
|
||||
|
||||
// The failed first attempt must not roll back the retry that replaced it.
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [retried],
|
||||
});
|
||||
await expect(manager.confirmQueued(retried)).resolves.toBe(true);
|
||||
await expect(manager.confirmQueued(message)).resolves.toBe(false);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("replaces an existing message when an enqueue retry uses the same id", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const manager = createThreadOutboxManager({
|
||||
|
||||
@@ -20,6 +20,11 @@ export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promis
|
||||
return threadOutboxManager.enqueue(message);
|
||||
}
|
||||
|
||||
/** Waits for pending writes to settle; false if the message was rolled back. */
|
||||
export function confirmThreadOutboxMessageQueued(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.confirmQueued(message);
|
||||
}
|
||||
|
||||
/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
|
||||
export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.update(message);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -70,14 +71,19 @@ export function useSelectedThreadRequests() {
|
||||
null,
|
||||
);
|
||||
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
[selectedThread],
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
@@ -148,27 +149,36 @@ export function useThreadComposerState() {
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
// Enqueue publishes the queued atom synchronously (the durable write
|
||||
// happens behind it), so clearing the draft here gives send feedback on
|
||||
// the tap frame instead of after file I/O. If the write fails the message
|
||||
// is rolled out of the queue and the content is merged back into the
|
||||
// draft, preserving anything typed since.
|
||||
const enqueuePromise = enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
enqueuePromise.catch((error: unknown) => {
|
||||
// Restore text via merge (idempotent) but attachments via the uncapped
|
||||
// append: the merge path slots existing attachments first and truncates
|
||||
// at the send limit, which would silently drop this message's images if
|
||||
// the user attached new ones while the write was in flight.
|
||||
void mergeComposerDraftContent(threadKey, { text, attachments: [] });
|
||||
appendComposerDraftAttachments(threadKey, attachments);
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
return messageId;
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
|
||||
@@ -21,7 +21,11 @@ import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
confirmThreadOutboxMessageQueued,
|
||||
ensureThreadOutboxLoaded,
|
||||
removeThreadOutboxMessage,
|
||||
} from "./thread-outbox";
|
||||
import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
@@ -33,7 +37,7 @@ import {
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { environmentThreadShells, threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import {
|
||||
editingQueuedMessageIdsAtom,
|
||||
@@ -349,8 +353,32 @@ export function useThreadOutboxDrain(): void {
|
||||
return false;
|
||||
},
|
||||
);
|
||||
const delivery =
|
||||
deliveryAction === "remove"
|
||||
// Enqueues publish optimistically before their durable write settles.
|
||||
// Confirm the write landed (and the message wasn't rolled back) before
|
||||
// sending, so a failed write can never chase an already-delivered turn.
|
||||
const delivery = confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => {
|
||||
if (!queued) {
|
||||
// Rolled back by a failed write; nothing to deliver or retry.
|
||||
return true;
|
||||
}
|
||||
// The guards evaluated before the confirmation await are stale by now:
|
||||
// the thread may have gone busy, or the user may have opened this
|
||||
// message in the editor. Re-read both and defer to the next drain pass
|
||||
// (returning true skips the failure/backoff path) rather than sending
|
||||
// a payload the user is editing or racing an active turn.
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
|
||||
return true;
|
||||
}
|
||||
const freshThread = findThread(
|
||||
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
|
||||
nextQueuedMessage,
|
||||
);
|
||||
const freshThreadBusy =
|
||||
freshThread?.session?.status === "running" || freshThread?.session?.status === "starting";
|
||||
if (deliveryAction === "send" && creation === undefined && freshThreadBusy) {
|
||||
return true;
|
||||
}
|
||||
return deliveryAction === "remove"
|
||||
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
: creation !== undefined
|
||||
? creationProjectCwd !== null
|
||||
@@ -359,6 +387,7 @@ export function useThreadOutboxDrain(): void {
|
||||
: thread !== undefined
|
||||
? sendQueuedMessage(nextQueuedMessage, thread)
|
||||
: Promise.resolve(false);
|
||||
});
|
||||
void delivery
|
||||
.then((sent) => {
|
||||
if (sent) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.29",
|
||||
"version": "0.0.31",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
AuthOrchestrationOperateScope,
|
||||
AuthOrchestrationReadScope,
|
||||
AuthRelayReadScope,
|
||||
AuthRelayWriteScope,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { RPC_REQUIRED_SCOPES, requiredScopeForRpcMethod } from "./RpcAuthorization.ts";
|
||||
|
||||
describe("RPC authorization scopes", () => {
|
||||
it("declares exactly one scope for every RPC in the server group", () => {
|
||||
expect(new Set(Object.keys(RPC_REQUIRED_SCOPES))).toEqual(new Set(WsRpcGroup.requests.keys()));
|
||||
});
|
||||
|
||||
it("authorizes background policy reporting and observation deliberately", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverReportClientActivity)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverReportHostPowerState)).toBe(
|
||||
AuthOrchestrationOperateScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.serverGetBackgroundPolicy)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.subscribeBackgroundPolicy)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows relay status reads without granting relay installation access", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(
|
||||
AuthRelayReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);
|
||||
});
|
||||
|
||||
it("rejects unknown RPC method names", () => {
|
||||
for (const method of ["server.notRegistered", "toString", "constructor"]) {
|
||||
expect(() => requiredScopeForRpcMethod(method)).toThrow(
|
||||
`RPC method ${method} has no declared authorization scope.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
AuthAccessReadScope,
|
||||
AuthOrchestrationOperateScope,
|
||||
AuthOrchestrationReadScope,
|
||||
AuthRelayReadScope,
|
||||
AuthRelayWriteScope,
|
||||
AuthReviewWriteScope,
|
||||
AuthTerminalOperateScope,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type AuthEnvironmentScope,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as RpcGroup from "effect/unstable/rpc/RpcGroup";
|
||||
|
||||
type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
||||
|
||||
/**
|
||||
* Keep authorization coverage coupled to the RPC group itself. Adding an RPC to
|
||||
* `WsRpcGroup` without choosing a scope is a type error instead of a production
|
||||
* runtime failure.
|
||||
*/
|
||||
export const RPC_REQUIRED_SCOPES = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverUpdateServer]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverUpsertKeybinding]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverUpdateSettings]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetTraceDiagnostics]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetProcessDiagnostics]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,
|
||||
[WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
|
||||
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.gitPreparePullRequestThread]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.vcsCreateWorktree]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsRemoveWorktree]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsCreateRef]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,
|
||||
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalResize]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalClear]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalRestart]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.terminalClose]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.subscribeTerminalEvents]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.subscribeTerminalMetadata]: AuthTerminalOperateScope,
|
||||
[WS_METHODS.previewOpen]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewNavigate]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewResize]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewRefresh]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewClose]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewList]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.previewReportStatus]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewAutomationConnect]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewAutomationRespond]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.previewAutomationFocusHost]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,
|
||||
[WS_METHODS.subscribeBackgroundPolicy]: AuthOrchestrationReadScope,
|
||||
} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;
|
||||
|
||||
export function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {
|
||||
if (!Object.hasOwn(RPC_REQUIRED_SCOPES, method)) {
|
||||
throw new Error(`RPC method ${method} has no declared authorization scope.`);
|
||||
}
|
||||
const requiredScope = RPC_REQUIRED_SCOPES[method as WsRpcMethod];
|
||||
if (requiredScope === undefined) {
|
||||
throw new Error(`RPC method ${method} has no declared authorization scope.`);
|
||||
}
|
||||
return requiredScope;
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
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 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 { 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(AuthSessionId.make("session-1"), 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("keeps leases from another session when rpc client ids are reused", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const rpcClientId = RpcClientId.make(1);
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
rpcClientId,
|
||||
makeReport({ clientId: "client-1" }),
|
||||
);
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-2"),
|
||||
rpcClientId,
|
||||
makeReport({ clientId: "client-2" }),
|
||||
);
|
||||
|
||||
yield* policy.removeRpcClient(AuthSessionId.make("session-1"), rpcClientId);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.equal(snapshot.leases[0]?.sessionId, AuthSessionId.make("session-2"));
|
||||
assert.equal(snapshot.leases[0]?.clientId, "client-2");
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("serializes lease mutation publications", () =>
|
||||
Effect.gen(function* () {
|
||||
const firstSnapshotStarted = yield* Deferred.make<void>();
|
||||
const releaseFirstSnapshot = yield* Deferred.make<void>();
|
||||
const snapshotReads = yield* Ref.make(0);
|
||||
const hostLayer = Layer.succeed(
|
||||
HostPowerMonitor.HostPowerMonitor,
|
||||
HostPowerMonitor.HostPowerMonitor.of({
|
||||
snapshot: Ref.updateAndGet(snapshotReads, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 1
|
||||
? Deferred.succeed(firstSnapshotStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseFirstSnapshot)),
|
||||
Effect.as(nominalHostPower),
|
||||
)
|
||||
: Effect.succeed(nominalHostPower),
|
||||
),
|
||||
),
|
||||
report: () => Effect.void,
|
||||
streamChanges: Stream.empty,
|
||||
}),
|
||||
);
|
||||
const layer = BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest())),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const updatesFiber = yield* policy.streamChanges.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
const reportFiber = yield* policy
|
||||
.reportClientActivity(AuthSessionId.make("session-1"), RpcClientId.make(1), makeReport())
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(firstSnapshotStarted);
|
||||
const removeFiber = yield* policy
|
||||
.removeRpcClient(AuthSessionId.make("session-1"), RpcClientId.make(1))
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Deferred.succeed(releaseFirstSnapshot, undefined);
|
||||
yield* Fiber.join(reportFiber);
|
||||
yield* Fiber.join(removeFiber);
|
||||
const updates = Array.from(yield* Fiber.join(updatesFiber));
|
||||
|
||||
assert.equal(updates.at(-1)?.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(updates.at(-1)?.activeScopeKeys, []);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bounds client-id churn for one websocket connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const sessionId = AuthSessionId.make("session-1");
|
||||
const rpcClientId = RpcClientId.make(1);
|
||||
for (
|
||||
let index = 0;
|
||||
index <= BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT;
|
||||
index += 1
|
||||
) {
|
||||
yield* policy.reportClientActivity(
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
makeReport({ clientId: `client-${index}` }),
|
||||
);
|
||||
}
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(
|
||||
snapshot.leases.length,
|
||||
BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT,
|
||||
);
|
||||
assert.isTrue(
|
||||
snapshot.leases.some(
|
||||
(lease) =>
|
||||
lease.clientId ===
|
||||
`client-${BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT}`,
|
||||
),
|
||||
);
|
||||
}).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("host suspension disables scoped and opportunistic work", () =>
|
||||
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.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({
|
||||
...nominalHostPower,
|
||||
suspended: true,
|
||||
stale: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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("keeps scoped work active after a recently used visible window loses focus", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, recentlyInteracted: true }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("pauses scoped work for a visible unfocused client without recent interaction", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, recentlyInteracted: false }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
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,349 @@
|
||||
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 Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { subscribeBeforeSnapshot } from "../utils/subscribeBeforeSnapshot.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
export class BackgroundPolicy extends Context.Service<
|
||||
BackgroundPolicy,
|
||||
{
|
||||
readonly reportClientActivity: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
input: ClientActivityReportInput,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeRpcClient: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
) => Effect.Effect<void>;
|
||||
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
|
||||
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
readonly subscribe: Effect.Effect<
|
||||
{
|
||||
readonly latest: BackgroundPolicySnapshot;
|
||||
readonly changes: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
|
||||
}
|
||||
>()("t3/background/BackgroundPolicy") {}
|
||||
|
||||
const DEFAULT_LEASE_TTL_MS = 45_000;
|
||||
const MAX_LEASE_TTL_MS = 120_000;
|
||||
export const MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT = 16;
|
||||
|
||||
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 leaseKey(lease: Pick<ClientActivityLease, "sessionId" | "rpcClientId" | "clientId">) {
|
||||
return JSON.stringify([lease.sessionId, lease.rpcClientId, lease.clientId]);
|
||||
}
|
||||
|
||||
export function upsertClientActivityLease(
|
||||
leases: ReadonlyMap<string, ClientActivityLease>,
|
||||
lease: ClientActivityLease,
|
||||
now: DateTime.Utc,
|
||||
): Map<string, ClientActivityLease> {
|
||||
const next = new Map(leases);
|
||||
for (const [key, current] of next) {
|
||||
if (!isLeaseActive(current, now)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
const key = leaseKey(lease);
|
||||
if (!next.has(key)) {
|
||||
let connectionLeaseCount = 0;
|
||||
let oldestConnectionLease:
|
||||
| {
|
||||
readonly key: string;
|
||||
readonly updatedAtMs: number;
|
||||
}
|
||||
| undefined;
|
||||
for (const [currentKey, current] of next) {
|
||||
if (current.sessionId !== lease.sessionId || current.rpcClientId !== lease.rpcClientId) {
|
||||
continue;
|
||||
}
|
||||
connectionLeaseCount += 1;
|
||||
const updatedAtMs = DateTime.toEpochMillis(current.updatedAt);
|
||||
if (oldestConnectionLease === undefined || updatedAtMs < oldestConnectionLease.updatedAtMs) {
|
||||
oldestConnectionLease = { key: currentKey, updatedAtMs };
|
||||
}
|
||||
}
|
||||
if (
|
||||
connectionLeaseCount >= MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT &&
|
||||
oldestConnectionLease !== undefined
|
||||
) {
|
||||
next.delete(oldestConnectionLease.key);
|
||||
}
|
||||
}
|
||||
|
||||
next.set(key, lease);
|
||||
return next;
|
||||
}
|
||||
|
||||
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return isLeaseActive(lease, now) && lease.visible && (lease.focused || lease.recentlyInteracted);
|
||||
}
|
||||
|
||||
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 (
|
||||
hostPower.suspended ||
|
||||
(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 publishMutex = yield* Semaphore.make(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 publishSnapshotUnlocked = snapshot.pipe(
|
||||
Effect.flatMap((next) => PubSub.publish(changes, next)),
|
||||
);
|
||||
const publishSnapshot = publishMutex.withPermits(1)(publishSnapshotUnlocked);
|
||||
|
||||
const reportClientActivity: BackgroundPolicy["Service"]["reportClientActivity"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
input,
|
||||
) =>
|
||||
publishMutex.withPermits(1)(
|
||||
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) => upsertClientActivityLease(leases, lease, now));
|
||||
yield* publishSnapshotUnlocked;
|
||||
}),
|
||||
);
|
||||
|
||||
const removeRpcClient: BackgroundPolicy["Service"]["removeRpcClient"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
) =>
|
||||
publishMutex.withPermits(1)(
|
||||
Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const [key, lease] of next) {
|
||||
if (lease.sessionId === sessionId && lease.rpcClientId === rpcClientId) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}).pipe(Effect.andThen(publishSnapshotUnlocked), Effect.asVoid),
|
||||
);
|
||||
|
||||
const hasDemand: BackgroundPolicy["Service"]["hasDemand"] = (scope) =>
|
||||
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
|
||||
|
||||
const shouldRunScopeWork: BackgroundPolicy["Service"]["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* Stream.runForEach(serverSettings.streamChanges, () => publishSnapshot).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep("15 seconds").pipe(
|
||||
Effect.andThen(
|
||||
publishMutex.withPermits(1)(
|
||||
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;
|
||||
});
|
||||
yield* publishSnapshotUnlocked;
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return BackgroundPolicy.of({
|
||||
reportClientActivity,
|
||||
removeRpcClient,
|
||||
reportHostPowerState: hostPowerMonitor.report,
|
||||
snapshot,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
subscribe: subscribeBeforeSnapshot(changes, snapshot, publishMutex),
|
||||
hasDemand,
|
||||
shouldRunScopeWork,
|
||||
shouldRunOpportunisticWork,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BackgroundPolicy, make());
|
||||
@@ -0,0 +1,188 @@
|
||||
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("ignores host power reports older than the latest accepted snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const initial = {
|
||||
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"),
|
||||
} as const;
|
||||
const monitor = yield* HostPowerMonitor.make(initial);
|
||||
const latestAt = DateTime.makeUnsafe("2026-06-17T12:00:02.000Z");
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
locked: "true",
|
||||
updatedAt: latestAt,
|
||||
});
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
|
||||
});
|
||||
|
||||
const snapshot = yield* monitor.snapshot;
|
||||
expect(snapshot.locked).toBe("true");
|
||||
expect(DateTime.toEpochMillis(snapshot.updatedAt)).toBe(DateTime.toEpochMillis(latestAt));
|
||||
}),
|
||||
);
|
||||
|
||||
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));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"subscribes before reading the desktop snapshot so concurrent power updates survive",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
|
||||
const initial: DesktopHostTelemetrySnapshot = {
|
||||
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: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [],
|
||||
};
|
||||
const updated: DesktopHostTelemetrySnapshot = {
|
||||
...initial,
|
||||
sequence: 2,
|
||||
power: {
|
||||
...initial.power,
|
||||
onBattery: "true",
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
|
||||
},
|
||||
};
|
||||
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
|
||||
const receiverLayer = DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(initial),
|
||||
changes: Stream.empty,
|
||||
subscribe: Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(desktopChanges);
|
||||
yield* PubSub.publish(desktopChanges, updated);
|
||||
return {
|
||||
latest: Option.some(initial),
|
||||
changes: Stream.fromSubscription(subscription),
|
||||
};
|
||||
}),
|
||||
});
|
||||
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 100 && (yield* monitor.snapshot).onBattery !== "true";
|
||||
attempt += 1
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect((yield* monitor.snapshot).onBattery).toBe("true");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
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 class HostPowerMonitor extends Context.Service<
|
||||
HostPowerMonitor,
|
||||
{
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
>()("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* (
|
||||
initialSnapshot?: HostPowerSnapshot,
|
||||
) {
|
||||
const initial = initialSnapshot ?? makeUnknownSnapshot("unknown", yield* DateTime.now);
|
||||
const latestRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitor["Service"]["report"] = (snapshot) =>
|
||||
Ref.modify(latestRef, (current) => {
|
||||
if (DateTime.isLessThan(snapshot.updatedAt, current.updatedAt)) {
|
||||
return [Option.none<HostPowerSnapshot>(), current] as const;
|
||||
}
|
||||
return [
|
||||
samePowerState(current, snapshot) ? Option.none() : Option.some(snapshot),
|
||||
snapshot,
|
||||
] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.void,
|
||||
onSome: (next) => PubSub.publish(changes, next),
|
||||
}),
|
||||
),
|
||||
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 desktopSubscription = yield* desktopTelemetry.subscribe;
|
||||
const initial = desktopSubscription.latest;
|
||||
const monitor = yield* Option.match(initial, {
|
||||
onNone: () => make(),
|
||||
onSome: (snapshot) => make(snapshot.power),
|
||||
});
|
||||
yield* desktopSubscription.changes.pipe(
|
||||
Stream.map((snapshot) => snapshot.power),
|
||||
Stream.runForEach(monitor.report),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
return monitor;
|
||||
}),
|
||||
);
|
||||
@@ -41,7 +41,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,
|
||||
@@ -286,6 +286,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",
|
||||
@@ -341,12 +343,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);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -85,7 +85,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),
|
||||
@@ -303,6 +303,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),
|
||||
@@ -376,6 +379,9 @@ export const resolveServerConfig = (
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
desktopTelemetryFd,
|
||||
desktopTelemetryControlFd,
|
||||
resourceMonitorPath,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
|
||||
@@ -46,6 +46,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ExternalLauncher from "../process/externalLauncher.ts";
|
||||
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
|
||||
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
import { resolveCliCommand } from "./invocation.ts";
|
||||
import {
|
||||
bootServiceLayer,
|
||||
offerServiceDuringOnboarding,
|
||||
@@ -526,10 +527,11 @@ const connectLinkCommand = Command.make("link", {
|
||||
yield* Console.log("T3 Connect\n");
|
||||
const linked = yield* linkEnvironmentForConnect(flags);
|
||||
if (linked) {
|
||||
const serveCommand = yield* resolveCliCommand("serve");
|
||||
yield* Console.log(
|
||||
flags.publishOnly
|
||||
? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
|
||||
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`t3 serve\` to make this machine reachable.`,
|
||||
: `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
|
||||
);
|
||||
}
|
||||
}),
|
||||
@@ -691,10 +693,15 @@ export const connectCommand = Command.make("connect", {
|
||||
// Connect itself already succeeded; a boot-service failure must not
|
||||
// fail the command, just tell the user what happened and move on.
|
||||
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
|
||||
if (background) {
|
||||
yield* Console.log(
|
||||
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const serveCommand = yield* resolveCliCommand("serve");
|
||||
yield* Console.log(
|
||||
background
|
||||
? "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out."
|
||||
: "\nNext\n Start the server with `t3 serve` to make this machine reachable.",
|
||||
`\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { detectCliRunner, formatCliCommand, suggestedPackageSpec } from "./invocation.ts";
|
||||
|
||||
it("detects package runners from their cache entry paths", () => {
|
||||
assert.equal(detectCliRunner("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"), "npx");
|
||||
assert.equal(
|
||||
detectCliRunner(
|
||||
"C:\\Users\\theo\\AppData\\Local\\npm-cache\\_npx\\abc\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
"npx",
|
||||
);
|
||||
assert.equal(
|
||||
detectCliRunner("/home/theo/.cache/pnpm/dlx/abc/node_modules/t3/dist/bin.mjs"),
|
||||
"pnpm dlx",
|
||||
);
|
||||
assert.equal(
|
||||
detectCliRunner("/home/theo/.local/share/pnpm/.pnpm/dlx/abc/node_modules/t3/dist/bin.mjs"),
|
||||
"pnpm dlx",
|
||||
);
|
||||
assert.equal(
|
||||
detectCliRunner(
|
||||
"C:\\Users\\theo\\AppData\\Local\\pnpm-cache\\dlx\\abc\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
"pnpm dlx",
|
||||
);
|
||||
assert.equal(detectCliRunner("/home/theo/.bun/install/cache/[email protected]/dist/bin.mjs"), "bunx");
|
||||
assert.equal(detectCliRunner("/tmp/bunx-1000-t3@latest/node_modules/t3/dist/bin.mjs"), "bunx");
|
||||
assert.equal(
|
||||
detectCliRunner(
|
||||
"C:\\Users\\theo\\AppData\\Local\\Temp\\bunx-0-t3@latest\\node_modules\\t3\\dist\\bin.mjs",
|
||||
),
|
||||
"bunx",
|
||||
);
|
||||
});
|
||||
|
||||
it("treats stable installs as direct invocations", () => {
|
||||
assert.isNull(detectCliRunner("/usr/local/lib/node_modules/t3/dist/bin.mjs"));
|
||||
assert.isNull(detectCliRunner("/home/theo/Code/work/t3code/apps/server/dist/bin.mjs"));
|
||||
assert.isNull(detectCliRunner("/home/theo/.t3/runtime/0.0.31/node_modules/t3/dist/bin.mjs"));
|
||||
assert.isNull(detectCliRunner(""));
|
||||
});
|
||||
|
||||
it("re-suggests the nightly channel only for nightly builds", () => {
|
||||
assert.equal(suggestedPackageSpec("0.0.31-nightly.20260729"), "t3@nightly");
|
||||
assert.equal(suggestedPackageSpec("0.0.31"), "t3");
|
||||
});
|
||||
|
||||
it("formats serve suggestions to match the launching command", () => {
|
||||
assert.equal(
|
||||
formatCliCommand({
|
||||
subcommand: "serve",
|
||||
entryPath: "/home/theo/.npm/_npx/abc/node_modules/t3/dist/bin.mjs",
|
||||
version: "0.0.31-nightly.20260729",
|
||||
}),
|
||||
"npx t3@nightly serve",
|
||||
);
|
||||
assert.equal(
|
||||
formatCliCommand({
|
||||
subcommand: "serve",
|
||||
entryPath: "/tmp/bunx-1000-t3@latest/node_modules/t3/dist/bin.mjs",
|
||||
version: "0.0.31",
|
||||
}),
|
||||
"bunx t3 serve",
|
||||
);
|
||||
assert.equal(
|
||||
formatCliCommand({
|
||||
subcommand: "serve",
|
||||
entryPath: "/usr/local/lib/node_modules/t3/dist/bin.mjs",
|
||||
version: "0.0.31-nightly.20260729",
|
||||
}),
|
||||
"t3 serve",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { HostProcessArguments } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
|
||||
export type CliRunner = "npx" | "pnpm dlx" | "bunx";
|
||||
|
||||
/**
|
||||
* How the CLI was launched, judged by where its entry script lives. Each
|
||||
* package runner executes out of a distinctive cache/temp layout:
|
||||
*
|
||||
* npx ~/.npm/_npx/<hash>/node_modules/...
|
||||
* pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
|
||||
* or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
|
||||
* bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
|
||||
*
|
||||
* Global installs and repo checkouts match none of these and return null.
|
||||
* Detection is best-effort; callers must fail closed to a plain `t3` command.
|
||||
*/
|
||||
export function detectCliRunner(entryPath: string): CliRunner | null {
|
||||
const path = entryPath.replaceAll("\\", "/");
|
||||
if (path.includes("/_npx/")) {
|
||||
return "npx";
|
||||
}
|
||||
if (
|
||||
path.includes("/pnpm/dlx/") ||
|
||||
path.includes("/.pnpm/dlx/") ||
|
||||
path.includes("/pnpm-cache/dlx/")
|
||||
) {
|
||||
return "pnpm dlx";
|
||||
}
|
||||
if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
|
||||
return "bunx";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `t3` package spec to suggest. The literal spec the user typed (e.g.
|
||||
* `t3@nightly`) is resolved away before our process starts, so re-derive it
|
||||
* from the running version: nightly builds re-suggest the nightly channel,
|
||||
* anything else suggests the bare package.
|
||||
*/
|
||||
export function suggestedPackageSpec(version: string): string {
|
||||
return version.includes("-nightly.") ? "t3@nightly" : "t3";
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a `t3 <subcommand>` suggestion that matches how this process was
|
||||
* launched, so copy/pasting it actually works: `npx t3 connect` suggests
|
||||
* `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
|
||||
* keeps the `@nightly` tag.
|
||||
*/
|
||||
export function formatCliCommand(input: {
|
||||
readonly subcommand: string;
|
||||
readonly entryPath: string;
|
||||
readonly version: string;
|
||||
}): string {
|
||||
const runner = detectCliRunner(input.entryPath);
|
||||
if (runner === null) {
|
||||
return `t3 ${input.subcommand}`;
|
||||
}
|
||||
return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
|
||||
}
|
||||
|
||||
/** `formatCliCommand` against this process's real entry path and version. */
|
||||
export const resolveCliCommand = (subcommand: string) =>
|
||||
Effect.map(HostProcessArguments, (processArguments) =>
|
||||
formatCliCommand({
|
||||
subcommand,
|
||||
entryPath: processArguments[1] ?? "",
|
||||
version: packageJson.version,
|
||||
}),
|
||||
);
|
||||
@@ -337,7 +337,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
return yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
|
||||
@@ -76,6 +76,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;
|
||||
@@ -186,6 +189,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
desktopTelemetryFd: undefined,
|
||||
desktopTelemetryControlFd: undefined,
|
||||
resourceMonitorPath: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
|
||||
@@ -1,282 +1,132 @@
|
||||
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({ generation: 0, 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 processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
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,8 +134,160 @@ 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("refuses to signal when a fresh identity check cannot be collected", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
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 staleTelemetry = yield* Effect.service(ResourceTelemetry.ResourceTelemetry).pipe(
|
||||
Effect.flatMap((telemetry) => telemetry.latest),
|
||||
Effect.provide(makeTelemetryLayer(snapshot)),
|
||||
);
|
||||
const telemetryLayer = Layer.succeed(
|
||||
ResourceTelemetry.ResourceTelemetry,
|
||||
ResourceTelemetry.ResourceTelemetry.of({
|
||||
latest: Effect.succeed(staleTelemetry),
|
||||
changes: Stream.empty,
|
||||
subscribe: Effect.die("unused"),
|
||||
readHistory: () => Effect.die("unused"),
|
||||
refresh: Effect.fail(
|
||||
new ResourceTelemetry.ResourceTelemetryRefreshFailed({
|
||||
operation: "refresh",
|
||||
cause: new Error("collector unavailable"),
|
||||
}),
|
||||
),
|
||||
validateProcessIdentity: () => Effect.die("unused"),
|
||||
retry: Effect.die("unused"),
|
||||
}),
|
||||
);
|
||||
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: "SIGINT",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4_242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
"Could not refresh process 4242; refusing to signal a stale 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."),
|
||||
});
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((processDiagnostics) => processDiagnostics.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
expect(diagnostics.processes).toEqual([]);
|
||||
expect(diagnostics.processCount).toBe(0);
|
||||
expect(diagnostics.totalCpuPercent).toBe(0);
|
||||
expect(diagnostics.totalRssBytes).toBe(0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,105 +1,20 @@
|
||||
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;
|
||||
}
|
||||
|
||||
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>;
|
||||
}
|
||||
>()("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",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
serverPid: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
|
||||
"ProcessDiagnosticsSignalFailedError",
|
||||
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
|
||||
"ProcessSignalFailed",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
signal: Schema.String,
|
||||
@@ -111,458 +26,136 @@ 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);
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
{
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly startTimeMs: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
return rows;
|
||||
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 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 refreshedTelemetry = telemetry.refresh.pipe(Effect.catch(() => telemetry.latest));
|
||||
const read: ProcessDiagnostics["Service"]["read"] = refreshedTelemetry.pipe(
|
||||
Effect.map((snapshot) => {
|
||||
const processes = snapshot.processes
|
||||
.filter((entry) => canSignalCategory(entry.category))
|
||||
.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")(
|
||||
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,
|
||||
}),
|
||||
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.refresh.pipe(Effect.option);
|
||||
if (Option.isNone(current)) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
`Could not refresh process ${input.pid}; refusing to signal a stale identity.`,
|
||||
),
|
||||
};
|
||||
}
|
||||
const selected = current.value.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* 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: ProcessDiagnosticsError) =>
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
message: Option.some(
|
||||
error instanceof Error ? error.message : "Failed to signal process.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -572,4 +165,4 @@ export const make = Effect.gen(function* () {
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make);
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,255 +1,170 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
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 type { ResourceTelemetryHistoryWithLegacyBuckets } from "../resourceTelemetry/ResourceTelemetryHistory.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: ResourceTelemetryHistoryWithLegacyBuckets = {
|
||||
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,
|
||||
},
|
||||
],
|
||||
legacyBackendBuckets: [
|
||||
{
|
||||
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
|
||||
endedAt: readAt,
|
||||
avgCpuPercent: 5,
|
||||
maxCpuPercent: 8,
|
||||
maxRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
maxProcessCount: 1,
|
||||
},
|
||||
],
|
||||
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,
|
||||
},
|
||||
{
|
||||
identity: { pid: 5_000, startTimeMs: 200 },
|
||||
ppid: 1,
|
||||
depth: 0,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
category: "electron-main",
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 50,
|
||||
avgCpuPercent: 40,
|
||||
maxCpuPercent: 80,
|
||||
cpuTimeMs: 15_000,
|
||||
currentRssBytes: 20_480,
|
||||
peakRssBytes: 40_960,
|
||||
ioReadBytes: 10_240,
|
||||
ioWriteBytes: 20_480,
|
||||
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.ResourceTelemetry["Service"] = {
|
||||
latest: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
subscribe: Effect.die("unused"),
|
||||
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: 5,
|
||||
maxCpuPercent: 8,
|
||||
maxRssBytes: 4_096,
|
||||
maxProcessCount: 1,
|
||||
});
|
||||
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
|
||||
expect(result.error).toEqual(
|
||||
Option.some({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "collector stalled",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,55 +1,14 @@
|
||||
import {
|
||||
ServerProcessResourceHistoryFailureTag,
|
||||
type ServerProcessResourceHistoryBucket,
|
||||
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
|
||||
type ServerProcessResourceHistoryInput,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProcessResourceHistorySummary,
|
||||
import type {
|
||||
ResourceTelemetryProcessCategory,
|
||||
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";
|
||||
|
||||
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;
|
||||
}
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
@@ -60,270 +19,69 @@ export class ProcessResourceMonitor extends Context.Service<
|
||||
}
|
||||
>()("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),
|
||||
function isLegacyBackendCategory(category: ResourceTelemetryProcessCategory): boolean {
|
||||
return (
|
||||
category === "server" ||
|
||||
category === "server-child" ||
|
||||
category === "provider-root" ||
|
||||
category === "terminal-root"
|
||||
);
|
||||
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,
|
||||
}),
|
||||
}));
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
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,
|
||||
});
|
||||
});
|
||||
telemetry.readHistory(input).pipe(
|
||||
Effect.map((history) => {
|
||||
const topProcesses = history.topProcesses
|
||||
.filter((entry) => isLegacyBackendCategory(entry.category))
|
||||
.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.legacyBackendBuckets ?? 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,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make);
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
@@ -10,6 +10,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";
|
||||
|
||||
@@ -18,6 +19,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),
|
||||
@@ -32,6 +34,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
|
||||
|
||||
@@ -1270,6 +1270,175 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("windows thread activity while preserving unresolved request payloads", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_pending_approvals`;
|
||||
yield* sql`DELETE FROM projection_thread_activities`;
|
||||
yield* sql`DELETE FROM projection_threads`;
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id, title, workspace_root, default_model_selection_json,
|
||||
scripts_json, created_at, updated_at, deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-window', 'Window Project', '/tmp/window-project',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
|
||||
'2026-04-10T00:00:00.000Z', '2026-04-10T00:00:01.000Z', NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id, project_id, title, model_selection_json, runtime_mode,
|
||||
interaction_mode, branch, worktree_path, latest_turn_id,
|
||||
latest_user_message_at, pending_approval_count, pending_user_input_count,
|
||||
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-window', 'project-window', 'Window Thread',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
|
||||
NULL, NULL, NULL, NULL, 1, 1, 0,
|
||||
'2026-04-10T00:00:02.000Z', '2026-04-10T00:00:03.000Z', NULL, NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'approval-old', 'thread-window', NULL, 'approval', 'approval.requested',
|
||||
'Approve old command', '{"requestId":"approval-1","requestKind":"command"}',
|
||||
NULL, '2026-04-10T00:00:04.000Z'
|
||||
),
|
||||
(
|
||||
'user-input-old', 'thread-window', NULL, 'approval', 'user-input.requested',
|
||||
'Answer old question',
|
||||
'{"requestId":"input-1","questions":[{"id":"q1","header":"Choice","question":"Continue?","options":[{"label":"Yes","description":"Continue"}]}]}',
|
||||
NULL, '2026-04-10T00:00:05.000Z'
|
||||
),
|
||||
(
|
||||
'user-input-closed', 'thread-window', NULL, 'approval', 'user-input.requested',
|
||||
'Closed old question', '{"requestId":"input-closed"}',
|
||||
NULL, '2026-04-10T00:00:06.000Z'
|
||||
),
|
||||
(
|
||||
'user-input-closed-resolution', 'thread-window', NULL, 'info',
|
||||
'user-input.resolved', 'Closed old question', '{"requestId":"input-closed"}',
|
||||
NULL, '2026-04-10T00:00:07.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_pending_approvals (
|
||||
request_id, thread_id, turn_id, status, decision, created_at, resolved_at
|
||||
)
|
||||
VALUES (
|
||||
'approval-1', 'thread-window', NULL, 'pending', NULL,
|
||||
'2026-04-10T00:00:04.000Z', NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
WITH RECURSIVE activity_sequence(value) AS (
|
||||
SELECT 1
|
||||
UNION ALL
|
||||
SELECT value + 1 FROM activity_sequence WHERE value < 510
|
||||
)
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
)
|
||||
SELECT
|
||||
printf('recent-%04d', value),
|
||||
'thread-window',
|
||||
NULL,
|
||||
'tool',
|
||||
'command',
|
||||
printf('Recent activity %d', value),
|
||||
'{}',
|
||||
value,
|
||||
'2026-04-10T00:01:00.000Z'
|
||||
FROM activity_sequence
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
|
||||
sequence, created_at
|
||||
)
|
||||
VALUES (
|
||||
'opaque-newest', 'thread-window', NULL, 'tool', 'command',
|
||||
'Newest sequenced activity', '{}', 511, '2026-04-10T00:01:00.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
const detail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-window"));
|
||||
assert.equal(detail._tag, "Some");
|
||||
if (detail._tag === "Some") {
|
||||
assert.equal(detail.value.hasMoreActivities, true);
|
||||
assert.equal(detail.value.activities.length, 502);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "approval-old"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "user-input-old"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "user-input-closed"),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "recent-0010"),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "recent-0011"),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
detail.value.activities.some((row) => row.id === "recent-0012"),
|
||||
true,
|
||||
);
|
||||
assert.equal(detail.value.activities.at(-1)?.id, "opaque-newest");
|
||||
}
|
||||
|
||||
yield* sql`
|
||||
DELETE FROM projection_thread_activities
|
||||
WHERE activity_id IN (
|
||||
'user-input-old',
|
||||
'user-input-closed',
|
||||
'user-input-closed-resolution'
|
||||
)
|
||||
OR activity_id BETWEEN 'recent-0001' AND 'recent-0011'
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET pending_user_input_count = 0
|
||||
WHERE thread_id = 'thread-window'
|
||||
`;
|
||||
|
||||
const fullyHydratedDetail = yield* snapshotQuery.getThreadDetailById(
|
||||
ThreadId.make("thread-window"),
|
||||
);
|
||||
assert.equal(fullyHydratedDetail._tag, "Some");
|
||||
if (fullyHydratedDetail._tag === "Some") {
|
||||
assert.equal(fullyHydratedDetail.value.activities.length, 501);
|
||||
assert.equal(fullyHydratedDetail.value.hasMoreActivities, undefined);
|
||||
assert.equal(fullyHydratedDetail.value.activities[0]?.id, "approval-old");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
@@ -108,6 +108,9 @@ const ProjectionCountsRowSchema = Schema.Struct({
|
||||
projectCount: Schema.Number,
|
||||
threadCount: Schema.Number,
|
||||
});
|
||||
const ProjectionThreadActivityCountRowSchema = Schema.Struct({
|
||||
activityCount: Schema.Number,
|
||||
});
|
||||
const WorkspaceRootLookupInput = Schema.Struct({
|
||||
workspaceRoot: Schema.String,
|
||||
});
|
||||
@@ -139,6 +142,7 @@ const ProjectionFullThreadDiffContextRowSchema = Schema.Struct({
|
||||
latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),
|
||||
toCheckpointRef: Schema.NullOr(CheckpointRef),
|
||||
});
|
||||
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
@@ -254,6 +258,21 @@ function mapProposedPlanRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapThreadActivityRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -839,12 +858,128 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM (
|
||||
SELECT *
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY sequence DESC, created_at DESC, activity_id DESC
|
||||
-- The extra row tells the caller whether older work activity exists.
|
||||
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
|
||||
)
|
||||
ORDER BY sequence ASC, created_at ASC, activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadActivityCount = SqlSchema.findOne({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityCountRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT COUNT(*) AS "activityCount"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
// Blocking requests must remain actionable even when their request activity
|
||||
// predates the normal detail window. Return only the latest unresolved
|
||||
// request row for each request id; callers merge these rows with the window.
|
||||
const listPinnedThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
WITH pending_approval_activities AS (
|
||||
SELECT
|
||||
activity.activity_id AS "activityId",
|
||||
activity.thread_id AS "threadId",
|
||||
activity.turn_id AS "turnId",
|
||||
activity.tone,
|
||||
activity.kind,
|
||||
activity.summary,
|
||||
activity.payload_json AS "payload",
|
||||
activity.sequence,
|
||||
activity.created_at AS "createdAt",
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY pending.request_id
|
||||
ORDER BY activity.created_at DESC, activity.activity_id DESC
|
||||
) AS request_order
|
||||
FROM projection_pending_approvals AS pending
|
||||
INNER JOIN projection_thread_activities AS activity
|
||||
ON activity.thread_id = pending.thread_id
|
||||
AND activity.kind = 'approval.requested'
|
||||
AND json_extract(activity.payload_json, '$.requestId') = pending.request_id
|
||||
WHERE pending.thread_id = ${threadId}
|
||||
AND pending.status = 'pending'
|
||||
),
|
||||
user_input_lifecycle AS (
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt",
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY json_extract(payload_json, '$.requestId')
|
||||
ORDER BY created_at DESC, activity_id DESC
|
||||
) AS request_order
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_threads
|
||||
WHERE projection_threads.thread_id = ${threadId}
|
||||
AND projection_threads.pending_user_input_count > 0
|
||||
)
|
||||
AND json_extract(payload_json, '$.requestId') IS NOT NULL
|
||||
AND (
|
||||
kind IN ('user-input.requested', 'user-input.resolved')
|
||||
OR (
|
||||
kind = 'provider.user-input.respond.failed'
|
||||
AND (
|
||||
lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%stale pending user-input request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending user-input request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending user input request%'
|
||||
OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))
|
||||
LIKE '%unknown pending codex user input request%'
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
SELECT
|
||||
"activityId",
|
||||
"threadId",
|
||||
"turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
"payload",
|
||||
sequence,
|
||||
"createdAt"
|
||||
FROM pending_approval_activities
|
||||
WHERE request_order = 1
|
||||
UNION ALL
|
||||
SELECT
|
||||
"activityId",
|
||||
"threadId",
|
||||
"turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
"payload",
|
||||
sequence,
|
||||
"createdAt"
|
||||
FROM user_input_lifecycle
|
||||
WHERE request_order = 1
|
||||
AND kind = 'user-input.requested'
|
||||
ORDER BY "createdAt" ASC, "activityId" ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -1938,6 +2073,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
pinnedActivityRows,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
@@ -1974,6 +2110,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listPinnedThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -2004,6 +2148,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const activityWindowOverflowed = activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW;
|
||||
const recentActivityRows = activityWindowOverflowed
|
||||
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
|
||||
: activityRows;
|
||||
const selectedActivityRows = [
|
||||
...new Map(
|
||||
[...recentActivityRows, ...pinnedActivityRows].map(
|
||||
(row) => [row.activityId, row] as const,
|
||||
),
|
||||
).values(),
|
||||
].toSorted(
|
||||
(left, right) =>
|
||||
(left.sequence ?? -1) - (right.sequence ?? -1) ||
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
const hasMoreActivities = activityWindowOverflowed
|
||||
? (yield* getThreadActivityCount({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getActivityCount:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getActivityCount:decodeRow",
|
||||
),
|
||||
),
|
||||
)).activityCount > selectedActivityRows.length
|
||||
: false;
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
@@ -2038,21 +2209,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
activities: activityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
activities: selectedActivityRows.map(mapThreadActivityRow),
|
||||
...(hasMoreActivities ? { hasMoreActivities: true } : {}),
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
|
||||
@@ -27,9 +27,8 @@ export interface OrchestrationEngineShape {
|
||||
*
|
||||
* @param fromSequenceExclusive - Sequence cursor (exclusive).
|
||||
* @param limit - Maximum number of events to read. Defaults to the event
|
||||
* store's page-bounded default; pass a higher value when the caller must
|
||||
* read every event after the cursor (e.g. per-thread catch-up that filters
|
||||
* a small subset out of a potentially larger global range).
|
||||
* store's page-bounded default. Callers must keep this bounded and replace
|
||||
* stale cursors with a projection snapshot.
|
||||
* @returns Stream containing ordered events.
|
||||
*/
|
||||
readonly readEvents: (
|
||||
|
||||
@@ -32,8 +32,10 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
Effect.fn("environment.orchestration.snapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
// This compatibility endpoint is only used to resolve projects. Keep
|
||||
// its read model lightweight instead of hydrating every thread body.
|
||||
return yield* projectionSnapshotQuery
|
||||
.getSnapshot()
|
||||
.getCommandReadModel()
|
||||
.pipe(
|
||||
Effect.catch((cause) =>
|
||||
failEnvironmentInternal("orchestration_snapshot_failed", cause),
|
||||
|
||||
@@ -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
|
||||
@@ -190,7 +191,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: ProviderMaintenanceCapabilitiesResolver = {
|
||||
resolve: (options) =>
|
||||
makeProviderMaintenanceCapabilities({
|
||||
@@ -66,6 +65,7 @@ const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
|
||||
};
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
@@ -160,8 +160,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
|
||||
@@ -136,7 +136,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,
|
||||
) {
|
||||
@@ -3922,6 +3924,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),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1291,7 +1291,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
scopeClosed = true;
|
||||
|
||||
const threadLogPath = NodePath.join(tempDir, "thread-logger.log");
|
||||
const threadLogPath = NodePath.join(tempDir, "provider-native.thread-logger.log");
|
||||
NodeAssert.equal(NodeFS.existsSync(threadLogPath), true);
|
||||
const contents = NodeFS.readFileSync(threadLogPath, "utf8");
|
||||
NodeAssert.match(contents, /NTIVE: .*"message":"native flush test"/);
|
||||
|
||||
@@ -1646,7 +1646,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;
|
||||
}
|
||||
|
||||
@@ -5,14 +5,30 @@ 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 Fiber from "effect/Fiber";
|
||||
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,
|
||||
type PendingRecord,
|
||||
writeBatchedMessages,
|
||||
} from "./EventNdjsonLogger.ts";
|
||||
|
||||
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
function ownedLogPath(basePath: string, segment: string): string {
|
||||
const basename = NodePath.basename(basePath);
|
||||
const extension = NodePath.extname(basename);
|
||||
const stem = extension.length > 0 ? basename.slice(0, -extension.length) : basename;
|
||||
return NodePath.join(NodePath.dirname(basePath), `${stem}.${segment}.log`);
|
||||
}
|
||||
|
||||
function parseLogLine(line: string) {
|
||||
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
|
||||
assert.notEqual(match, null);
|
||||
@@ -87,8 +103,8 @@ describe("EventNdjsonLogger", () => {
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const threadOnePath = NodePath.join(tempDir, "thread-1.log");
|
||||
const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
|
||||
const threadOnePath = ownedLogPath(basePath, "thread-1");
|
||||
const threadTwoPath = ownedLogPath(basePath, "thread-2");
|
||||
assert.equal(NodeFS.existsSync(threadOnePath), true);
|
||||
assert.equal(NodeFS.existsSync(threadTwoPath), true);
|
||||
|
||||
@@ -129,7 +145,7 @@ describe("EventNdjsonLogger", () => {
|
||||
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = NodePath.join(tempDir, "_global.log");
|
||||
const globalPath = ownedLogPath(basePath, "_global");
|
||||
assert.equal(NodeFS.existsSync(globalPath), true);
|
||||
const lines = NodeFS.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
@@ -138,9 +154,9 @@ describe("EventNdjsonLogger", () => {
|
||||
assert.equal(lines.length, 2);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
|
||||
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
|
||||
assert.equal(lines[0]?.stream, "CANON");
|
||||
assert.equal(lines[0]?.stream, "ORCH");
|
||||
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
|
||||
assert.equal(lines[1]?.stream, "CANON");
|
||||
assert.equal(lines[1]?.stream, "ORCH");
|
||||
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
@@ -148,6 +164,197 @@ 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(ownedLogPath(basePath, "thread-shared"), "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("keeps shared store views non-owning when one adapter closes", () =>
|
||||
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-close");
|
||||
|
||||
yield* native.write({ id: "before-close" }, threadId);
|
||||
yield* native.close();
|
||||
yield* canonical.write({ type: "item.completed", id: "after-close" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-shared-close"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "NTIVE", payload: '{"id":"before-close"}' },
|
||||
{
|
||||
stream: "CANON",
|
||||
payload: '{"type":"item.completed","id":"after-close"}',
|
||||
},
|
||||
],
|
||||
);
|
||||
} 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 = ownedLogPath(basePath, "thread-batched");
|
||||
|
||||
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("does not strand a later batch after an interrupted write", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const threadPath = ownedLogPath(basePath, "thread-interrupted");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
|
||||
const logger = store.logger("native");
|
||||
const interruptedWrite = yield* logger
|
||||
.write({ id: "possibly-interrupted" }, ThreadId.make("thread-interrupted"))
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Fiber.interrupt(interruptedWrite);
|
||||
yield* logger.write({ id: "accepted" }, ThreadId.make("thread-interrupted"));
|
||||
|
||||
yield* TestClock.adjust(1_000);
|
||||
|
||||
assert.equal(NodeFS.existsSync(threadPath), true);
|
||||
assert.include(NodeFS.readFileSync(threadPath, "utf8"), '{"id":"accepted"}');
|
||||
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(ownedLogPath(basePath, "thread-filtered"), "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("contains hostile event accessors inside guarded serialization", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "canonical",
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
assert.exists(logger);
|
||||
if (!logger) return;
|
||||
const hostile = new Proxy(
|
||||
{ id: "hostile" },
|
||||
{
|
||||
get(_target, property) {
|
||||
if (property === "type") throw new Error("blocked");
|
||||
return undefined;
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
yield* logger.write(hostile, ThreadId.make("thread-hostile"));
|
||||
yield* logger.close();
|
||||
|
||||
const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8");
|
||||
assert.notInclude(contents, "blocked");
|
||||
} 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-"));
|
||||
@@ -172,7 +379,7 @@ describe("EventNdjsonLogger", () => {
|
||||
);
|
||||
yield* logger.close();
|
||||
|
||||
const globalPath = NodePath.join(tempDir, "_global.log");
|
||||
const globalPath = ownedLogPath(basePath, "_global");
|
||||
assert.equal(NodeFS.existsSync(globalPath), true);
|
||||
const lines = NodeFS.readFileSync(globalPath, "utf8")
|
||||
.trim()
|
||||
@@ -196,19 +403,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,9 +423,9 @@ describe("EventNdjsonLogger", () => {
|
||||
ThreadId.make("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
yield* store.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const fileStem = NodePath.basename(ownedLogPath(basePath, "thread-rotate"));
|
||||
const matchingFiles = NodeFS.readdirSync(tempDir)
|
||||
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
|
||||
.toSorted();
|
||||
@@ -240,4 +447,143 @@ 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 = ownedLogPath(basePath, "expired");
|
||||
const oldPath = ownedLogPath(basePath, "old");
|
||||
const newPath = ownedLogPath(basePath, "new");
|
||||
const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
|
||||
const legacyLogPath = NodePath.join(tempDir, "legacy-thread.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, unrelatedLogPath, ignoredPath]) {
|
||||
NodeFS.writeFileSync(filePath, "x".repeat(40));
|
||||
}
|
||||
NodeFS.writeFileSync(
|
||||
legacyLogPath,
|
||||
"[2026-01-01T00:00:00.000Z] CANON: legacy provider event\n",
|
||||
);
|
||||
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
|
||||
NodeFS.utimesSync(legacyLogPath, (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(legacyLogPath), false);
|
||||
assert.equal(NodeFS.existsSync(oldPath), false);
|
||||
assert.equal(NodeFS.existsSync(newPath), true);
|
||||
assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
|
||||
assert.equal(NodeFS.existsSync(ignoredPath), true);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not prune an active thread sink during an unrelated flush", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const activePath = ownedLogPath(basePath, "active");
|
||||
|
||||
try {
|
||||
yield* TestClock.setTime(1_800_000_000_000);
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
batchWindowMs: 0,
|
||||
maxAgeMs: 1,
|
||||
retentionCheckIntervalMs: 1,
|
||||
});
|
||||
const logger = store.logger("native");
|
||||
|
||||
yield* logger.write({ id: "active-before-retention" }, ThreadId.make("active"));
|
||||
assert.equal(NodeFS.existsSync(activePath), true);
|
||||
|
||||
yield* TestClock.adjust("2 millis");
|
||||
yield* logger.write({ id: "retention-trigger" }, ThreadId.make("other"));
|
||||
|
||||
assert.equal(NodeFS.existsSync(activePath), true);
|
||||
yield* store.close();
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("attributes batches that were written before a later chunk fails", () => {
|
||||
const records: ReadonlyArray<PendingRecord> = [
|
||||
{
|
||||
stream: "native",
|
||||
threadSegment: "thread",
|
||||
line: "first",
|
||||
bytes: 5,
|
||||
},
|
||||
{
|
||||
stream: "canonical",
|
||||
threadSegment: "thread",
|
||||
line: "second",
|
||||
bytes: 6,
|
||||
},
|
||||
];
|
||||
const attributed: Array<PendingRecord> = [];
|
||||
let writes = 0;
|
||||
|
||||
assert.throws(() =>
|
||||
writeBatchedMessages(
|
||||
{
|
||||
write: () => {
|
||||
writes += 1;
|
||||
if (writes === 2) throw new Error("simulated disk exhaustion");
|
||||
},
|
||||
},
|
||||
records,
|
||||
5,
|
||||
(written) => attributed.push(...written),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(attributed, [records[0]]);
|
||||
});
|
||||
|
||||
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,147 @@ 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 { ResourceAttribution } 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 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?: ResourceAttribution["Service"];
|
||||
}
|
||||
|
||||
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: ResourceAttribution["Service"] | undefined;
|
||||
}
|
||||
|
||||
export 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 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 +163,281 @@ 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" : stream === "orchestration" ? "ORCH" : "CANON";
|
||||
}
|
||||
|
||||
function providerLogPrefix(filePath: string): string {
|
||||
const basename = NodePath.basename(filePath);
|
||||
const extension = NodePath.extname(basename);
|
||||
return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;
|
||||
}
|
||||
|
||||
function providerLogPath(directory: string, prefix: string, threadSegment: string): string {
|
||||
return NodePath.join(directory, `${prefix}${threadSegment}.log`);
|
||||
}
|
||||
|
||||
function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
|
||||
if (stream !== "canonical" || typeof event !== "object" || event === null) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const type = Reflect.get(event, "type");
|
||||
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
export function writeBatchedMessages(
|
||||
sink: Pick<RotatingFileSink, "write">,
|
||||
records: ReadonlyArray<PendingRecord>,
|
||||
maxBytes: number,
|
||||
onWritten: (records: ReadonlyArray<PendingRecord>) => void,
|
||||
): void {
|
||||
let pendingRecords: Array<PendingRecord> = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (pendingRecords.length === 0) return;
|
||||
const writtenRecords = pendingRecords;
|
||||
sink.write(writtenRecords.map((record) => record.line).join(""));
|
||||
onWritten(writtenRecords);
|
||||
pendingRecords = [];
|
||||
pendingBytes = 0;
|
||||
};
|
||||
|
||||
for (const record of records) {
|
||||
if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
|
||||
flush();
|
||||
}
|
||||
pendingRecords.push(record);
|
||||
pendingBytes += record.bytes;
|
||||
if (pendingBytes >= maxBytes) {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {
|
||||
if (!/\.log(?:\.\d+)?$/u.test(fileName)) return false;
|
||||
if (fileName.startsWith(filePrefix)) return true;
|
||||
|
||||
const descriptor = NodeFS.openSync(filePath, "r");
|
||||
try {
|
||||
const header = Buffer.alloc(256);
|
||||
const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);
|
||||
return /^\[[^\]\r\n]+\] (?:NTIVE|CANON|ORCH): /u.test(header.toString("utf8", 0, bytesRead));
|
||||
} finally {
|
||||
NodeFS.closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
function enforceRetention(input: {
|
||||
readonly directory: string;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly activeFilePaths: ReadonlySet<string>;
|
||||
readonly filePrefix: 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()) continue;
|
||||
const filePath = NodePath.join(input.directory, entry.name);
|
||||
try {
|
||||
if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;
|
||||
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 filePrefix: string;
|
||||
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 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) {
|
||||
const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);
|
||||
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) {
|
||||
failures.push({ filePath, cause });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {
|
||||
for (const record of writtenRecords) {
|
||||
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) {
|
||||
sinks.delete(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) =>
|
||||
providerLogPath(input.directory, input.filePrefix, threadSegment),
|
||||
),
|
||||
),
|
||||
filePrefix: input.filePrefix,
|
||||
now: input.now,
|
||||
})
|
||||
: { failures: [] };
|
||||
|
||||
return [
|
||||
{
|
||||
attributions: Array.from(attributionByStream, ([stream, value]) => ({
|
||||
stream,
|
||||
...value,
|
||||
})),
|
||||
failures: [...failures, ...retention.failures],
|
||||
},
|
||||
{
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks,
|
||||
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 +447,170 @@ 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 filePrefix = providerLogPrefix(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(),
|
||||
filePrefix,
|
||||
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(),
|
||||
failedSegments: new Set(),
|
||||
const stateRef = yield* SynchronizedRef.make<StoreState>({
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks: new Map(),
|
||||
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,
|
||||
filePrefix,
|
||||
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.modifyEffect(stateRef, (state) => {
|
||||
if (state.closed) {
|
||||
return Effect.succeed([{ flush: 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;
|
||||
const nextState = {
|
||||
...state,
|
||||
pending,
|
||||
pendingBytes,
|
||||
flushScheduled: state.flushScheduled || schedule,
|
||||
};
|
||||
return (schedule ? scheduleFlush() : Effect.void).pipe(
|
||||
Effect.as([{ flush }, nextState] as const),
|
||||
);
|
||||
}).pipe(Effect.uninterruptible);
|
||||
|
||||
if (action.flush) {
|
||||
yield* flush(false, false);
|
||||
}
|
||||
});
|
||||
|
||||
const view = { filePath, write, close: () => Effect.void } 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),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!store) return undefined;
|
||||
return { ...store.logger(options.stream), close: store.close };
|
||||
});
|
||||
@@ -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,24 +29,23 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderEventLoggersShape {
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger | undefined;
|
||||
}
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as EventNdjsonLogger from "./EventNdjsonLogger.ts";
|
||||
|
||||
/**
|
||||
* Shared logger pair for native + canonical provider event streams.
|
||||
*
|
||||
* Service value is intentionally a struct of two optional loggers rather
|
||||
* than two parallel tags. Construction site is one place
|
||||
* (`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,
|
||||
ProviderEventLoggersShape
|
||||
{
|
||||
readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
}
|
||||
>()("t3/provider/Layers/ProviderEventLoggers") {}
|
||||
|
||||
/**
|
||||
@@ -57,29 +53,38 @@ export class ProviderEventLoggers extends Context.Service<
|
||||
* + canonical logging entirely. Keeps the tag non-optional in the type
|
||||
* system while letting the runtime treat absence as a no-op.
|
||||
*/
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
|
||||
native: undefined,
|
||||
canonical: undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* 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",
|
||||
@@ -109,6 +143,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)),
|
||||
@@ -247,6 +282,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";
|
||||
@@ -65,6 +67,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,
|
||||
@@ -73,6 +76,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,
|
||||
@@ -297,6 +329,11 @@ function makeMutableServerSettingsService(
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changes);
|
||||
},
|
||||
get subscribeChanges() {
|
||||
return PubSub.subscribe(changes).pipe(
|
||||
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
||||
);
|
||||
},
|
||||
} satisfies ServerSettingsModule.ServerSettingsService["Service"];
|
||||
});
|
||||
}
|
||||
@@ -1000,6 +1037,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));
|
||||
@@ -1235,6 +1273,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));
|
||||
@@ -1342,6 +1381,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));
|
||||
@@ -1446,6 +1486,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
|
||||
@@ -1545,6 +1586,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),
|
||||
@@ -1660,6 +1702,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),
|
||||
@@ -1720,6 +1763,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "cursor-agent") {
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
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 Duration from "effect/Duration";
|
||||
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 +99,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 +189,125 @@ 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("disables periodic provider refreshes when the explicit interval is zero", () =>
|
||||
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(() => Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: 0,
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* TestClock.adjust("5 minutes");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(AlwaysRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("wakes a sleeping provider refresh loop when its interval changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const initialServerSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerHealthRefreshInterval: Duration.hours(1),
|
||||
};
|
||||
const serverSettingsRef = yield* Ref.make(initialServerSettings);
|
||||
const serverSettingsChanges = yield* PubSub.unbounded<typeof initialServerSettings>();
|
||||
const serverSettingsLayer = Layer.succeed(
|
||||
ServerSettingsService,
|
||||
ServerSettingsService.of({
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(serverSettingsRef),
|
||||
updateSettings: () => Effect.die(new Error("unused in this test")),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: PubSub.subscribe(serverSettingsChanges).pipe(
|
||||
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
const periodicCheckDone = 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)
|
||||
: Deferred.succeed(periodicCheckDone, undefined).pipe(Effect.ignore),
|
||||
),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
}).pipe(Effect.provide(Layer.merge(BackgroundPolicyAlwaysRunLayer, serverSettingsLayer)));
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
const nextServerSettings = {
|
||||
...initialServerSettings,
|
||||
providerHealthRefreshInterval: Duration.seconds(1),
|
||||
};
|
||||
yield* Ref.set(serverSettingsRef, nextServerSettings);
|
||||
yield* PubSub.publish(serverSettingsChanges, nextServerSettings);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* TestClock.adjust("999 millis");
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
yield* TestClock.adjust("1 millis");
|
||||
yield* Deferred.await(periodicCheckDone);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("reruns the provider check when streamed settings change", () =>
|
||||
@@ -185,7 +352,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 +390,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 +451,6 @@ describe("makeManagedServerProvider", () => {
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,16 +1,23 @@
|
||||
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";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
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 +40,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 +147,68 @@ 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 !== undefined
|
||||
? Effect.succeed(input.refreshInterval)
|
||||
: serverSettings.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) =>
|
||||
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
|
||||
),
|
||||
Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
|
||||
);
|
||||
|
||||
const refreshIntervalChanges = yield* Queue.sliding<void>(1);
|
||||
if (input.refreshInterval === undefined) {
|
||||
const serverSettingsChanges = yield* serverSettings.subscribeChanges;
|
||||
yield* serverSettingsChanges.pipe(
|
||||
Stream.map((settings) =>
|
||||
Duration.toMillis(
|
||||
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
|
||||
),
|
||||
),
|
||||
Stream.changes,
|
||||
Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
|
||||
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) =>
|
||||
Effect.raceFirst(
|
||||
Effect.sleep(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
|
||||
? "60 seconds"
|
||||
: refreshInterval,
|
||||
).pipe(Effect.as(true)),
|
||||
Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
|
||||
).pipe(
|
||||
Effect.flatMap((intervalElapsed) =>
|
||||
intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
|
||||
? hasProviderStatusDemand.pipe(
|
||||
Effect.flatMap((shouldRefresh) =>
|
||||
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user