Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 58340604f0 Prevent leaked Git status fetch packs
Co-authored-by: codex <[email protected]>
2026-06-23 13:20:44 -07:00
Julius Marmingeandcodex 8e2d5d326a Reduce provider observability disk churn
Co-authored-by: codex <[email protected]>
2026-06-23 12:37:48 -07:00
Julius Marminge b239fa9c6d Remove legacy local backend and telemetry RPC
- drop browser-only local backend stubs in favor of desktop bridge
- route resource telemetry through the subscription path
2026-06-23 12:19:40 -07:00
Julius Marmingeandcodex a03b7bce5a Buffer backend output before persisting failure logs
- Capture child process output in memory during normal runs
- Persist buffered output only on failures and bound retained data
- Increase trace/event batching windows to reduce flush churn

Co-authored-by: codex <[email protected]>
2026-06-23 12:19:11 -07:00
Julius Marmingeandcodex 041f875ae5 Route desktop telemetry control and stale power handling
- Add fd5 control channel for desktop telemetry demand
- Stop gating background work on stale host power
- Update telemetry sampling and receiver tests

Co-authored-by: codex <[email protected]>
2026-06-23 12:16:53 -07:00
Julius Marmingeandcodex 1732212b43 feat: add native resource telemetry
Replace scheduled process shell probes with a persistent native collector, Electron power/process telemetry, Effect services, diagnostics UI, attribution, and release packaging.

Co-authored-by: codex <[email protected]>
2026-06-23 12:16:21 -07:00
Julius Marmingeandcodex 1115b14e4d Add background activity policy and host power monitoring
- Track client leases, host power, and background work eligibility
- Route provider snapshot refreshes through shared background policy
- Add tests for the new policy and related server settings wiring

Co-authored-by: codex <[email protected]>
2026-06-23 12:13:16 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
Illia Panasenko 28107e89c2 chore: remove AnnotatableFileDiff leftovers, rename file (#3488) 2026-06-21 20:31:26 -07:00
Julius Marminge 82a9bcc7f4 [codex] add session context to credential errors (#3349) 2026-06-20 20:45:17 -07:00
Julius Marminge 61f8d46fa2 [codex] Enforce Effect error handling conventions (#3380) 2026-06-20 20:43:41 -07:00
Julius Marminge 0debebafbb [codex] Structure thread archive blocked error (#3451) 2026-06-20 20:41:58 -07:00
Julius Marmingeandcodex 2a29de7502 [codex] Structure primary auth validation failures (#3471)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:12 -07:00
Julius Marmingeandcodex 8c1605b383 [codex] Structure OpenCode text generation failures (#3472)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:09 -07:00
Julius Marmingeandcodex 90074e359f [codex] Preserve desktop update state causes (#3473)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:07 -07:00
Julius Marmingeandcodex 6155f5cf64 [codex] Preserve VCS project config error causes (#3474)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:04 -07:00
Julius Marmingeandcodex e3970e755b [codex] Preserve APNs delivery failure context (#3475)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:01 -07:00
Julius Marmingeandcodex 3c246f56b4 [codex] Structure VCS process boundary errors (#3476)
Co-authored-by: codex <[email protected]>
2026-06-20 20:19:59 -07:00
293 changed files with 18139 additions and 13343 deletions

No files matched your search

+12
View File
@@ -22,6 +22,9 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
@@ -31,6 +34,9 @@ jobs:
- name: Typecheck
run: vpr typecheck
- name: Check resource monitor formatting
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
- name: Build desktop pipeline
run: vp run build:desktop
@@ -55,12 +61,18 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
run: vp run test
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
+51
View File
@@ -272,21 +272,29 @@ jobs:
platform: mac
target: dmg
arch: arm64
rust_target: aarch64-apple-darwin
resource_key: darwin-arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
platform: mac
target: dmg
arch: x64
rust_target: x86_64-apple-darwin
resource_key: darwin-x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
platform: linux
target: AppImage
arch: x64
rust_target: x86_64-unknown-linux-gnu
resource_key: linux-x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
platform: win
target: nsis
arch: x64
rust_target: x86_64-pc-windows-msvc
resource_key: win32-x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
@@ -306,6 +314,11 @@ jobs:
cache: true
run-install: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_target }}
- name: Download relay client tracing config
uses: actions/download-artifact@v8
with:
@@ -533,6 +546,19 @@ jobs:
# done
# fi
- name: Collect resource monitor
shell: bash
run: |
set -euo pipefail
binary_name="t3-resource-monitor"
if [[ "${{ matrix.platform }}" == "win" ]]; then
binary_name="${binary_name}.exe"
fi
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
mkdir -p "$target_dir"
cp "$source_path" "$target_dir/$binary_name"
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -540,6 +566,13 @@ jobs:
path: release-publish/*
if-no-files-found: error
- name: Upload resource monitor
uses: actions/upload-artifact@v7
with:
name: resource-monitor-${{ matrix.resource_key }}
path: resource-monitor-publish/${{ matrix.resource_key }}/*
if-no-files-found: error
publish_cli:
name: Publish CLI to npm
needs: [preflight, relay_public_config, build]
@@ -594,6 +627,24 @@ jobs:
- name: Build CLI package
run: vp run --filter t3 build
- name: Download resource monitors
uses: actions/download-artifact@v8
with:
pattern: resource-monitor-*
path: ${{ runner.temp }}/resource-monitors
- name: Bundle resource monitors into CLI package
shell: bash
run: |
set -euo pipefail
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
resource_key="${artifact_dir##*/resource-monitor-}"
target_dir="apps/server/dist/resource-monitor/${resource_key}"
mkdir -p "$target_dir"
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
done
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
+1
View File
@@ -27,6 +27,7 @@ squashfs-root/
.gstack/
dist-electron/
.electron-runtime/
native/**/target/
node_modules/
.alchemy/
*.log
@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
@@ -55,6 +55,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
@@ -60,7 +60,7 @@ describe("DesktopBackendOutputLog", () => {
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
yield* outputLog.beginSession({ details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
@@ -102,7 +102,8 @@ describe("DesktopBackendOutputLog", () => {
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
yield* outputLog.beginSession({ details: "test" });
yield* outputLog.persistFailure({ details: "failed" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
+133 -32
View File
@@ -17,6 +17,8 @@ export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
interface RotatingLogFileWriter {
readonly filePath: string;
@@ -93,14 +95,13 @@ export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<Des
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
{
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
readonly discardSession: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
@@ -122,10 +123,76 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
writeSessionBoundary: () => Effect.void,
beginSession: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
};
interface BufferedBackendOutputChunk {
readonly streamName: "stdout" | "stderr";
readonly chunk: Uint8Array;
}
interface BackendOutputSession {
readonly runId: string;
readonly startDetails: string;
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
readonly byteLength: number;
}
function appendBoundedOutputChunk(
session: BackendOutputSession,
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): BackendOutputSession {
if (chunk.byteLength === 0) {
return session;
}
const retainedChunk =
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
: chunk.slice();
const chunks = [...session.chunks, { streamName, chunk: retainedChunk }];
let byteLength = session.byteLength + retainedChunk.byteLength;
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
let firstRetainedIndex = 0;
while (overflow > 0) {
const first = chunks[firstRetainedIndex];
if (!first) break;
if (first.chunk.byteLength <= overflow) {
overflow -= first.chunk.byteLength;
byteLength -= first.chunk.byteLength;
firstRetainedIndex += 1;
continue;
}
chunks[firstRetainedIndex] = {
...first,
chunk: first.chunk.slice(overflow),
};
byteLength -= overflow;
overflow = 0;
}
const excessChunks = Math.max(
0,
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
);
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
}
firstRetainedIndex += excessChunks;
return {
...session,
chunks: chunks.slice(firstRetainedIndex),
byteLength,
};
}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
@@ -338,44 +405,78 @@ export const make = Effect.gen(function* () {
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
phase,
details: sanitizeLogValue(details),
},
});
},
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
details,
}) {
const runId = yield* currentDesktopRunId;
yield* Ref.set(
sessionRef,
Option.some({
runId,
startDetails: sanitizeLogValue(details),
chunks: [],
byteLength: 0,
}),
);
}),
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
yield* Ref.update(
sessionRef,
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
);
}),
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
details,
}) {
const session = yield* Ref.modify(sessionRef, (current) => [
current,
Option.map(current, (value) => ({ ...value, chunks: [], byteLength: 0 })),
]);
if (Option.isNone(session)) return;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process failure output start",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId: session.value.runId,
phase: "START",
details: session.value.startDetails,
},
});
for (const output of session.value.chunks) {
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
level: output.streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
runId: session.value.runId,
stream: output.streamName,
text: textDecoder.decode(output.chunk),
},
});
},
),
}
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process failure output end",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId: session.value.runId,
phase: "END",
details: sanitizeLogValue(details),
},
});
}),
discardSession: Ref.set(sessionRef, Option.none()),
}) satisfies DesktopBackendOutputLog["Service"],
});
+128 -21
View File
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
runningUnderArm64Translation: false,
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
const makeEnvironmentLayer = (baseDir: string) =>
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
}),
),
),
@@ -112,41 +112,56 @@ describe("DesktopObservability", () => {
),
);
it.effect("persists backend child output as structured JSON records in development", () =>
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-log-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir);
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const tracePath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
});
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
yield* Effect.scoped(
Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.beginSession({
details: "pid=123 port=3773 cwd=/repo",
});
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
assert.isFalse(yield* fileSystem.exists(logPath));
yield* outputLog.persistFailure({ details: "code=1" });
yield* outputLog.beginSession({ details: "pid=456" });
yield* outputLog.writeOutputChunk(
"stderr",
new TextEncoder().encode("normal shutdown\n"),
);
yield* outputLog.discardSession;
}).pipe(
Effect.annotateLogs({ runId: "test-run" }),
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const log = yield* fileSystem.readFileString(logPath);
const lines = log.trimEnd().split("\n");
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
assert.equal(boundary.message, "backend child process session start");
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(lines.length, 3);
assert.equal(start.message, "backend child process failure output start");
assert.equal(start.level, "ERROR");
assert.equal(start.annotations.component, "desktop-backend-child");
assert.equal(start.annotations.runId, "test-run");
assert.equal(start.annotations.phase, "START");
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
assert.equal(output.message, "backend child process output");
assert.equal(output.level, "INFO");
@@ -154,6 +169,98 @@ describe("DesktopObservability", () => {
assert.equal(output.annotations.runId, "test-run");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
assert.equal(end.message, "backend child process failure output end");
assert.equal(end.level, "ERROR");
assert.equal(end.annotations.phase, "END");
assert.equal(end.annotations.details, "code=1");
const traceRecords = (yield* fileSystem.readFileString(tracePath))
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => decodeTraceRecordLine(line));
assert.isFalse(
traceRecords.some(
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
),
);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("retains only the last mebibyte of backend child output", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-bound-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
const maxBufferedBytes = 1024 * 1024;
const discardedPrefixBytes = 128;
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
output.fill("x".charCodeAt(0));
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
yield* Effect.scoped(
Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.beginSession({ details: "pid=123" });
yield* outputLog.writeOutputChunk("stderr", output);
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
const text = record.annotations.text;
assert.equal(typeof text, "string");
if (typeof text !== "string") {
return;
}
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
assert.isFalse(text.includes("y"));
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
),
);
it.effect("bounds the number of retained backend child output chunks", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-output-chunks-test-",
});
const environmentLayer = makeEnvironmentLayer(baseDir, false);
const logPath = yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return environment.path.join(environment.logDir, "server-child.log");
}).pipe(Effect.provide(environmentLayer));
yield* Effect.scoped(
Effect.gen(function* () {
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.beginSession({ details: "pid=123" });
for (let index = 0; index < 300; index += 1) {
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
}
yield* outputLog.persistFailure({ details: "code=1" });
}).pipe(
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
),
);
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
assert.equal(lines.length, 258);
}).pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
+1 -1
View File
@@ -12,7 +12,7 @@ import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
@@ -47,6 +47,7 @@ function makeEnvironmentLayer(
options?: {
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly resourcesPath?: string;
},
) {
return DesktopEnvironment.layer({
@@ -57,7 +58,7 @@ function makeEnvironmentLayer(
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: options?.isPackaged ?? true,
resourcesPath: "/missing/resources",
resourcesPath: options?.resourcesPath ?? "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
@@ -254,4 +255,39 @@ describe("DesktopBackendConfiguration", () => {
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("passes the packaged resource monitor path to the backend", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const resourcesPath = `${baseDir}/resources`;
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
recursive: true,
});
yield* fileSystem.writeFileString(monitorPath, "binary");
yield* fileSystem.chmod(monitorPath, 0o755);
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolve;
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
resourcesPath,
}),
),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -75,6 +75,42 @@ const logBackendObservabilitySettingsReadFailure = (
);
};
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
}
const resolveResourceMonitorPath = Effect.fn(
"desktop.backendConfiguration.resolveResourceMonitorPath",
)(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const binaryName = resourceMonitorBinaryName(environment.platform);
const candidates = environment.isDevelopment
? [
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/debug",
binaryName,
),
environment.path.join(
environment.rootDir,
"native/resource-monitor/target/release",
binaryName,
),
]
: environment.resolveResourcePathCandidates(
environment.path.join("resource-monitor", binaryName),
);
for (const candidate of candidates) {
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return Option.some(candidate);
}
}
return Option.none<string>();
});
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -104,6 +140,7 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
function* (input: {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
readonly resourceMonitorPath: Option.Option<string>;
}): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
@@ -130,6 +167,12 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
...Option.match(input.resourceMonitorPath, {
onNone: () => ({}),
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
}),
...Option.match(input.observabilitySettings.otlpTracesUrl, {
onNone: () => ({}),
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
@@ -169,9 +212,14 @@ export const make = Effect.gen(function* () {
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
resourceMonitorPath,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
@@ -1,6 +1,7 @@
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
DesktopTelemetryControlMessage,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
@@ -26,12 +27,16 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const encodeDesktopTelemetryControl = Schema.encodeSync(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -47,6 +52,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
desktopBootstrapToken: "token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
},
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
@@ -63,6 +70,7 @@ function makeProcess(options?: {
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
@@ -74,7 +82,7 @@ function makeProcess(options?: {
kill: options?.kill ?? (() => Effect.void),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
unref: Effect.succeed(Effect.void),
});
}
@@ -111,6 +119,9 @@ function makeManagerLayer(input: {
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
readonly desktopState?: DesktopState.DesktopState["Service"];
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
readonly desktopTelemetryPublisher?: Partial<
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) {
return DesktopBackendManager.layer.pipe(
@@ -124,12 +135,21 @@ function makeManagerLayer(input: {
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
latest: Effect.succeed(Option.none()),
changes: Stream.empty,
encoded: Stream.empty,
handleControl: () => Effect.void,
...input.desktopTelemetryPublisher,
}),
input.desktopState
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
: DesktopState.layer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
writeSessionBoundary: () => Effect.void,
beginSession: () => Effect.void,
writeOutputChunk: () => Effect.void,
persistFailure: () => Effect.void,
discardSession: Effect.void,
...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
Layer.succeed(DesktopWindow.DesktopWindow, {
@@ -205,8 +225,7 @@ describe("DesktopBackendManager", () => {
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
},
});
@@ -229,6 +248,8 @@ describe("DesktopBackendManager", () => {
assert.equal(spawnedCommand.options.stderr, "pipe");
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
assert.isDefined(spawnedCommand.options.forceKillAfter);
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
assert.equal(
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
2_000,
@@ -288,6 +309,7 @@ describe("DesktopBackendManager", () => {
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
@@ -327,7 +349,10 @@ describe("DesktopBackendManager", () => {
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
@@ -368,7 +393,10 @@ describe("DesktopBackendManager", () => {
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
@@ -412,6 +440,7 @@ describe("DesktopBackendManager", () => {
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
@@ -451,6 +480,7 @@ describe("DesktopBackendManager", () => {
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
onOutput: () => Effect.fail(outputCause),
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
@@ -476,6 +506,88 @@ describe("DesktopBackendManager", () => {
}),
);
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
Effect.gen(function* () {
const handled = yield* Deferred.make<boolean>();
const controlMessage = encodeDesktopTelemetryControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
getOutputFd: (fd) =>
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
desktopTelemetryPublisher: {
handleControl: (message) =>
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.isTrue(yield* Deferred.await(handled));
}).pipe(Effect.provide(managerLayer));
}),
);
it.effect("drains trailing child output before persisting an unexpected exit", () =>
Effect.gen(function* () {
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
const outputDrainStarted = yield* Deferred.make<void>();
const outputChunks = yield* Ref.make<Array<string>>([]);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fromEffect(
Deferred.succeed(outputDrainStarted, void 0).pipe(
Effect.andThen(Effect.sleep(Duration.millis(50))),
Effect.as(new TextEncoder().encode("trailing output\n")),
),
),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
}),
),
),
);
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
writeOutputChunk: (_streamName, chunk) =>
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
persistFailure: () =>
Ref.get(outputChunks).pipe(
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
Effect.asVoid,
),
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* Deferred.await(outputDrainStarted);
yield* TestClock.adjust(Duration.millis(50));
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
@@ -513,8 +625,7 @@ describe("DesktopBackendManager", () => {
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
},
});
@@ -547,6 +658,8 @@ describe("DesktopBackendManager", () => {
const ready = yield* Deferred.make<void>();
const backendReady = yield* Ref.make(false);
const quitting = yield* Ref.make(false);
let persistedFailureCount = 0;
let discardedSessionCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -578,6 +691,15 @@ describe("DesktopBackendManager", () => {
desktopWindow: {
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
},
backendOutputLog: {
persistFailure: () =>
Effect.sync(() => {
persistedFailureCount += 1;
}),
discardSession: Effect.sync(() => {
discardedSessionCount += 1;
}),
},
});
yield* Effect.gen(function* () {
@@ -597,6 +719,8 @@ describe("DesktopBackendManager", () => {
yield* manager.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
assert.equal(persistedFailureCount, 0);
assert.equal(discardedSessionCount, 1);
const stoppedSnapshot = yield* manager.snapshot;
assert.isFalse(yield* Ref.get(backendReady));
@@ -610,6 +734,7 @@ describe("DesktopBackendManager", () => {
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const failures = yield* Queue.unbounded<string>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
@@ -629,6 +754,9 @@ describe("DesktopBackendManager", () => {
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
backendOutputLog: {
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
},
});
yield* Effect.gen(function* () {
@@ -636,6 +764,7 @@ describe("DesktopBackendManager", () => {
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
yield* TestClock.adjust(Duration.millis(499));
assert.equal(yield* Queue.size(starts), 0);
@@ -692,6 +821,13 @@ describe("DesktopBackendManager", () => {
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* manager.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* manager.start;
assert.equal(yield* Queue.take(starts), 2);
+103 -32
View File
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Ndjson from "effect/unstable/encoding/Ndjson";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -21,11 +22,14 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
DesktopTelemetryControlMessage,
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
} from "@t3tools/contracts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
@@ -34,6 +38,7 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.millis(250);
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
@@ -172,6 +177,10 @@ export const BackendProcessError = Schema.Union([
export type BackendProcessError = typeof BackendProcessError.Type;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
readonly onDesktopTelemetryControl?: (
message: DesktopTelemetryControlMessageValue,
) => Effect.Effect<void>;
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
@@ -327,6 +336,7 @@ function drainBackendOutput(
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
@@ -345,6 +355,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
fd3: {
type: "input",
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
},
};
if (options.bootstrap.desktopTelemetryFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
type: "input",
stream: options.desktopTelemetryStream,
};
}
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
type: "output",
};
}
const command = ChildProcess.make(
options.executablePath,
[options.entryPath, "--bootstrap-fd", "3"],
@@ -359,12 +386,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
stderr: options.captureOutput ? "pipe" : "inherit",
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
additionalFds: {
fd3: {
type: "input",
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
},
},
additionalFds,
},
);
@@ -380,8 +402,35 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
}),
),
);
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (
options.bootstrap.desktopTelemetryControlFd !== undefined &&
options.onDesktopTelemetryControl !== undefined
) {
const controlFd = options.bootstrap.desktopTelemetryControlFd;
const handleControl = options.onDesktopTelemetryControl;
yield* handle.getOutputFd(controlFd).pipe(
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
Stream.runForEach(handleControl),
Effect.catchCause((cause) =>
logBackendManagerWarning("desktop telemetry control stream stopped", {
fd: controlFd,
cause: Cause.pretty(cause),
}),
),
Effect.ensuring(
handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
}),
),
Effect.forkScoped,
);
}
if (options.captureOutput) {
const outputContext = {
executablePath: options.executablePath,
@@ -391,20 +440,22 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
outputFibers.push(
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped),
);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
@@ -420,7 +471,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.forkScoped,
);
const exitCode = yield* handle.exitCode.pipe(
const exit = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
@@ -432,7 +483,16 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
cause,
}),
),
Effect.exit,
);
yield* Effect.forEach(outputFibers, Fiber.await, {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
if (Exit.isFailure(exit)) {
return yield* Effect.failCause(exit.cause);
}
const exitCode = exit.value;
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
@@ -445,6 +505,7 @@ export const make = Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const desktopState = yield* DesktopState.DesktopState;
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
@@ -581,10 +642,13 @@ export const make = Effect.gen(function* () {
if (isCurrentRun) {
if (Option.isSome(pid)) {
yield* backendOutputLog.writeSessionBoundary({
phase: "END",
details: `pid=${pid.value} ${reason}`,
});
if (nextState.desiredRunning) {
yield* backendOutputLog.persistFailure({
details: `pid=${pid.value} ${reason}`,
});
} else {
yield* backendOutputLog.discardSession;
}
}
yield* Ref.set(desktopState.backendReady, false);
}
@@ -598,13 +662,14 @@ export const make = Effect.gen(function* () {
const program = runBackendProcess({
...config.value,
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
yield* backendOutputLog.beginSession({
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
@@ -637,10 +702,16 @@ export const make = Effect.gen(function* () {
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error,
}),
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
function* (error) {
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
error,
});
yield* backendOutputLog.persistFailure({
details: error.message,
});
},
),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
@@ -761,7 +832,7 @@ export const make = Effect.gen(function* () {
});
yield* Option.match(active, {
onNone: () => Effect.void,
onSome: (run) => closeRun(run, options),
onSome: (run) => closeRun(run, options).pipe(Effect.andThen(backendOutputLog.discardSession)),
});
});
+2
View File
@@ -57,6 +57,7 @@ export class ElectronApp extends Context.Service<
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
protocol: string,
@@ -150,6 +151,7 @@ export const make = ElectronApp.of({
Electron.app.setAppUserModelId(id);
}),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
setAsDefaultProtocolClient: (protocol, path, args) =>
@@ -0,0 +1,89 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
export interface ElectronPowerMonitorShape {
readonly isOnBatteryPower: Effect.Effect<boolean>;
readonly getSystemIdleTime: Effect.Effect<number>;
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
readonly onSimpleEvent: (
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onThermalStateChange: (
listener: (state: ElectronThermalState) => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly onSpeedLimitChange: (
listener: (limit: number) => void,
) => Effect.Effect<void, never, Scope.Scope>;
}
export class ElectronPowerMonitor extends Context.Service<
ElectronPowerMonitor,
ElectronPowerMonitorShape
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on(eventName as any, listener as any);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener(eventName as any, listener as any);
}),
).pipe(Effect.asVoid);
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
): void => {
listener(event.state);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("thermal-state-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
}),
).pipe(Effect.asVoid);
};
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
const wrapped = (
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
): void => {
listener(event.limit);
};
return Effect.acquireRelease(
Effect.sync(() => {
Electron.powerMonitor.on("speed-limit-change", wrapped);
}),
() =>
Effect.sync(() => {
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
}),
).pipe(Effect.asVoid);
};
export const make = ElectronPowerMonitor.of({
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
getSystemIdleState: (idleThresholdSeconds) =>
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
onSimpleEvent,
onThermalStateChange,
onSpeedLimitChange,
});
export const layer = Layer.succeed(ElectronPowerMonitor, make);
@@ -46,49 +46,14 @@ describe("ElectronShell", () => {
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("preserves safe URL context and cause when Electron rejects openExternal", () =>
it.effect("returns false when Electron rejects openExternal", () =>
Effect.gen(function* () {
const cause = new Error("open failed");
openExternalMock.mockRejectedValue(cause);
const externalUrl =
"HTTPS://user:[email protected]:443/signed-secret-token/path?access_token=secret#fragment";
openExternalMock.mockRejectedValue(new Error("open failed"));
const electronShell = yield* ElectronShell.ElectronShell;
const error = yield* Effect.flip(electronShell.openExternal(externalUrl));
const result = yield* electronShell.openExternal("https://example.com/path");
assert.instanceOf(error, ElectronShell.ElectronShellOpenExternalError);
assert.isTrue(ElectronShell.isElectronShellError(error));
assert.strictEqual(error.urlHostname, "example.com");
assert.strictEqual(error.urlLength, externalUrl.length);
assert.strictEqual(error.urlProtocol, "https:");
assert.strictEqual(error.cause, cause);
assert.notProperty(error, "externalUrl");
assert.notProperty(error, "requestTarget");
assert.notMatch(
error.message,
/user|password|signed-secret-token|path|access_token|secret|fragment/,
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronShell.layer)),
);
it.effect("preserves non-sensitive clipboard context and cause", () =>
Effect.gen(function* () {
const cause = new Error("clipboard failed");
writeTextMock.mockImplementation(() => {
throw cause;
});
const electronShell = yield* ElectronShell.ElectronShell;
const error = yield* Effect.flip(electronShell.copyText("secret text"));
assert.instanceOf(error, ElectronShell.ElectronShellCopyTextError);
assert.isTrue(ElectronShell.isElectronShellError(error));
assert.strictEqual(error.textLength, 11);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "11 characters");
assert.notInclude(error.message, "secret text");
assert.notInclude(error.message, cause.message);
assert.equal(result, false);
}).pipe(Effect.provide(ElectronShell.layer)),
);
});
+13 -65
View File
@@ -1,47 +1,12 @@
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as Context from "effect/Context";
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 Electron from "electron";
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
export class ElectronShellOpenExternalError extends Schema.TaggedErrorClass<ElectronShellOpenExternalError>()(
"ElectronShellOpenExternalError",
{
urlHostname: Schema.String,
urlLength: Schema.Number,
urlProtocol: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to open external URL for ${this.urlHostname} (${this.urlProtocol}, input length ${this.urlLength}).`;
}
}
export class ElectronShellCopyTextError extends Schema.TaggedErrorClass<ElectronShellCopyTextError>()(
"ElectronShellCopyTextError",
{
textLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to copy ${this.textLength} characters to the clipboard.`;
}
}
export const ElectronShellError = Schema.Union([
ElectronShellOpenExternalError,
ElectronShellCopyTextError,
]);
export type ElectronShellError = typeof ElectronShellError.Type;
export const isElectronShellError = Schema.is(ElectronShellError);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
return Option.none();
@@ -55,46 +20,29 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
}
}
function describeExternalUrl(externalUrl: string, inputLength: number) {
const diagnostics = getUrlDiagnostics(externalUrl);
return {
urlHostname: diagnostics.hostname ?? "",
urlLength: inputLength,
urlProtocol: diagnostics.protocol ?? "",
};
}
export class ElectronShell extends Context.Service<
ElectronShell,
{
readonly openExternal: (
rawUrl: unknown,
) => Effect.Effect<boolean, ElectronShellOpenExternalError>;
readonly copyText: (text: string) => Effect.Effect<void, ElectronShellCopyTextError>;
readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
readonly copyText: (text: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronShell") {}
export const make = ElectronShell.of({
openExternal: (rawUrl) => {
const inputLength = typeof rawUrl === "string" ? rawUrl.length : 0;
return Option.match(parseSafeExternalUrl(rawUrl), {
openExternal: (rawUrl) =>
Option.match(parseSafeExternalUrl(rawUrl), {
onNone: () => Effect.succeed(false),
onSome: (externalUrl) =>
Effect.tryPromise({
try: () => Electron.shell.openExternal(externalUrl),
catch: (cause) =>
new ElectronShellOpenExternalError({
...describeExternalUrl(externalUrl, inputLength),
cause,
}),
}).pipe(Effect.as(true)),
});
},
Effect.promise(() =>
Electron.shell.openExternal(externalUrl).then(
() => true,
() => false,
),
),
}),
copyText: (text) =>
Effect.try({
try: () => Electron.clipboard.writeText(text),
catch: (cause) => new ElectronShellCopyTextError({ textLength: text.length, cause }),
Effect.sync(() => {
Electron.clipboard.writeText(text);
}),
});
+1
View File
@@ -32,6 +32,7 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
@@ -1,28 +1,16 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshPasswordPromptCancellationError,
} from "@t3tools/contracts";
import { SshHttpBridgeError, SshPasswordPromptError } from "@t3tools/ssh/errors";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import {
DesktopSshEnvironmentRequestError,
ensureSshEnvironment,
fetchSshEnvironmentDescriptor,
} from "./sshEnvironment.ts";
import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
const decodeDesktopSshEnvironmentEnsureResult = Schema.decodeUnknownEffect(
DesktopSshEnvironmentEnsureResultSchema,
);
function jsonResponse(request: HttpClientRequest.HttpClientRequest, body: unknown, status = 200) {
return HttpClientResponse.fromWeb(
@@ -46,44 +34,6 @@ function makeHttpClientLayer(
}
describe("SSH environment IPC", () => {
it.effect("encodes password prompt cancellations with structured context and their cause", () => {
const promptCause = new DesktopSshPasswordPrompts.DesktopSshPromptWindowClosedError({
requestId: "prompt-1",
destination: "[email protected]",
});
const cause = new SshPasswordPromptError({
message: promptCause.message,
cause: promptCause,
});
const layer = Layer.succeed(
DesktopSshEnvironment.DesktopSshEnvironment,
DesktopSshEnvironment.DesktopSshEnvironment.of({
discoverHosts: () => Effect.die("unexpected host discovery"),
ensureEnvironment: () => Effect.fail(cause),
disconnectEnvironment: () => Effect.die("unexpected disconnect"),
}),
);
return Effect.gen(function* () {
const encoded = yield* ensureSshEnvironment.handler({
target: {
alias: "devbox",
hostname: "devbox.example.test",
username: "developer",
port: 22,
},
});
const error = yield* decodeDesktopSshEnvironmentEnsureResult(encoded);
assert.instanceOf(error, DesktopSshPasswordPromptCancellationError);
assert.equal(error.reason, "window-closed");
assert.equal(error.requestId, "prompt-1");
assert.equal(error.destination, "[email protected]");
assert.instanceOf(error.cause, Error);
assert.instanceOf(error.cause.cause, Error);
}).pipe(Effect.provide(layer));
});
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
const layer = makeHttpClientLayer((request) =>
+14 -23
View File
@@ -2,7 +2,7 @@ import {
bootstrapRemoteBearerSession,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
isRemoteEnvironmentAuthUndeclaredStatusError,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
@@ -15,7 +15,7 @@ import {
DesktopSshEnvironmentEnsureResultSchema,
DesktopSshEnvironmentTargetSchema,
DesktopSshHttpBaseUrlInputSchema,
DesktopSshPasswordPromptCancellationError,
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
EnvironmentInternalError,
@@ -45,13 +45,6 @@ type DesktopSshEnvironmentRequestOperation =
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
const desktopSshPasswordPromptCancellationReasons = {
DesktopSshPromptCancelledError: "user-cancelled",
DesktopSshPromptWindowClosedError: "window-closed",
DesktopSshPromptServiceStoppedError: "service-stopped",
DesktopSshPromptTimedOutError: "timed-out",
} as const;
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
@@ -59,7 +52,10 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || cause instanceof SshHttpBridgeError) {
if (
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
cause instanceof SshHttpBridgeError
) {
return cause.status ?? null;
}
if (isEnvironmentRequestInvalidError(cause)) {
@@ -131,19 +127,14 @@ export const ensureSshEnvironment = DesktopIpc.makeIpcMethod({
}) {
const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment;
return yield* sshEnvironment.ensureEnvironment(target, options).pipe(
Effect.catchTags({
SshPasswordPromptError: (error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed(
new DesktopSshPasswordPromptCancellationError({
reason: desktopSshPasswordPromptCancellationReasons[error.cause._tag],
requestId: error.cause.requestId,
destination: error.cause.destination,
cause: error,
}),
)
: Effect.fail(error),
}),
Effect.catch((error) =>
DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation(error)
? Effect.succeed({
type: DesktopSshPasswordPromptCancelledType,
message: error.message,
})
: Effect.fail(error),
),
);
}),
});
@@ -1,34 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import { openExternal } from "./window.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
describe("window IPC", () => {
it.effect("returns false when Electron rejects an external URL", () => {
const url = "https://example.com/path";
const error = new ElectronShell.ElectronShellOpenExternalError({
urlHostname: "example.com",
urlLength: url.length,
urlProtocol: "https:",
cause: new Error("open failed"),
});
const layer = Layer.mergeAll(
Layer.succeed(
ElectronShell.ElectronShell,
ElectronShell.ElectronShell.of({
openExternal: () => Effect.fail(error),
copyText: () => Effect.void,
}),
),
Logger.layer([], { mergeWithExisting: false }),
);
return Effect.gen(function* () {
const opened = yield* openExternal.handler(url);
assert.equal(opened, false);
}).pipe(Effect.provide(layer));
});
});
+1 -15
View File
@@ -7,7 +7,6 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
@@ -142,19 +141,6 @@ export const openExternal = DesktopIpc.makeIpcMethod({
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
const shell = yield* ElectronShell.ElectronShell;
return yield* shell.openExternal(url).pipe(
Effect.catchTag("ElectronShellOpenExternalError", (error) =>
Effect.logWarning(error.message).pipe(
Effect.annotateLogs({
error: Redacted.make(error, { label: error._tag }),
"error.type": error._tag,
"desktop.external_url.hostname": error.urlHostname,
"desktop.external_url.input_length": error.urlLength,
"desktop.external_url.protocol": error.urlProtocol,
}),
Effect.as(false),
),
),
);
return yield* shell.openExternal(url);
}),
});
+4
View File
@@ -18,6 +18,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
import * as ElectronMenu from "./electron/ElectronMenu.ts";
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
@@ -46,6 +47,7 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -105,6 +107,7 @@ const electronLayer = Layer.mergeAll(
ElectronApp.layer,
ElectronDialog.layer,
ElectronMenu.layer,
ElectronPowerMonitor.layer,
ElectronProtocol.layer,
ElectronSafeStorage.layer,
ElectronShell.layer,
@@ -146,6 +149,7 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopTelemetryPublisher.layer),
Layer.provideMerge(desktopWindowLayer),
);
+12 -15
View File
@@ -1,31 +1,28 @@
import {
DesktopSshPasswordPromptCancellationError,
DesktopSshPasswordPromptCancellationErrorTag,
type DesktopBridge,
type DesktopPreviewPointerEvent,
type DesktopPreviewRecordingFrame,
type DesktopPreviewTabState,
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import * as Schema from "effect/Schema";
import * as IpcChannels from "./ipc/channels.ts";
exposeClerkBridge({ passkeys: true });
const decodeDesktopSshPasswordPromptCancellationError = Schema.decodeUnknownSync(
DesktopSshPasswordPromptCancellationError,
);
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
result !== null &&
"_tag" in result &&
result._tag === DesktopSshPasswordPromptCancellationErrorTag
"type" in result &&
result.type === IpcChannels.SSH_PASSWORD_PROMPT_CANCELLED_RESULT
) {
throw decodeDesktopSshPasswordPromptCancellationError(result);
const message =
"message" in result && typeof result.message === "string"
? result.message
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}
+41 -44
View File
@@ -534,9 +534,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
),
);
const tabIdForWebContents = Effect.fn("PreviewManager.tabIdForWebContents")(function* (
webContentsId: number,
) {
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
const tabs = yield* SynchronizedRef.get(tabsRef);
return (
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
@@ -546,7 +544,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
const captureDiagnosticMessage = Effect.fnUntraced(function* (
webContentsId: number,
method: string,
params: Record<string, unknown>,
@@ -724,47 +722,46 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
const semaphore = yield* Semaphore.make(1);
const scope = yield* Scope.fork(parentScope, "sequential");
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
function* (method: string, params: Record<string, unknown>) {
if (method === "Page.screencastFrame") {
const sessionId = params["sessionId"];
if (typeof sessionId === "number") {
yield* attemptPromise(
{
operation: "ackScreencastFrame",
webContentsId: wc.id,
},
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
).pipe(Effect.ignore);
}
const tabId = yield* tabIdForWebContents(wc.id);
const metadata =
typeof params["metadata"] === "object" && params["metadata"] !== null
? (params["metadata"] as Record<string, unknown>)
: {};
if (tabId && typeof params["data"] === "string") {
const receivedAt = yield* currentIso;
const listeners = yield* Ref.get(recordingFrameListenersRef);
const frame: DesktopPreviewRecordingFrame = {
tabId,
data: params["data"],
width:
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
height:
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
receivedAt,
};
yield* Effect.forEach(
listeners,
(listener) =>
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
const handleDebuggerMessage = Effect.fnUntraced(function* (
method: string,
params: Record<string, unknown>,
) {
if (method === "Page.screencastFrame") {
const sessionId = params["sessionId"];
if (typeof sessionId === "number") {
yield* attemptPromise(
{
operation: "ackScreencastFrame",
webContentsId: wc.id,
},
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
).pipe(Effect.ignore);
}
yield* captureDiagnosticMessage(wc.id, method, params);
},
);
const tabId = yield* tabIdForWebContents(wc.id);
const metadata =
typeof params["metadata"] === "object" && params["metadata"] !== null
? (params["metadata"] as Record<string, unknown>)
: {};
if (tabId && typeof params["data"] === "string") {
const receivedAt = yield* currentIso;
const listeners = yield* Ref.get(recordingFrameListenersRef);
const frame: DesktopPreviewRecordingFrame = {
tabId,
data: params["data"],
width: typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
height:
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
receivedAt,
};
yield* Effect.forEach(
listeners,
(listener) => deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
}
yield* captureDiagnosticMessage(wc.id, method, params);
});
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
runFork(handleDebuggerMessage(method, params));
};
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -75,9 +75,7 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError & {
readonly cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptCancellation;
} {
): error is SshPasswordPromptError {
return (
error instanceof SshPasswordPromptError &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
@@ -0,0 +1,196 @@
import { assert, describe, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
function makeElectronAppLayer(
metrics: ReadonlyArray<Electron.ProcessMetric>,
onMetricsRead: () => void = () => undefined,
) {
return Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
relaunch: () => Effect.void,
setPath: () => Effect.void,
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.sync(() => {
onMetricsRead();
return metrics;
}),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
}
describe("DesktopTelemetryPublisher", () => {
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
Effect.gen(function* () {
const onBattery = yield* Ref.make(false);
let metricsReadCount = 0;
const simpleListeners = new Map<string, () => void>();
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
null;
let speedLimitListener: ((limit: number) => void) | null = null;
const metrics = [
{
pid: 4_242,
type: "Browser",
creationTime: 1_000,
name: "electron",
cpu: {
percentCPUUsage: 12.5,
cumulativeCPUUsage: 3.25,
idleWakeupsPerSecond: 7,
},
memory: {
workingSetSize: 2_048,
peakWorkingSetSize: 4_096,
},
} as Electron.ProcessMetric,
];
const powerLayer = Layer.succeed(
ElectronPowerMonitor.ElectronPowerMonitor,
ElectronPowerMonitor.ElectronPowerMonitor.of({
isOnBatteryPower: Ref.get(onBattery),
getSystemIdleTime: Effect.succeed(5),
getSystemIdleState: () => Effect.succeed("active"),
getCurrentThermalState: Effect.succeed("nominal"),
onSimpleEvent: (eventName, listener) =>
Effect.sync(() => {
simpleListeners.set(eventName, listener);
}),
onThermalStateChange: (listener) =>
Effect.sync(() => {
thermalListener = listener;
}),
onSpeedLimitChange: (listener) =>
Effect.sync(() => {
speedLimitListener = listener;
}),
}),
);
const layer = DesktopTelemetryPublisher.layer.pipe(
Layer.provide(
Layer.mergeAll(
makeElectronAppLayer(metrics, () => {
metricsReadCount += 1;
}),
powerLayer,
),
),
);
yield* Effect.gen(function* () {
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
const decoder = new TextDecoder();
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
assert.equal(messages[0]?.type, "desktopTelemetryHello");
assert.equal(messages[0]?.electronPid, process.pid);
assert.equal(messages[1]?.type, "desktopTelemetry");
assert.deepEqual(messages[1]?.electronProcesses, []);
assert.equal(messages[1]?.electronPid, process.pid);
assert.equal(metricsReadCount, 0);
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: true,
});
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
assert.equal(metricsReadCount, 1);
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* Ref.set(onBattery, true);
simpleListeners.get("on-battery")?.();
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
assert.equal(batterySnapshot.power.onBattery, "true");
const metricsAfterBatteryEvent = metricsReadCount;
yield* TestClock.adjust(Duration.millis(4_999));
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
thermalListener?.("serious");
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
assert.equal(constrainedSnapshot.power.thermalState, "serious");
const metricsAfterThermalEvent = metricsReadCount;
yield* TestClock.adjust(Duration.millis(14_999));
assert.equal(metricsReadCount, metricsAfterThermalEvent);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
speedLimitListener?.(65);
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* publisher.handleControl({
version: 1,
type: "setDiagnosticsDemand",
enabled: false,
});
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
const backgroundSequence = stoppedSnapshot.sequence;
const metricsAfterStopping = metricsReadCount;
yield* TestClock.adjust(Duration.seconds(29));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
backgroundSequence,
);
assert.equal(metricsReadCount, metricsAfterStopping);
yield* TestClock.adjust(Duration.seconds(1));
assert.equal(
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
backgroundSequence + 1,
);
assert.equal(metricsReadCount, metricsAfterStopping);
}).pipe(Effect.provide(layer));
}),
);
});
@@ -0,0 +1,264 @@
import {
DesktopHostTelemetryMessage,
type DesktopHostTelemetrySnapshot,
type DesktopTelemetryControlMessage,
type HostPowerSnapshot,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
const IDLE_THRESHOLD_SECONDS = 60;
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
const textEncoder = new TextEncoder();
type PowerEvent =
| { readonly type: "locked"; readonly value: boolean }
| { readonly type: "suspended"; readonly value: boolean }
| { readonly type: "onBattery"; readonly value: boolean }
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
| { readonly type: "speedLimit"; readonly value: number };
interface PowerState {
readonly locked: HostPowerSnapshot["locked"];
readonly suspended: boolean;
readonly onBattery: HostPowerSnapshot["onBattery"];
readonly thermalState: HostPowerSnapshot["thermalState"];
readonly speedLimitPercent: Option.Option<number>;
}
export interface DesktopTelemetryPublisherShape {
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
readonly encoded: Stream.Stream<Uint8Array>;
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
}
export class DesktopTelemetryPublisher extends Context.Service<
DesktopTelemetryPublisher,
DesktopTelemetryPublisherShape
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
return value ? "true" : "false";
}
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
switch (value) {
case "active":
return "false";
case "idle":
case "locked":
return "true";
case "unknown":
return "unknown";
}
}
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
switch (event.type) {
case "locked":
return { ...state, locked: booleanState(event.value) };
case "suspended":
return { ...state, suspended: event.value };
case "onBattery":
return { ...state, onBattery: booleanState(event.value) };
case "thermal":
return { ...state, thermalState: event.value };
case "speedLimit":
return { ...state, speedLimitPercent: Option.some(event.value) };
}
}
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
if (
power.suspended ||
power.locked === "true" ||
power.thermalState === "serious" ||
power.thermalState === "critical"
) {
return CONSTRAINED_SAMPLE_INTERVAL;
}
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
return LIVE_SAMPLE_INTERVAL;
}
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
yield* electronApp.whenReady;
const initialPowerState: PowerState = {
locked: "unknown",
suspended: false,
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
thermalState: yield* powerMonitor.getCurrentThermalState,
speedLimitPercent: Option.none(),
};
const powerState = yield* Ref.make(initialPowerState);
const powerEvents = yield* Queue.unbounded<PowerEvent>();
const sampleTriggers = yield* Queue.sliding<void>(1);
const diagnosticsDemand = yield* Ref.make(false);
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
const sequence = yield* Ref.make(0);
const offer = (event: PowerEvent): void => {
Queue.offerUnsafe(powerEvents, event);
};
yield* Effect.all(
[
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
],
{ concurrency: "unbounded" },
);
yield* Effect.forever(
Queue.take(powerEvents).pipe(
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
),
).pipe(Effect.forkScoped);
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
const demand = yield* Ref.get(diagnosticsDemand);
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
[
Ref.get(powerState),
powerMonitor.getSystemIdleTime,
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
powerMonitor.isOnBatteryPower,
demand ? electronApp.getAppMetrics : Effect.succeed([]),
],
{ concurrency: "unbounded" },
);
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
const snapshot: DesktopHostTelemetrySnapshot = {
version: 1,
type: "desktopTelemetry",
sequence: nextSequence,
sampledAtUnixMs,
electronPid: process.pid,
power: {
source: "electron-main",
idle: idleState(systemIdleState),
idleSeconds,
locked,
suspended: currentPower.suspended,
onBattery: booleanState(onBattery),
lowPowerMode: "unknown",
thermalState: currentPower.thermalState,
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: currentPower.speedLimitPercent,
electronProcesses: metrics.map((metric) => ({
pid: metric.pid,
creationTimeMs: metric.creationTime,
type: metric.type,
...(metric.name === undefined ? {} : { name: metric.name }),
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
cpuPercent: metric.cpu.percentCPUUsage,
...(metric.cpu.cumulativeCPUUsage === undefined
? {}
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
})),
};
yield* Ref.set(latest, Option.some(snapshot));
yield* PubSub.publish(changes, snapshot);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to sample Electron telemetry", {
cause: String(cause),
}),
),
);
yield* Effect.gen(function* () {
yield* sampleOnce;
while (true) {
const [currentPower, demand] = yield* Effect.all([
Ref.get(powerState),
Ref.get(diagnosticsDemand),
]);
yield* Effect.raceFirst(
Queue.take(sampleTriggers),
Effect.sleep(sampleInterval(currentPower, demand)),
);
yield* sampleOnce;
}
}).pipe(Effect.forkScoped);
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
switch (message.type) {
case "setDiagnosticsDemand":
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
Effect.flatMap((previous) =>
previous === message.enabled
? Effect.void
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
),
);
}
};
const snapshots = Stream.concat(
Stream.unwrap(
Ref.get(latest).pipe(
Effect.map(
Option.match({
onNone: () => Stream.empty,
onSome: Stream.make,
}),
),
),
),
Stream.fromPubSub(changes),
);
const encoded = Stream.concat(
Stream.make({
version: 1,
type: "desktopTelemetryHello",
electronPid: process.pid,
} as const),
snapshots,
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
return DesktopTelemetryPublisher.of({
latest: Ref.get(latest),
changes: Stream.fromPubSub(changes),
encoded,
handleControl,
});
});
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
@@ -40,6 +40,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
+3 -5
View File
@@ -226,9 +226,7 @@ export const make = Effect.gen(function* () {
{
label: "Copy Link",
click: () => {
void runPromise(
electronShell.copyText(params.linkURL).pipe(Effect.ignore({ log: true })),
);
void runPromise(electronShell.copyText(params.linkURL));
},
},
{ type: "separator" },
@@ -255,7 +253,7 @@ export const make = Effect.gen(function* () {
window.webContents.setWindowOpenHandler(({ url }) => {
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
void runPromise(electronShell.openExternal(url));
}
return { action: "deny" };
});
@@ -271,7 +269,7 @@ export const make = Effect.gen(function* () {
event.preventDefault();
if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) {
void runPromise(electronShell.openExternal(url).pipe(Effect.ignore({ log: true })));
void runPromise(electronShell.openExternal(url));
}
});
+28 -49
View File
@@ -3,10 +3,7 @@ import {
type ConnectionCatalogDocument as ConnectionCatalogDocumentType,
EMPTY_CONNECTION_CATALOG_DOCUMENT,
} from "@t3tools/client-runtime/platform";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
} from "@t3tools/client-runtime/connection";
import { ConnectionTransientError } from "@t3tools/client-runtime/connection";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -18,38 +15,30 @@ import { migrateLegacyConnectionCatalog } from "./migration";
export const CONNECTION_CATALOG_KEY = "t3code.connection-catalog.v1";
export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
const decodeCatalog = Effect.fn("mobile.connectionStorage.decodeCatalog")(function* (raw: string) {
return yield* decodeConnectionCatalogDocument(raw).pipe(
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "decode",
backend: "schema",
cause,
}),
),
),
);
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => catalogError("decode", cause),
});
return yield* Effect.fromResult(
Schema.decodeUnknownResult(ConnectionCatalogDocument)(parsed),
).pipe(Effect.mapError((cause) => catalogError("decode", cause)));
});
const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(function* (
catalog: ConnectionCatalogDocumentType,
) {
return yield* encodeConnectionCatalogDocument(catalog).pipe(
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "encode",
backend: "schema",
cause,
}),
),
),
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(ConnectionCatalogDocument)(catalog),
).pipe(Effect.mapError((cause) => catalogError("encode", cause)));
return JSON.stringify(encoded);
});
interface CatalogStore {
@@ -77,21 +66,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
legacyRaw === null || legacyRaw.trim() === ""
? EMPTY_CONNECTION_CATALOG_DOCUMENT
: yield* migrateLegacyConnectionCatalog(legacyRaw).pipe(
Effect.mapError((cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "migrate",
backend: "legacy-migration",
cause,
}),
Effect.mapError((cause) => catalogError("migrate", cause)),
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
),
),
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning("Discarding corrupt legacy mobile connections", error).pipe(
Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
),
}),
);
if (legacyRaw !== null && legacyRaw.trim() !== "") {
const encoded = yield* encodeCatalog(catalog);
@@ -110,13 +90,12 @@ export const makeCatalogStore = Effect.fn("mobile.connectionStorage.makeCatalogS
let catalog: ConnectionCatalogDocumentType;
if (raw !== null && raw.trim() !== "") {
catalog = yield* decodeCatalog(raw).pipe(
Effect.catchTags({
ConnectionTransientError: (error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
}),
Effect.catch((error) =>
Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
Effect.andThen(loadLegacyCatalog()),
),
),
);
} else {
catalog = yield* loadLegacyCatalog();
+1 -25
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { LegacyConnectionMigrationError, migrateLegacyConnectionCatalog } from "./migration";
import { migrateLegacyConnectionCatalog } from "./migration";
describe("migrateLegacyConnectionCatalog", () => {
it.effect("migrates bearer and relay-managed connections into the new catalog", () =>
@@ -75,28 +75,4 @@ describe("migrateLegacyConnectionCatalog", () => {
expect(catalog.targets).toEqual([]);
}),
);
it.effect("preserves parse failures with a stable structural error", () =>
Effect.gen(function* () {
const error = yield* migrateLegacyConnectionCatalog("{not-json").pipe(Effect.flip);
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
expect(error.stage).toBe("parse");
expect(error.cause).toBeInstanceOf(SyntaxError);
expect(error.message).toBe("Could not parse the legacy mobile connection catalog.");
}),
);
it.effect("distinguishes catalog decoding failures", () =>
Effect.gen(function* () {
const error = yield* migrateLegacyConnectionCatalog('{"connections":"invalid"}').pipe(
Effect.flip,
);
expect(error).toBeInstanceOf(LegacyConnectionMigrationError);
expect(error.stage).toBe("decode");
expect(error.cause).toBeDefined();
expect(error.message).toBe("Could not decode the legacy mobile connection catalog.");
}),
);
});
+12 -9
View File
@@ -36,14 +36,9 @@ const decodeLegacyConnectionDocument = Schema.decodeUnknownEffect(LegacyConnecti
export class LegacyConnectionMigrationError extends Schema.TaggedErrorClass<LegacyConnectionMigrationError>()(
"LegacyConnectionMigrationError",
{
stage: Schema.Literals(["parse", "decode"]),
cause: Schema.Defect(),
message: Schema.String,
},
) {
override get message(): string {
return `Could not ${this.stage} the legacy mobile connection catalog.`;
}
}
) {}
function isRelayManaged(connection: typeof LegacySavedRemoteConnection.Type): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
@@ -97,10 +92,18 @@ export const migrateLegacyConnectionCatalog = Effect.fn(
)(function* (raw: string) {
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => new LegacyConnectionMigrationError({ stage: "parse", cause }),
catch: (cause) =>
new LegacyConnectionMigrationError({
message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
}),
});
const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
Effect.mapError((cause) => new LegacyConnectionMigrationError({ stage: "decode", cause })),
Effect.mapError(
(cause) =>
new LegacyConnectionMigrationError({
message: `Could not decode the legacy mobile connection catalog: ${String(cause)}`,
}),
),
);
return (legacy.connections ?? []).reduce(migrateConnection, EMPTY_CONNECTION_CATALOG_DOCUMENT);
+2 -4
View File
@@ -100,8 +100,7 @@ const capabilitiesLayer = Layer.succeedContext(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: "Could not read the T3 Cloud session token.",
cause: error,
detail: error.message,
}),
),
);
@@ -127,8 +126,7 @@ const capabilitiesLayer = Layer.succeedContext(
catch: (cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: "Could not load the mobile device identity.",
cause,
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
}).pipe(Effect.map(Option.some)),
}),
+85 -268
View File
@@ -10,7 +10,6 @@ import {
} from "@t3tools/client-runtime/platform";
import { TokenStore } from "@t3tools/client-runtime/authorization";
import {
ConnectionStorageOperationError,
ConnectionTransientError,
CredentialStore,
ProfileStore,
@@ -55,11 +54,29 @@ const LegacyStoredShellSnapshot = Schema.Struct({
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeEffect(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshot);
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownEffect(LegacyStoredShellSnapshot);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
});
}
function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
@@ -83,14 +100,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource: "thread-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError(operation, cause),
});
},
);
@@ -100,63 +110,38 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
threadId: ThreadId,
operation: "load-thread" | "save-thread" | "remove-thread",
) {
const directory = yield* threadSnapshotDirectory(environmentId, operation);
return yield* Effect.tryPromise({
try: async () => {
const { File } = await import("expo-file-system");
return new File(directory, threadSnapshotFileName(threadId));
},
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
});
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(
yield* threadSnapshotDirectory(environmentId, operation),
threadSnapshotFileName(threadId),
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.getItemAsync(key),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "load",
backend: "mobile-secure-storage",
key,
cause,
}),
),
catch: (cause) => catalogError("load", cause),
}),
setItem: (key, value) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(key, value),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "save",
backend: "mobile-secure-storage",
key,
cause,
}),
),
catch: (cause) => catalogError("save", cause),
}),
deleteItem: (key) =>
Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(key),
catch: (cause) =>
ConnectionTransientError.fromStorageFailure(
new ConnectionStorageOperationError({
operation: "delete",
backend: "mobile-secure-storage",
key,
cause,
}),
),
catch: (cause) => catalogError("delete", cause),
}),
};
@@ -171,8 +156,6 @@ const shellSnapshotFileInDirectory = Effect.fn(
operation: "load-shell" | "save-shell" | "clear-environment",
directoryName: string,
) {
const resource =
directoryName === LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY ? "legacy-shell-cache" : "shell-cache";
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
@@ -180,14 +163,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) =>
new ConnectionPersistenceError({
operation,
stage: "resolve",
resource,
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError(operation, cause),
});
});
@@ -208,45 +184,18 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((cause) =>
ConnectionPersistenceError.fromStorageFailure({
operation: "list-targets",
fallbackStage: "read",
resource: "connection-catalog",
cause,
}),
),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(
Effect.mapError((cause) =>
ConnectionPersistenceError.fromStorageFailure({
operation: "register-connection",
fallbackStage: "write",
resource: "connection-catalog",
environmentId: registration.target.environmentId,
cause,
}),
),
),
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(
Effect.mapError((cause) =>
ConnectionPersistenceError.fromStorageFailure({
operation: "remove-connection",
fallbackStage: "write",
resource: "connection-catalog",
environmentId: target.environmentId,
cause,
}),
),
),
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -334,38 +283,15 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "read",
resource: "shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "parse",
resource: "shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* decodeStoredShellSnapshot(parsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "decode",
resource: "shell-cache",
environmentId,
cause,
}),
),
);
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -377,38 +303,15 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "read",
resource: "legacy-shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "parse",
resource: "legacy-shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* decodeLegacyStoredShellSnapshot(legacyParsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-shell",
stage: "decode",
resource: "legacy-shell-cache",
environmentId,
cause,
}),
),
);
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -421,18 +324,9 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
snapshot,
} as const;
const encoded = yield* encodeStoredShellSnapshot(stored).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "encode",
resource: "shell-cache",
environmentId,
cause,
}),
),
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -440,14 +334,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) =>
new ConnectionPersistenceError({
operation: "save-shell",
stage: "write",
resource: "shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadThread: (environmentId, threadId) =>
@@ -458,41 +345,15 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "read",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "parse",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* decodeStoredThreadSnapshot(parsed).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "load-thread",
stage: "decode",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
),
);
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -500,24 +361,14 @@ export const connectionStorageLayer = Layer.effectContext(
saveThread: (environmentId, thread) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}).pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "encode",
resource: "thread-cache",
environmentId,
threadId: thread.id,
cause,
}),
),
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -525,63 +376,36 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) =>
new ConnectionPersistenceError({
operation: "save-thread",
stage: "write",
resource: "thread-cache",
environmentId,
threadId: thread.id,
cause,
}),
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "remove-thread",
stage: "remove",
resource: "thread-cache",
environmentId,
threadId,
cause,
}),
});
file.delete();
}
}),
}).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
),
),
clear: (environmentId) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "legacy-shell-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -591,14 +415,7 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) =>
new ConnectionPersistenceError({
operation: "clear-environment",
stage: "remove",
resource: "thread-cache",
environmentId,
cause,
}),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
+1 -79
View File
@@ -9,11 +9,8 @@ import * as Effect from "effect/Effect";
import { verifyDpopProof } from "@t3tools/shared/dpop";
import {
CloudDpopProofError,
CloudDpopStorageError,
createDpopProof,
generateDpopProofKeyPair,
isCloudDpopError,
loadOrCreateDpopProofKeyPair,
cryptoLayer,
} from "./dpop";
@@ -98,82 +95,7 @@ describe("mobile DPoP", () => {
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error).toBeInstanceOf(CloudDpopStorageError);
expect(error).toMatchObject({
operation: "decode",
storageKey: "t3code.cloud.dpop-proof-key",
});
expect(isCloudDpopError(error)).toBe(true);
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("rejects stored key material whose public coordinates do not match", () =>
Effect.gen(function* () {
secureStore.clear();
const generated = yield* generateDpopProofKeyPair();
secureStore.set(
"t3code.cloud.dpop-proof-key",
JSON.stringify({ ...generated.privateJwk, x: generated.privateJwk.y }),
);
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
expect(error).toBeInstanceOf(CloudDpopStorageError);
expect(error).toMatchObject({
operation: "restore",
storageKey: "t3code.cloud.dpop-proof-key",
});
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("preserves request context for an invalid proof URL", () =>
Effect.gen(function* () {
const proofKey = yield* generateDpopProofKeyPair();
const error = yield* createDpopProof({
method: "POST",
url: "http://",
proofKey,
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(CloudDpopProofError);
expect(error).toMatchObject({
operation: "normalize-url",
method: "POST",
requestTarget: "<invalid-url>",
urlLength: "http://".length,
thumbprint: proofKey.thumbprint,
});
expect(isCloudDpopError(error)).toBe(true);
}).pipe(Effect.provide(cryptoLayer)),
);
it.effect("redacts credentials and non-HTU URL components from proof failures", () =>
Effect.gen(function* () {
const proofKey = yield* generateDpopProofKeyPair();
const url = "https://user:[email protected]/oauth/token?access_token=secret#fragment";
const error = yield* createDpopProof({
method: "POST",
url,
proofKey: {
...proofKey,
privateJwk: { ...proofKey.privateJwk, d: "%" },
},
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(CloudDpopProofError);
expect(error).toMatchObject({
operation: "import-private-key",
method: "POST",
requestTarget: "https://example.com/oauth/token",
urlLength: url.length,
thumbprint: proofKey.thumbprint,
});
expect(error).not.toHaveProperty("url");
expect(error.message).not.toContain("user");
expect(error.message).not.toContain("password");
expect(error.message).not.toContain("access_token");
expect(error.message).not.toContain("secret");
expect(error.message).not.toContain("fragment");
expect(error.message).toBe("Stored DPoP proof key is invalid.");
}).pipe(Effect.provide(cryptoLayer)),
);
+57 -212
View File
@@ -1,8 +1,8 @@
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as ExpoCrypto from "expo-crypto";
@@ -12,91 +12,19 @@ import {
computeDpopAccessTokenHash,
computeDpopJwkThumbprint,
DpopPublicJwk,
redactDpopRequestTarget,
normalizeDpopHtu,
} from "@t3tools/shared/dpop";
import * as Layer from "effect/Layer";
export class CloudDpopStorageError extends Schema.TaggedErrorClass<CloudDpopStorageError>()(
"CloudDpopStorageError",
{
operation: Schema.Literals(["read", "decode", "restore", "encode", "write"]),
storageKey: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile DPoP key storage operation "${this.operation}" failed for key "${this.storageKey}".`;
}
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
function cloudDpopError(message: string) {
return (cause: unknown) => new CloudDpopError({ message, cause });
}
export class CloudDpopKeyError extends Schema.TaggedErrorClass<CloudDpopKeyError>()(
"CloudDpopKeyError",
{
operation: Schema.Literals(["generate-randomness", "derive-public-key"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile DPoP key operation "${this.operation}" failed.`;
}
}
export class CloudDpopProofError extends Schema.TaggedErrorClass<CloudDpopProofError>()(
"CloudDpopProofError",
{
operation: Schema.Literals([
"import-private-key",
"generate-id",
"normalize-url",
"encode-header",
"encode-payload",
"hash-signing-input",
"sign",
]),
method: Schema.String,
requestTarget: Schema.String,
urlLength: Schema.Number,
thumbprint: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Mobile DPoP proof operation "${this.operation}" failed for ${this.method.toUpperCase()} ${this.requestTarget}.`;
}
}
export class DpopPublicKeyFormatError extends Schema.TaggedErrorClass<DpopPublicKeyFormatError>()(
"DpopPublicKeyFormatError",
{
byteLength: Schema.Number,
firstByte: Schema.optional(Schema.Number),
},
) {
override get message(): string {
const prefix =
this.firstByte === undefined
? "no prefix byte"
: `prefix 0x${this.firstByte.toString(16).padStart(2, "0")}`;
return `Expected a 65-byte uncompressed P-256 public key beginning with 0x04; received ${this.byteLength} bytes with ${prefix}.`;
}
}
export class DpopStoredPublicKeyMismatchError extends Schema.TaggedErrorClass<DpopStoredPublicKeyMismatchError>()(
"DpopStoredPublicKeyMismatchError",
{},
) {
override get message(): string {
return "Stored DPoP private and public key material do not match.";
}
}
export const CloudDpopError = Schema.Union([
CloudDpopStorageError,
CloudDpopKeyError,
CloudDpopProofError,
]);
export type CloudDpopError = typeof CloudDpopError.Type;
export const isCloudDpopError = Schema.is(CloudDpopError);
const DpopPrivateJwkSchema = Schema.Struct({
...DpopPublicJwk.fields,
d: Schema.String,
@@ -169,12 +97,29 @@ function base64UrlToBytes(value: string): Uint8Array {
return Result.getOrThrow(Encoding.decodeBase64Url(value));
}
function sha256Digest(
data: Uint8Array,
message: string,
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
Effect.mapError(cloudDpopError(message)),
);
}
function secureRandomBytes(
byteCount: number,
message: string,
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
Effect.mapError(cloudDpopError(message)),
);
}
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
throw new DpopPublicKeyFormatError({
byteLength: publicKey.length,
...(publicKey[0] === undefined ? {} : { firstByte: publicKey[0] }),
});
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
}
return {
kty: "EC",
@@ -199,16 +144,14 @@ export function generateDpopProofKeyPair(): Effect.Effect<
return Effect.gen(function* () {
let privateKey: Uint8Array;
do {
privateKey = yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomBytes(p256.CURVE.nByteLength)),
Effect.mapError(
(cause) => new CloudDpopKeyError({ operation: "generate-randomness", cause }),
),
privateKey = yield* secureRandomBytes(
p256.CURVE.nByteLength,
"Could not generate DPoP key pair randomness.",
);
} while (!p256.utils.isValidPrivateKey(privateKey));
const publicJwk = yield* Effect.try({
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
catch: (cause) => new CloudDpopKeyError({ operation: "derive-public-key", cause }),
catch: cloudDpopError("Generated DPoP public key is invalid."),
});
const thumbprint = computeDpopJwkThumbprint(publicJwk);
return {
@@ -227,23 +170,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
return Effect.gen(function* () {
const stored = yield* Effect.tryPromise({
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
catch: (cause) =>
new CloudDpopStorageError({
operation: "read",
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
cause,
}),
catch: cloudDpopError("Could not read the DPoP proof key."),
});
if (stored) {
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
Effect.mapError(
(cause) =>
new CloudDpopStorageError({
operation: "decode",
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
cause,
}),
),
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
);
const restored = yield* Effect.try({
try: () => {
@@ -252,16 +183,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
p256.getPublicKey(privateKey, false),
);
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
throw new DpopStoredPublicKeyMismatchError();
throw new Error("Stored DPoP key does not match its public key.");
}
return { privateJwk: storedPrivateJwk, publicJwk };
},
catch: (cause) =>
new CloudDpopStorageError({
operation: "restore",
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
cause,
}),
catch: cloudDpopError("Stored DPoP proof key is invalid."),
});
return {
...restored,
@@ -270,28 +196,23 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
}
const generated = yield* generateDpopProofKeyPair();
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
Effect.mapError(
(cause) =>
new CloudDpopStorageError({
operation: "encode",
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
cause,
}),
),
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
);
yield* Effect.tryPromise({
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
catch: (cause) =>
new CloudDpopStorageError({
operation: "write",
storageKey: DPOP_PROOF_KEY_STORAGE_KEY,
cause,
}),
catch: cloudDpopError("Could not store the DPoP proof key."),
});
return generated;
});
}
function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
const normalized = normalizeDpopHtu(url);
return normalized
? Effect.succeed(normalized)
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
}
export function createDpopProof(input: {
readonly method: string;
readonly url: string;
@@ -304,69 +225,23 @@ export function createDpopProof(input: {
> {
return Effect.gen(function* () {
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
const requestTarget = redactDpopRequestTarget(input.url);
const urlLength = input.url.length;
const privateKey = yield* Effect.try({
try: () => base64UrlToBytes(keyPair.privateJwk.d),
catch: (cause) =>
new CloudDpopProofError({
operation: "import-private-key",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
catch: cloudDpopError("Could not import DPoP private key."),
});
const nowMs = yield* Clock.currentTimeMillis;
const jti = yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
(cause) =>
new CloudDpopProofError({
operation: "generate-id",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
),
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
);
const htu = yield* Effect.try({
try: () => {
const parsed = new URL(input.url);
parsed.hash = "";
parsed.search = "";
return parsed.toString();
},
catch: (cause) =>
new CloudDpopProofError({
operation: "normalize-url",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
});
const htu = yield* normalizeHtu(input.url);
const header = yield* encodeDpopJwtHeaderJson({
typ: "dpop+jwt",
alg: "ES256",
jwk: keyPair.publicJwk,
}).pipe(
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(
(cause) =>
new CloudDpopProofError({
operation: "encode-header",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
),
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
);
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
const payload = yield* encodeDpopJwtPayloadJson({
@@ -377,45 +252,15 @@ export function createDpopProof(input: {
...(ath ? { ath } : {}),
}).pipe(
Effect.map(Encoding.encodeBase64Url),
Effect.mapError(
(cause) =>
new CloudDpopProofError({
operation: "encode-payload",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
),
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
);
const signatureInputHash = yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) =>
crypto.digest("SHA-256", new TextEncoder().encode(`${header}.${payload}`)),
),
Effect.mapError(
(cause) =>
new CloudDpopProofError({
operation: "hash-signing-input",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
),
const signatureInputHash = yield* sha256Digest(
new TextEncoder().encode(`${header}.${payload}`),
"Could not hash DPoP signing input.",
);
const signature = yield* Effect.try({
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
catch: (cause) =>
new CloudDpopProofError({
operation: "sign",
method: input.method,
requestTarget,
urlLength,
thumbprint: keyPair.thumbprint,
cause,
}),
catch: cloudDpopError("Could not sign DPoP proof."),
});
return {
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
@@ -9,11 +9,9 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/unstable/http";
import {
CloudEnvironmentLinkOperationError,
cloudEnvironmentsPendingStatus,
linkEnvironmentToCloud,
connectCloudEnvironment,
isCloudEnvironmentLinkError,
listCloudEnvironments,
listCloudEnvironmentsWithStatus,
normalizeRelayBaseUrl,
@@ -150,46 +148,6 @@ describe("mobile cloud link environment client", () => {
createProofMock.mockClear();
});
it("keeps URL secrets out of operation error diagnostics", () => {
const relayUrl =
"https://relay-user:[email protected]/private/workspace?access_token=relay-secret#relay-fragment";
const httpBaseUrl =
"https://desktop-user:[email protected]/private/workspace?access_token=desktop-secret#desktop-fragment";
const cause = new Error("request failed");
const error = CloudEnvironmentLinkOperationError.fromCause({
action: "link the environment",
cause,
environmentId: "env-1",
relayUrl,
httpBaseUrl,
});
expect(error).toMatchObject({
relayUrlInputLength: relayUrl.length,
relayUrlProtocol: "https:",
relayUrlHostname: "relay.example.test",
httpBaseUrlInputLength: httpBaseUrl.length,
httpBaseUrlProtocol: "https:",
httpBaseUrlHostname: "desktop.example.test",
});
const serialized = JSON.stringify(error);
for (const secret of [
"relay-user",
"relay-password",
"relay-secret",
"relay-fragment",
"/private/workspace",
"desktop-user",
"desktop-password",
"desktop-secret",
"desktop-fragment",
]) {
expect(serialized).not.toContain(secret);
expect(error.message).not.toContain(secret);
}
});
it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
"https://relay.example.test",
@@ -277,14 +235,9 @@ describe("mobile cloud link environment client", () => {
listCloudEnvironments({ clerkToken: "clerk-token" }),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkOperationError",
action: "list cloud environments",
relayUrlInputLength: "https://relay.example.test".length,
relayUrlProtocol: "https:",
relayUrlHostname: "relay.example.test",
_tag: "CloudEnvironmentLinkError",
message: "https://relay.example.test/v1/environments failed",
});
expect(error.message).toBe("Could not list cloud environments.");
expect(isCloudEnvironmentLinkError(error)).toBe(true);
}),
);
@@ -545,7 +498,7 @@ describe("mobile cloud link environment client", () => {
label: "Desktop",
},
status: null,
statusError: 'Could not read cloud environment status for environment "env-1".',
statusError: "https://relay.example.test/v1/environments/env-1/status failed",
},
]);
}),
@@ -609,8 +562,7 @@ describe("mobile cloud link environment client", () => {
label: "Desktop",
},
status: null,
statusError:
'The environment status response identified environment "env-other" instead of "env-1".',
statusError: "Relay returned status for a different environment.",
},
]);
}),
@@ -638,55 +590,13 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentIdMismatchError",
source: "environment link response",
expectedEnvironmentId: "env-1",
actualEnvironmentId: "env-other",
_tag: "CloudEnvironmentLinkError",
message: "Relay returned credentials for a different environment.",
});
expect(fetchMock).toHaveBeenCalledTimes(3);
}),
);
it.effect("reports invalid endpoint URLs with redacted diagnostics", () =>
Effect.gen(function* () {
vi.stubGlobal(
"fetch",
vi.fn(() => Promise.resolve(Response.json(validLinkChallengeResponse()))),
);
const httpBaseUrl =
"https://desktop-user:desktop-password@[invalid-host]/private/workspace?access_token=desktop-secret#desktop-fragment";
const error = yield* withCloudServices(
linkEnvironmentToCloud({
clerkToken: "clerk-token",
connection: {
...savedConnection,
httpBaseUrl,
},
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkOperationError",
action: "derive the environment endpoint origin",
environmentId: "env-1",
httpBaseUrlInputLength: httpBaseUrl.length,
});
expect(error).not.toHaveProperty("httpBaseUrl");
const serialized = JSON.stringify({ ...error, cause: undefined });
for (const secret of [
"desktop-user",
"desktop-password",
"/private/workspace",
"desktop-secret",
"desktop-fragment",
]) {
expect(serialized).not.toContain(secret);
expect(error.message).not.toContain(secret);
}
}),
);
it.effect("preserves typed local environment failures while obtaining a link proof", () =>
Effect.gen(function* () {
const fetchMock = vi.fn((url: string | URL) => {
@@ -697,8 +607,7 @@ describe("mobile cloud link environment client", () => {
Response.json(
{
_tag: "EnvironmentHttpUnauthorizedError",
reason: "cloud_cli_authorization_required",
message: "Run `t3 connect link` to authorize this environment.",
message: "Invalid environment bearer session.",
},
{ status: 401 },
),
@@ -712,20 +621,9 @@ describe("mobile cloud link environment client", () => {
connection: savedConnection,
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkOperationError",
action: "obtain an environment link proof",
environmentId: "env-1",
httpBaseUrlInputLength: "https://desktop.example.test/".length,
httpBaseUrlProtocol: "https:",
httpBaseUrlHostname: "desktop.example.test",
environmentError: {
_tag: "EnvironmentHttpUnauthorizedError",
reason: "cloud_cli_authorization_required",
},
});
expect(error._tag).toBe("CloudEnvironmentLinkError");
expect(error.message).toBe(
'Could not obtain an environment link proof for environment "env-1".',
"Could not obtain environment link proof: Invalid environment bearer session.",
);
expect(fetchMock).toHaveBeenCalledTimes(2);
}),
@@ -761,19 +659,11 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkOperationError",
action: "link the environment",
environmentId: "env-1",
relayUrlInputLength: "https://relay.example.test".length,
relayUrlProtocol: "https:",
relayUrlHostname: "relay.example.test",
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
traceId: "trace-test",
relayError: {
_tag: "RelayEnvironmentLinkProofInvalidError",
reason: "origin_not_allowed",
},
});
expect(error.message).toBe('Could not link the environment for environment "env-1".');
expect(fetchMock).toHaveBeenCalledTimes(3);
}),
);
@@ -806,10 +696,8 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentEndpointProviderMismatchError",
environmentId: "env-1",
expectedProviderKind: "cloudflare_tunnel",
actualProviderKind: "manual",
_tag: "CloudEnvironmentLinkError",
message: "Relay returned credentials for a different endpoint provider.",
});
expect(fetchMock).toHaveBeenCalledTimes(3);
}),
@@ -1074,10 +962,8 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentIdMismatchError",
source: "environment connect response",
expectedEnvironmentId: "env-1",
actualEnvironmentId: "env-other",
_tag: "CloudEnvironmentLinkError",
message: "Relay returned credentials for a different environment.",
});
}),
);
@@ -1119,21 +1005,11 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentLinkOperationError",
action: "connect to the cloud environment",
environmentId: "env-1",
relayUrlInputLength: "https://relay.example.test".length,
relayUrlProtocol: "https:",
relayUrlHostname: "relay.example.test",
_tag: "CloudEnvironmentLinkError",
message:
"https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
traceId: "trace-connect",
relayError: {
_tag: "RelayAuthInvalidError",
reason: "invalid_dpop",
},
});
expect(error.message).toBe(
'Could not connect to the cloud environment for environment "env-1".',
);
}),
);
@@ -1175,23 +1051,8 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentEndpointMismatchError",
source: "environment connect response",
environmentId: "env-1",
expectedProviderKind: "cloudflare_tunnel",
expectedHttpBaseUrlInputLength: "https://desktop.example.test/".length,
expectedHttpBaseUrlProtocol: "https:",
expectedHttpBaseUrlHostname: "desktop.example.test",
expectedWsBaseUrlInputLength: "wss://desktop.example.test/ws".length,
expectedWsBaseUrlProtocol: "wss:",
expectedWsBaseUrlHostname: "desktop.example.test",
actualProviderKind: "cloudflare_tunnel",
actualHttpBaseUrlInputLength: "https://other-desktop.example.test/".length,
actualHttpBaseUrlProtocol: "https:",
actualHttpBaseUrlHostname: "other-desktop.example.test",
actualWsBaseUrlInputLength: "wss://other-desktop.example.test/ws".length,
actualWsBaseUrlProtocol: "wss:",
actualWsBaseUrlHostname: "other-desktop.example.test",
_tag: "CloudEnvironmentLinkError",
message: "Relay returned credentials for a different endpoint.",
});
}),
);
@@ -1244,10 +1105,8 @@ describe("mobile cloud link environment client", () => {
}),
).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "CloudEnvironmentIdMismatchError",
source: "connected environment descriptor",
expectedEnvironmentId: "env-1",
actualEnvironmentId: "env-other",
_tag: "CloudEnvironmentLinkError",
message: "Connected endpoint descriptor does not match the selected environment.",
});
}),
);
+185 -464
View File
@@ -1,3 +1,4 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
@@ -16,17 +17,16 @@ import {
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
type RelayDpopAccessTokenScope,
type RelayProtectedError as RelayProtectedErrorType,
type RelayClientEnvironmentRecord,
type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
RelayManagedEndpointProviderKind,
RelayProtectedError,
type RelayManagedEndpointProviderKind,
} from "@t3tools/contracts/relay";
import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import { authClientMetadata } from "../../lib/authClientMetadata";
import type { SavedRemoteConnection } from "../../lib/connection";
@@ -50,268 +50,11 @@ function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relay.url;
}
const EnvironmentCloudApiError = Schema.Union([
EnvironmentHttpBadRequestError,
EnvironmentHttpUnauthorizedError,
EnvironmentHttpForbiddenError,
EnvironmentHttpConflictError,
EnvironmentHttpInternalServerError,
EnvironmentCloudEndpointUnavailableError,
]);
type EnvironmentCloudApiError = typeof EnvironmentCloudApiError.Type;
const isEnvironmentCloudApiError = Schema.is(EnvironmentCloudApiError);
const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
export const CloudEnvironmentLinkAction = Schema.Literals([
"load the mobile device id",
"load mobile notification preferences",
"create an environment link challenge",
"obtain an environment link proof",
"link the environment",
"configure environment relay access",
"list cloud environments",
"read cloud environment status",
"connect to the cloud environment",
"fetch the connected environment descriptor",
"create a bootstrap DPoP proof",
"exchange a managed endpoint DPoP access token",
"derive the environment endpoint origin",
"initialize the environment HTTP client",
"parse the managed endpoint URL",
]);
export type CloudEnvironmentLinkAction = typeof CloudEnvironmentLinkAction.Type;
function relayUrlDiagnosticFields(relayUrl: string | undefined) {
if (relayUrl === undefined) {
return {};
}
const diagnostics = getUrlDiagnostics(relayUrl);
return {
relayUrlInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { relayUrlProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { relayUrlHostname: diagnostics.hostname }),
};
}
function httpBaseUrlDiagnosticFields(httpBaseUrl: string | undefined) {
if (httpBaseUrl === undefined) {
return {};
}
const diagnostics = getUrlDiagnostics(httpBaseUrl);
return {
httpBaseUrlInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
};
}
export class CloudEnvironmentLinkOperationError extends Schema.TaggedErrorClass<CloudEnvironmentLinkOperationError>()(
"CloudEnvironmentLinkOperationError",
{
action: CloudEnvironmentLinkAction,
environmentId: Schema.optionalKey(Schema.String),
relayUrlInputLength: Schema.optionalKey(Schema.Number),
relayUrlProtocol: Schema.optionalKey(Schema.String),
relayUrlHostname: Schema.optionalKey(Schema.String),
httpBaseUrlInputLength: Schema.optionalKey(Schema.Number),
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
traceId: Schema.optionalKey(Schema.String),
relayError: Schema.optionalKey(RelayProtectedError),
environmentError: Schema.optionalKey(EnvironmentCloudApiError),
cause: Schema.Defect(),
},
) {
static fromCause(input: {
readonly action: CloudEnvironmentLinkAction;
readonly cause: unknown;
readonly environmentId?: string;
readonly relayUrl?: string;
readonly httpBaseUrl?: string;
}): CloudEnvironmentLinkOperationError {
const relayFailure = isManagedRelayRequestFailedError(input.cause) ? input.cause : undefined;
const environmentError = CloudEnvironmentLinkOperationError.findEnvironmentApiError(
input.cause,
);
const traceId = relayFailure?.traceId ?? findErrorTraceId(input.cause);
return new CloudEnvironmentLinkOperationError({
action: input.action,
cause: input.cause,
...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
...relayUrlDiagnosticFields(input.relayUrl),
...httpBaseUrlDiagnosticFields(input.httpBaseUrl),
...(traceId === null || traceId === undefined ? {} : { traceId }),
...(relayFailure?.relayError === undefined ? {} : { relayError: relayFailure.relayError }),
...(environmentError === undefined ? {} : { environmentError }),
});
}
private static findEnvironmentApiError(cause: unknown): EnvironmentCloudApiError | undefined {
const seen = new Set<unknown>();
let current = cause;
while (typeof current === "object" && current !== null && !seen.has(current)) {
if (isEnvironmentCloudApiError(current)) {
return current;
}
seen.add(current);
current = "cause" in current ? current.cause : undefined;
}
return undefined;
}
override get message(): string {
const environment =
this.environmentId === undefined ? "" : ` for environment "${this.environmentId}"`;
return `Could not ${this.action}${environment}.`;
}
}
export class CloudRelayUrlNotConfiguredError extends Schema.TaggedErrorClass<CloudRelayUrlNotConfiguredError>()(
"CloudRelayUrlNotConfiguredError",
{},
) {
override get message(): string {
return "Relay URL is not configured.";
}
}
export class CloudEnvironmentLocalBearerRequiredError extends Schema.TaggedErrorClass<CloudEnvironmentLocalBearerRequiredError>()(
"CloudEnvironmentLocalBearerRequiredError",
{
environmentId: Schema.String,
httpBaseUrlInputLength: Schema.Number,
httpBaseUrlProtocol: Schema.optionalKey(Schema.String),
httpBaseUrlHostname: Schema.optionalKey(Schema.String),
},
) {
static fromConnection(input: {
readonly environmentId: string;
readonly httpBaseUrl: string;
}): CloudEnvironmentLocalBearerRequiredError {
const diagnostics = getUrlDiagnostics(input.httpBaseUrl);
return new CloudEnvironmentLocalBearerRequiredError({
environmentId: input.environmentId,
httpBaseUrlInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { httpBaseUrlProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { httpBaseUrlHostname: diagnostics.hostname }),
});
}
override get message(): string {
return "Only a locally paired bearer connection can be linked to the cloud.";
}
}
export class CloudEnvironmentIdMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentIdMismatchError>()(
"CloudEnvironmentIdMismatchError",
{
source: Schema.Literals([
"environment link response",
"environment status response",
"environment status descriptor",
"environment connect response",
"connected environment descriptor",
]),
expectedEnvironmentId: Schema.String,
actualEnvironmentId: Schema.String,
},
) {
override get message(): string {
return `The ${this.source} identified environment "${this.actualEnvironmentId}" instead of "${this.expectedEnvironmentId}".`;
}
}
export class CloudEnvironmentEndpointMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointMismatchError>()(
"CloudEnvironmentEndpointMismatchError",
{
source: Schema.Literals(["environment status response", "environment connect response"]),
environmentId: Schema.String,
expectedProviderKind: RelayManagedEndpointProviderKind,
expectedHttpBaseUrlInputLength: Schema.Number,
expectedHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
expectedHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
expectedWsBaseUrlInputLength: Schema.Number,
expectedWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
expectedWsBaseUrlHostname: Schema.optionalKey(Schema.String),
actualProviderKind: RelayManagedEndpointProviderKind,
actualHttpBaseUrlInputLength: Schema.Number,
actualHttpBaseUrlProtocol: Schema.optionalKey(Schema.String),
actualHttpBaseUrlHostname: Schema.optionalKey(Schema.String),
actualWsBaseUrlInputLength: Schema.Number,
actualWsBaseUrlProtocol: Schema.optionalKey(Schema.String),
actualWsBaseUrlHostname: Schema.optionalKey(Schema.String),
},
) {
static fromEndpoints(input: {
readonly source: "environment status response" | "environment connect response";
readonly environmentId: string;
readonly expectedEndpoint: RelayClientEnvironmentRecord["endpoint"];
readonly actualEndpoint: RelayClientEnvironmentRecord["endpoint"];
}): CloudEnvironmentEndpointMismatchError {
const expectedHttp = getUrlDiagnostics(input.expectedEndpoint.httpBaseUrl);
const expectedWs = getUrlDiagnostics(input.expectedEndpoint.wsBaseUrl);
const actualHttp = getUrlDiagnostics(input.actualEndpoint.httpBaseUrl);
const actualWs = getUrlDiagnostics(input.actualEndpoint.wsBaseUrl);
return new CloudEnvironmentEndpointMismatchError({
source: input.source,
environmentId: input.environmentId,
expectedProviderKind: input.expectedEndpoint.providerKind,
expectedHttpBaseUrlInputLength: expectedHttp.inputLength,
...(expectedHttp.protocol === undefined
? {}
: { expectedHttpBaseUrlProtocol: expectedHttp.protocol }),
...(expectedHttp.hostname === undefined
? {}
: { expectedHttpBaseUrlHostname: expectedHttp.hostname }),
expectedWsBaseUrlInputLength: expectedWs.inputLength,
...(expectedWs.protocol === undefined
? {}
: { expectedWsBaseUrlProtocol: expectedWs.protocol }),
...(expectedWs.hostname === undefined
? {}
: { expectedWsBaseUrlHostname: expectedWs.hostname }),
actualProviderKind: input.actualEndpoint.providerKind,
actualHttpBaseUrlInputLength: actualHttp.inputLength,
...(actualHttp.protocol === undefined
? {}
: { actualHttpBaseUrlProtocol: actualHttp.protocol }),
...(actualHttp.hostname === undefined
? {}
: { actualHttpBaseUrlHostname: actualHttp.hostname }),
actualWsBaseUrlInputLength: actualWs.inputLength,
...(actualWs.protocol === undefined ? {} : { actualWsBaseUrlProtocol: actualWs.protocol }),
...(actualWs.hostname === undefined ? {} : { actualWsBaseUrlHostname: actualWs.hostname }),
});
}
override get message(): string {
return `The ${this.source} returned a different endpoint for environment "${this.environmentId}".`;
}
}
export class CloudEnvironmentEndpointProviderMismatchError extends Schema.TaggedErrorClass<CloudEnvironmentEndpointProviderMismatchError>()(
"CloudEnvironmentEndpointProviderMismatchError",
{
environmentId: Schema.String,
expectedProviderKind: RelayManagedEndpointProviderKind,
actualProviderKind: RelayManagedEndpointProviderKind,
},
) {
override get message(): string {
return `Relay returned link credentials with endpoint provider "${this.actualProviderKind}" instead of "${this.expectedProviderKind}".`;
}
}
export const CloudEnvironmentLinkError = Schema.Union([
CloudEnvironmentLinkOperationError,
CloudRelayUrlNotConfiguredError,
CloudEnvironmentLocalBearerRequiredError,
CloudEnvironmentIdMismatchError,
CloudEnvironmentEndpointMismatchError,
CloudEnvironmentEndpointProviderMismatchError,
]);
export type CloudEnvironmentLinkError = typeof CloudEnvironmentLinkError.Type;
export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
readonly message: string;
readonly cause?: unknown;
readonly traceId?: string;
}> {}
export interface CloudEnvironmentRecordWithStatus {
readonly environment: RelayClientEnvironmentRecord;
@@ -319,47 +62,132 @@ export interface CloudEnvironmentRecordWithStatus {
readonly statusError: string | null;
}
const isEnvironmentCloudApiError = Schema.is(
Schema.Union([
EnvironmentHttpBadRequestError,
EnvironmentHttpUnauthorizedError,
EnvironmentHttpForbiddenError,
EnvironmentHttpConflictError,
EnvironmentHttpInternalServerError,
EnvironmentCloudEndpointUnavailableError,
]),
);
const MANAGED_ENDPOINT_PROVIDER_KIND =
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
function cloudEnvironmentLinkError(message: string) {
return (cause: unknown) => {
const environmentError = findEnvironmentCloudApiError(cause);
const traceId = findErrorTraceId(cause);
return new CloudEnvironmentLinkError({
message: environmentError
? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
: withDevCause(message, cause),
cause,
...(traceId === null ? {} : { traceId }),
});
};
}
function isDevRuntime(): boolean {
return typeof __DEV__ !== "undefined" && __DEV__;
}
function causeMessage(cause: unknown): string | null {
if (cause instanceof Error && cause.message) {
return cause.message;
}
if (typeof cause === "object" && cause !== null) {
const record = cause as { readonly message?: unknown; readonly cause?: unknown };
if (typeof record.message === "string" && record.message.length > 0) {
const nested = causeMessage(record.cause);
return nested ? `${record.message}: ${nested}` : record.message;
}
}
return null;
}
function withDevCause(message: string, cause: unknown): string {
if (!isDevRuntime()) {
return message;
}
const detail = causeMessage(cause);
return detail ? `${message} (${detail})` : message;
}
function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
switch (error._tag) {
case "RelayAuthInvalidError":
switch (error.reason) {
case "missing_bearer":
case "invalid_bearer":
return "Relay rejected the cloud session token.";
case "invalid_dpop":
return "Relay rejected the DPoP proof.";
case "not_authorized":
return "Relay rejected the authenticated request.";
}
case "RelayEnvironmentLinkProofExpiredError":
return "Relay rejected an expired environment link proof.";
case "RelayEnvironmentLinkProofInvalidError":
return `Relay rejected the environment link proof (${error.reason}).`;
case "RelayEnvironmentConnectNotAuthorizedError":
return "Relay rejected the environment connection request.";
case "RelayEnvironmentEndpointUnavailableError":
return `Relay could not reach the environment endpoint (${error.reason}).`;
case "RelayEnvironmentEndpointTimedOutError":
return "Relay timed out while contacting the environment endpoint.";
case "RelayEnvironmentLinkFailedError":
return `Relay could not link the environment (${error.reason}).`;
case "RelayEnvironmentLinkUnavailableError":
return `Relay cannot provision the managed endpoint (${error.reason}).`;
case "RelayAgentActivityPublishProofExpiredError":
return "Relay rejected an expired agent activity publish proof.";
case "RelayAgentActivityPublishProofInvalidError":
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}).`;
}
}
function decodedRelayClientError(message: string) {
return (cause: ManagedRelay.ManagedRelayClientError) => {
const relayError =
cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
return new CloudEnvironmentLinkError({
message: detail ? `${message}: ${detail}` : message,
cause,
...(traceId ? { traceId } : {}),
});
};
}
function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
if (isEnvironmentCloudApiError(cause)) {
return cause;
}
if (typeof cause !== "object" || cause === null) {
return null;
}
return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
}
function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
const relayUrl = readRelayUrl();
return relayUrl ? Effect.succeed(relayUrl) : Effect.fail(new CloudRelayUrlNotConfiguredError());
return relayUrl
? Effect.succeed(relayUrl)
: Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
}
function endpointOrigin(input: { readonly environmentId: string; readonly httpBaseUrl: string }) {
return Effect.try({
try: () => {
const url = new URL(input.httpBaseUrl);
return {
localHttpHost: "127.0.0.1",
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
};
},
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "derive the environment endpoint origin",
environmentId: input.environmentId,
httpBaseUrl: input.httpBaseUrl,
cause,
}),
});
}
function makeCloudEnvironmentHttpApiClient(input: {
readonly environmentId: string;
readonly httpBaseUrl: string;
}) {
return Effect.try({
try: () => makeEnvironmentHttpApiClient(input.httpBaseUrl),
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "initialize the environment HTTP client",
environmentId: input.environmentId,
httpBaseUrl: input.httpBaseUrl,
cause,
}),
}).pipe(Effect.flatten);
function endpointOrigin(httpBaseUrl: string) {
const url = new URL(httpBaseUrl);
return {
localHttpHost: "127.0.0.1",
localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
};
}
function ensureLinkedEnvironmentMatches(input: {
@@ -368,17 +196,13 @@ function ensureLinkedEnvironmentMatches(input: {
readonly link: RelayEnvironmentLinkResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (input.link.environmentId !== input.expectedEnvironmentId) {
return new CloudEnvironmentIdMismatchError({
source: "environment link response",
expectedEnvironmentId: input.expectedEnvironmentId,
actualEnvironmentId: input.link.environmentId,
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different environment.",
});
}
if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
return new CloudEnvironmentEndpointProviderMismatchError({
environmentId: input.expectedEnvironmentId,
expectedProviderKind: input.expectedProviderKind,
actualProviderKind: input.link.endpoint.providerKind,
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different endpoint provider.",
});
}
return Effect.void;
@@ -400,28 +224,21 @@ function ensureStatusMatchesEnvironment(input: {
readonly status: RelayEnvironmentStatusResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (input.status.environmentId !== input.environment.environmentId) {
return new CloudEnvironmentIdMismatchError({
source: "environment status response",
expectedEnvironmentId: input.environment.environmentId,
actualEnvironmentId: input.status.environmentId,
return new CloudEnvironmentLinkError({
message: "Relay returned status for a different environment.",
});
}
if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
source: "environment status response",
environmentId: input.environment.environmentId,
expectedEndpoint: input.environment.endpoint,
actualEndpoint: input.status.endpoint,
return new CloudEnvironmentLinkError({
message: "Relay returned status for a different endpoint.",
});
}
if (
input.status.descriptor &&
input.status.descriptor.environmentId !== input.environment.environmentId
) {
return new CloudEnvironmentIdMismatchError({
source: "environment status descriptor",
expectedEnvironmentId: input.environment.environmentId,
actualEnvironmentId: input.status.descriptor.environmentId,
return new CloudEnvironmentLinkError({
message: "Relay returned status descriptor for a different environment.",
});
}
return Effect.void;
@@ -432,11 +249,8 @@ function ensureConnectEndpointMatchesEnvironment(input: {
readonly connect: RelayEnvironmentConnectResponseType;
}): Effect.Effect<void, CloudEnvironmentLinkError> {
if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
return CloudEnvironmentEndpointMismatchError.fromEndpoints({
source: "environment connect response",
environmentId: input.environment.environmentId,
expectedEndpoint: input.environment.endpoint,
actualEndpoint: input.connect.endpoint,
return new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different endpoint.",
});
}
return Effect.void;
@@ -452,9 +266,8 @@ export function linkEnvironmentToCloud(input: {
> {
return Effect.gen(function* () {
if (!input.connection.bearerToken) {
return yield* CloudEnvironmentLocalBearerRequiredError.fromConnection({
environmentId: input.connection.environmentId,
httpBaseUrl: input.connection.httpBaseUrl,
return yield* new CloudEnvironmentLinkError({
message: "Only a locally paired bearer connection can be linked to the cloud.",
});
}
const localBearerToken = input.connection.bearerToken;
@@ -462,21 +275,11 @@ export function linkEnvironmentToCloud(input: {
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "load the mobile device id",
environmentId: input.connection.environmentId,
cause,
}),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
const preferences = yield* Effect.tryPromise({
try: () => loadPreferences(),
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "load mobile notification preferences",
environmentId: input.connection.environmentId,
cause,
}),
catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
});
const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
const challenge = yield* relayClient
@@ -489,23 +292,11 @@ export function linkEnvironmentToCloud(input: {
},
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "create an environment link challenge",
environmentId: input.connection.environmentId,
relayUrl,
cause,
}),
Effect.mapError(
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
),
);
const origin = yield* endpointOrigin({
environmentId: input.connection.environmentId,
httpBaseUrl: input.connection.httpBaseUrl,
});
const environmentClient = yield* makeCloudEnvironmentHttpApiClient({
environmentId: input.connection.environmentId,
httpBaseUrl: input.connection.httpBaseUrl,
});
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const proof = yield* environmentClient.connect
.linkProof({
headers: { authorization: `Bearer ${localBearerToken}` },
@@ -517,19 +308,10 @@ export function linkEnvironmentToCloud(input: {
wsBaseUrl: input.connection.wsBaseUrl,
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
},
origin,
origin: endpointOrigin(input.connection.httpBaseUrl),
},
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "obtain an environment link proof",
environmentId: input.connection.environmentId,
httpBaseUrl: input.connection.httpBaseUrl,
cause,
}),
),
);
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
const link = yield* relayClient
.linkEnvironment({
clerkToken: input.clerkToken,
@@ -542,14 +324,7 @@ export function linkEnvironmentToCloud(input: {
},
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "link the environment",
environmentId: input.connection.environmentId,
relayUrl,
cause,
}),
),
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
);
yield* ensureLinkedEnvironmentMatches({
expectedEnvironmentId: input.connection.environmentId,
@@ -570,14 +345,7 @@ export function linkEnvironmentToCloud(input: {
},
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "configure environment relay access",
environmentId: input.connection.environmentId,
httpBaseUrl: input.connection.httpBaseUrl,
cause,
}),
),
Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
);
});
}
@@ -593,15 +361,11 @@ export function listCloudEnvironments(input: {
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelay.ManagedRelayClient;
return yield* relayClient.listEnvironments({ clerkToken: input.clerkToken }).pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "list cloud environments",
relayUrl,
cause,
}),
),
);
return yield* relayClient
.listEnvironments({
clerkToken: input.clerkToken,
})
.pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
});
}
@@ -624,13 +388,10 @@ export function getCloudEnvironmentStatus(input: {
environmentId: input.environment.environmentId,
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "read cloud environment status",
environmentId: input.environment.environmentId,
relayUrl,
cause,
}),
Effect.mapError(
decodedRelayClientError(
`${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
),
),
);
yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
@@ -697,19 +458,14 @@ export function listCloudEnvironmentsWithStatus(input: {
});
}
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(function* (
environmentId: string,
) {
return yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "load the mobile device id",
environmentId,
cause,
}),
});
});
const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
function* () {
return yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
});
},
);
const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
function* (input: {
@@ -721,7 +477,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* loadAgentAwarenessDeviceId(input.environmentId);
const deviceId = yield* loadAgentAwarenessDeviceId();
const connect = yield* relayClient
.connectEnvironment({
clerkToken: input.clerkToken,
@@ -730,20 +486,15 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
deviceId,
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "connect to the cloud environment",
environmentId: input.environmentId,
relayUrl,
cause,
}),
Effect.mapError(
decodedRelayClientError(
`${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
),
),
);
if (connect.environmentId !== input.environmentId) {
return yield* new CloudEnvironmentIdMismatchError({
source: "environment connect response",
expectedEnvironmentId: input.environmentId,
actualEnvironmentId: connect.environmentId,
return yield* new CloudEnvironmentLinkError({
message: "Relay returned credentials for a different environment.",
});
}
if (input.expectedEnvironment) {
@@ -756,69 +507,39 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: connect.endpoint.httpBaseUrl,
}).pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "fetch the connected environment descriptor",
environmentId: input.environmentId,
httpBaseUrl: connect.endpoint.httpBaseUrl,
cause,
}),
Effect.mapError(
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
),
);
if (descriptor.environmentId !== connect.environmentId) {
return yield* new CloudEnvironmentIdMismatchError({
source: "connected environment descriptor",
expectedEnvironmentId: connect.environmentId,
actualEnvironmentId: descriptor.environmentId,
return yield* new CloudEnvironmentLinkError({
message: "Connected endpoint descriptor does not match the selected environment.",
});
}
const endpointUrl = yield* Effect.try({
try: () => new URL(connect.endpoint.httpBaseUrl),
catch: (cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "parse the managed endpoint URL",
environmentId: input.environmentId,
httpBaseUrl: connect.endpoint.httpBaseUrl,
cause,
}),
});
const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
url: new URL("/oauth/token", endpointUrl).toString(),
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
})
.pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "create a bootstrap DPoP proof",
environmentId: input.environmentId,
httpBaseUrl: connect.endpoint.httpBaseUrl,
cause,
}),
),
);
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
const bootstrap = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
dpopProof: bootstrapDpop,
clientMetadata: authClientMetadata(),
}).pipe(
Effect.mapError((cause) =>
CloudEnvironmentLinkOperationError.fromCause({
action: "exchange a managed endpoint DPoP access token",
environmentId: input.environmentId,
httpBaseUrl: connect.endpoint.httpBaseUrl,
cause,
}),
Effect.mapError(
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
),
);
endpointUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: stripPairingTokenFromUrl(endpointUrl).toString(),
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
displayUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
wsBaseUrl: connect.endpoint.wsBaseUrl,
@@ -28,24 +28,25 @@ const relayDpopSignerLayer = Layer.effect(
),
createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
const proofKey = yield* loadProofKey.pipe(
Effect.mapError((error) =>
ManagedRelay.ManagedRelayDpopKeyLoadError.fromTarget({
keyStore: "expo-secure-store",
method: input.method,
url: input.url,
cause: error,
}),
Effect.mapError(
(error) =>
new ManagedRelay.ManagedRelayDpopProofCreationError({
method: input.method,
url: input.url,
cause: error,
}),
),
);
return yield* createDpopProof({ ...input, proofKey }).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((proof) => proof.proof),
Effect.mapError((error) =>
ManagedRelay.ManagedRelayDpopProofCreationError.fromTarget({
method: input.method,
url: input.url,
cause: error,
}),
Effect.mapError(
(error) =>
new ManagedRelay.ManagedRelayDpopProofCreationError({
method: input.method,
url: input.url,
cause: error,
}),
),
);
}),
@@ -58,7 +58,7 @@ export function useConnectionController() {
environment: entry.environment,
availability: entry.availability,
status: Option.getOrNull(entry.status),
error: Option.getOrNull(entry.error)?.detail ?? null,
error: Option.getOrNull(entry.error)?.message ?? null,
traceId: Option.getOrNull(entry.error)?.traceId ?? null,
})),
[discovery.environments],
@@ -112,7 +112,7 @@ export function useConnectionController() {
relayDiscovery: {
isRefreshing: discovery.refreshing,
isOffline: discovery.offline,
error: Option.getOrNull(discovery.error)?.detail ?? null,
error: Option.getOrNull(discovery.error)?.message ?? null,
errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,
},
connectPairingUrl,
@@ -1,11 +1,9 @@
import * as Cause from "effect/Cause";
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
createSourceHighlightAtomFamily,
SourceHighlightError,
type SourceHighlightTokens,
} from "./sourceHighlightingState";
@@ -102,29 +100,22 @@ describe("sourceHighlightingState", () => {
registry.dispose();
});
it("preserves highlighter failures with the source path and theme", async () => {
const cause = new Error("highlight failed");
const highlight = vi.fn(() => Promise.reject(cause));
it("exposes highlighter errors as a failed async result", async () => {
const highlight = vi.fn(async () => {
throw new Error("highlight failed");
});
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
const registry = AtomRegistry.make();
const path = "src/example.ts";
const theme = "light" as const;
const atom = sourceHighlightAtom({
path,
path: "src/example.ts",
contents: "const value = 1;",
theme,
theme: "light",
});
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
const result = registry.get(atom);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toEqual(new SourceHighlightError({ path, theme, cause }));
expect((error as SourceHighlightError).cause).toBe(cause);
}
unmount();
registry.dispose();
@@ -1,6 +1,5 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Atom } from "effect/unstable/reactivity";
import {
@@ -23,18 +22,9 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
"SourceHighlightError",
{
path: Schema.String,
theme: Schema.Literals(["light", "dark"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not highlight ${this.path} with the ${this.theme} theme.`;
}
}
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
readonly cause: unknown;
}> {}
export function createSourceHighlightAtomFamily(options?: {
readonly highlight?: SourceHighlighter;
@@ -46,8 +36,7 @@ export function createSourceHighlightAtomFamily(options?: {
Atom.make(
Effect.tryPromise({
try: () => highlight(request),
catch: (cause) =>
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
catch: (cause) => new SourceHighlightError({ cause }),
}),
).pipe(
Atom.setIdleTTL(idleTtlMs),
@@ -1,14 +1,8 @@
import * as Cause from "effect/Cause";
import * as Hash from "effect/Hash";
import { AtomRegistry } from "effect/unstable/reactivity";
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
import { describe, expect, it, vi } from "vite-plus/test";
import {
createWorkspaceFileImageAtomFamily,
WorkspaceImagePrefetchFailedError,
WorkspaceImagePrefetchUnavailableError,
} from "./workspace-file-image-cache";
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
describe("workspaceFileImageAtom", () => {
it("reuses a prefetched image across route remounts", async () => {
@@ -54,65 +48,15 @@ describe("workspaceFileImageAtom", () => {
registry.dispose();
});
it("reports an unavailable image when prefetch completes without caching it", async () => {
const uri = "https://example.test/api/assets/signed-secret-token/missing.png?signature=private";
it("exposes prefetch failures", async () => {
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
const registry = AtomRegistry.make();
const atom = imageAtom(uri);
expect(atom.label?.[0]).not.toContain("signed-secret-token");
expect(atom.label?.[0]).not.toContain("signature=private");
const atom = imageAtom("https://example.test/missing.png");
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
const result = registry.get(atom);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toEqual(
new WorkspaceImagePrefetchUnavailableError({
uriHash: Hash.hash(uri),
uriLength: uri.length,
uriProtocol: "https:",
}),
);
expect(error).not.toHaveProperty("uri");
expect(String(error)).not.toContain("signed-secret-token");
expect(String(error)).not.toContain("signature=private");
}
unmount();
registry.dispose();
});
it("preserves rejected prefetch causes without retaining the signed image URI", async () => {
const uri =
"https://example.test/api/assets/signed-secret-token/rejected.png?signature=private";
const cause = new Error("native image loader failed");
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: () => Promise.reject(cause) });
const registry = AtomRegistry.make();
const atom = imageAtom(uri);
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
const result = registry.get(atom);
if (AsyncResult.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toEqual(
new WorkspaceImagePrefetchFailedError({
uriHash: Hash.hash(uri),
uriLength: uri.length,
uriProtocol: "https:",
cause,
}),
);
expect((error as WorkspaceImagePrefetchFailedError).cause).toBe(cause);
expect(error).not.toHaveProperty("uri");
expect(String(error)).not.toContain("signed-secret-token");
expect(String(error)).not.toContain("signature=private");
}
unmount();
registry.dispose();
@@ -1,8 +1,5 @@
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Hash from "effect/Hash";
import * as Schema from "effect/Schema";
import { Atom } from "effect/unstable/reactivity";
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
@@ -11,77 +8,39 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
export class WorkspaceImagePrefetchUnavailableError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchUnavailableError>()(
"WorkspaceImagePrefetchUnavailableError",
{
uriHash: Schema.Number,
uriLength: Schema.Number,
uriProtocol: Schema.NullOr(Schema.String),
},
) {
override get message(): string {
return `Image prefetch did not cache the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
}
}
export class WorkspaceImagePrefetchFailedError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchFailedError>()(
"WorkspaceImagePrefetchFailedError",
{
uriHash: Schema.Number,
uriLength: Schema.Number,
uriProtocol: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Image prefetch failed for the requested ${this.uriProtocol ?? "unknown-protocol"} resource (URI length ${this.uriLength}).`;
}
}
export const WorkspaceImagePrefetchError = Schema.Union([
WorkspaceImagePrefetchUnavailableError,
WorkspaceImagePrefetchFailedError,
]);
export type WorkspaceImagePrefetchError = typeof WorkspaceImagePrefetchError.Type;
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
readonly cause?: unknown;
readonly uri: string;
}> {}
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
const { Image } = await import("react-native");
return Image.prefetch(uri);
}
function describeWorkspaceImageUri(uri: string) {
const diagnostics = getUrlDiagnostics(uri);
return {
uriHash: Hash.hash(uri),
uriLength: diagnostics.inputLength,
uriProtocol: diagnostics.protocol ?? null,
};
}
export function createWorkspaceFileImageAtomFamily(options?: {
readonly idleTtlMs?: number;
readonly prefetch?: ImagePrefetch;
}) {
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
const family = Atom.family((key: WorkspaceImageCacheKey) => {
const uriContext = describeWorkspaceImageUri(key.uri);
return Atom.make(
Effect.gen(function* () {
const cached = yield* Effect.tryPromise({
try: () => prefetch(key.uri),
catch: (cause) => new WorkspaceImagePrefetchFailedError({ ...uriContext, cause }),
});
if (!cached) {
return yield* new WorkspaceImagePrefetchUnavailableError(uriContext);
}
return key.uri;
const family = Atom.family((key: WorkspaceImageCacheKey) =>
Atom.make(
Effect.tryPromise({
try: async () => {
const cached = await prefetch(key.uri);
if (!cached) {
throw new WorkspaceImagePrefetchError({ uri: key.uri });
}
return key.uri;
},
catch: (cause) =>
cause instanceof WorkspaceImagePrefetchError
? cause
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
}),
).pipe(
Atom.setIdleTTL(idleTtlMs),
Atom.withLabel(`mobile:workspace-image:${uriContext.uriHash.toString(36)}`),
);
});
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
);
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
}
@@ -30,7 +30,9 @@ import {
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const borderColor = useThemeColor("--color-border");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
) {
return;
}
setProject(directProject);
return;
}
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
useEffect(() => {
if (!selectedProject) {
loadedBranchesProjectKeyRef.current = null;
return;
}
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
if (loadedBranchesProjectKeyRef.current === projectKey) {
return;
}
loadedBranchesProjectKeyRef.current = projectKey;
void flow.loadBranches();
}, [flow, selectedProject]);
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
if (!selectedProject) {
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("model:")) {
return;
}
// Defer state update so the native menu dismiss animation completes
// before re-rendering the menu actions (prevents submenu jump).
setTimeout(() => {
flow.setSelectedModelKey(event.slice("model:".length));
}, 150);
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
);
async function handleStart(): Promise<void> {
const selectedProject = flow.selectedProject;
if (!selectedProject) {
return;
}
const draft = getComposerDraftSnapshot(
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
);
const modelSelection = draft.modelSelection ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
const interactionMode = draft.interactionMode ?? flow.interactionMode;
const initialMessageText = draft.text.trim();
if (
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
!modelSelection ||
initialMessageText.length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
(workspaceMode === "worktree" && !selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
const result = await createProjectThread({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
});
flow.setSubmitting(false);
@@ -1,13 +1,7 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const setThreadRuntimeMode = useAtomCommand(
threadEnvironment.setRuntimeMode,
"thread runtime mode",
);
const setThreadInteractionMode = useAtomCommand(
threadEnvironment.setInteractionMode,
"thread interaction mode",
);
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
? {
...selectedThread,
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
}
: null,
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
);
/* ─── Native header theming ──────────────────────────────────────── */
const iconColor = String(useThemeColor("--color-icon"));
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
const handleUpdateThreadModelSelection = useCallback(
(modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
return updateThreadMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateThreadMetadata],
);
const handleUpdateThreadRuntimeMode = useCallback(
(runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
return setThreadRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setThreadRuntimeMode],
);
const handleUpdateThreadInteractionMode = useCallback(
(interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
return setThreadInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setThreadInteractionMode],
);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
@@ -23,6 +23,7 @@ import {
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
? selectedEnvironmentIdOverride
: (projects[0]?.environmentId ?? null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
const branchLoadVersionRef = useRef(0);
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE,
);
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
Record<string, ModelSelection>
>({});
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setSubmitting(false);
setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setModelSelectionOverrides({});
setExpandedProvider(null);
}, []);
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
),
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
);
const defaultModelKey = selectedProject?.defaultModelSelection
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
: null;
const baseSelectedModel =
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
(defaultModelKey
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
: null) ??
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
const selectedModelKey = selectedModel
? `${selectedModel.instanceId}:${selectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
const selectedProviderSkills =
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
const selectedProviderSkills = useMemo(
() =>
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [],
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
(key: string | null) => {
if (!key || !selectedProjectDraftKey) {
return;
}
const option = modelOptions.find((candidate) => candidate.key === key);
if (!option) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
);
const setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedModelIdentity) {
if (!selectedModel || !selectedProjectDraftKey) {
return;
}
const nextSelection: ModelSelection = options
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: nextSelection,
});
},
[selectedModel, selectedModelIdentity],
[selectedModel, selectedProjectDraftKey],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const setProject = useCallback((project: EnvironmentProject) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
if (!selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
(branch: VcsRef) => {
setSelectedBranchName(branch.name);
setSelectedWorktreePath(
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
);
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
},
});
},
[selectedProject],
[selectedProject, selectedProjectDraftKey, workspaceMode],
);
const refreshBranches = branchState.refresh;
const loadBranches = useCallback(async () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
}, [refreshBranches, selectedProject]);
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
setPendingConnectionError(null);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
availableBranches.find((branch) => branch.current)?.name ??
availableBranches.find((branch) => branch.isDefault)?.name ??
null;
if (preferredBranch) {
setSelectedBranchName(preferredBranch);
}
const preferredBranch =
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
}
},
[selectedProjectDraftKey],
);
const setInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
}
},
[selectedProjectDraftKey],
);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setProject,
selectBranch,
selectEnvironment,
setInteractionMode,
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setWorkspaceMode,
submitting,
workspaceMode,
appendAttachments,
@@ -0,0 +1,11 @@
import * as Schema from "effect/Schema";
export const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
+1 -28
View File
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
const missingFileCause = new Error("missing file");
const files = new Map<string, { base64: string; deleted: boolean }>();
vi.mock("expo-file-system", () => ({
@@ -19,7 +18,7 @@ vi.mock("expo-file-system", () => ({
async base64(): Promise<string> {
const entry = files.get(this.uri);
if (!entry || entry.deleted) {
throw missingFileCause;
throw new Error("missing file");
}
return entry.base64;
}
@@ -92,30 +91,4 @@ describe("native pasted image cleanup", () => {
expect(files.get(overflow)?.deleted).toBe(true);
expect(files.get(userOwned)?.deleted).toBe(false);
});
it("reports structured context when reading a pasted image fails", async () => {
const uri = "file:///private/var/mobile/photos/signed-secret-token/missing.png?token=private";
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
await expect(
convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 }),
).resolves.toEqual([]);
expect(warn).toHaveBeenCalledWith(
"[composer-images] failed to read pasted image",
expect.objectContaining({
_tag: "ComposerImageOperationError",
operation: "read-pasted-image",
uriLength: uri.length,
uriProtocol: "file:",
cause: missingFileCause,
message: `Composer image operation read-pasted-image failed for a file: URI (length ${uri.length}).`,
}),
);
const error = warn.mock.calls[0]?.[1];
expect(error).not.toHaveProperty("uri");
expect(String(error)).not.toContain("signed-secret-token");
expect(String(error)).not.toContain("token=private");
warn.mockRestore();
});
});
+23 -113
View File
@@ -3,8 +3,6 @@ import {
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type UploadChatImageAttachment,
} from "@t3tools/contracts";
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as Schema from "effect/Schema";
import { uuidv4 } from "./uuid";
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
@@ -14,31 +12,6 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
export class ComposerImageOperationError extends Schema.TaggedErrorClass<ComposerImageOperationError>()(
"ComposerImageOperationError",
{
operation: Schema.Literals([
"load-image-picker",
"request-media-library-permission",
"launch-image-library",
"load-clipboard",
"check-clipboard-image",
"read-clipboard-image",
"check-clipboard-text",
"read-clipboard-text",
"read-pasted-image",
"remove-pasted-image",
]),
uriLength: Schema.optional(Schema.Number),
uriProtocol: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Composer image operation ${this.operation} failed${this.uriLength === undefined ? "" : ` for a ${this.uriProtocol ?? "unknown-protocol"} URI (length ${this.uriLength})`}.`;
}
}
function estimateBase64ByteSize(base64: string): number {
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return Math.floor((base64.length * 3) / 4) - padding;
@@ -47,22 +20,16 @@ function estimateBase64ByteSize(base64: string): number {
async function loadImagePicker() {
try {
return await import("expo-image-picker");
} catch (cause) {
throw new ComposerImageOperationError({
operation: "load-image-picker",
cause,
});
} catch (error) {
throw new Error("Image attachments are unavailable right now.", { cause: error });
}
}
async function loadClipboard() {
try {
return await import("expo-clipboard");
} catch (cause) {
throw new ComposerImageOperationError({
operation: "load-clipboard",
cause,
});
} catch (error) {
throw new Error("Clipboard paste is unavailable right now.", { cause: error });
}
}
@@ -82,19 +49,14 @@ export async function pickComposerImages(input: { readonly existingCount: number
try {
imagePicker = await loadImagePicker();
} catch (error) {
console.warn("[composer-images] image picker unavailable", error);
return {
images: [],
error: "Image attachments are unavailable right now.",
error:
error instanceof Error ? error.message : "Image attachments are unavailable right now.",
};
}
const permission = await imagePicker.requestMediaLibraryPermissionsAsync().catch((cause) => {
throw new ComposerImageOperationError({
operation: "request-media-library-permission",
cause,
});
});
const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
if (!permission.granted) {
return {
images: [],
@@ -102,20 +64,13 @@ export async function pickComposerImages(input: { readonly existingCount: number
};
}
const result = await imagePicker
.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
})
.catch((cause) => {
throw new ComposerImageOperationError({
operation: "launch-image-library",
cause,
});
});
const result = await imagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
allowsMultipleSelection: true,
selectionLimit: remainingSlots,
base64: true,
quality: 1,
});
if (result.canceled) {
return {
@@ -172,23 +127,16 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
try {
clipboard = await loadClipboard();
} catch (error) {
console.warn("[composer-images] clipboard unavailable", error);
return {
images: [],
text: null,
error: "Clipboard paste is unavailable right now.",
error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
};
}
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
const hasImage = await clipboard.hasImageAsync().catch((cause) => {
throw new ComposerImageOperationError({
operation: "check-clipboard-image",
cause,
});
});
if (hasImage) {
if (await clipboard.hasImageAsync()) {
if (remainingSlots <= 0) {
return {
images: [],
@@ -196,12 +144,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
};
}
const image = await clipboard.getImageAsync({ format: "png" }).catch((cause) => {
throw new ComposerImageOperationError({
operation: "read-clipboard-image",
cause,
});
});
const image = await clipboard.getImageAsync({ format: "png" });
if (!image) {
return {
images: [],
@@ -237,19 +180,8 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
};
}
const hasText = await clipboard.hasStringAsync().catch((cause) => {
throw new ComposerImageOperationError({
operation: "check-clipboard-text",
cause,
});
});
if (hasText) {
const text = await clipboard.getStringAsync().catch((cause) => {
throw new ComposerImageOperationError({
operation: "read-clipboard-text",
cause,
});
});
if (await clipboard.hasStringAsync()) {
const text = await clipboard.getStringAsync();
return {
images: [],
text: text.length > 0 ? text : null,
@@ -298,14 +230,6 @@ export function isOwnedPastedImageUri(uri: string): boolean {
}
}
function describeComposerImageUri(uri: string) {
const diagnostics = getUrlDiagnostics(uri);
return {
uriLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { uriProtocol: diagnostics.protocol }),
};
}
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray<string>;
readonly existingCount: number;
@@ -336,15 +260,8 @@ export async function convertPastedImagesToAttachments(input: {
dataUrl: `data:${mimeType};base64,${base64}`,
previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
});
} catch (cause) {
console.warn(
"[composer-images] failed to read pasted image",
new ComposerImageOperationError({
operation: "read-pasted-image",
...describeComposerImageUri(uri),
cause,
}),
);
} catch (error) {
console.warn("Failed to read pasted image", uri, error);
} finally {
if (ownedTemporaryFile) {
try {
@@ -352,15 +269,8 @@ export async function convertPastedImagesToAttachments(input: {
if (file.exists) {
file.delete();
}
} catch (cause) {
console.warn(
"[composer-images] failed to remove temporary pasted image",
new ComposerImageOperationError({
operation: "remove-pasted-image",
...describeComposerImageUri(uri),
cause,
}),
);
} catch (error) {
console.warn("Failed to remove temporary pasted image", uri, error);
}
}
}
+65 -17
View File
@@ -1,33 +1,38 @@
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
import { isEnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
IsoDateTime,
MessageId,
ModelSelection,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
type ModelSelection as ModelSelectionType,
type ProviderInteractionMode as ProviderInteractionModeType,
type RuntimeMode as RuntimeModeType,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
export const QueuedThreadMessageSchema = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
environmentId: EnvironmentId,
threadId: ThreadId,
messageId: MessageId,
commandId: CommandId,
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelection),
runtimeMode: Schema.optional(RuntimeMode),
interactionMode: Schema.optional(ProviderInteractionMode),
createdAt: IsoDateTime,
});
@@ -41,9 +46,37 @@ export interface QueuedThreadMessage {
readonly commandId: CommandId;
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelectionType;
readonly runtimeMode?: RuntimeModeType;
readonly interactionMode?: ProviderInteractionModeType;
readonly createdAt: string;
}
export interface ThreadSettingsSnapshot {
readonly modelSelection: ModelSelectionType;
readonly runtimeMode: RuntimeModeType;
readonly interactionMode: ProviderInteractionModeType;
}
export function resolveQueuedThreadSettings(
message: QueuedThreadMessage,
thread: ThreadSettingsSnapshot,
): ThreadSettingsSnapshot {
return {
modelSelection: message.modelSelection ?? thread.modelSelection,
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
interactionMode: message.interactionMode ?? thread.interactionMode,
};
}
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
return (
left.instanceId === right.instanceId &&
left.model === right.model &&
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
);
}
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
return encodeStoredQueuedThreadMessage({
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
@@ -110,9 +143,6 @@ function errorMessage(error: unknown): string | null {
}
export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
if (isEnvironmentRpcUnavailableError(error)) {
return true;
}
if (
typeof error === "object" &&
error !== null &&
@@ -123,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
}
return isTransportConnectionErrorMessage(errorMessage(error));
}
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
export type ThreadOutboxFailureAction = "retry" | "discard";
export function resolveThreadOutboxFailureAction(input: {
readonly stage: ThreadOutboxCommandStage;
readonly error: unknown;
readonly interrupted: boolean;
}): ThreadOutboxFailureAction {
if (
input.stage === "settings-sync" ||
input.interrupted ||
shouldRetryThreadOutboxDelivery(input.error)
) {
return "retry";
}
return "discard";
}
+78 -11
View File
@@ -1,12 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
@@ -67,6 +76,54 @@ describe("thread outbox", () => {
).toThrow();
});
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
const legacyMessage = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const selectedMessage = {
...legacyMessage,
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
} satisfies QueuedThreadMessage;
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
selectedMessage,
);
expect(
resolveQueuedThreadSettings(legacyMessage, {
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
}),
).toEqual({
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
});
});
it("compares model options as part of the queued settings change", () => {
const base = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "medium" }],
} as const;
expect(modelSelectionsEqual(base, base)).toBe(true);
expect(
modelSelectionsEqual(base, {
...base,
options: [{ id: "reasoningEffort", value: "xhigh" }],
}),
).toBe(false);
});
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
@@ -263,15 +320,6 @@ describe("thread outbox", () => {
});
it("retries transport failures but drops deterministic command failures", () => {
expect(
shouldRetryThreadOutboxDelivery(
new EnvironmentRpcUnavailableError({
environmentId: EnvironmentId.make("environment-1"),
environmentLabel: "Test environment",
method: "thread.turn.start",
}),
),
).toBe(true);
expect(shouldRetryThreadOutboxDelivery(new Error("Socket is not connected"))).toBe(true);
expect(
shouldRetryThreadOutboxDelivery({
@@ -281,4 +329,23 @@ describe("thread outbox", () => {
).toBe(true);
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
});
it("retains queued messages when settings synchronization fails before startTurn", () => {
const deterministicFailure = new Error("Thread no longer exists");
expect(
resolveThreadOutboxFailureAction({
stage: "settings-sync",
error: deterministicFailure,
interrupted: false,
}),
).toBe("retry");
expect(
resolveThreadOutboxFailureAction({
stage: "start-turn",
error: deterministicFailure,
interrupted: false,
}),
).toBe("discard");
});
});
@@ -1,14 +1,136 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
removeComposerDraftsForEnvironment,
} from "./use-composer-drafts";
const DRAFT: ComposerDraft = {
text: "hello",
attachments: [],
};
afterEach(() => {
appAtomRegistry.set(composerDraftsAtom, {});
});
describe("mobile composer drafts", () => {
it("hydrates selector state even when the message content is empty", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
},
}),
).toEqual({
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
});
});
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": DRAFT,
},
}),
).toEqual({
"environment-1:thread-1": DRAFT,
});
expect(() =>
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": {
...DRAFT,
runtimeMode: "sometimes-safe",
},
},
}),
).toThrow();
});
it("clears sent content without clearing the selected model or workspace", () => {
const draftKey = "environment-1:thread-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
};
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
[draftKey]: {
...draft,
text: "",
attachments: [],
},
});
});
it("reads the latest selector state synchronously for send", () => {
const draftKey = "environment-1:thread-1";
const selectedDraft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
};
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
});
it("removes only drafts owned by the selected environment", () => {
const environmentId = EnvironmentId.make("environment-cloud");
const retainedEnvironmentId = EnvironmentId.make("environment-local");
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
removeComposerDraftsForEnvironment(
{
[`${environmentId}:thread-cloud`]: DRAFT,
[`new-task:${environmentId}:project-cloud`]: DRAFT,
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
},
environmentId,
),
).toEqual({
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
});
});
});
+124 -22
View File
@@ -1,9 +1,18 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import {
ModelSelection as ModelSelectionSchema,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { appAtomRegistry } from "./atom-registry";
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
}
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
}
export type ComposerDraftSettingsUpdate = Pick<
ComposerDraft,
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
>;
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
mode: Schema.Literals(["local", "worktree"]),
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
});
const ComposerDraftSchema = Schema.Struct({
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelectionSchema),
runtimeMode: Schema.optional(RuntimeModeSchema),
interactionMode: Schema.optional(ProviderInteractionModeSchema),
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
});
const PersistedComposerDraftsSchema = Schema.Struct({
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
});
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
PersistedComposerDraftsSchema,
);
const EMPTY_DRAFT: ComposerDraft = {
text: "",
attachments: [],
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
return EMPTY_DRAFT;
}
return {
...draft,
text: draft.text,
attachments: draft.attachments,
};
}
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
}
function isEmptyDraft(draft: ComposerDraft): boolean {
return draft.text.length === 0 && draft.attachments.length === 0;
return (
draft.text.length === 0 &&
draft.attachments.length === 0 &&
draft.modelSelection === undefined &&
draft.runtimeMode === undefined &&
draft.interactionMode === undefined &&
draft.workspaceSelection === undefined
);
}
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
const parsed = decodePersistedComposerDraftsDocument(value);
return Object.fromEntries(
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
}
async function getComposerDraftsFile() {
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "read";
const raw = await file.text();
operation = "decode";
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
return {};
}
return Object.fromEntries(
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
const draft = entry[1];
return (
typeof draft?.text === "string" &&
Array.isArray(draft.attachments) &&
!isEmptyDraft(draft)
);
}),
);
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
const document = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
} as const;
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
});
}
export function updateComposerDraftSettings(
draftKey: string,
settings: Partial<ComposerDraftSettingsUpdate>,
): void {
updateComposerDrafts((current) => {
const draft = {
...normalizeDraft(current[draftKey]),
...settings,
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function clearComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
): Record<string, ComposerDraft> {
const existing = current[draftKey];
if (!existing) {
return current;
}
const draft = {
...existing,
text: "",
attachments: [],
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
}
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
}
export function clearComposerDraft(draftKey: string): void {
updateComposerDrafts((current) => {
if (!current[draftKey]) {
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
environmentId: EnvironmentId,
): Record<string, ComposerDraft> {
const environmentPrefix = `${environmentId}:`;
const newTaskPrefix = `new-task:${environmentId}:`;
return Object.fromEntries(
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
Object.entries(drafts).filter(
([draftKey]) =>
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
),
);
}
@@ -1,7 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
clearComposerDraft,
clearComposerDraftContent,
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -98,6 +108,10 @@ export function useThreadComposerState() {
const draftMessage = selectedDraft?.text ?? "";
const draftAttachments = selectedDraft?.attachments ?? [];
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
const selectedThreadSessionActivity = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
@@ -130,7 +144,6 @@ export function useThreadComposerState() {
selectedThreadShell,
]);
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
@@ -141,9 +154,10 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = composerDrafts[threadKey];
const text = (draft?.text ?? "").trim();
const attachments = draft?.attachments ?? [];
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
return;
}
@@ -157,15 +171,18 @@ export function useThreadComposerState() {
commandId: CommandId.make(metadata.commandId),
text,
attachments,
modelSelection: draft.modelSelection ?? thread.modelSelection,
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
interactionMode: draft.interactionMode ?? thread.interactionMode,
createdAt: metadata.createdAt,
});
clearComposerDraft(threadKey);
clearComposerDraftContent(threadKey);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
}
}, [composerDrafts, selectedThreadShell]);
}, [selectedThreadDetail, selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -255,12 +272,45 @@ export function useThreadComposerState() {
[selectedThreadShell],
);
const onUpdateModelSelection = useCallback(
(value: ModelSelection) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
},
[selectedThreadKey],
);
const onUpdateRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
},
[selectedThreadKey],
);
const onUpdateInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
},
[selectedThreadKey],
);
return {
selectedThreadFeed,
selectedThreadQueueCount,
activeWorkStartedAt,
draftMessage,
draftAttachments,
modelSelection,
runtimeMode,
interactionMode,
activeThreadBusy,
onChangeDraftMessage,
onPickDraftImages,
@@ -268,5 +318,8 @@ export function useThreadComposerState() {
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,
onUpdateRuntimeMode,
onUpdateInteractionMode,
};
}
+116 -33
View File
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { type MessageId } from "@t3tools/contracts";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { CommandId, type MessageId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
import { useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
shouldRetryThreadOutboxDelivery,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
@@ -44,8 +48,21 @@ function findThread(
);
}
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
return CommandId.make(`${message.commandId}:${setting}`);
}
export function useThreadOutboxDrain(): void {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
});
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
reportFailure: false,
});
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const shellStatuses = useThreadOutboxShellStatuses();
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
const reportFailure = (
commandResult: AtomCommandResult<unknown, unknown>,
stage: ThreadOutboxCommandStage,
): boolean => {
if (!AsyncResult.isFailure(commandResult)) {
return false;
}
const action = resolveThreadOutboxFailureAction({
stage,
error: Cause.squash(commandResult.cause),
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
});
const retry = action === "retry";
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
stage,
cause: commandResult.cause,
retry,
});
return retry;
};
const completeDelivery = async (
deliveryResult: AtomCommandResult<unknown, unknown>,
): Promise<boolean> => {
if (reportFailure(deliveryResult, "start-turn")) {
return false;
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
};
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
const updateResult = await updateThreadMetadata({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "model-selection"),
threadId: queuedMessage.threadId,
modelSelection: settings.modelSelection,
},
});
if (AsyncResult.isFailure(updateResult)) {
reportFailure(updateResult, "settings-sync");
return false;
}
}
if (settings.runtimeMode !== thread.runtimeMode) {
const runtimeResult = await setThreadRuntimeMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
threadId: queuedMessage.threadId,
runtimeMode: settings.runtimeMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(runtimeResult)) {
reportFailure(runtimeResult, "settings-sync");
return false;
}
}
if (settings.interactionMode !== thread.interactionMode) {
const interactionResult = await setThreadInteractionMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
threadId: queuedMessage.threadId,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(interactionResult)) {
reportFailure(interactionResult, "settings-sync");
return false;
}
}
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: {
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(deliveryResult)) {
const error = Cause.squash(deliveryResult.cause);
const retry =
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
cause: deliveryResult.cause,
retry,
});
if (retry) {
return false;
}
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
return completeDelivery(deliveryResult);
},
[startTurn],
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
);
useEffect(() => {
@@ -114,16 +114,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
.pipe(Effect.flip);
expect(error._tag).toBe("ServerAuthScopeNotGrantedError");
if (error._tag === "ServerAuthScopeNotGrantedError") {
expect(error.requestedScopes).toEqual(["orchestration:read", "access:write"]);
expect(error.grantedScopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
]);
}
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
@@ -262,20 +252,4 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
),
),
);
it.effect("retains both session ids when rejecting self-revocation", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const issued = yield* serverAuth.issueSession();
const error = yield* serverAuth
.revokeClientSession(issued.sessionId, issued.sessionId)
.pipe(Effect.flip);
expect(error._tag).toBe("ServerAuthForbiddenOperationError");
if (error._tag === "ServerAuthForbiddenOperationError") {
expect(error.currentSessionId).toBe(issued.sessionId);
expect(error.targetSessionId).toBe(issued.sessionId);
}
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
});
+90 -167
View File
@@ -85,50 +85,44 @@ export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedE
export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
"ServerAuthSessionCredentialValidationError",
{
credentialKind: Schema.Literals(["session", "websocket-ticket"]),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to validate ${this.credentialKind} credential.`;
return "Failed to validate session credential.";
}
}
export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
"ServerAuthAuthenticatedSessionIssueError",
{
subject: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue authenticated session for ${this.subject}.`;
return "Failed to issue authenticated session.";
}
}
export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
"ServerAuthAuthenticatedAccessTokenIssueError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue authenticated access token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to issue authenticated access token.";
}
}
export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
"ServerAuthPairingLinkCreationError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to create pairing link for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to create pairing link.";
}
}
@@ -146,25 +140,22 @@ export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<Ser
export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
"ServerAuthPairingLinkRevocationError",
{
pairingLinkId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke pairing link ${this.pairingLinkId}.`;
return "Failed to revoke pairing link.";
}
}
export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
"ServerAuthSessionTokenIssueError",
{
subject: Schema.String,
scopes: Schema.Array(Schema.String),
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue session token for ${this.subject} with scopes [${this.scopes.join(", ")}].`;
return "Failed to issue session token.";
}
}
@@ -182,63 +173,55 @@ export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerA
export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
"ServerAuthSessionRevocationError",
{
sessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke session ${this.sessionId}.`;
return "Failed to revoke session.";
}
}
export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
"ServerAuthOtherSessionsRevocationError",
{
excludedSessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke sessions other than ${this.excludedSessionId}.`;
return "Failed to revoke other sessions.";
}
}
export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
"ServerAuthWebSocketTokenIssueError",
{
sessionId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to issue websocket token for session ${this.sessionId}.`;
return "Failed to issue websocket token.";
}
}
export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
"ServerAuthDpopReplayStateRecordError",
{
proofKeyThumbprint: Schema.String,
proofId: Schema.String,
replayKey: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to record replay state for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
return "Failed to record DPoP proof replay state.";
}
}
export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
"ServerAuthDpopReplayKeyCalculationError",
{
proofKeyThumbprint: Schema.String,
proofId: Schema.String,
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return `Failed to calculate replay key for DPoP proof ${this.proofId} (${this.proofKeyThumbprint}).`;
return "Failed to calculate DPoP replay key.";
}
}
@@ -377,6 +360,11 @@ export const ServerAuthCredentialError = Schema.Union([
ServerAuthInvalidCredentialError,
]);
export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
export const serverAuthCredentialReason = (
error: ServerAuthCredentialError,
): "missing_credential" | "invalid_credential" =>
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
"ServerAuthInvalidScopeError",
@@ -389,13 +377,10 @@ export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerA
export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
"ServerAuthScopeNotGrantedError",
{
requestedScopes: Schema.Array(Schema.String),
grantedScopes: Schema.Array(Schema.String),
},
{},
) {
override get message(): string {
return `Requested scopes [${this.requestedScopes.join(", ")}] exceed granted scopes [${this.grantedScopes.join(", ")}].`;
return "The requested authentication scope was not granted.";
}
}
@@ -404,35 +389,28 @@ export const ServerAuthInvalidRequestError = Schema.Union([
ServerAuthScopeNotGrantedError,
]);
export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
export const serverAuthInvalidRequestReason = (
error: ServerAuthInvalidRequestError,
): "invalid_scope" | "scope_not_granted" =>
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
"ServerAuthForbiddenOperationError",
{
currentSessionId: Schema.String,
targetSessionId: Schema.String,
},
{},
) {
override get message(): string {
return `Authentication session ${this.currentSessionId} cannot revoke itself.`;
return "The current authentication session cannot revoke itself.";
}
}
export type ServerAuthAuthenticationInternalError =
| ServerAuthSessionCredentialValidationError
| ServerAuthDpopReplayStateRecordError
| ServerAuthDpopReplayKeyCalculationError;
export type ServerAuthAuthenticationError =
| ServerAuthCredentialError
| ServerAuthAuthenticationInternalError;
export class EnvironmentAuth extends Context.Service<
EnvironmentAuth,
{
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
readonly getSessionState: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthSessionState, ServerAuthAuthenticationInternalError>;
) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
readonly createBrowserSession: (
credential: string,
requestMetadata: AuthClientMetadata,
@@ -441,9 +419,7 @@ export class EnvironmentAuth extends Context.Service<
readonly response: AuthBrowserSessionResult;
readonly sessionToken: string;
},
| ServerAuthInvalidCredentialError
| ServerAuthBootstrapCredentialValidationError
| ServerAuthAuthenticatedSessionIssueError
ServerAuthInvalidCredentialError | ServerAuthInternalError
>;
readonly exchangeBootstrapCredentialForAccessToken: (
credential: string,
@@ -454,10 +430,7 @@ export class EnvironmentAuth extends Context.Service<
},
) => Effect.Effect<
AuthAccessTokenResult,
| ServerAuthInvalidCredentialError
| ServerAuthScopeNotGrantedError
| ServerAuthBootstrapCredentialValidationError
| ServerAuthAuthenticatedAccessTokenIssueError
ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
>;
readonly createPairingLink: (input?: {
readonly ttl?: Duration.Duration;
@@ -465,61 +438,56 @@ export class EnvironmentAuth extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
}) => Effect.Effect<IssuedPairingLink, ServerAuthPairingLinkCreationError>;
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthPairingLinkCreationError>;
) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
readonly issueStartupPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthPairingLinkCreationError
ServerAuthInternalError
>;
readonly listPairingLinks: (input?: {
readonly excludeSubjects?: ReadonlyArray<string>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthPairingLinksListError>;
readonly revokePairingLink: (
id: string,
) => Effect.Effect<boolean, ServerAuthPairingLinkRevocationError>;
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly issueSession: (input?: {
readonly ttl?: Duration.Duration;
readonly subject?: string;
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly label?: string;
}) => Effect.Effect<IssuedBearerSession, ServerAuthSessionTokenIssueError>;
}) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
readonly listSessions: () => Effect.Effect<
ReadonlyArray<AuthClientSession>,
ServerAuthSessionsListError
ServerAuthInternalError
>;
readonly revokeSession: (
sessionId: AuthSessionId,
) => Effect.Effect<boolean, ServerAuthSessionRevocationError>;
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly revokeOtherSessionsExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
) => Effect.Effect<number, ServerAuthInternalError>;
readonly listClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthSessionsListError>;
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
readonly revokeClientSession: (
currentSessionId: AuthSessionId,
targetSessionId: AuthSessionId,
) => Effect.Effect<
boolean,
ServerAuthForbiddenOperationError | ServerAuthSessionRevocationError
>;
) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthOtherSessionsRevocationError>;
) => Effect.Effect<number, ServerAuthInternalError>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError>;
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly issueWebSocketTicket: (
session: Pick<AuthenticatedSession, "sessionId">,
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthWebSocketTokenIssueError>;
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthPairingLinkCreationError>;
) => Effect.Effect<string, ServerAuthInternalError>;
}
>()("t3/auth/EnvironmentAuth") {}
@@ -546,7 +514,7 @@ const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) =>
export function toBootstrapExchangeError(
cause: PairingGrantStore.BootstrapCredentialError,
): ServerAuthInvalidCredentialError | ServerAuthBootstrapCredentialValidationError {
): ServerAuthInvalidCredentialError | ServerAuthInternalError {
if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
return new ServerAuthBootstrapCredentialValidationError({ cause });
}
@@ -558,17 +526,12 @@ export function toBootstrapExchangeError(
const mapSessionVerificationErrors = <A, R>(
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
credentialKind: ServerAuthSessionCredentialValidationError["credentialKind"],
): Effect.Effect<
A,
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError,
R
> =>
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
effect.pipe(
Effect.mapError((cause) =>
SessionStore.isSessionCredentialInvalidError(cause)
? new ServerAuthInvalidCredentialError({ cause })
: new ServerAuthSessionCredentialValidationError({ credentialKind, cause }),
: new ServerAuthSessionCredentialValidationError({ cause }),
),
);
@@ -602,7 +565,7 @@ export const make = Effect.gen(function* () {
token: string,
): Effect.Effect<
AuthenticatedSession,
ServerAuthInvalidCredentialError | ServerAuthSessionCredentialValidationError
ServerAuthInvalidCredentialError | ServerAuthInternalError
> =>
sessions.verify(token).pipe(
Effect.tapError((cause) =>
@@ -622,12 +585,12 @@ export const make = Effect.gen(function* () {
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
(effect) => mapSessionVerificationErrors(effect, "session"),
mapSessionVerificationErrors,
);
const authenticateRequest = (
request: HttpServerRequest.HttpServerRequest,
): Effect.Effect<AuthenticatedSession, ServerAuthAuthenticationError> => {
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
const cookieToken = request.cookies[sessions.cookieName];
const bearerToken = parseBearerToken(request);
const dpopToken = parseDpopToken(request);
@@ -679,18 +642,12 @@ export const make = Effect.gen(function* () {
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
}) satisfies AuthSessionState,
),
Effect.catchTags({
ServerAuthMissingCredentialError: () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
ServerAuthInvalidCredentialError: () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
}),
Effect.catchIf(isServerAuthCredentialError, () =>
Effect.succeed({
authenticated: false,
auth: descriptor,
} satisfies AuthSessionState),
),
Effect.withSpan("EnvironmentAuth.getSessionState"),
);
@@ -712,13 +669,7 @@ export const make = Effect.gen(function* () {
},
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthAuthenticatedSessionIssueError({
subject: grant.subject,
cause,
}),
),
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
),
),
Effect.map(
@@ -744,10 +695,7 @@ export const make = Effect.gen(function* () {
Effect.gen(function* () {
const grantedScopes = requestedScopes ?? grant.scopes;
if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
return yield* new ServerAuthScopeNotGrantedError({
requestedScopes: grantedScopes,
grantedScopes: grant.scopes,
});
return yield* new ServerAuthScopeNotGrantedError({});
}
return yield* sessions
.issue({
@@ -767,12 +715,7 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError(
(cause) =>
new ServerAuthAuthenticatedAccessTokenIssueError({
subject: grant.subject,
scopes: grantedScopes,
cause,
}),
(cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
),
);
}),
@@ -822,33 +765,28 @@ export const make = Effect.gen(function* () {
const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
"EnvironmentAuth.createPairingLink",
)(function* (input) {
const scopes = input?.scopes ?? AuthStandardClientScopes;
const subject = input?.subject ?? "one-time-token";
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials
.issueOneTimeToken({
scopes,
subject,
)(
function* (input) {
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
})
.pipe(
Effect.mapError(
(cause) => new ServerAuthPairingLinkCreationError({ subject, scopes, cause }),
),
);
return {
id: issued.id,
credential: issued.credential,
scopes,
subject,
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
});
});
return {
id: issued.id,
credential: issued.credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
},
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
);
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
@@ -868,20 +806,16 @@ export const make = Effect.gen(function* () {
const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
bootstrapCredentials.revoke(id).pipe(
Effect.mapError(
(cause) => new ServerAuthPairingLinkRevocationError({ pairingLinkId: id, cause }),
),
Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokePairingLink"),
);
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) => {
const subject = input?.subject ?? DEFAULT_SESSION_SUBJECT;
const scopes = input?.scopes ?? AuthAdministrativeScopes;
return sessions
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
sessions
.issue({
subject,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
method: "bearer-access-token",
scopes,
scopes: input?.scopes ?? AuthAdministrativeScopes,
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
@@ -896,17 +830,14 @@ export const make = Effect.gen(function* () {
token: issued.token,
method: "bearer-access-token",
scopes: issued.scopes,
subject,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
}) satisfies IssuedBearerSession,
),
Effect.mapError(
(cause) => new ServerAuthSessionTokenIssueError({ subject, scopes, cause }),
),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueSession"),
);
};
const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
sessions.listActive().pipe(
@@ -917,7 +848,7 @@ export const make = Effect.gen(function* () {
const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
sessions.revoke(sessionId).pipe(
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ sessionId, cause })),
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeSession"),
);
@@ -925,10 +856,7 @@ export const make = Effect.gen(function* () {
sessionId,
) =>
sessions.revokeAllExcept(sessionId).pipe(
Effect.mapError(
(cause) =>
new ServerAuthOtherSessionsRevocationError({ excludedSessionId: sessionId, cause }),
),
Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
);
@@ -963,10 +891,7 @@ export const make = Effect.gen(function* () {
"EnvironmentAuth.revokeClientSession",
)(function* (currentSessionId, targetSessionId) {
if (currentSessionId === targetSessionId) {
return yield* new ServerAuthForbiddenOperationError({
currentSessionId,
targetSessionId,
});
return yield* new ServerAuthForbiddenOperationError({});
}
return yield* revokeSession(targetSessionId);
});
@@ -992,9 +917,7 @@ export const make = Effect.gen(function* () {
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
sessions.issueWebSocketToken(session.sessionId).pipe(
Effect.mapError(
(cause) => new ServerAuthWebSocketTokenIssueError({ sessionId: session.sessionId, cause }),
),
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
Effect.map(
(issued) =>
({
@@ -1024,7 +947,7 @@ export const make = Effect.gen(function* () {
scopes: session.scopes,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
(effect) => mapSessionVerificationErrors(effect, "websocket-ticket"),
mapSessionVerificationErrors,
);
}
}
+3 -100
View File
@@ -45,31 +45,6 @@ const makePermissionDeniedSecretStoreLayer = () =>
Layer.provideMerge(PermissionDeniedFileSystemLayer),
);
const DirectoryCreateFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
makeDirectory: (path) =>
Effect.fail(
PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: String(path),
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeDirectoryCreateFailureSecretStoreLayer = (config: ServerConfig.ServerConfig["Service"]) =>
ServerSecretStore.layer.pipe(
Layer.provide(Layer.succeed(ServerConfig.ServerConfig, config)),
Layer.provideMerge(DirectoryCreateFailureFileSystemLayer),
);
const RenameFailureFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
@@ -170,56 +145,7 @@ const makeConcurrentCreateSecretStoreLayer = () =>
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
);
const ConcurrentCreationWithoutReadableSecretFileSystemLayer = Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return {
...fileSystem,
readFile: (path) =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: path,
}),
),
open: (path) =>
Effect.fail(
PlatformError.systemError({
_tag: "AlreadyExists",
module: "FileSystem",
method: "open",
pathOrDescriptor: path,
}),
),
} satisfies FileSystem.FileSystem;
}),
).pipe(Layer.provide(NodeServices.layer));
const makeConcurrentCreationWithoutReadableSecretStoreLayer = () =>
ServerSecretStore.layer.pipe(
Layer.provide(makeServerConfigLayer()),
Layer.provideMerge(ConcurrentCreationWithoutReadableSecretFileSystemLayer),
);
it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
it.effect("preserves directory context when secret-store initialization fails", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(makeServerConfigLayer()));
const error = yield* Layer.build(makeDirectoryCreateFailureSecretStoreLayer(config)).pipe(
Effect.scoped,
Effect.flip,
);
assert.instanceOf(error, ServerSecretStore.SecretStoreDirectoryCreateError);
assert.match(error.directoryPath, /secrets$/u);
assert.instanceOf(error.cause, PlatformError.PlatformError);
}),
);
it.effect("returns Option.none when a secret file does not exist", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
@@ -260,25 +186,6 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);
it.effect("preserves the persist failure when a concurrent secret remains unreadable", () =>
Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
assert.instanceOf(error, ServerSecretStore.SecretStoreConcurrentReadError);
assert.equal(error.secretName, "session-signing-key");
assert.equal(
error.message,
"Failed to read secret session-signing-key after concurrent creation.",
);
assert.instanceOf(error.cause, ServerSecretStore.SecretStorePersistError);
assert.equal(error.cause.operation, "create");
assert.instanceOf(error.cause.cause, PlatformError.PlatformError);
assert.equal(error.cause.cause.reason._tag, "AlreadyExists");
}).pipe(Effect.provide(makeConcurrentCreationWithoutReadableSecretStoreLayer())),
);
it.effect("uses restrictive permissions for the secret directory and files", () =>
Effect.gen(function* () {
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
@@ -325,8 +232,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
assert.instanceOf(error, ServerSecretStore.SecretStoreReadError);
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to read secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
@@ -341,9 +247,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
);
assert.instanceOf(error, ServerSecretStore.SecretStorePersistError);
assert.equal(error.operation, "set");
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to persist secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
@@ -356,8 +260,7 @@ it.layer(NodeServices.layer)("ServerSecretStore.layer", (it) => {
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
assert.instanceOf(error, ServerSecretStore.SecretStoreRemoveError);
assert.equal(error.secretName, "session-signing-key");
assert.match(error.secretPath, /session-signing-key\.bin$/u);
assert.include(error.message, "Failed to remove secret session-signing-key.");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "PermissionDenied");
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
+62 -119
View File
@@ -11,137 +11,114 @@ import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
const storedSecretErrorContext = {
secretName: Schema.String,
secretPath: Schema.String,
const secretStoreErrorContext = {
resource: Schema.String,
cause: Schema.Defect(),
};
export class SecretStoreDirectoryCreateError extends Schema.TaggedErrorClass<SecretStoreDirectoryCreateError>()(
"SecretStoreDirectoryCreateError",
export class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(
"SecretStoreSecureError",
{
directoryPath: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to create secret store directory ${this.directoryPath}.`;
}
}
export class SecretStoreDirectorySecureError extends Schema.TaggedErrorClass<SecretStoreDirectorySecureError>()(
"SecretStoreDirectorySecureError",
{
directoryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to secure secret store directory ${this.directoryPath}.`;
return `Failed to secure ${this.resource}.`;
}
}
export class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(
"SecretStoreReadError",
{
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to read secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to read ${this.resource}.`;
}
}
export class SecretStoreTemporaryPathGenerationError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathGenerationError>()(
"SecretStoreTemporaryPathGenerationError",
export class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(
"SecretStoreTemporaryPathError",
{
secretName: Schema.String,
secretPath: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to generate a temporary path for secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to create temporary path for ${this.resource}.`;
}
}
export class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(
"SecretStorePersistError",
{
operation: Schema.Literals(["create", "set"]),
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to ${this.operation} secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to persist ${this.resource}.`;
}
}
export class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(
"SecretStoreRandomGenerationError",
{
secretName: Schema.String,
byteCount: Schema.Number,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to generate ${this.byteCount} random bytes for secret ${this.secretName}.`;
return `Failed to generate random bytes for ${this.resource}.`;
}
}
export class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(
"SecretStoreConcurrentReadError",
{
secretName: Schema.String,
cause: Schema.Defect(),
resource: Schema.String,
},
) {
override get message(): string {
return `Failed to read secret ${this.secretName} after concurrent creation.`;
return `Failed to read ${this.resource} after concurrent creation.`;
}
}
export class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(
"SecretStoreRemoveError",
{
...storedSecretErrorContext,
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to remove secret ${this.secretName} at ${this.secretPath}.`;
return `Failed to remove ${this.resource}.`;
}
}
export class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(
"SecretStoreDecodeError",
{
secretName: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to decode secret ${this.secretName}.`;
return `Failed to decode ${this.resource}.`;
}
}
export class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(
"SecretStoreEncodeError",
{
secretName: Schema.String,
cause: Schema.Defect(),
...secretStoreErrorContext,
},
) {
override get message(): string {
return `Failed to encode secret ${this.secretName}.`;
return `Failed to encode ${this.resource}.`;
}
}
export const SecretStoreError = Schema.Union([
SecretStoreDirectoryCreateError,
SecretStoreDirectorySecureError,
SecretStoreSecureError,
SecretStoreReadError,
SecretStoreTemporaryPathGenerationError,
SecretStoreTemporaryPathError,
SecretStorePersistError,
SecretStoreRandomGenerationError,
SecretStoreConcurrentReadError,
@@ -161,26 +138,14 @@ export const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>
export class ServerSecretStore extends Context.Service<
ServerSecretStore,
{
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreReadError>;
readonly set: (
name: string,
value: Uint8Array,
) => Effect.Effect<void, SecretStoreTemporaryPathGenerationError | SecretStorePersistError>;
readonly create: (
name: string,
value: Uint8Array,
) => Effect.Effect<void, SecretStorePersistError>;
readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
readonly getOrCreateRandom: (
name: string,
bytes: number,
) => Effect.Effect<
Uint8Array,
| SecretStoreReadError
| SecretStoreRandomGenerationError
| SecretStorePersistError
| SecretStoreConcurrentReadError
>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreRemoveError>;
) => Effect.Effect<Uint8Array, SecretStoreError>;
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
>()("t3/auth/ServerSecretStore") {}
@@ -190,20 +155,12 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new SecretStoreDirectoryCreateError({
directoryPath: serverConfig.secretsDir,
cause,
}),
),
);
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
Effect.mapError(
(cause) =>
new SecretStoreDirectorySecureError({
directoryPath: serverConfig.secretsDir,
new SecretStoreSecureError({
resource: `secrets directory ${serverConfig.secretsDir}`,
cause,
}),
),
@@ -211,33 +168,29 @@ export const make = Effect.gen(function* () {
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const get: ServerSecretStore["Service"]["get"] = (name) => {
const secretPath = resolveSecretPath(name);
return fileSystem.readFile(secretPath).pipe(
const get: ServerSecretStore["Service"]["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: Effect.fail(
new SecretStoreReadError({
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
),
Effect.withSpan("ServerSecretStore.get"),
);
};
const set: ServerSecretStore["Service"]["set"] = (name, value) => {
const secretPath = resolveSecretPath(name);
return crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new SecretStoreTemporaryPathGenerationError({
secretName: name,
secretPath,
new SecretStoreTemporaryPathError({
resource: `secret ${name}`,
cause,
}),
),
@@ -255,9 +208,7 @@ export const make = Effect.gen(function* () {
Effect.flatMap(() =>
Effect.fail(
new SecretStorePersistError({
operation: "set",
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
@@ -286,9 +237,7 @@ export const make = Effect.gen(function* () {
Effect.mapError(
(cause) =>
new SecretStorePersistError({
operation: "create",
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
@@ -305,33 +254,30 @@ export const make = Effect.gen(function* () {
Effect.mapError(
(cause) =>
new SecretStoreRandomGenerationError({
secretName: name,
byteCount: bytes,
resource: `secret ${name}`,
cause,
}),
),
Effect.flatMap((generated) =>
create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTags({
SecretStorePersistError: (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreConcurrentReadError({
secretName: name,
cause: error,
}),
),
}),
),
)
: Effect.fail(error),
}),
Effect.catchIf(isSecretStoreError, (error) =>
isSecretAlreadyExistsError(error)
? get(name).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new SecretStoreConcurrentReadError({
resource: `secret ${name}`,
}),
),
}),
),
)
: Effect.fail(error),
),
),
),
),
@@ -340,23 +286,20 @@ export const make = Effect.gen(function* () {
Effect.withSpan("ServerSecretStore.getOrCreateRandom"),
);
const remove: ServerSecretStore["Service"]["remove"] = (name) => {
const secretPath = resolveSecretPath(name);
return fileSystem.remove(secretPath).pipe(
const remove: ServerSecretStore["Service"]["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
? Effect.void
: Effect.fail(
new SecretStoreRemoveError({
secretName: name,
secretPath,
resource: `secret ${name}`,
cause,
}),
),
),
Effect.withSpan("ServerSecretStore.remove"),
);
};
return ServerSecretStore.of({
get,
+80 -4
View File
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
create: () => Effect.void,
getById: () => Effect.fail(repositoryFailure),
listActive: () => Effect.succeed([]),
revoke: () => Effect.succeed(false),
revokeAllExcept: () => Effect.succeed([]),
revoke: () => Effect.fail(repositoryFailure),
revokeAllExcept: () => Effect.fail(repositoryFailure),
setLastConnectedAt: () => Effect.void,
});
@@ -104,11 +104,29 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
expect(sessionError.cause).toBe(repositoryFailure);
expect(websocketError.cause).toBe(repositoryFailure);
if (sessionError._tag === "SessionCredentialVerificationError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
}
if (websocketError._tag === "WebSocketTokenVerificationError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
}
expect(revokeError).toMatchObject({
_tag: "SessionRevocationError",
sessionId: issued.sessionId,
cause: repositoryFailure,
});
expect(revokeOthersError).toMatchObject({
_tag: "OtherSessionsRevocationError",
currentSessionId: issued.sessionId,
cause: repositoryFailure,
});
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
);
it.effect("verifies session tokens against the Effect clock", () =>
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
yield* TestClock.adjust(Duration.seconds(2));
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(error.message).toContain("expired");
expect(error._tag).toBe("WebSocketSessionExpiredError");
if (error._tag === "WebSocketSessionExpiredError") {
expect(error.sessionId).toBe(issued.sessionId);
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
error.expiresAt.epochMilliseconds,
);
}
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
it.effect("includes expiry context when session and websocket tokens expire", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const issued = yield* sessions.issue({
method: "bearer-access-token",
subject: "short-lived-token",
ttl: Duration.seconds(1),
});
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
ttl: Duration.seconds(1),
});
yield* TestClock.adjust(Duration.seconds(2));
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(sessionError._tag).toBe("SessionTokenExpiredError");
if (sessionError._tag === "SessionTokenExpiredError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
sessionError.expiresAt.epochMilliseconds,
);
}
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
if (websocketError._tag === "WebSocketTokenExpiredError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
expect(websocketError.expiresAt.epochMilliseconds).toBe(
websocket.expiresAt.epochMilliseconds,
);
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
websocketError.expiresAt.epochMilliseconds,
);
}
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
@@ -173,12 +236,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
ipAddress: "192.168.1.88",
},
});
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
yield* sessions.markConnected(client.sessionId);
const beforeRevoke = yield* sessions.listActive();
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
const afterRevoke = yield* sessions.listActive();
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
const revokedClientWebSocket = yield* Effect.flip(
sessions.verifyWebSocketToken(clientWebSocket.token),
);
expect(beforeRevoke).toHaveLength(2);
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(revokedCount).toBe(1);
expect(afterRevoke).toHaveLength(1);
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
expect(revokedClient.message).toContain("revoked");
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
if (revokedClient._tag === "SessionTokenRevokedError") {
expect(revokedClient.sessionId).toBe(client.sessionId);
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
}).pipe(Effect.provide(makeSessionStoreLayer())),
);
+228 -149
View File
@@ -7,7 +7,6 @@ import {
type AuthEnvironmentScope,
type ServerAuthSessionMethod,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
@@ -93,7 +92,11 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
"SessionTokenExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Session token expired.";
@@ -102,7 +105,9 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
"UnknownSessionTokenError",
{},
{
sessionId: AuthSessionId,
},
) {
override get message(): string {
return "Unknown session token.";
@@ -111,7 +116,10 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
"SessionTokenRevokedError",
{},
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Session token revoked.";
@@ -120,7 +128,10 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
"InvalidSessionExpirationClaimError",
{},
{
sessionId: AuthSessionId,
expirationClaim: Schema.Number,
},
) {
override get message(): string {
return "Invalid `exp` claim";
@@ -158,7 +169,11 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
"WebSocketTokenExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket token expired.";
@@ -167,7 +182,9 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
"UnknownWebSocketSessionError",
{},
{
sessionId: AuthSessionId,
},
) {
override get message(): string {
return "Unknown websocket session.";
@@ -176,7 +193,11 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
"WebSocketSessionExpiredError",
{},
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket session expired.";
@@ -185,7 +206,10 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
"WebSocketSessionRevokedError",
{},
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
) {
override get message(): string {
return "Websocket session revoked.";
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
"SessionClaimsEncodingError",
{
sessionId: AuthSessionId,
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
...sessionCredentialInternalErrorContext,
},
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
"SessionCredentialIssueError",
{
sessionId: Schema.optional(AuthSessionId),
...sessionCredentialInternalErrorContext,
},
) {
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
"SessionCredentialVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
"WebSocketTokenIssueError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
"WebSocketTokenVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
"SessionRevocationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
"OtherSessionsRevocationError",
{
currentSessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -539,7 +570,11 @@ export const make = Effect.gen(function* () {
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
function* (input) {
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const sessionId = AuthSessionId.make(
yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
),
);
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
(cause) =>
new SessionCredentialIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_session_claims",
cause,
}),
}),
),
);
const signature = signPayload(encodedPayload, signingSecret);
const client = input?.client ?? createDefaultClientMetadata();
yield* authSessions.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
});
yield* authSessions
.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
})
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
yield* emitUpsert(
toAuthClientSession({
sessionId,
@@ -604,7 +649,6 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies IssuedSession;
},
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
);
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownSessionTokenError({});
}
if (row.value.revokedAt !== null) {
return yield* new SessionTokenRevokedError({});
}
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({});
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new SessionTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
),
);
if (Option.isNone(row)) {
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
}
if (row.value.revokedAt !== null) {
return yield* new SessionTokenRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
}
return {
@@ -652,95 +711,111 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new SessionCredentialVerificationError({ cause }),
),
);
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
"SessionStore.issueWebSocketToken",
)(
function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
},
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
);
)(function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new WebSocketTokenIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_websocket_claims",
cause,
}),
}),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
});
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
"SessionStore.verifyWebSocketToken",
)(
function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
)(function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
);
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new WebSocketTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new WebSocketTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({});
}
if (row.value.expiresAt.epochMilliseconds <= now) {
return yield* new WebSocketSessionExpiredError({});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
}
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
return yield* new WebSocketSessionExpiredError({
sessionId: claims.sid,
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new WebSocketTokenVerificationError({ cause }),
),
);
observedAt,
});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
});
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
function* () {
@@ -768,10 +843,12 @@ export const make = Effect.gen(function* () {
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revoked = yield* authSessions.revoke({
sessionId,
revokedAt,
});
const revoked = yield* authSessions
.revoke({
sessionId,
revokedAt,
})
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
if (revoked) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
@@ -782,39 +859,41 @@ export const make = Effect.gen(function* () {
}
return revoked;
},
Effect.mapError((cause) => new SessionRevocationError({ cause })),
);
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
"SessionStore.revokeAllExcept",
)(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions.revokeAllExcept({
)(function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions
.revokeAllExcept({
currentSessionId: sessionId,
revokedAt,
})
.pipe(
Effect.mapError(
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
),
);
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
},
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
);
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
});
return SessionStore.of({
cookieName,
+4 -19
View File
@@ -6,9 +6,7 @@ import { mapDpopReplayStoreError } from "./dpop.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new SecretStorePersistError({
operation: "create",
secretName: "DPoP proof",
secretPath: "dpop-proof.bin",
resource: "DPoP proof",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -17,16 +15,10 @@ const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
}),
});
const replayContext = {
proofKeyThumbprint: "proof-key-thumbprint",
proofId: "proof-id",
replayKey: "replay-key",
};
describe("mapDpopReplayStoreError", () => {
it("reports replay conflicts as invalid credentials", () => {
const cause = storeFailure("AlreadyExists");
const error = mapDpopReplayStoreError(cause, replayContext);
const error = mapDpopReplayStoreError(cause);
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
if (error._tag === "ServerAuthInvalidCredentialError") {
@@ -35,18 +27,11 @@ describe("mapDpopReplayStoreError", () => {
});
it("reports replay-store availability failures as internal errors", () => {
const cause = storeFailure("PermissionDenied");
const error = mapDpopReplayStoreError(cause, replayContext);
const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));
expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");
if (error._tag === "ServerAuthDpopReplayStateRecordError") {
expect(error.message).toBe(
"Failed to record replay state for DPoP proof proof-id (proof-key-thumbprint).",
);
expect(error.proofKeyThumbprint).toBe(replayContext.proofKeyThumbprint);
expect(error.proofId).toBe(replayContext.proofId);
expect(error.replayKey).toBe(replayContext.replayKey);
expect(error.cause).toBe(cause);
expect(error.message).toBe("Failed to record DPoP proof replay state.");
}
});
});
+13 -33
View File
@@ -3,46 +3,26 @@ import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
ServerAuthDpopReplayStateRecordError,
ServerAuthInvalidCredentialError,
type ServerAuthInternalError,
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
function firstHeaderValue(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first && first.length > 0 ? first : undefined;
}
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
try {
return new URL(request.originalUrl).href;
} catch {
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
return new URL(request.originalUrl, `${proto}://${host}`).href;
}
}
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
context: {
readonly proofKeyThumbprint: string;
readonly proofId: string;
readonly replayKey: string;
},
): ServerAuthInvalidCredentialError | ServerAuthDpopReplayStateRecordError =>
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? new ServerAuthInvalidCredentialError({
diagnostic: "DPoP proof replayed.",
cause: error,
})
: new ServerAuthDpopReplayStateRecordError({
...context,
cause: error,
});
@@ -53,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
}) =>
Effect.gen(function* () {
const proof = input.request.headers.dpop;
const url = HttpServerRequest.toURL(input.request);
if (Option.isNone(url)) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: "Invalid DPoP request URL.",
});
}
const now = yield* DateTime.now;
const result = verifyDpopProof({
proof,
method: input.request.method,
url: requestAbsoluteUrl(input.request),
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
@@ -76,8 +62,6 @@ export const verifyRequestDpopProof = (input: {
Effect.mapError(
(cause) =>
new ServerAuthDpopReplayKeyCalculationError({
proofKeyThumbprint: result.thumbprint,
proofId: result.jti,
cause,
}),
),
@@ -95,12 +79,8 @@ export const verifyRequestDpopProof = (input: {
),
)
.pipe(
Effect.mapError((error) =>
mapDpopReplayStoreError(error, {
proofKeyThumbprint: result.thumbprint,
proofId: result.jti,
replayKey,
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
Effect.fail(mapDpopReplayStoreError(error)),
),
);
return result.thumbprint;
+58 -86
View File
@@ -151,22 +151,6 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,
});
}
const failAuthenticationInternal = (error: EnvironmentAuth.ServerAuthAuthenticationInternalError) =>
failEnvironmentInternal("internal_error", error);
export const catchEnvironmentAuthenticationErrors = <A, R>(
effect: Effect.Effect<A, EnvironmentAuth.ServerAuthAuthenticationError, R>,
) =>
effect.pipe(
Effect.catchTags({
ServerAuthMissingCredentialError: () => failEnvironmentAuthInvalid("missing_credential"),
ServerAuthInvalidCredentialError: () => failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
}),
);
export const requireEnvironmentScope = Effect.fn("environment.auth.requireScope")(function* (
scope: AuthEnvironmentScope,
) {
@@ -184,8 +168,13 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
return (httpEffect) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const session = yield* catchEnvironmentAuthenticationErrors(
serverAuth.authenticateHttpRequest(request),
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
return yield* httpEffect.pipe(
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
@@ -194,11 +183,7 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(
}),
session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,
);
}).pipe(
Effect.catchTags({
EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized,
}),
);
}).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));
}),
);
@@ -218,11 +203,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const request = yield* HttpServerRequest.HttpServerRequest;
return yield* serverAuth.getSessionState(request);
},
Effect.catchTags({
ServerAuthSessionCredentialValidationError: failAuthenticationInternal,
ServerAuthDpopReplayStateRecordError: failAuthenticationInternal,
ServerAuthDpopReplayKeyCalculationError: failAuthenticationInternal,
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
),
)
.handle(
@@ -250,14 +233,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return result.response;
},
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthBootstrapCredentialValidationError: (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
ServerAuthAuthenticatedSessionIssueError: (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("browser_session_issuance_failed", error),
),
),
)
.handle(
@@ -287,16 +268,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
const proofKeyThumbprint = args.headers.dpop
? yield* verifyRequestDpopProof({ request }).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
ServerAuthDpopReplayStateRecordError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
ServerAuthDpopReplayKeyCalculationError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>
appendDpopChallengeHeader.pipe(
Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),
),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
)
: undefined;
yield* appendCredentialResponseHeaders;
@@ -317,16 +296,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
},
traceRelayRequest,
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
failEnvironmentAuthInvalid("invalid_credential"),
ServerAuthScopeNotGrantedError: () =>
failEnvironmentInvalidRequest("scope_not_granted"),
ServerAuthBootstrapCredentialValidationError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
ServerAuthAuthenticatedAccessTokenIssueError: (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("access_token_issuance_failed", error),
),
),
)
.handle(
@@ -338,10 +316,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* appendCredentialResponseHeaders;
return yield* serverAuth.issueWebSocketTicket(session);
},
Effect.catchTags({
ServerAuthWebSocketTokenIssueError: (error) =>
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("websocket_ticket_issuance_failed", error),
),
),
)
.handle(
@@ -364,10 +341,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
}
return yield* serverAuth.issuePairingCredential(args.payload);
},
Effect.catchTags({
ServerAuthPairingLinkCreationError: (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
),
),
)
.handle(
@@ -378,10 +354,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listPairingLinks();
},
Effect.catchTags({
ServerAuthPairingLinksListError: (error) =>
failEnvironmentInternal("pairing_links_load_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_links_load_failed", error),
),
),
)
.handle(
@@ -393,10 +368,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revoked = yield* serverAuth.revokePairingLink(args.payload.id);
return { revoked };
},
Effect.catchTags({
ServerAuthPairingLinkRevocationError: (error) =>
failEnvironmentInternal("pairing_link_revoke_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_link_revoke_failed", error),
),
),
)
.handle(
@@ -407,10 +381,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const session = yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listClientSessions(session.sessionId);
},
Effect.catchTags({
ServerAuthSessionsListError: (error) =>
failEnvironmentInternal("client_sessions_load_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_sessions_load_failed", error),
),
),
)
.handle(
@@ -425,12 +398,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
);
return { revoked };
},
Effect.catchTags({
ServerAuthForbiddenOperationError: () =>
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
ServerAuthSessionRevocationError: (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
}),
Effect.catchTag("ServerAuthForbiddenOperationError", () =>
failEnvironmentOperationForbidden("current_session_revoke_not_allowed"),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
)
.handle(
@@ -442,10 +415,9 @@ export const authHttpApiLayer = HttpApiBuilder.group(
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
return { revokedCount };
},
Effect.catchTags({
ServerAuthOtherSessionsRevocationError: (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
);
}),
@@ -0,0 +1,217 @@
import { assert, describe, it } from "@effect/vitest";
import {
AuthSessionId,
RpcClientId,
type HostPowerSnapshot,
type ClientActivityReportInput,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
const nominalHostPower: HostPowerSnapshot = {
source: "unknown",
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt: TEST_NOW,
};
const constrainedHostPower: HostPowerSnapshot = {
...nominalHostPower,
lowPowerMode: "true",
stale: false,
};
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
return {
clientId: "client-1",
clientKind: "web",
visible: true,
focused: true,
recentlyInteracted: true,
scopes: [{ type: "vcs-status", cwd: "/repo" }],
ttlMs: 45_000,
observedAt: TEST_NOW,
...overrides,
};
}
function makeLayer(
hostPower: HostPowerSnapshot,
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
) {
const hostLayer = Layer.effect(
HostPowerMonitor.HostPowerMonitor,
Effect.gen(function* () {
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
let snapshot = hostPower;
return HostPowerMonitor.HostPowerMonitor.of({
snapshot: Effect.sync(() => snapshot),
report: (next) =>
Effect.sync(() => {
snapshot = next;
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
streamChanges: Stream.fromPubSub(changes),
});
}),
);
return BackgroundPolicy.layer.pipe(
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
);
}
describe("BackgroundPolicy", () => {
it.effect("records foreground scoped client demand", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 1);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(snapshot.shouldRunOpportunisticWork, true);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect("removes all leases for a disconnected websocket connection", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
yield* policy.removeRpcClient(RpcClientId.make(1));
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 0);
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
assert.equal(snapshot.shouldRunOpportunisticWork, false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 1);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(snapshot.shouldRunOpportunisticWork, false);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
);
it.effect("keeps background demand visible while preventing scoped work", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport({ focused: false, visible: false }),
);
const snapshot = yield* policy.snapshot;
assert.equal(snapshot.activeForegroundLeaseCount, 0);
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
);
it.effect(
"performance profile allows background scoped work while a scoped lease is active",
() =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport({ focused: false, visible: false }),
);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
}).pipe(
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
),
);
it.effect("battery saver profile pauses scoped work on battery", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
}).pipe(
Effect.provide(
makeLayer(
{
...nominalHostPower,
onBattery: "true",
stale: false,
},
{ backgroundActivityProfile: "battery-saver" },
),
),
),
);
it.effect("does not gate work on stale host power values", () =>
Effect.gen(function* () {
const policy = yield* BackgroundPolicy.BackgroundPolicy;
yield* policy.reportClientActivity(
AuthSessionId.make("session-1"),
RpcClientId.make(1),
makeReport(),
);
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
}).pipe(
Effect.provide(
makeLayer(
{
...nominalHostPower,
locked: "true",
onBattery: "true",
lowPowerMode: "true",
thermalState: "critical",
stale: true,
},
{ backgroundActivityProfile: "battery-saver" },
),
),
),
);
});
@@ -0,0 +1,274 @@
import {
type AuthSessionId,
type BackgroundPolicySnapshot,
type BackgroundScope,
type ClientActivityLease,
type ClientActivityReportInput,
type HostPowerSnapshot,
type RpcClientId,
} from "@t3tools/contracts";
import {
getBackgroundActivityPresetSettings,
resolveServerBackgroundActivitySettings,
type ResolvedBackgroundActivitySettings,
} from "@t3tools/shared/backgroundActivitySettings";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
export interface BackgroundPolicyShape {
readonly reportClientActivity: (
sessionId: AuthSessionId,
rpcClientId: RpcClientId,
input: ClientActivityReportInput,
) => Effect.Effect<void>;
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
}
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
"t3/background/BackgroundPolicy",
) {}
const DEFAULT_LEASE_TTL_MS = 45_000;
const MAX_LEASE_TTL_MS = 120_000;
function scopeKey(scope: BackgroundScope): string {
switch (scope.type) {
case "server-config":
case "diagnostics":
return scope.type;
case "provider-status":
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
case "vcs-status":
case "git-refs":
return `${scope.type}:${scope.cwd}`;
case "thread":
return `${scope.type}:${scope.threadId}`;
}
}
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
return DateTime.isGreaterThan(lease.expiresAt, now);
}
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
return isLeaseActive(lease, now) && lease.visible && lease.focused;
}
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
const key = scopeKey(scope);
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
}
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
}
function isHostConstrained(
hostPower: HostPowerSnapshot,
settings: ResolvedBackgroundActivitySettings,
): boolean {
if (hostPower.stale) return false;
if (
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
hasThermalPressure(hostPower)
) {
return true;
}
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
}
function isClientConstrained(
lease: ClientActivityLease,
settings: ResolvedBackgroundActivitySettings,
): boolean {
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
}
function leaseMayRunScopedWork(
lease: ClientActivityLease,
scope: BackgroundScope,
now: DateTime.Utc,
settings: ResolvedBackgroundActivitySettings,
): boolean {
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
if (!activeWithScope || isClientConstrained(lease, settings)) {
return false;
}
if (settings.profile === "performance") {
return true;
}
return isForegroundLease(lease, now);
}
function computeSnapshot(input: {
readonly hostPower: HostPowerSnapshot;
readonly leases: ReadonlyMap<string, ClientActivityLease>;
readonly now: DateTime.Utc;
readonly settings: ResolvedBackgroundActivitySettings;
readonly updatedAt: DateTime.Utc;
}): BackgroundPolicySnapshot {
const activeLeases = [...input.leases.values()].filter((lease) =>
isLeaseActive(lease, input.now),
);
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
const activeScopeKeys = new Set<string>();
for (const lease of activeLeases) {
for (const scope of lease.scopes) {
activeScopeKeys.add(scopeKey(scope));
}
}
return {
hostPower: input.hostPower,
leases: activeLeases,
activeForegroundLeaseCount: foregroundLeases.length,
activeScopeKeys: [...activeScopeKeys].toSorted(),
shouldRunOpportunisticWork:
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
!isHostConstrained(input.hostPower, input.settings),
updatedAt: input.updatedAt,
};
}
export const make = Effect.fn("background.policy.make")(function* () {
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
const serverSettings = yield* ServerSettingsService;
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
const backgroundActivitySettings = serverSettings.getSettings.pipe(
Effect.map(resolveServerBackgroundActivitySettings),
Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
);
const snapshot = Effect.gen(function* () {
const [hostPower, leases, now, settings] = yield* Effect.all([
hostPowerMonitor.snapshot,
Ref.get(leasesRef),
DateTime.now,
backgroundActivitySettings,
]);
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
});
const publishSnapshot = snapshot.pipe(Effect.flatMap((next) => PubSub.publish(changes, next)));
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
sessionId,
rpcClientId,
input,
) =>
Effect.gen(function* () {
const ttlMs = Math.min(
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
MAX_LEASE_TTL_MS,
);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
const lease: ClientActivityLease = {
sessionId,
rpcClientId,
clientId: input.clientId,
clientKind: input.clientKind,
visible: input.visible,
focused: input.focused,
recentlyInteracted: input.recentlyInteracted,
...(input.appState !== undefined ? { appState: input.appState } : {}),
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
scopes: input.scopes,
updatedAt: now,
expiresAt,
};
yield* Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
next.set(`${rpcClientId}:${input.clientId}`, lease);
return next;
});
yield* publishSnapshot;
});
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
for (const key of next.keys()) {
if (key.startsWith(`${rpcClientId}:`)) {
next.delete(key);
}
}
return next;
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
Effect.gen(function* () {
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
if (isHostConstrained(current.hostPower, settings)) {
return false;
}
return current.leases.some((lease) =>
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
);
});
const shouldRunOpportunisticWork = Effect.map(
snapshot,
(current) => current.shouldRunOpportunisticWork,
);
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
Effect.forkScoped,
);
yield* Effect.forever(
Effect.sleep("15 seconds").pipe(
Effect.andThen(
Effect.gen(function* () {
const now = yield* DateTime.now;
yield* Ref.update(leasesRef, (leases) => {
const next = new Map(leases);
for (const [key, lease] of next) {
if (!isLeaseActive(lease, now)) {
next.delete(key);
}
}
return next;
});
}),
),
Effect.andThen(publishSnapshot),
),
).pipe(Effect.forkScoped);
return BackgroundPolicy.of({
reportClientActivity,
removeRpcClient,
reportHostPowerState: hostPowerMonitor.report,
snapshot,
streamChanges: Stream.fromPubSub(changes),
hasDemand,
shouldRunScopeWork,
shouldRunOpportunisticWork,
});
});
export const layer = Layer.effect(BackgroundPolicy, make());
@@ -0,0 +1,92 @@
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
describe("HostPowerMonitor", () => {
it.effect("publishes semantic power changes without idle-time heartbeat churn", () =>
Effect.gen(function* () {
const monitor = yield* HostPowerMonitor.make();
const initial = {
source: "electron-main",
idle: "false",
idleSeconds: 0,
locked: "false",
suspended: false,
onBattery: "false",
lowPowerMode: "unknown",
thermalState: "nominal",
stale: false,
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
} as const;
yield* monitor.report(initial);
const nextChange = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* monitor.report({
...initial,
idleSeconds: 1,
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
});
yield* monitor.report({
...initial,
locked: "true",
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:02.000Z"),
});
expect(Option.getOrThrow(yield* Fiber.join(nextChange)).locked).toBe("true");
}),
);
it.effect("consumes desktop power directly without retaining diagnostics telemetry", () =>
Effect.gen(function* () {
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
const diagnosticsDemandWrites = yield* Ref.make(0);
const receiverLayer = DesktopTelemetryReceiver.layerTest({
changes: Stream.fromPubSub(desktopChanges),
setDiagnosticsDemand: () => Ref.update(diagnosticsDemandWrites, (count) => count + 1),
});
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
yield* Effect.gen(function* () {
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
const nextPower = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
yield* Effect.yieldNow;
yield* PubSub.publish(desktopChanges, {
version: 1,
type: "desktopTelemetry",
sequence: 1,
sampledAtUnixMs: DateTime.toEpochMillis(sampledAt),
electronPid: 100,
power: {
source: "electron-main",
idle: "false",
idleSeconds: 0,
locked: "false",
suspended: false,
onBattery: "true",
lowPowerMode: "unknown",
thermalState: "nominal",
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: Option.none(),
electronProcesses: [],
});
expect(Option.getOrThrow(yield* Fiber.join(nextPower)).onBattery).toBe("true");
expect(yield* Ref.get(diagnosticsDemandWrites)).toBe(0);
}).pipe(Effect.provide(layer));
}),
);
});
@@ -0,0 +1,93 @@
import type { HostPowerSnapshot } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
export interface HostPowerMonitorShape {
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
}
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
"t3/background/HostPowerMonitor",
) {}
export const makeUnknownSnapshot = (
source: HostPowerSnapshot["source"],
updatedAt: HostPowerSnapshot["updatedAt"],
): HostPowerSnapshot => ({
source,
idle: "unknown",
idleSeconds: null,
locked: "unknown",
suspended: false,
onBattery: "unknown",
lowPowerMode: "unknown",
thermalState: "unknown",
stale: true,
updatedAt,
});
function samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {
return (
left.source === right.source &&
left.idle === right.idle &&
left.locked === right.locked &&
left.suspended === right.suspended &&
left.onBattery === right.onBattery &&
left.lowPowerMode === right.lowPowerMode &&
left.thermalState === right.thermalState &&
left.stale === right.stale
);
}
export const make = Effect.fn("background.hostPower.make")(function* (
initialSource: HostPowerSnapshot["source"] = "unknown",
) {
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
const latestRef = yield* Ref.make(initial);
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
const report: HostPowerMonitorShape["report"] = (snapshot) =>
Ref.modify(latestRef, (current) => [!samePowerState(current, snapshot), snapshot]).pipe(
Effect.flatMap((changed) => (changed ? PubSub.publish(changes, snapshot) : Effect.void)),
Effect.asVoid,
);
return HostPowerMonitor.of({
snapshot: Ref.get(latestRef),
report,
streamChanges: Stream.fromPubSub(changes),
});
});
export const layer = Layer.effect(
HostPowerMonitor,
Effect.gen(function* () {
const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
const initial = yield* desktopTelemetry.latest;
const monitor = yield* make(
Option.match(initial, {
onNone: () => "unknown" as const,
onSome: (snapshot) => snapshot.power.source,
}),
);
if (Option.isSome(initial)) {
yield* monitor.report(initial.value.power);
}
yield* desktopTelemetry.changes.pipe(
Stream.map((snapshot) => snapshot.power),
Stream.runForEach(monitor.report),
Effect.forkScoped,
);
return monitor;
}),
);
+8 -1
View File
@@ -38,7 +38,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const defaultObservabilityConfig = {
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceBatchWindowMs: 1_000,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
@@ -268,6 +268,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
t3Home: baseDir,
noBrowser: true,
desktopBootstrapToken: "desktop-token",
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
otlpTracesUrl: "http://localhost:4318/v1/traces",
@@ -323,12 +325,17 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: "desktop-token",
desktopTelemetryFd: 4,
desktopTelemetryControlFd: 5,
resourceMonitorPath: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
assert.equal(resolved.desktopTelemetryFd, 4);
assert.equal(resolved.desktopTelemetryControlFd, 5);
}),
);
+7 -1
View File
@@ -83,7 +83,7 @@ const EnvServerConfig = Config.all({
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -290,6 +290,9 @@ export const resolveServerConfig = (
() => mode === "desktop",
);
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
const autoBootstrapProjectFromCwd = Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
@@ -362,6 +365,9 @@ export const resolveServerConfig = (
noBrowser,
startupPresentation,
desktopBootstrapToken,
desktopTelemetryFd,
desktopTelemetryControlFd,
resourceMonitorPath,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
@@ -1,184 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
function makeSecretStore(
overrides: Partial<ServerSecretStore.ServerSecretStore["Service"]>,
): ServerSecretStore.ServerSecretStore["Service"] {
return {
get: unusedSecretStoreOperation,
set: unusedSecretStoreOperation,
create: unusedSecretStoreOperation,
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
...overrides,
};
}
function makeTokenManager(secretStore: ServerSecretStore.ServerSecretStore["Service"]) {
return CliTokenManager.make.pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ServerSecretStore.ServerSecretStore, secretStore),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unused HTTP client")),
),
),
),
);
}
describe("CloudCliTokenManager", () => {
it("redacts OAuth endpoint credentials while retaining exact causes", () => {
const tokenEndpoint =
"https://user:[email protected]/private/token?client_secret=secret#fragment";
const redirectUri =
"https://callback-user:callback-password@localhost/private/callback?code=secret#fragment";
const cause = new Error("exchange failed");
const refreshError = CliTokenManager.CloudCliCredentialRefreshError.fromStage({
stage: "exchange-token",
tokenEndpoint,
cause,
});
const authorizationError = CliTokenManager.CloudCliAuthorizationError.fromStage({
stage: "exchange-token",
tokenEndpoint,
redirectUri,
cause,
});
const timeoutError = CliTokenManager.CloudCliAuthorizationTimeoutError.fromRedirectUri({
redirectUri,
timeoutMillis: 1000,
cause,
});
expect(refreshError).toMatchObject({
tokenEndpointInputLength: tokenEndpoint.length,
tokenEndpointProtocol: "https:",
tokenEndpointHostname: "auth.example.test",
cause,
});
expect(authorizationError).toMatchObject({
tokenEndpointInputLength: tokenEndpoint.length,
tokenEndpointHostname: "auth.example.test",
redirectUriInputLength: redirectUri.length,
redirectUriHostname: "localhost",
cause,
});
expect(timeoutError).toMatchObject({
redirectUriInputLength: redirectUri.length,
redirectUriHostname: "localhost",
cause,
});
expect(refreshError.cause).toBe(cause);
expect(authorizationError.cause).toBe(cause);
expect(timeoutError.cause).toBe(cause);
for (const error of [refreshError, authorizationError, timeoutError]) {
expect(error).not.toHaveProperty("tokenEndpoint");
expect(error).not.toHaveProperty("redirectUri");
const serialized = JSON.stringify(error);
for (const secret of [
"user:password",
"callback-user:callback-password",
"/private/",
"client_secret=secret",
"code=secret",
"#fragment",
]) {
expect(error.message).not.toContain(secret);
expect(serialized).not.toContain(secret);
}
}
});
it.effect("retains secret context and cause when credential removal fails", () => {
const failure = new ServerSecretStore.SecretStoreRemoveError({
secretName: "cloud-cli-oauth-token",
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
cause: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "remove",
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
}),
});
return Effect.gen(function* () {
const tokens = yield* makeTokenManager(
makeSecretStore({ remove: () => Effect.fail(failure) }),
);
const error = yield* Effect.flip(tokens.clear);
expect(error).toMatchObject({
_tag: "CloudCliCredentialRemovalError",
secretName: "cloud-cli-oauth-token",
cause: failure,
});
expect(error.message).toBe(
"Could not remove the stored T3 Connect CLI credential cloud-cli-oauth-token.",
);
});
});
it.effect("classifies credential read failures without replacing the cause", () => {
const failure = new ServerSecretStore.SecretStoreReadError({
secretName: "cloud-cli-oauth-token",
secretPath: "/tmp/secrets/cloud-cli-oauth-token.bin",
cause: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: "/tmp/secrets/cloud-cli-oauth-token.bin",
}),
});
return Effect.gen(function* () {
const tokens = yield* makeTokenManager(makeSecretStore({ get: () => Effect.fail(failure) }));
const error = yield* Effect.flip(tokens.hasCredential);
expect(error).toMatchObject({
_tag: "CloudCliCredentialReadError",
stage: "read-credential",
secretName: "cloud-cli-oauth-token",
cause: failure,
});
expect(error.message).toBe(
"Could not inspect the stored T3 Connect CLI credential cloud-cli-oauth-token during read-credential.",
);
});
});
it.effect("classifies malformed persisted credentials as refresh decode failures", () =>
Effect.gen(function* () {
const tokens = yield* makeTokenManager(
makeSecretStore({
get: () =>
Effect.succeed(Option.some(new TextEncoder().encode("not valid credential JSON"))),
}),
);
const error = yield* Effect.flip(tokens.getExisting);
expect(error).toMatchObject({
_tag: "CloudCliCredentialRefreshError",
stage: "decode-credential",
secretName: "cloud-cli-oauth-token",
cause: { _tag: "SchemaError" },
});
expect(error.message).toBe(
"Could not refresh the T3 Connect CLI credential cloud-cli-oauth-token during decode-credential.",
);
}),
);
});
+47 -302
View File
@@ -20,7 +20,6 @@ import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
@@ -28,8 +27,6 @@ import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const CLOUD_CLI_OAUTH_CALLBACK_HOST = "127.0.0.1";
const CLOUD_CLI_OAUTH_CALLBACK_PORT = 34338;
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
@@ -49,223 +46,48 @@ const OAuthTokenResponse = Schema.Struct({
token_type: Schema.String,
});
type CredentialReadFailure = ServerSecretStore.SecretStoreReadError | Schema.SchemaError;
type CredentialPersistFailure =
| Schema.SchemaError
| ServerSecretStore.SecretStoreTemporaryPathGenerationError
| ServerSecretStore.SecretStorePersistError;
const CloudCliCredentialRefreshStage = Schema.Literals([
"read-credential",
"decode-credential",
"load-oauth-config",
"exchange-token",
"encode-credential",
"persist-credential",
]);
type CloudCliCredentialRefreshStage = typeof CloudCliCredentialRefreshStage.Type;
const CloudCliAuthorizationStage = Schema.Literals([
"load-oauth-config",
"prepare-pkce",
"start-callback-server",
"exchange-token",
"encode-credential",
"persist-credential",
]);
type CloudCliAuthorizationStage = typeof CloudCliAuthorizationStage.Type;
function tokenEndpointDiagnosticFields(tokenEndpoint: string | undefined) {
if (tokenEndpoint === undefined) return {};
const diagnostics = getUrlDiagnostics(tokenEndpoint);
return {
tokenEndpointInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { tokenEndpointProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { tokenEndpointHostname: diagnostics.hostname }),
};
}
function redirectUriDiagnosticFields(redirectUri: string | undefined) {
if (redirectUri === undefined) return {};
const diagnostics = getUrlDiagnostics(redirectUri);
return {
redirectUriInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
};
}
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
override get message(): string {
return `Could not remove the stored T3 Connect CLI credential ${this.secretName}.`;
return "Could not remove the stored T3 Connect CLI credential.";
}
}
export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(
"CloudCliCredentialRefreshError",
{
stage: CloudCliCredentialRefreshStage,
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
tokenEndpointHostname: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromStage(input: {
readonly stage: CloudCliCredentialRefreshStage;
readonly cause: unknown;
readonly tokenEndpoint?: string;
}): CloudCliCredentialRefreshError {
return new CloudCliCredentialRefreshError({
stage: input.stage,
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
cause: input.cause,
});
}
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialRefreshError {
return new CloudCliCredentialRefreshError({
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliCredentialRefreshError {
return new CloudCliCredentialRefreshError({
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
const tokenEndpoint =
this.tokenEndpointInputLength === undefined
? ""
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
return `Could not refresh the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}.`;
return "Could not refresh the T3 Connect CLI credential.";
}
}
export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(
"CloudCliCredentialReadError",
{
stage: Schema.Literals(["read-credential", "decode-credential"]),
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromCredentialRead(cause: CredentialReadFailure): CloudCliCredentialReadError {
return new CloudCliCredentialReadError({
stage: cause._tag === "SecretStoreReadError" ? "read-credential" : "decode-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
return `Could not inspect the stored T3 Connect CLI credential ${this.secretName} during ${this.stage}.`;
return "Could not read the stored T3 Connect CLI credential.";
}
}
export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(
"CloudCliAuthorizationError",
{
stage: CloudCliAuthorizationStage,
secretName: Schema.Literal(CLOUD_CLI_OAUTH_TOKEN_SECRET),
tokenEndpointInputLength: Schema.optionalKey(Schema.Number),
tokenEndpointProtocol: Schema.optionalKey(Schema.String),
tokenEndpointHostname: Schema.optionalKey(Schema.String),
redirectUriInputLength: Schema.optionalKey(Schema.Number),
redirectUriProtocol: Schema.optionalKey(Schema.String),
redirectUriHostname: Schema.optionalKey(Schema.String),
callbackHost: Schema.optional(Schema.String),
callbackPort: Schema.optional(Schema.Number),
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromStage(input: {
readonly stage: CloudCliAuthorizationStage;
readonly cause: unknown;
readonly tokenEndpoint?: string;
readonly redirectUri?: string;
readonly callbackHost?: string;
readonly callbackPort?: number;
}): CloudCliAuthorizationError {
return new CloudCliAuthorizationError({
stage: input.stage,
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
...tokenEndpointDiagnosticFields(input.tokenEndpoint),
...redirectUriDiagnosticFields(input.redirectUri),
...(input.callbackHost === undefined ? {} : { callbackHost: input.callbackHost }),
...(input.callbackPort === undefined ? {} : { callbackPort: input.callbackPort }),
cause: input.cause,
});
}
static fromCredentialPersist(cause: CredentialPersistFailure): CloudCliAuthorizationError {
return new CloudCliAuthorizationError({
stage: cause._tag === "SchemaError" ? "encode-credential" : "persist-credential",
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
});
}
override get message(): string {
const tokenEndpoint =
this.tokenEndpointInputLength === undefined
? ""
: ` using the token endpoint${this.tokenEndpointHostname ? ` at ${this.tokenEndpointHostname}` : ""} (input length ${this.tokenEndpointInputLength})`;
const redirectUri =
this.redirectUriInputLength === undefined
? ""
: ` with a callback URI input of length ${this.redirectUriInputLength}`;
const callbackAddress =
this.callbackHost && this.callbackPort !== undefined
? ` on ${this.callbackHost}:${this.callbackPort}`
: "";
return `Could not authorize the T3 Connect CLI credential ${this.secretName} during ${this.stage}${tokenEndpoint}${redirectUri}${callbackAddress}.`;
return "Could not authorize the T3 Connect CLI.";
}
}
export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(
"CloudCliAuthorizationTimeoutError",
{
redirectUriInputLength: Schema.Number,
redirectUriProtocol: Schema.optionalKey(Schema.String),
redirectUriHostname: Schema.optionalKey(Schema.String),
timeoutMillis: Schema.Number,
cause: Schema.Defect(),
},
{ cause: Schema.Defect() },
) {
static fromRedirectUri(input: {
readonly redirectUri: string;
readonly timeoutMillis: number;
readonly cause: unknown;
}): CloudCliAuthorizationTimeoutError {
const diagnostics = getUrlDiagnostics(input.redirectUri);
return new CloudCliAuthorizationTimeoutError({
redirectUriInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { redirectUriProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { redirectUriHostname: diagnostics.hostname }),
timeoutMillis: input.timeoutMillis,
cause: input.cause,
});
}
override get message(): string {
const callback = this.redirectUriHostname ? ` for ${this.redirectUriHostname}` : "";
return `Timed out after ${this.timeoutMillis}ms waiting for T3 Connect authorization${callback} (callback URI input length ${this.redirectUriInputLength}).`;
return "Timed out waiting for T3 Connect authorization.";
}
}
@@ -281,21 +103,18 @@ export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;
export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<
PersistedToken,
| CloudCliCredentialRefreshError
| CloudCliAuthorizationError
| CloudCliAuthorizationTimeoutError
>;
readonly getExisting: Effect.Effect<
Option.Option<PersistedToken>,
CloudCliCredentialRefreshError
>;
readonly hasCredential: Effect.Effect<boolean, CloudCliCredentialReadError>;
readonly clear: Effect.Effect<void, CloudCliCredentialRemovalError>;
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
}
>()("t3/cloud/CliTokenManager/CloudCliTokenManager") {}
const wrapError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -315,15 +134,9 @@ export const make = Effect.gen(function* () {
return token;
});
const clear = secrets.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET).pipe(
Effect.mapError(
(cause) =>
new CloudCliCredentialRemovalError({
secretName: CLOUD_CLI_OAUTH_TOKEN_SECRET,
cause,
}),
),
);
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError((cause) => new CloudCliCredentialRemovalError({ cause })));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -349,54 +162,21 @@ export const make = Effect.gen(function* () {
});
const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {
const metadata = yield* cloudCliOAuthConfig.pipe(
Effect.mapError((cause) =>
CloudCliCredentialRefreshError.fromStage({
stage: "load-oauth-config",
cause,
}),
),
);
const metadata = yield* cloudCliOAuthConfig;
return yield* exchangeToken(metadata, {
grant_type: "refresh_token",
refresh_token: token.refreshToken,
client_id: metadata.clientId,
}).pipe(
Effect.mapError((cause) =>
CloudCliCredentialRefreshError.fromStage({
stage: "exchange-token",
tokenEndpoint: metadata.tokenEndpoint,
cause,
}),
),
);
});
});
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig.pipe(
Effect.mapError((cause) =>
CloudCliAuthorizationError.fromStage({
stage: "load-oauth-config",
cause,
}),
),
);
const { challenge, state, verifier } = yield* Effect.gen(function* () {
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
return { challenge, state, verifier };
}).pipe(
Effect.mapError((cause) =>
CloudCliAuthorizationError.fromStage({
stage: "prepare-pkce",
redirectUri: metadata.redirectUri,
cause,
}),
),
const metadata = yield* cloudCliOAuthConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const state = yield* crypto.randomUUIDv4;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
"GET",
@@ -427,21 +207,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: CLOUD_CLI_OAUTH_CALLBACK_HOST,
port: CLOUD_CLI_OAUTH_CALLBACK_PORT,
host: "127.0.0.1",
port: 34338,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
Effect.mapError((cause) =>
CloudCliAuthorizationError.fromStage({
stage: "start-callback-server",
redirectUri: metadata.redirectUri,
callbackHost: CLOUD_CLI_OAUTH_CALLBACK_HOST,
callbackPort: CLOUD_CLI_OAUTH_CALLBACK_PORT,
cause,
}),
),
);
const authorizationUrl = new URL(metadata.authorizationEndpoint);
authorizationUrl.searchParams.set("client_id", metadata.clientId);
@@ -454,16 +225,13 @@ export const make = Effect.gen(function* () {
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTags({
TimeoutError: (cause) =>
Effect.fail(
CloudCliAuthorizationTimeoutError.fromRedirectUri({
redirectUri: metadata.redirectUri,
timeoutMillis: Duration.toMillis(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
cause,
}),
),
}),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(
new CloudCliAuthorizationTimeoutError({
cause,
}),
),
),
);
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
@@ -471,43 +239,26 @@ export const make = Effect.gen(function* () {
redirect_uri: metadata.redirectUri,
client_id: metadata.clientId,
code_verifier: verifier,
}).pipe(
Effect.mapError((cause) =>
CloudCliAuthorizationError.fromStage({
stage: "exchange-token",
tokenEndpoint: metadata.tokenEndpoint,
redirectUri: metadata.redirectUri,
cause,
}),
),
);
});
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
const token = yield* read().pipe(
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialRead),
);
const token = yield* read();
if (Option.isNone(token)) return token;
const now = yield* Clock.currentTimeMillis;
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
return token;
}
return Option.some(
yield* refresh(token.value).pipe(
Effect.flatMap((refreshed) =>
persist(refreshed).pipe(
Effect.mapError(CloudCliCredentialRefreshError.fromCredentialPersist),
),
),
),
);
return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
});
const getExisting = semaphore.withPermits(1)(getExistingNoLock());
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError((cause) => new CloudCliCredentialRefreshError({ cause }))),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
Effect.mapError(CloudCliCredentialReadError.fromCredentialRead),
wrapError((cause) => new CloudCliCredentialReadError({ cause })),
),
);
const get = semaphore.withPermits(1)(
@@ -515,14 +266,8 @@ export const make = Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(
Effect.flatMap((authorized) =>
persist(authorized).pipe(
Effect.mapError(CloudCliAuthorizationError.fromCredentialPersist),
),
),
);
}),
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
+1 -23
View File
@@ -66,9 +66,7 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
Effect.flatMap(() =>
Effect.fail(
new ServerSecretStore.SecretStorePersistError({
operation: "create",
secretName: "cloud-link-ed25519-key-pair",
secretPath: "cloud-link-ed25519-key-pair.bin",
resource: "environment signing key pair",
cause: PlatformError.systemError({
_tag: "AlreadyExists",
module: "FileSystem",
@@ -89,24 +87,4 @@ it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it
});
}),
);
it.effect("retains the secret name and decode cause for malformed keypairs", () =>
Effect.gen(function* () {
const secretStore = {
get: () => Effect.succeed(Option.some(new TextEncoder().encode("not-json"))),
set: unusedSecretStoreOperation,
create: unusedSecretStoreOperation,
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
} satisfies ServerSecretStore.ServerSecretStore["Service"];
const error = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore).pipe(
Effect.flip,
);
assert.instanceOf(error, ServerSecretStore.SecretStoreDecodeError);
assert.equal(error.secretName, "cloud-link-ed25519-key-pair");
assert.exists(error.cause);
}),
);
});
+25 -33
View File
@@ -27,6 +27,17 @@ function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
const KEY_PAIR_RESOURCE = "environment signing key pair";
const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
secrets: ServerSecretStore.ServerSecretStore["Service"],
) {
@@ -35,13 +46,7 @@ const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
return Option.none<EnvironmentKeyPair>();
}
const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
Effect.mapError(
(cause) =>
new ServerSecretStore.SecretStoreDecodeError({
secretName: CLOUD_LINK_KEY_PAIR,
cause,
}),
),
Effect.mapError(keyPairDecodeError),
);
return Option.some(decoded);
});
@@ -51,35 +56,22 @@ const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(functio
keyPair: EnvironmentKeyPair,
) {
const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
Effect.mapError(
(cause) =>
new ServerSecretStore.SecretStoreEncodeError({
secretName: CLOUD_LINK_KEY_PAIR,
cause,
}),
),
Effect.mapError(keyPairEncodeError),
);
return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
Effect.as(keyPair),
Effect.catchTags({
SecretStorePersistError: (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new ServerSecretStore.SecretStoreConcurrentReadError({
secretName: CLOUD_LINK_KEY_PAIR,
cause: error,
}),
),
}),
),
)
: Effect.fail(error),
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? readEnvironmentKeyPair(secrets).pipe(
Effect.flatMap(
Option.match({
onSome: Effect.succeed,
onNone: () => Effect.fail(keyPairConcurrentReadError()),
}),
),
)
: Effect.fail(error),
),
);
});
+41 -270
View File
@@ -1,45 +1,23 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientError from "effect/unstable/http/HttpClientError";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import { EnvironmentHttpInternalServerError } from "@t3tools/contracts";
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import {
CloudRelayRequestError,
consumeCloudReplayGuards,
reconcileDesiredCloudLink,
} from "./http.ts";
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
const encodeEnvironmentHttpInternalServerError = Schema.encodeUnknownSync(
EnvironmentHttpInternalServerError,
);
const decodeEnvironmentHttpInternalServerError = Schema.decodeUnknownSync(
EnvironmentHttpInternalServerError,
);
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStorePersistError({
operation: "create",
secretName: "cloud replay guard",
secretPath: "cloud-replay-guard.bin",
resource: "cloud replay guard",
cause: PlatformError.systemError({
_tag: tag,
module: "FileSystem",
@@ -62,56 +40,6 @@ function makeSecretStore(
};
}
function reconcileWith(input: {
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
readonly httpClient?: HttpClient.HttpClient;
readonly secretStore?: ServerSecretStore.ServerSecretStore["Service"];
readonly env?: Readonly<Record<string, string>>;
}) {
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
input.secretStore ?? makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
getEnvironmentId: unusedSecretStoreOperation(),
getDescriptor: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
applyConfig: unusedSecretStoreOperation,
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: input.getExisting,
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
HttpClient.HttpClient,
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
),
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
),
),
);
}
it("preserves messages surfaced by cloud 500 responses", () => {
const cause = new Error("cloud operation failed");
@@ -165,84 +93,6 @@ describe("consumeCloudReplayGuards", () => {
);
});
describe("CloudRelayRequestError", () => {
it("classifies response failures without deriving its message from the cause", () => {
const requestUrl =
"https://relay-user:[email protected]/private/environment-links?token=relay-secret#relay-fragment";
const request = HttpClientRequest.post(requestUrl);
const response = HttpClientResponse.fromWeb(
request,
new Response("sensitive upstream response", { status: 502 }),
);
const upstreamCause = new Error("sensitive upstream response details");
const cause = new HttpClientError.HttpClientError({
reason: new HttpClientError.StatusCodeError({
request,
response,
cause: upstreamCause,
}),
});
const error = CloudRelayRequestError.fromClientFailure({
operation: "create-environment-link",
url: request.url,
cause,
});
expect(error).toMatchObject({
operation: "create-environment-link",
phase: "check-response-status",
method: "POST",
requestUrlInputLength: requestUrl.length,
requestUrlProtocol: "https:",
requestUrlHostname: "relay.example.test",
responseStatus: 502,
cause,
});
expect(error.cause).toBe(cause);
expect(error).not.toHaveProperty("url");
expect(error.message).toBe(
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
);
expect(error.message).not.toContain(upstreamCause.message);
for (const secret of [
"relay-user",
"relay-password",
"/private/environment-links",
"relay-secret",
"relay-fragment",
]) {
expect(error.message).not.toContain(secret);
expect(Object.values(error).join(" ")).not.toContain(secret);
}
});
});
it("keeps internal causes out of encoded HTTP error bodies", () => {
const cause = new Error("private upstream detail");
const error = new EnvironmentHttpInternalServerError({
operation: "generate_link_proof",
cause,
});
expect(error.cause).toBe(cause);
expect(encodeEnvironmentHttpInternalServerError(error)).toEqual({
_tag: "EnvironmentHttpInternalServerError",
operation: "generate_link_proof",
message: "Could not generate environment link proof.",
});
});
it("decodes legacy message-only HTTP errors during rolling deployments", () => {
const error = decodeEnvironmentHttpInternalServerError({
_tag: "EnvironmentHttpInternalServerError",
message: "Legacy environment server failure.",
});
expect(error.operation).toBeUndefined();
expect(error.message).toBe("Legacy environment server failure.");
});
describe("relay request tracing", () => {
it.effect("does not accept an unauthenticated request trace parent", () =>
Effect.gen(function* () {
@@ -310,127 +160,48 @@ describe("relay request tracing", () => {
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
);
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
reason: "cloud_cli_authorization_required",
message: "Run `t3 connect link` to authorize this environment.",
});
}),
}).pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
getEnvironmentId: unusedSecretStoreOperation(),
getDescriptor: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
applyConfig: unusedSecretStoreOperation,
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => unusedSecretStoreOperation()),
),
Effect.provide(NodeServices.layer),
),
);
it.effect("attributes link-proof secret failures to proof generation", () => {
const cause = new Error("private secret-store detail");
const secretFailure = new ServerSecretStore.SecretStoreReadError({
secretName: "environment-key-pair",
secretPath: "environment-key-pair.json",
cause,
});
const httpClient = HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
challenge: "relay-link-challenge",
expiresAt: "2099-01-01T00:00:00.000Z",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
),
),
);
const secretStore = makeSecretStore(unusedSecretStoreOperation);
return Effect.gen(function* () {
const error = yield* Effect.flip(
reconcileWith({
getExisting: Effect.succeed(
Option.some({
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
}),
),
httpClient,
secretStore: {
...secretStore,
get: () => Effect.fail(secretFailure),
},
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
}),
);
expect(error).toMatchObject({
_tag: "EnvironmentHttpInternalServerError",
operation: "generate_link_proof",
cause: secretFailure,
});
expect(error.message).toBe("Could not generate environment link proof.");
expect(error.cause).toBe(secretFailure);
expect(error.message).not.toContain(cause.message);
});
});
it.effect("redacts relay transport failures behind a stable structural message", () => {
const transportCause = new Error("upstream included a sensitive database password");
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
const logger = Logger.make(({ message }) => {
capturedLogs.push(Array.isArray(message) ? message : [message]);
});
const httpClient = HttpClient.make((request) =>
Effect.fail(
new HttpClientError.HttpClientError({
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
}),
),
);
return Effect.gen(function* () {
const error = yield* Effect.flip(
reconcileWith({
getExisting: Effect.succeed(
Option.some({
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
}),
),
httpClient,
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
);
expect(error).toMatchObject({
_tag: "EnvironmentHttpInternalServerError",
operation: "relay_request",
relayOperation: "create-link-challenge",
relayPhase: "send-request",
message: "T3 Connect relay create-link-challenge failed during send-request.",
cause: {
_tag: "CloudRelayRequestError",
operation: "create-link-challenge",
phase: "send-request",
},
});
expect(error.message).not.toContain(transportCause.message);
expect(capturedLogs).toHaveLength(1);
const logFields = capturedLogs[0]?.find(
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
);
expect(logFields).toMatchObject({
operation: "relay_request",
relayOperation: "create-link-challenge",
relayPhase: "send-request",
causeTag: "CloudRelayRequestError",
});
expect(logFields).not.toHaveProperty("cause");
expect(capturedLogs[0]?.filter((value) => typeof value === "string").join(" ")).not.toContain(
transportCause.message,
);
});
});
});
+116 -333
View File
@@ -9,10 +9,7 @@ import {
EnvironmentHttpApi,
EnvironmentHttpBadRequestError,
EnvironmentHttpConflictError,
type EnvironmentHttpInternalOperation,
EnvironmentHttpInternalServerError,
EnvironmentHttpRelayOperation,
EnvironmentHttpRelayPhase,
EnvironmentHttpUnauthorizedError,
} from "@t3tools/contracts";
import {
@@ -44,7 +41,6 @@ import {
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
@@ -52,13 +48,8 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import * as HttpBody from "effect/unstable/http/HttpBody";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientError from "effect/unstable/http/HttpClientError";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
@@ -94,145 +85,26 @@ const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {
pragma: "no-cache",
} as const;
export class CloudRelayConfigurationError extends Schema.TaggedErrorClass<CloudRelayConfigurationError>()(
"CloudRelayConfigurationError",
{
configKey: Schema.Literal("T3CODE_RELAY_URL"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `${this.configKey} must be configured as a secure absolute HTTPS origin.`;
}
}
export class CloudRelayRequestError extends Schema.TaggedErrorClass<CloudRelayRequestError>()(
"CloudRelayRequestError",
{
operation: EnvironmentHttpRelayOperation,
phase: EnvironmentHttpRelayPhase,
method: Schema.Literal("POST"),
requestUrlInputLength: Schema.Number,
requestUrlProtocol: Schema.optionalKey(Schema.String),
requestUrlHostname: Schema.optionalKey(Schema.String),
responseStatus: Schema.optional(Schema.Number),
cause: Schema.Defect(),
},
) {
static fromClientFailure(input: {
readonly operation: CloudRelayRequestError["operation"];
readonly url: string;
readonly cause: HttpBody.HttpBodyError | HttpClientError.HttpClientError | Schema.SchemaError;
readonly responseStatus?: number;
}): CloudRelayRequestError {
const diagnostics = getUrlDiagnostics(input.url);
const context = {
operation: input.operation,
method: "POST" as const,
requestUrlInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { requestUrlProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { requestUrlHostname: diagnostics.hostname }),
};
if (input.cause._tag === "SchemaError") {
return new CloudRelayRequestError({
...context,
phase: "decode-response",
...(input.responseStatus === undefined ? {} : { responseStatus: input.responseStatus }),
cause: input.cause,
});
}
if (!HttpClientError.isHttpClientError(input.cause)) {
return new CloudRelayRequestError({
...context,
phase: "encode-request",
cause: input.cause,
});
}
const phase: CloudRelayRequestError["phase"] = (() => {
switch (input.cause.reason._tag) {
case "EncodeError":
return "encode-request";
case "TransportError":
case "InvalidUrlError":
return "send-request";
case "StatusCodeError":
return "check-response-status";
case "DecodeError":
case "EmptyBodyError":
return "decode-response";
}
})();
return new CloudRelayRequestError({
...context,
phase,
...(input.cause.response === undefined
? input.responseStatus === undefined
? {}
: { responseStatus: input.responseStatus }
: { responseStatus: input.cause.response.status }),
cause: input.cause,
});
}
override get message(): string {
const responseStatus =
this.responseStatus === undefined ? "" : ` with response status ${this.responseStatus}`;
return `T3 Connect relay ${this.operation} failed during ${this.phase}${responseStatus}.`;
}
}
const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
(_request, response) =>
Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),
);
function errorDiagnosticTag(cause: unknown): string {
if (
typeof cause === "object" &&
cause !== null &&
"_tag" in cause &&
typeof cause._tag === "string"
) {
return cause._tag;
}
if (cause instanceof Error) return cause.name;
return typeof cause;
}
type EnvironmentCloudInternalErrorContext =
| Exclude<EnvironmentHttpInternalOperation, "relay_request">
| {
readonly operation: "relay_request";
readonly relayOperation: CloudRelayRequestError["operation"];
readonly relayPhase: CloudRelayRequestError["phase"];
readonly responseStatus?: number;
};
const failEnvironmentCloudInternalError =
(context: EnvironmentCloudInternalErrorContext) =>
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> => {
const error =
typeof context === "string"
? new EnvironmentHttpInternalServerError({ operation: context, cause })
: new EnvironmentHttpInternalServerError({ ...context, cause });
const logContext =
typeof context === "string"
? { operation: context, causeTag: errorDiagnosticTag(cause) }
: { ...context, causeTag: errorDiagnosticTag(cause) };
return Effect.logError(error.message, logContext).pipe(
Effect.flatMap(() => Effect.fail(error)),
(message: string) =>
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
Effect.logError(message, { cause }).pipe(
Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),
);
};
const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>
failEnvironmentCloudInternalError(error.message)(error);
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
(cause) =>
new CloudRelayConfigurationError({
configKey: "T3CODE_RELAY_URL",
cause,
() =>
new EnvironmentHttpInternalServerError({
message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
}),
),
);
@@ -254,12 +126,11 @@ export function consumeCloudReplayGuards(input: {
input.names.map((name) =>
input.secrets.create(name, input.value).pipe(
Effect.as(true),
Effect.catchTags({
SecretStorePersistError: (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
}),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
),
),
),
{ concurrency: input.names.length },
@@ -282,10 +153,9 @@ function validateCloudMintPublicKey(
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
return Effect.try({
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
catch: (cause) =>
catch: () =>
new EnvironmentHttpBadRequestError({
reason: "invalid_cloud_mint_public_key",
cause,
message: "Cloud mint public key must be a valid Ed25519 public key.",
}),
}).pipe(
Effect.flatMap((key) =>
@@ -293,7 +163,7 @@ function validateCloudMintPublicKey(
? Effect.void
: Effect.fail(
new EnvironmentHttpBadRequestError({
reason: "invalid_cloud_mint_public_key",
message: "Cloud mint public key must be a valid Ed25519 public key.",
}),
),
),
@@ -306,28 +176,28 @@ function validateRelayConfigPayload(
if (!isSecureRelayUrl(payload.relayUrl)) {
return Effect.fail(
new EnvironmentHttpBadRequestError({
reason: "invalid_relay_url",
message: "Relay URL must be a secure absolute HTTPS URL.",
}),
);
}
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
return Effect.fail(
new EnvironmentHttpBadRequestError({
reason: "invalid_relay_issuer",
message: "Relay issuer must be a secure absolute HTTPS URL.",
}),
);
}
if (payload.environmentCredential.trim().length === 0) {
return Effect.fail(
new EnvironmentHttpBadRequestError({
reason: "missing_relay_environment_credential",
message: "Relay environment credential is required.",
}),
);
}
if (payload.cloudUserId.trim().length === 0) {
return Effect.fail(
new EnvironmentHttpBadRequestError({
reason: "missing_cloud_user_id",
message: "Cloud user id is required.",
}),
);
}
@@ -337,7 +207,7 @@ function validateRelayConfigPayload(
function validateLinkedCloudUser(input: {
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
readonly cloudUserId: string;
}) {
}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {
return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
@@ -354,14 +224,17 @@ function validateLinkedCloudUser(input: {
? Effect.void
: Effect.fail(
new EnvironmentHttpConflictError({
reason: "linked_to_different_cloud_account",
message:
"This environment is already linked to a different cloud account. Unlink it before switching accounts.",
}),
);
}),
);
}
function readInstalledCloudUserId(secrets: ServerSecretStore.ServerSecretStore["Service"]) {
function readInstalledCloudUserId(
secrets: ServerSecretStore.ServerSecretStore["Service"],
): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {
return secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
@@ -486,7 +359,7 @@ const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function
})
) {
return yield* new EnvironmentHttpBadRequestError({
reason: "invalid_managed_endpoint_origin",
message: "Invalid managed endpoint origin.",
});
}
const now = yield* DateTime.now;
@@ -529,23 +402,24 @@ const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(
const requestUrl = requestAbsoluteUrl(httpRequest);
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
return yield* new EnvironmentHttpBadRequestError({
reason: "invalid_managed_endpoint_origin",
message: "Invalid managed endpoint origin.",
});
}
const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);
yield* appendCloudCredentialResponseHeaders;
return proof satisfies RelayEnvironmentLinkProof;
},
Effect.catchTags({
ServerAuthCloudLinkJwtSigningError: (error) =>
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not generate environment link proof."),
),
);
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
@@ -565,6 +439,7 @@ const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(fu
endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";
if (!ok) {
return yield* new EnvironmentCloudEndpointUnavailableError({
message: "Managed endpoint runtime could not be started.",
endpointRuntimeStatus,
});
}
@@ -597,22 +472,22 @@ const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(
yield* requireEnvironmentScope(AuthRelayWriteScope);
return yield* applyCloudRelayConfig(dependencies, payload);
},
Effect.catchTags({
ServerAuthLinkedCloudAccountVerificationError: (error) =>
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"persist_relay_configuration",
),
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
Effect.catchTag(
"SchemaError",
failEnvironmentCloudInternalError("Could not persist environment relay configuration."),
),
);
const relayClientRequest = <A>(
dependencies: CloudHttpDependencies,
input: {
readonly operation: CloudRelayRequestError["operation"];
readonly url: string;
readonly token: string;
readonly payload: unknown;
@@ -622,46 +497,14 @@ const relayClientRequest = <A>(
HttpClientRequest.post(input.url).pipe(
HttpClientRequest.bearerToken(input.token),
HttpClientRequest.bodyJson(input.payload),
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
Effect.flatMap((request) =>
dependencies.httpClient.execute(request).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
),
),
Effect.flatMap((response) =>
HttpClientResponse.filterStatusOk(response).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
cause,
}),
),
),
),
Effect.flatMap((response) =>
HttpClientResponse.schemaBodyJson(input.schema)(response).pipe(
Effect.mapError((cause) =>
CloudRelayRequestError.fromClientFailure({
operation: input.operation,
url: input.url,
responseStatus: response.status,
cause,
}),
),
),
Effect.flatMap(dependencies.httpClient.execute),
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Connect relay request failed: ${String(cause)}`,
}),
),
withRelayClientTracing,
);
@@ -670,15 +513,14 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
function* (dependencies: CloudHttpDependencies, localOrigin: string) {
const localUrl = yield* Effect.try({
try: () => new URL(localOrigin),
catch: (cause) =>
catch: () =>
new EnvironmentHttpBadRequestError({
reason: "invalid_local_environment_origin",
cause,
message: "Could not resolve local environment origin.",
}),
});
if (localUrl.origin !== localOrigin) {
return yield* new EnvironmentHttpBadRequestError({
reason: "invalid_local_environment_origin",
message: "Could not resolve local environment origin.",
});
}
const localWsOrigin = localOrigin.replace(/^http/u, "ws");
@@ -688,7 +530,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
onNone: () =>
Effect.fail(
new EnvironmentHttpUnauthorizedError({
reason: "cloud_cli_authorization_required",
message: "Run `t3 connect link` to authorize this environment.",
}),
),
onSome: Effect.succeed,
@@ -697,7 +539,6 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
);
const relayUrl = yield* requireRelayUrl;
const challenge = yield* relayClientRequest(dependencies, {
operation: "create-link-challenge",
url: `${relayUrl}/v1/client/environment-link-challenges`,
token: token.accessToken,
payload: {
@@ -723,20 +564,8 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
},
},
localOrigin,
).pipe(
Effect.catchTags({
ServerAuthCloudLinkJwtSigningError: (error) =>
failEnvironmentCloudInternalError("sign_cloud_link_jwt")(error),
SecretStoreReadError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreDecodeError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreEncodeError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStorePersistError: failEnvironmentCloudInternalError("generate_link_proof"),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError("generate_link_proof"),
PlatformError: failEnvironmentCloudInternalError("generate_link_proof"),
}),
);
const link = yield* relayClientRequest(dependencies, {
operation: "create-environment-link",
url: `${relayUrl}/v1/client/environment-links`,
token: token.accessToken,
payload: {
@@ -747,15 +576,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
},
schema: RelayEnvironmentLinkResponse,
});
yield* setCliDesiredCloudLink(true).pipe(
Effect.catchTags({
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"persist_desired_link_state",
),
SecretStorePersistError: failEnvironmentCloudInternalError("persist_desired_link_state"),
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_desired_link_state"),
}),
);
yield* setCliDesiredCloudLink(true);
return yield* applyCloudRelayConfig(dependencies, {
relayUrl,
relayIssuer: link.relayIssuer,
@@ -763,31 +584,18 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
environmentCredential: link.environmentCredential,
cloudMintPublicKey: link.cloudMintPublicKey,
endpointRuntime: link.endpointRuntime,
}).pipe(
Effect.catchTags({
ServerAuthLinkedCloudAccountVerificationError: (error) =>
failEnvironmentCloudInternalError("verify_linked_cloud_account")(error),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"persist_relay_configuration",
),
SecretStorePersistError: failEnvironmentCloudInternalError("persist_relay_configuration"),
SecretStoreRemoveError: failEnvironmentCloudInternalError("persist_relay_configuration"),
SchemaError: failEnvironmentCloudInternalError("persist_relay_configuration"),
}),
);
});
},
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),
),
Effect.catchTags({
CloudRelayConfigurationError: (error) =>
failEnvironmentCloudInternalError("read_relay_url_configuration")(error),
CloudRelayRequestError: (error) =>
failEnvironmentCloudInternalError({
operation: "relay_request",
relayOperation: error.operation,
relayPhase: error.phase,
...(error.responseStatus === undefined ? {} : { responseStatus: error.responseStatus }),
})(error),
CloudCliCredentialRefreshError: (error) =>
failEnvironmentCloudInternalError("refresh_cloud_cli_credential")(error),
CloudCliCredentialRemovalError: failCloudCliTokenManagerError,
CloudCliCredentialRefreshError: failCloudCliTokenManagerError,
CloudCliCredentialReadError: failCloudCliTokenManagerError,
CloudCliAuthorizationError: failCloudCliTokenManagerError,
CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,
}),
);
@@ -825,9 +633,10 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
yield* requireEnvironmentScope(AuthRelayReadScope);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTags({
SecretStoreReadError: failEnvironmentCloudInternalError("read_relay_configuration"),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
);
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
@@ -849,13 +658,10 @@ const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
yield* setCliDesiredCloudLink(false);
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
},
Effect.catchTags({
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"remove_relay_configuration",
),
SecretStorePersistError: failEnvironmentCloudInternalError("remove_relay_configuration"),
SecretStoreRemoveError: failEnvironmentCloudInternalError("remove_relay_configuration"),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not remove environment relay configuration."),
),
);
const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
@@ -870,13 +676,10 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
);
return yield* readCloudLinkState(dependencies);
},
Effect.catchTags({
SecretStoreReadError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
SecretStoreTemporaryPathGenerationError: failEnvironmentCloudInternalError(
"persist_cloud_preferences",
),
SecretStorePersistError: failEnvironmentCloudInternalError("persist_cloud_preferences"),
}),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
@@ -927,7 +730,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })
) {
return yield* new EnvironmentHttpUnauthorizedError({
reason: "invalid_cloud_health_request",
message: "Invalid cloud health request.",
});
}
const proof = proofOption.value;
@@ -941,7 +744,7 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
});
if (!consumedReplayGuards) {
return yield* new EnvironmentHttpConflictError({
reason: "cloud_health_request_replayed",
message: "Cloud health request was already consumed.",
});
}
@@ -984,26 +787,17 @@ const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTags({
ServerAuthLinkedCloudAccountReadError: (error) =>
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
ServerAuthLinkedCloudAccountMissingError: (error) =>
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
ServerAuthCloudMintPublicKeyMissingError: (error) =>
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
ServerAuthCloudRelayIssuerMissingError: (error) =>
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
ServerAuthCloudHealthJwtSigningError: (error) =>
failEnvironmentCloudInternalError("sign_cloud_health_jwt")(error),
SecretStoreReadError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
SecretStorePersistError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
SecretStoreDecodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
SecretStoreEncodeError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"answer_cloud_health_request",
),
PlatformError: failEnvironmentCloudInternalError("answer_cloud_health_request"),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not answer cloud health request."),
),
);
const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(
@@ -1055,7 +849,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
!hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })
) {
return yield* new EnvironmentHttpUnauthorizedError({
reason: "invalid_cloud_mint_request",
message: "Invalid cloud mint request.",
});
}
const proof = proofOption.value;
@@ -1069,7 +863,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
});
if (!consumedReplayGuards) {
return yield* new EnvironmentHttpConflictError({
reason: "cloud_mint_request_replayed",
message: "Cloud mint request was already consumed.",
});
}
@@ -1114,28 +908,17 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
yield* appendCloudCredentialResponseHeaders;
return response;
},
Effect.catchTags({
ServerAuthLinkedCloudAccountReadError: (error) =>
failEnvironmentCloudInternalError("read_linked_cloud_account")(error),
ServerAuthLinkedCloudAccountMissingError: (error) =>
failEnvironmentCloudInternalError("require_linked_cloud_account")(error),
ServerAuthCloudMintPublicKeyMissingError: (error) =>
failEnvironmentCloudInternalError("read_cloud_mint_public_key")(error),
ServerAuthCloudRelayIssuerMissingError: (error) =>
failEnvironmentCloudInternalError("read_cloud_relay_issuer")(error),
ServerAuthPairingLinkCreationError: (error) =>
failEnvironmentCloudInternalError("create_cloud_pairing_link")(error),
ServerAuthCloudMintJwtSigningError: (error) =>
failEnvironmentCloudInternalError("sign_cloud_mint_jwt")(error),
SecretStoreReadError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
SecretStorePersistError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
SecretStoreDecodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
SecretStoreEncodeError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
SecretStoreConcurrentReadError: failEnvironmentCloudInternalError(
"issue_cloud_connection_credential",
),
PlatformError: failEnvironmentCloudInternalError("issue_cloud_connection_credential"),
}),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
Effect.catchIf(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
Effect.catchTag(
"PlatformError",
failEnvironmentCloudInternalError("Could not issue cloud connection credential."),
),
);
export const connectHttpApiLayer = HttpApiBuilder.group(
+6
View File
@@ -71,6 +71,9 @@ export class ServerConfig extends Context.Service<
readonly noBrowser: boolean;
readonly startupPresentation: StartupPresentation;
readonly desktopBootstrapToken: string | undefined;
readonly desktopTelemetryFd?: number | undefined;
readonly desktopTelemetryControlFd?: number | undefined;
readonly resourceMonitorPath?: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
readonly tailscaleServeEnabled: boolean;
@@ -177,6 +180,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
desktopTelemetryFd: undefined,
desktopTelemetryControlFd: undefined,
resourceMonitorPath: undefined,
staticDir: undefined,
devUrl,
noBrowser: false,
@@ -1,282 +1,133 @@
import { describe, expect, it } from "@effect/vitest";
import type {
DesktopHostTelemetrySnapshot,
ResourceMonitorSnapshotEvent,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
function makeNativeSnapshot(
processes: ResourceMonitorSnapshotEvent["processes"],
): ResourceMonitorSnapshotEvent {
return {
version: 2,
type: "snapshot",
sequence: 1,
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
collectionDurationMicros: 250,
scannedProcessCount: processes.length,
retainedProcessCount: processes.length,
inaccessibleProcessCount: 0,
processes,
};
}
function mockHandle(result: {
readonly stdout?: string;
readonly stderr?: string;
readonly code?: number;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
function makeTelemetryLayer(
snapshot: ResourceMonitorSnapshotEvent,
desktopSnapshot?: DesktopHostTelemetrySnapshot,
) {
const nativeLayer = NativeTelemetryClient.layerTest({
sampleNow: Effect.succeed(snapshot),
health: Effect.succeed({
status: "healthy",
hello: Option.none(),
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
lastError: Option.none(),
restartCount: 0,
sampleIntervalMs: 1_000,
}),
});
const desktopLayer = desktopSnapshot
? DesktopTelemetryReceiver.layerTest({
latest: Effect.succeedSome(desktopSnapshot),
health: Effect.succeed({
status: "healthy",
lastSampleAt: Option.some(DateTime.makeUnsafe(desktopSnapshot.sampledAtUnixMs)),
lastError: Option.none(),
}),
})
: DesktopTelemetryReceiver.layerTest();
return ResourceTelemetry.layer.pipe(
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
);
}
describe("ProcessDiagnostics", () => {
it.effect("parses POSIX ps rows with full commands", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parsePosixProcessRows(
[
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
].join("\n"),
);
expect(rows).toEqual([
it.effect("projects live process data from resource telemetry", () =>
Effect.gen(function* () {
const snapshot = makeNativeSnapshot([
{
pid: 10,
pid: process.pid,
ppid: 1,
pgid: 10,
status: "Ss",
startTimeMs: 1_000,
runTimeMs: 60_000,
name: "node",
command: "t3 server",
status: "Running",
cpuPercent: 0,
rssBytes: 1024 * 1024,
elapsed: "01:02.03",
command: "/usr/bin/node server.js",
cpuTimeMs: 100,
residentBytes: 1_024,
virtualBytes: 2_048,
ioReadBytes: 100,
ioWriteBytes: 200,
ioSemantics: "storage",
},
{
pid: 11,
ppid: 10,
pgid: 10,
status: "S+",
cpuPercent: 12.5,
rssBytes: 20480 * 1024,
elapsed: "00:04",
command: "codex app-server --config /tmp/one two",
pid: 4_242,
ppid: process.pid,
startTimeMs: 2_000,
runTimeMs: 4_000,
name: "agent",
command: "codex app-server",
status: "Running",
cpuPercent: 1.5,
cpuTimeMs: 60,
residentBytes: 2_048,
virtualBytes: 4_096,
ioReadBytes: 300,
ioWriteBytes: 400,
ioSemantics: "storage",
},
]);
}),
);
const telemetryLayer = makeTelemetryLayer(snapshot);
const layer = ProcessDiagnostics.layer.pipe(Layer.provideMerge(telemetryLayer));
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 1.5,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 3.25,
rssBytes: 4_000,
elapsed: "00:05",
command: "git status",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "S",
cpuPercent: 99,
rssBytes: 8_000,
elapsed: "00:01",
command: "unrelated",
},
{
pid: 201,
ppid: 100,
pgid: 100,
status: "R",
cpuPercent: 9,
rssBytes: 9_000,
elapsed: "00:00",
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
},
],
});
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
it.effect("preserves ascending sibling order for nested descendants", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
serverPid: 100,
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
rows: [
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "agent",
},
{
pid: 103,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-b",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "S",
cpuPercent: 0,
rssBytes: 100,
elapsed: "00:10",
command: "child-a",
},
],
});
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
it.effect("queries processes through the ChildProcessSpawner service", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
].join("\n"),
}),
);
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.read),
Effect.provide(layer),
);
const diagnostics = yield* Effect.gen(function* () {
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
yield* telemetry.refresh;
return yield* processDiagnostics.read;
}).pipe(Effect.provide(layer));
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
},
]);
expect(diagnostics.processes[0]?.startTimeMs).toBe(2_000);
expect(diagnostics.processes[0]?.cpuPercent).toBe(1.5);
expect(diagnostics.processes[0]?.rssBytes).toBe(2_048);
}),
);
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
it.effect("rejects stale process identities before signaling", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
code: 17,
stdout: "partial process output",
stderr: "process access denied",
}),
),
),
);
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
cwd: process.cwd(),
exitCode: 17,
stdoutBytes: 22,
stderrBytes: 21,
stdoutTruncated: false,
stderrTruncated: false,
});
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
stdout: [
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
].join("\n"),
}),
),
),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const snapshot = makeNativeSnapshot([]);
const telemetryLayer = makeTelemetryLayer(snapshot);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
Effect.flatMap((processDiagnostics) =>
processDiagnostics.signal({
pid: 4_242,
startTimeMs: 2_000,
signal: "SIGINT",
}),
),
Effect.provide(layer),
);
@@ -284,7 +135,85 @@ describe("ProcessDiagnostics", () => {
pid: 4242,
signal: "SIGINT",
signaled: false,
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
message: Option.some("Process 4242 no longer matches the selected process identity."),
});
}),
);
it.effect("rejects Electron processes as signal targets", () =>
Effect.gen(function* () {
const sampledAtUnixMs = DateTime.toEpochMillis(
DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
);
const snapshot = makeNativeSnapshot([
{
pid: 4_242,
ppid: 1,
startTimeMs: 2_000,
runTimeMs: 4_000,
name: "electron",
command: "electron",
status: "Running",
cpuPercent: 1.5,
cpuTimeMs: 60,
residentBytes: 2_048,
virtualBytes: 4_096,
ioReadBytes: 300,
ioWriteBytes: 400,
ioSemantics: "storage",
},
]);
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
const telemetryLayer = makeTelemetryLayer(snapshot, {
version: 1,
type: "desktopTelemetry",
sequence: 1,
sampledAtUnixMs,
electronPid: 4_242,
power: {
source: "electron-main",
idle: "false",
idleSeconds: 0,
locked: "false",
suspended: false,
onBattery: "false",
lowPowerMode: "unknown",
thermalState: "nominal",
stale: false,
updatedAt: sampledAt,
},
speedLimitPercent: Option.none(),
electronProcesses: [
{
pid: 4_242,
creationTimeMs: 2_000,
type: "Browser",
name: "electron",
cpuPercent: 1.5,
idleWakeupsPerSecond: 0,
workingSetBytes: 2_048,
peakWorkingSetBytes: 2_048,
},
],
});
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((processDiagnostics) =>
processDiagnostics.signal({
pid: 4_242,
startTimeMs: 2_000,
signal: "SIGKILL",
}),
),
Effect.provide(layer),
);
expect(result).toEqual({
pid: 4_242,
signal: "SIGKILL",
signaled: false,
message: Option.some("Process 4242 is not a signalable T3 backend descendant."),
});
}),
);
+134 -518
View File
@@ -1,105 +1,46 @@
import type {
ResourceTelemetryProcessCategory,
ServerProcessDiagnosticsEntry,
ServerProcessDiagnosticsResult,
ServerProcessSignal,
ServerSignalProcessResult,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
export interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
readonly status: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly elapsed: string;
readonly command: string;
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
readonly pid: number;
readonly startTimeMs: number;
readonly signal: ServerProcessSignal;
}) => Effect.Effect<ServerSignalProcessResult>;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
{
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
readonly pid: number;
readonly signal: ServerProcessSignal;
}) => Effect.Effect<ServerSignalProcessResult>;
}
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
"ProcessDiagnosticsQueryTimeoutError",
{
command: Schema.String,
argCount: Schema.Number,
cwd: Schema.String,
timeoutMillis: Schema.Number,
},
) {
override get message(): string {
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
}
}
class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
"ProcessDiagnosticsQueryFailedError",
{
command: Schema.String,
argCount: Schema.Number,
cwd: Schema.String,
exitCode: Schema.optional(Schema.Number),
stdoutBytes: Schema.optional(Schema.Number),
stderrBytes: Schema.optional(Schema.Number),
stdoutTruncated: Schema.optional(Schema.Boolean),
stderrTruncated: Schema.optional(Schema.Boolean),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
}
}
class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
"ProcessDiagnosticsServerProcessSignalError",
{ pid: Schema.Number },
) {
override get message(): string {
return "Refusing to signal the T3 server process.";
}
}
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
"ProcessDiagnosticsNotDescendantError",
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
"ProcessIdentityChanged",
{
pid: Schema.Number,
serverPid: Schema.Number,
startTimeMs: Schema.Number,
},
) {
override get message(): string {
return `Process ${this.pid} is not a live descendant of the T3 server.`;
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
}
}
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
"ProcessDiagnosticsSignalFailedError",
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
"ProcessSignalFailed",
{
pid: Schema.Number,
signal: Schema.String,
@@ -111,465 +52,140 @@ class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<Proces
}
}
const ProcessDiagnosticsError = Schema.Union([
ProcessDiagnosticsQueryTimeoutError,
ProcessDiagnosticsQueryFailedError,
ProcessDiagnosticsServerProcessSignalError,
ProcessDiagnosticsNotDescendantError,
ProcessDiagnosticsSignalFailedError,
]);
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
function formatElapsed(runTimeMs: number): string {
const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
const hours = Math.floor(totalSeconds / 3_600);
const minutes = Math.floor((totalSeconds % 3_600) / 60);
const seconds = totalSeconds % 60;
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
: `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
for (const line of output.split(/\r?\n/)) {
if (line.trim().length === 0) continue;
const match = rowPattern.exec(line);
if (!match) continue;
const pidText = match[1];
const ppidText = match[2];
const pgidText = match[3];
const status = match[4];
const cpuText = match[5];
const rssText = match[6];
const elapsed = match[7];
const command = match[8];
if (
pidText === undefined ||
ppidText === undefined ||
pgidText === undefined ||
status === undefined ||
cpuText === undefined ||
rssText === undefined ||
elapsed === undefined ||
command === undefined
) {
continue;
}
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid,
ppid,
pgid,
status,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
}
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
export function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
const childrenByParent = new Map<number, ProcessRow[]>();
for (const row of rows) {
const children = childrenByParent.get(row.ppid) ?? [];
children.push(row);
childrenByParent.set(row.ppid, children);
}
const entries: ServerProcessDiagnosticsEntry[] = [];
const visited = new Set<number>();
const stack = [...(childrenByParent.get(serverPid) ?? [])]
.toSorted((left, right) => left.pid - right.pid)
.map((row) => ({ row, depth: 0 }));
while (stack.length > 0) {
const item = stack.shift();
if (!item || visited.has(item.row.pid)) continue;
visited.add(item.row.pid);
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
(left, right) => left.pid - right.pid,
);
entries.push({
pid: item.row.pid,
ppid: item.row.ppid,
pgid: Option.fromNullishOr(item.row.pgid),
status: item.row.status,
cpuPercent: item.row.cpuPercent,
rssBytes: item.row.rssBytes,
elapsed: item.row.elapsed || "n/a",
command: item.row.command,
depth: item.depth,
childPids: children.map((child) => child.pid),
});
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
}
return entries;
}
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
const command = row.command.trim();
function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
return (
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
category === "server-child" || category === "provider-root" || category === "terminal-root"
);
}
function makeResult(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
readonly error?: string;
}): ServerProcessDiagnosticsResult {
const readAt = input.readAt;
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const processes = buildDescendantEntries(rows, input.serverPid);
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
return {
serverPid: input.serverPid,
readAt,
processCount: processes.length,
totalRssBytes,
totalCpuPercent,
processes,
error: input.error ? Option.some({ message: input.error }) : Option.none(),
};
}
interface ProcessOutput {
readonly cwd: string;
readonly exitCode: number;
readonly stdout: string;
readonly stdoutBytes: number;
readonly stdoutTruncated: boolean;
readonly stderr: string;
readonly stderrBytes: number;
readonly stderrTruncated: boolean;
}
const runProcess = Effect.fn("runProcess")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
}) {
const cwd = process.cwd();
return yield* Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
// shell mode would re-tokenize the PowerShell `-Command` payload (which
// contains pipes) before PowerShell ever sees it.
const child = yield* spawner.spawn(
ChildProcess.make(input.command, input.args, {
cwd,
}),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectUint8StreamText({
stream: child.stdout,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
collectUint8StreamText({
stream: child.stderr,
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
truncatedMarker: "\n\n[truncated]",
}),
child.exitCode,
],
{ concurrency: "unbounded" },
);
return {
cwd,
exitCode,
stdout: stdout.text,
stdoutBytes: stdout.bytes,
stdoutTruncated: stdout.truncated,
stderr: stderr.text,
stderrBytes: stderr.bytes,
stderrTruncated: stderr.truncated,
} satisfies ProcessOutput;
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new ProcessDiagnosticsQueryTimeoutError({
command: input.command,
argCount: input.args.length,
cwd,
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
}),
),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: new ProcessDiagnosticsQueryFailedError({
command: input.command,
argCount: input.args.length,
cwd,
cause,
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const read: ProcessDiagnosticsShape["read"] = telemetry.latest.pipe(
Effect.map((snapshot) => {
const processes = snapshot.processes
.filter((entry) => entry.identity.pid !== process.pid)
.map(
(entry): ServerProcessDiagnosticsEntry => ({
pid: entry.identity.pid,
startTimeMs: entry.identity.startTimeMs,
ppid: entry.ppid,
pgid: Option.none(),
status: entry.status || "Unknown",
cpuPercent: entry.cpuPercent,
rssBytes: entry.residentBytes,
elapsed: formatElapsed(entry.runTimeMs),
command: entry.command || entry.name || "unknown",
depth: Math.max(0, entry.depth - 1),
childPids: entry.childPids,
}),
),
);
});
function readPosixProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
return runProcess({
command: "ps",
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
new ProcessDiagnosticsQueryFailedError({
command: "ps",
argCount: 2,
cwd: result.cwd,
exitCode: result.exitCode,
stdoutBytes: result.stdoutBytes,
stderrBytes: result.stderrBytes,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
}),
)
: Effect.succeed(parsePosixProcessRows(result.stdout)),
),
);
}
function readWindowsProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
const command = [
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
"};",
"$processes | ConvertTo-Json -Compress -Depth 3",
].join(" ");
return runProcess({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
new ProcessDiagnosticsQueryFailedError({
command: "powershell.exe",
argCount: 4,
cwd: result.cwd,
exitCode: result.exitCode,
stdoutBytes: result.stdoutBytes,
stderrBytes: result.stderrBytes,
stdoutTruncated: result.stdoutTruncated,
stderrTruncated: result.stderrTruncated,
}),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
),
);
}
export const readProcessRows = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
});
export function aggregateProcessDiagnostics(input: {
readonly serverPid: number;
readonly rows: ReadonlyArray<ProcessRow>;
readonly readAt: DateTime.Utc;
}): ServerProcessDiagnosticsResult {
return makeResult(input);
}
function assertDescendantPid(
pid: number,
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
if (pid === process.pid) {
return Effect.fail(
new ProcessDiagnosticsServerProcessSignalError({
pid,
}),
);
}
return readProcessRows.pipe(
Effect.flatMap((rows) => {
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
(entry) => entry.pid === pid,
);
return descendant
? Effect.void
: Effect.fail(
new ProcessDiagnosticsNotDescendantError({
pid,
serverPid: process.pid,
}),
);
);
return {
serverPid: process.pid,
readAt: snapshot.readAt,
processCount: processes.length,
totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
processes,
error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
};
}),
);
}
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
const readAt = yield* DateTime.now;
const rows = yield* readProcessRows.pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return makeResult({ serverPid: process.pid, rows, readAt });
}).pipe(
Effect.catch((error: ProcessDiagnosticsError) =>
DateTime.now.pipe(
Effect.map((readAt) =>
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
),
),
),
);
const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
function* (input) {
return yield* assertDescendantPid(input.pid).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.flatMap(() =>
Effect.try({
try: () => {
process.kill(input.pid, input.signal);
return {
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
};
},
catch: (cause) =>
new ProcessDiagnosticsSignalFailedError({
pid: input.pid,
signal: input.signal,
cause,
}),
}),
),
Effect.catch((error: ProcessDiagnosticsError) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(error.message),
}),
),
if (input.pid === process.pid) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some("Refusing to signal the T3 server process."),
};
}
const current = yield* telemetry.latest;
const selected = current.processes.find(
(entry) =>
entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
);
if (!selected) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(
`Process ${input.pid} no longer matches the selected process identity.`,
),
};
}
if (!canSignalCategory(selected.category)) {
return {
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
};
}
return yield* telemetry
.validateProcessIdentity({
pid: input.pid,
startTimeMs: input.startTimeMs,
})
.pipe(
Effect.flatMap((valid) =>
valid
? Effect.void
: Effect.fail(
new ProcessIdentityChanged({
pid: input.pid,
startTimeMs: input.startTimeMs,
}),
),
),
Effect.flatMap(() =>
Effect.try({
try: () => {
process.kill(input.pid, input.signal);
return {
pid: input.pid,
signal: input.signal,
signaled: true,
message: Option.none(),
};
},
catch: (cause) =>
new ProcessSignalFailed({
pid: input.pid,
signal: input.signal,
cause,
}),
}),
),
Effect.catch((error) =>
Effect.succeed({
pid: input.pid,
signal: input.signal,
signaled: false,
message: Option.some(
error instanceof Error ? error.message : "Failed to signal process.",
),
}),
),
);
},
);
return ProcessDiagnostics.of({ read, signal });
});
export const layer = Layer.effect(ProcessDiagnostics, make);
export const layer = Layer.effect(ProcessDiagnostics, make());
@@ -1,255 +1,137 @@
import { describe, expect, it } from "@effect/vitest";
import type { ResourceTelemetryHistory } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
describe("ProcessResourceMonitor", () => {
it.effect("samples the server root process and descendants", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 50,
rssBytes: 3_000,
elapsed: "00:05",
command: "rg needle",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "R",
cpuPercent: 99,
rssBytes: 9_000,
elapsed: "00:05",
command: "unrelated",
},
],
});
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
it.effect("rolls samples up by process and CPU time", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
const samples = [
...ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 30,
rssBytes: 2_000,
elapsed: "01:05",
command: "t3 server",
},
],
}),
];
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastFailure: null,
});
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
const samples = [
...ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 2_000,
elapsed: "01:06",
command: "t3 server",
},
],
}),
];
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastFailure: null,
});
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
it.effect("returns all process summaries in the selected window", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = ProcessResourceMonitor.collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
...Array.from({ length: 35 }, (_, index) => ({
pid: 200 + index,
ppid: index === 0 ? 100 : 199 + index,
pgid: 100,
status: "S",
cpuPercent: 35 - index,
rssBytes: 2_000 + index,
elapsed: "00:10",
command: `worker ${index}`,
})),
],
});
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastFailure: null,
});
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
Effect.sync(() => {
it.effect("projects resource telemetry history into the legacy diagnostics contract", () =>
Effect.gen(function* () {
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const cause = new Error("stderr included credential=secret-value");
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
failureTag: "ProcessDiagnosticsQueryFailedError",
cause,
});
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
samples: [],
const history: ResourceTelemetryHistory = {
readAt,
readAtMs: DateTime.toEpochMillis(readAt),
windowMs: 60_000,
bucketMs: 10_000,
lastFailure: failure,
});
sampleIntervalMs: 1_000,
retainedSampleCount: 2,
buckets: [
{
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
endedAt: readAt,
avgCpuPercent: 15,
maxCpuPercent: 25,
maxRssBytes: 4_096,
ioReadBytes: 1_024,
ioWriteBytes: 2_048,
maxProcessCount: 2,
},
],
topProcesses: [
{
identity: { pid: process.pid, startTimeMs: 100 },
ppid: 1,
depth: 0,
name: "node",
command: "t3 server",
category: "server",
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
lastSeenAt: readAt,
currentCpuPercent: 5,
avgCpuPercent: 4,
maxCpuPercent: 8,
cpuTimeMs: 1_500,
currentRssBytes: 2_048,
peakRssBytes: 4_096,
ioReadBytes: 1_024,
ioWriteBytes: 2_048,
ioSemantics: "storage",
sampleCount: 2,
},
],
health: {
native: {
status: "degraded",
lastSampleAt: Option.some(readAt),
lastError: Option.some("collector stalled"),
},
desktop: {
status: "healthy",
lastSampleAt: Option.some(readAt),
lastError: Option.none(),
},
sidecarVersion: Option.some("0.1.0"),
sidecarPid: Option.some(9_000),
restartCount: 1,
collectionDurationMicros: 250,
scannedProcessCount: 80,
retainedProcessCount: 2,
inaccessibleProcessCount: 0,
},
};
const telemetry: ResourceTelemetry.ResourceTelemetryShape = {
latest: Effect.die("unused"),
changes: Stream.empty,
readHistory: () => Effect.succeed(history),
refresh: Effect.die("unused"),
validateProcessIdentity: () => Effect.die("unused"),
retry: Effect.die("unused"),
};
const layer = ProcessResourceMonitor.layer.pipe(
Layer.provide(
Layer.succeed(
ResourceTelemetry.ResourceTelemetry,
ResourceTelemetry.ResourceTelemetry.of(telemetry),
),
),
);
expect(failure.cause).toBe(cause);
expect(Option.getOrThrow(result.error)).toEqual({
failureTag: "ProcessDiagnosticsQueryFailedError",
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
Effect.flatMap((monitor) =>
monitor.readHistory({
windowMs: 60_000,
bucketMs: 10_000,
}),
),
Effect.provide(layer),
);
expect(result.totalCpuSecondsApprox).toBe(1.5);
expect(result.topProcesses).toEqual([
{
processKey: `${process.pid}:100`,
pid: process.pid,
ppid: 1,
command: "t3 server",
depth: 0,
isServerRoot: true,
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
lastSeenAt: readAt,
currentCpuPercent: 5,
avgCpuPercent: 4,
maxCpuPercent: 8,
cpuSecondsApprox: 1.5,
currentRssBytes: 2_048,
maxRssBytes: 4_096,
sampleCount: 2,
},
]);
expect(result.buckets[0]).toMatchObject({
avgCpuPercent: 15,
maxCpuPercent: 25,
maxRssBytes: 4_096,
maxProcessCount: 2,
});
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
expect(result.error).toEqual(
Option.some({
failureTag: "ProcessDiagnosticsQueryFailedError",
message: "collector stalled",
}),
);
}),
);
});
@@ -1,329 +1,77 @@
import {
ServerProcessResourceHistoryFailureTag,
type ServerProcessResourceHistoryBucket,
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
type ServerProcessResourceHistoryInput,
type ServerProcessResourceHistoryResult,
type ServerProcessResourceHistorySummary,
import type {
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
"ProcessResourceSamplingError",
{
failureTag: ServerProcessResourceHistoryFailureTag,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to sample process resources (${this.failureTag}).`;
}
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastFailure: ProcessResourceSamplingError | null;
export interface ProcessResourceMonitorShape {
readonly readHistory: (
input: ServerProcessResourceHistoryInput,
) => Effect.Effect<ServerProcessResourceHistoryResult>;
}
export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitor,
{
readonly readHistory: (
input: ServerProcessResourceHistoryInput,
) => Effect.Effect<ServerProcessResourceHistoryResult>;
}
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessDiagnostics.ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(
rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>,
serverPid: number,
): ProcessDiagnostics.ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter(
(row) => !ProcessDiagnostics.isDiagnosticsQueryProcess(row, input.serverPid),
);
const root = findServerRootRow(rows, input.serverPid);
const descendants = ProcessDiagnostics.buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
}
for (const process of descendants) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(process),
pid: process.pid,
ppid: process.ppid,
command: process.command,
cpuPercent: process.cpuPercent,
rssBytes: process.rssBytes,
depth: process.depth + 1,
isServerRoot: false,
});
}
return samples;
}
function trimSamples(
samples: ReadonlyArray<ProcessResourceSample>,
nowMs: number,
): ReadonlyArray<ProcessResourceSample> {
const minSampledAtMs = nowMs - RETENTION_MS;
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
return retained.length <= MAX_RETAINED_SAMPLES
? retained
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
}
function summarizeProcesses(
samples: ReadonlyArray<ProcessResourceSample>,
): ReadonlyArray<ServerProcessResourceHistorySummary> {
const groups = new Map<string, ProcessResourceSample[]>();
for (const sample of samples) {
const processSamples = groups.get(sample.processKey) ?? [];
processSamples.push(sample);
groups.set(sample.processKey, processSamples);
}
return [...groups.entries()]
.map(([processKey, processSamples]) => {
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
const first = sorted[0]!;
const latest = sorted[sorted.length - 1]!;
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
const cpuSecondsApprox = sorted.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
processKey,
pid: latest.pid,
ppid: latest.ppid,
command: latest.command,
depth: latest.depth,
isServerRoot: latest.isServerRoot,
firstSeenAt: first.sampledAt,
lastSeenAt: latest.sampledAt,
currentCpuPercent: latest.cpuPercent,
avgCpuPercent: cpuPercentTotal / sorted.length,
maxCpuPercent,
cpuSecondsApprox,
currentRssBytes: latest.rssBytes,
maxRssBytes,
sampleCount: sorted.length,
} satisfies ServerProcessResourceHistorySummary;
})
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
}
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
const bucketSamples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const samplesByRead = new Map<number, ProcessResourceSample[]>();
for (const sample of bucketSamples) {
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
samplesAtTime.push(sample);
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
}
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
processCount: samplesAtTime.length,
}));
const avgCpuPercent =
readTotals.length === 0
? 0
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
buckets.push({
startedAt: dateTimeFromMillis(startedAtMs),
endedAt: dateTimeFromMillis(endedAtMs),
avgCpuPercent,
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
maxProcessCount: readTotals.length
? Math.max(...readTotals.map((read) => read.processCount))
: 0,
});
}
return buckets;
}
export function aggregateProcessResourceHistory(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly readAt: DateTime.Utc;
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastFailure: ProcessResourceSamplingError | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
const totalCpuSecondsApprox = samples.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
readAt: input.readAt,
windowMs,
bucketMs,
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastFailure
? Option.some({
failureTag: input.lastFailure.failureTag,
message: input.lastFailure.message,
})
: Option.none(),
};
}
export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
const recordSamplingFailure = (cause: {
readonly _tag: ServerProcessResourceHistoryFailureTagType;
}) =>
Ref.update(state, (current) => ({
...current,
lastFailure: new ProcessResourceSamplingError({
failureTag: cause._tag,
cause,
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
telemetry.readHistory(input).pipe(
Effect.map((history) => {
const topProcesses = history.topProcesses.map((entry) => ({
processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
pid: entry.identity.pid,
ppid: entry.ppid,
command: entry.command || entry.name || "unknown",
depth: entry.depth,
isServerRoot: entry.category === "server",
firstSeenAt: entry.firstSeenAt,
lastSeenAt: entry.lastSeenAt,
currentCpuPercent: entry.currentCpuPercent,
avgCpuPercent: entry.avgCpuPercent,
maxCpuPercent: entry.maxCpuPercent,
cpuSecondsApprox: entry.cpuTimeMs / 1_000,
currentRssBytes: entry.currentRssBytes,
maxRssBytes: entry.peakRssBytes,
sampleCount: entry.sampleCount,
}));
return {
readAt: history.readAt,
windowMs: history.windowMs,
bucketMs: history.bucketMs,
sampleIntervalMs: history.sampleIntervalMs,
retainedSampleCount: history.retainedSampleCount,
totalCpuSecondsApprox: topProcesses.reduce(
(total, entry) => total + entry.cpuSecondsApprox,
0,
),
buckets: history.buckets.map((bucket) => ({
startedAt: bucket.startedAt,
endedAt: bucket.endedAt,
avgCpuPercent: bucket.avgCpuPercent,
maxCpuPercent: bucket.maxCpuPercent,
maxRssBytes: bucket.maxRssBytes,
maxProcessCount: bucket.maxProcessCount,
})),
topProcesses,
error: history.health.native.lastError.pipe(
Option.map((message) => ({
failureTag: "ProcessDiagnosticsQueryFailedError" as const,
message,
})),
),
};
}),
}));
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const samples = collectMonitoredSamples({
rows,
serverPid: process.pid,
sampledAt,
sampledAtMs,
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastFailure: null,
}));
}).pipe(
Effect.catchTags({
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
}),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
Effect.gen(function* () {
const readAt = yield* DateTime.now;
const readAtMs = DateTime.toEpochMillis(readAt);
const current = yield* Ref.get(state);
return aggregateProcessResourceHistory({
samples: current.samples,
readAt,
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastFailure: current.lastFailure,
});
});
return ProcessResourceMonitor.of({ readHistory });
});
export const layer = Layer.effect(ProcessResourceMonitor, make);
export const layer = Layer.effect(ProcessResourceMonitor, make());
@@ -114,6 +114,33 @@ describe("GitWorkflowService", () => {
}).pipe(Effect.provide(testLayer));
});
it.effect("routes explicit upstream refreshes through the Git driver", () => {
const refreshStatusUpstream = vi.fn(() => Effect.void);
const testLayer = GitWorkflowService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
detect: () =>
Effect.succeed({
kind: "git",
} as VcsDriverRegistry.VcsDriverHandle),
}),
),
Layer.provide(
Layer.mock(GitVcsDriver.GitVcsDriver)({
refreshStatusUpstream,
}),
),
Layer.provide(Layer.mock(GitManager.GitManager)({})),
);
return Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
yield* workflow.refreshStatusUpstream("/repo");
assert.deepStrictEqual(refreshStatusUpstream.mock.calls, [["/repo"]]);
}).pipe(Effect.provide(testLayer));
});
it.effect("returns an empty ref list when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
@@ -45,6 +45,7 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -270,6 +271,12 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
refreshStatusUpstream: (cwd) =>
detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void,
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
+1 -77
View File
@@ -1,12 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
BrowserOtlpTraceCollectionError,
BrowserOtlpTraceDecodeError,
BrowserOtlpTraceExportError,
isLoopbackHostname,
resolveDevRedirectUrl,
} from "./http.ts";
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
describe("http dev routing", () => {
it("treats localhost and loopback addresses as local", () => {
@@ -31,73 +25,3 @@ describe("http dev routing", () => {
);
});
});
describe("browser OTLP diagnostics", () => {
it("retains decode causes without retaining the trace payload", () => {
const cause = new Error("private trace payload detail");
const error = BrowserOtlpTraceDecodeError.fromPayload({ resourceSpans: [] }, cause);
expect(error).toMatchObject({
resourceSpanCount: 0,
cause,
message: "Failed to decode browser OTLP payload with 0 resource spans.",
});
expect(error.cause).toBe(cause);
expect(error).not.toHaveProperty("bodyJson");
});
it("describes malformed trace payloads without inspecting unsafe fields", () => {
const cause = new Error("private malformed trace payload detail");
const error = BrowserOtlpTraceDecodeError.fromPayload(
{ resourceSpans: "private malformed resource spans" },
cause,
);
expect(error).toMatchObject({
resourceSpanCount: 0,
cause,
message: "Failed to decode browser OTLP payload with 0 resource spans.",
});
expect(error.cause).toBe(cause);
expect(error).not.toHaveProperty("resourceSpans");
});
it("retains local collection causes with a structural record count", () => {
const records = [{ type: "private trace record" }];
const cause = new Error("private local collector detail");
const error = BrowserOtlpTraceCollectionError.fromRecords(records, cause);
expect(error).toMatchObject({
recordCount: 1,
cause,
message: "Failed to collect 1 browser OTLP trace records locally.",
});
expect(error.cause).toBe(cause);
expect(error).not.toHaveProperty("records");
});
it("redacts collector URL credentials while retaining the exact cause", () => {
const collectorUrl =
"https://collector-user:[email protected]/private/v1/traces?access_token=collector-secret#collector-fragment";
const cause = new Error("collector transport failed");
const error = BrowserOtlpTraceExportError.fromCollectorUrl(collectorUrl, cause);
expect(error).toMatchObject({
collectorUrlInputLength: collectorUrl.length,
collectorUrlProtocol: "https:",
collectorUrlHostname: "traces.example.test",
cause,
});
expect(error.cause).toBe(cause);
expect(error).not.toHaveProperty("collectorUrl");
for (const secret of [
"collector-user",
"collector-password",
"/private/v1/traces",
"collector-secret",
"collector-fragment",
]) {
expect(error.message).not.toContain(secret);
}
});
});
+29 -133
View File
@@ -5,13 +5,12 @@ import {
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
import { getUrlDiagnostics } from "@t3tools/shared/urlDiagnostics";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { cast } from "effect/Function";
import {
HttpBody,
@@ -36,8 +35,9 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
import {
annotateEnvironmentRequest,
catchEnvironmentAuthenticationErrors,
failEnvironmentScopeRequired,
failEnvironmentAuthInvalid,
failEnvironmentInternal,
} from "./auth/http.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
@@ -80,8 +80,13 @@ const authenticateRawRouteWithScope = (
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const session = yield* catchEnvironmentAuthenticationErrors(
serverAuth.authenticateHttpRequest(request),
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("internal_error", error),
),
);
if (!session.scopes.includes(scope)) {
return yield* failEnvironmentScopeRequired(scope);
@@ -103,95 +108,10 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
}),
);
function errorDiagnosticTag(cause: unknown): string {
if (
typeof cause === "object" &&
cause !== null &&
"_tag" in cause &&
typeof cause._tag === "string"
) {
return cause._tag;
}
if (cause instanceof Error) return cause.name;
return typeof cause;
}
export class BrowserOtlpTraceDecodeError extends Schema.TaggedErrorClass<BrowserOtlpTraceDecodeError>()(
"BrowserOtlpTraceDecodeError",
{
resourceSpanCount: Schema.Number,
cause: Schema.Defect(),
},
) {
static fromPayload(payload: unknown, cause: unknown): BrowserOtlpTraceDecodeError {
const resourceSpanCount =
typeof payload === "object" &&
payload !== null &&
"resourceSpans" in payload &&
Array.isArray(payload.resourceSpans)
? payload.resourceSpans.length
: 0;
return new BrowserOtlpTraceDecodeError({
resourceSpanCount,
cause,
});
}
override get message(): string {
return `Failed to decode browser OTLP payload with ${this.resourceSpanCount} resource spans.`;
}
}
export class BrowserOtlpTraceCollectionError extends Schema.TaggedErrorClass<BrowserOtlpTraceCollectionError>()(
"BrowserOtlpTraceCollectionError",
{
recordCount: Schema.Number,
cause: Schema.Defect(),
},
) {
static fromRecords(
records: ReadonlyArray<unknown>,
cause: unknown,
): BrowserOtlpTraceCollectionError {
return new BrowserOtlpTraceCollectionError({
recordCount: records.length,
cause,
});
}
override get message(): string {
return `Failed to collect ${this.recordCount} browser OTLP trace records locally.`;
}
}
export class BrowserOtlpTraceExportError extends Schema.TaggedErrorClass<BrowserOtlpTraceExportError>()(
"BrowserOtlpTraceExportError",
{
collectorUrlInputLength: Schema.Number,
collectorUrlProtocol: Schema.optionalKey(Schema.String),
collectorUrlHostname: Schema.optionalKey(Schema.String),
cause: Schema.Defect(),
},
) {
static fromCollectorUrl(collectorUrl: string, cause: unknown): BrowserOtlpTraceExportError {
const diagnostics = getUrlDiagnostics(collectorUrl);
return new BrowserOtlpTraceExportError({
collectorUrlInputLength: diagnostics.inputLength,
...(diagnostics.protocol === undefined ? {} : { collectorUrlProtocol: diagnostics.protocol }),
...(diagnostics.hostname === undefined ? {} : { collectorUrlHostname: diagnostics.hostname }),
cause,
});
}
override get message(): string {
const collector =
this.collectorUrlHostname === undefined
? "the configured collector"
: this.collectorUrlHostname;
return `Failed to export browser OTLP traces to ${collector} (collector URL input length ${this.collectorUrlInputLength}).`;
}
}
class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
readonly cause: unknown;
readonly bodyJson: OtlpTracer.TraceData;
}> {}
export const otlpTracesProxyRouteLayer = HttpRouter.add(
"POST",
@@ -207,31 +127,15 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
yield* Effect.try({
try: () => decodeOtlpTraceRecords(bodyJson),
catch: (cause) => BrowserOtlpTraceDecodeError.fromPayload(bodyJson, cause),
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
}).pipe(
Effect.flatMap((records) =>
browserTraceCollector
.record(records)
.pipe(
Effect.catchDefect((cause) =>
Effect.fail(BrowserOtlpTraceCollectionError.fromRecords(records, cause)),
),
),
Effect.flatMap((records) => browserTraceCollector.record(records)),
Effect.catch((cause) =>
Effect.logWarning("Failed to decode browser OTLP traces", {
cause,
bodyJson,
}),
),
Effect.catchTags({
BrowserOtlpTraceDecodeError: (error) =>
Effect.logWarning(error.message, {
errorTag: error._tag,
resourceSpanCount: error.resourceSpanCount,
causeTag: errorDiagnosticTag(error.cause),
}),
BrowserOtlpTraceCollectionError: (error) =>
Effect.logWarning(error.message, {
errorTag: error._tag,
recordCount: error.recordCount,
causeTag: errorDiagnosticTag(error.cause),
}),
}),
);
if (otlpTracesUrl === undefined) {
@@ -245,23 +149,15 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
.pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.as(HttpServerResponse.empty({ status: 204 })),
Effect.mapError((cause) =>
BrowserOtlpTraceExportError.fromCollectorUrl(otlpTracesUrl, cause),
Effect.tapError((cause) =>
Effect.logWarning("Failed to export browser OTLP traces", {
cause,
otlpTracesUrl,
}),
),
Effect.orElseSucceed(() =>
HttpServerResponse.text("Trace export failed.", { status: 502 }),
),
Effect.catchTags({
BrowserOtlpTraceExportError: (error) =>
Effect.logWarning(error.message, {
errorTag: error._tag,
collectorUrlInputLength: error.collectorUrlInputLength,
...(error.collectorUrlProtocol === undefined
? {}
: { collectorUrlProtocol: error.collectorUrlProtocol }),
...(error.collectorUrlHostname === undefined
? {}
: { collectorUrlHostname: error.collectorUrlHostname }),
causeTag: errorDiagnosticTag(error.cause),
}).pipe(Effect.as(HttpServerResponse.text("Trace export failed.", { status: 502 }))),
}),
);
}).pipe(
Effect.catchTags({
+35 -96
View File
@@ -1,16 +1,17 @@
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
@@ -33,6 +34,12 @@ const makeKeybindingsLayer = () => {
);
};
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
Effect.mapError((error) => error.detail),
Effect.result,
);
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -191,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
@@ -216,21 +224,15 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.deepEqual(configState.issues, [
{
kind: "keybindings.malformed-config",
message: "Expected the keybindings configuration to be a JSON array.",
message: configState.issues[0]?.message ?? "",
},
]);
assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("ignores invalid entries in runtime and reports them as issues", () => {
const logs: ReadonlyArray<unknown>[] = [];
const logger = Logger.make(({ message }) => {
logs.push(Array.isArray(message) ? message : [message]);
});
const secret = "private-shortcut-payload";
return Effect.gen(function* () {
it.effect("ignores invalid entries in runtime and reports them as issues", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
yield* fs.writeFileString(
@@ -239,7 +241,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
JSON.stringify([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+d+o", command: "terminal.new" },
{ key: "mod+x", command: secret },
{ key: "mod+x", command: "invalid.command" },
]),
);
@@ -249,55 +251,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === secret));
assert.isFalse(
configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
);
assert.deepEqual(configState.issues, [
{
kind: "keybindings.invalid-entry",
index: 1,
message: "The keybinding entry contains an invalid shortcut or when expression.",
message: configState.issues[0]?.message ?? "",
},
{
kind: "keybindings.invalid-entry",
index: 2,
message: "Expected a keybinding entry with key, command, and optional when fields.",
message: configState.issues[1]?.message ?? "",
},
]);
const invalidEntryLog = logs.find((log) => {
const attributes = log[1];
return (
String(log[0]).includes("ignoring invalid keybinding entry") &&
typeof attributes === "object" &&
attributes !== null &&
Reflect.get(attributes, "entryIndex") === 2
);
});
if (!invalidEntryLog) {
return assert.fail("Expected invalid keybinding warning");
}
const attributes = invalidEntryLog[1];
if (typeof attributes !== "object" || attributes === null) {
return assert.fail("Expected structured invalid keybinding attributes");
}
assert.equal(Reflect.get(attributes, "validationStage"), "entry-schema");
assert.equal(Reflect.get(attributes, "validationInputKind"), "object");
assert.equal(Reflect.get(attributes, "validationInputSize"), 2);
assert.equal(Reflect.get(attributes, "validationHasKeyField"), true);
assert.equal(Reflect.get(attributes, "validationHasCommandField"), true);
assert.equal(Reflect.get(attributes, "validationHasWhenField"), false);
assert.equal(Reflect.get(attributes, "causeReasonCount"), 1);
assert.isFalse("entry" in attributes);
assert.isFalse("cause" in attributes);
assert.isFalse(String(invalidEntryLog[0]).includes(secret));
assert.isFalse(Object.values(attributes).some((value) => String(value).includes(secret)));
}).pipe(
Effect.provide(
Layer.mergeAll(
makeKeybindingsLayer(),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
});
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect(
"upserts missing default keybindings on startup without overriding existing command rules",
@@ -332,9 +302,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
);
it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
const logs: ReadonlyArray<unknown>[] = [];
const messages: string[] = [];
const logger = Logger.make(({ message }) => {
logs.push(Array.isArray(message) ? message : [message]);
messages.push(String(message));
});
return Effect.gen(function* () {
@@ -352,21 +322,11 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
const warning = logs.find((log) =>
String(log[0]).includes("skipping default keybinding due to shortcut conflict"),
assert.isTrue(
messages.some((message) =>
message.includes("skipping default keybinding due to shortcut conflict"),
),
);
if (!warning) {
return assert.fail("Expected shortcut conflict warning");
}
const attributes = warning[1];
if (typeof attributes !== "object" || attributes === null) {
return assert.fail("Expected structured shortcut conflict attributes");
}
assert.equal(Reflect.get(attributes, "defaultCommand"), "terminal.toggle");
assert.equal(Reflect.get(attributes, "conflictingCommand"), "script.custom-action.run");
assert.equal(Reflect.get(attributes, "hasWhenContext"), false);
assert.isFalse("key" in attributes);
assert.isFalse("when" in attributes);
}).pipe(
Effect.provide(
Layer.mergeAll(
@@ -484,24 +444,15 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(Effect.result);
if (Result.isSuccess(result)) {
return assert.fail("Expected malformed config update to fail");
}
assert.equal(result.failure._tag, "KeybindingsConfigError");
assert.equal(result.failure.operation, "decode");
assert.isTrue(Schema.isSchemaError(result.failure.cause));
assert.equal(
result.failure.message,
`Keybindings config operation 'decode' failed at ${keybindingsConfigPath}.`,
);
}).pipe(toDetailResult);
assertFailure(result, "expected JSON array");
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
assert.equal(persistedRaw, "{ not-json");
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("returns stable structured decode errors across retries", () =>
it.effect("reports non-array config parse errors without duplicate prefix", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
@@ -516,12 +467,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(Effect.result);
if (Result.isSuccess(firstResult)) {
return assert.fail("Expected first malformed config update to fail");
}
assert.equal(firstResult.failure.operation, "decode");
assert.isTrue(Schema.isSchemaError(firstResult.failure.cause));
}).pipe(toDetailResult);
assertFailure(firstResult, "expected JSON array");
const secondResult = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings.Keybindings;
@@ -529,13 +476,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(Effect.result);
if (Result.isSuccess(secondResult)) {
return assert.fail("Expected second malformed config update to fail");
}
assert.equal(secondResult.failure.operation, "decode");
assert.isTrue(Schema.isSchemaError(secondResult.failure.cause));
assert.equal(secondResult.failure.message, firstResult.failure.message);
}).pipe(toDetailResult);
assertFailure(secondResult, "expected JSON array");
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
@@ -555,11 +497,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
key: "mod+shift+r",
command: "script.run-tests.run",
});
}).pipe(Effect.result);
if (Result.isSuccess(result)) {
return assert.fail("Expected update in a read-only directory to fail");
}
assert.equal(result.failure.operation, "write");
}).pipe(toDetailResult);
assertFailure(result, "failed to write keybindings config");
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
+49 -139
View File
@@ -44,7 +44,6 @@ import * as Semaphore from "effect/Semaphore";
import * as ServerConfig from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import { causeErrorTag } from "@t3tools/shared/observability";
import {
DEFAULT_KEYBINDINGS,
DEFAULT_RESOLVED_KEYBINDINGS,
@@ -187,53 +186,23 @@ export interface KeybindingsChangeEvent {
readonly issues: readonly ServerConfigIssue[];
}
const MALFORMED_KEYBINDINGS_CONFIG_MESSAGE =
"Expected the keybindings configuration to be a JSON array.";
const INVALID_KEYBINDING_ENTRY_MESSAGE =
"Expected a keybinding entry with key, command, and optional when fields.";
const INVALID_KEYBINDING_RULE_MESSAGE =
"The keybinding entry contains an invalid shortcut or when expression.";
function trimIssueMessage(message: string): string {
const trimmed = message.trim();
return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
}
function keybindingsCauseLogAttributes(cause: Cause.Cause<unknown>) {
function malformedConfigIssue(detail: string): ServerConfigIssue {
return {
errorTag: causeErrorTag(cause),
causeReasonCount: cause.reasons.length,
causeFailureCount: cause.reasons.filter(Cause.isFailReason).length,
causeDefectCount: cause.reasons.filter(Cause.isDieReason).length,
causeInterruptionCount: cause.reasons.filter(Cause.isInterruptReason).length,
kind: "keybindings.malformed-config",
message: trimIssueMessage(detail),
};
}
function keybindingsValidationInputLogAttributes(value: unknown) {
if (typeof value === "string") {
return { validationInputKind: "string", validationInputSize: value.length };
}
if (Array.isArray(value)) {
return { validationInputKind: "array", validationInputSize: value.length };
}
if (typeof value === "object" && value !== null) {
return {
validationInputKind: "object",
validationInputSize: Object.keys(value).length,
validationHasKeyField: Object.hasOwn(value, "key"),
validationHasCommandField: Object.hasOwn(value, "command"),
validationHasWhenField: Object.hasOwn(value, "when"),
};
}
return { validationInputKind: value === null ? "null" : typeof value };
}
function keybindingsValidationLogAttributes(input: {
readonly stage: "document" | "entry-schema" | "resolved-rule";
readonly value: unknown;
readonly cause: Cause.Cause<unknown>;
readonly index?: number;
}) {
function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
return {
validationStage: input.stage,
...(input.index === undefined ? {} : { entryIndex: input.index }),
...keybindingsValidationInputLogAttributes(input.value),
...keybindingsCauseLogAttributes(input.cause),
kind: "keybindings.invalid-entry",
index,
message: trimIssueMessage(detail),
};
}
@@ -337,7 +306,7 @@ const make = Effect.gen(function* () {
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "access",
detail: "failed to access keybindings config",
cause,
}),
),
@@ -348,7 +317,7 @@ const make = Effect.gen(function* () {
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "read",
detail: "failed to read keybindings config",
cause,
}),
),
@@ -368,24 +337,20 @@ const make = Effect.gen(function* () {
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "decode",
detail: "expected JSON array",
cause,
}),
),
);
return yield* Effect.forEach(rawConfig, (entry, index) =>
return yield* Effect.forEach(rawConfig, (entry) =>
Effect.gen(function* () {
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
...keybindingsValidationLogAttributes({
stage: "entry-schema",
value: entry,
cause: decodedRule.cause,
index,
}),
entry,
error: Cause.pretty(decodedRule.cause),
});
return null;
}
@@ -393,12 +358,8 @@ const make = Effect.gen(function* () {
if (resolved._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
...keybindingsValidationLogAttributes({
stage: "resolved-rule",
value: entry,
cause: resolved.cause,
index,
}),
entry,
error: Cause.pretty(resolved.cause),
});
return null;
}
@@ -421,22 +382,10 @@ const make = Effect.gen(function* () {
const rawConfig = yield* readRawConfig;
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
if (decodedEntries._tag === "Failure") {
yield* Effect.logWarning("ignoring malformed keybindings config", {
path: keybindingsConfigPath,
...keybindingsValidationLogAttributes({
stage: "document",
value: rawConfig,
cause: decodedEntries.cause,
}),
});
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
return {
keybindings: [],
issues: [
{
kind: "keybindings.malformed-config",
message: MALFORMED_KEYBINDINGS_CONFIG_MESSAGE,
},
],
issues: [malformedConfigIssue(detail)],
};
}
@@ -445,38 +394,26 @@ const make = Effect.gen(function* () {
for (const [index, entry] of decodedEntries.value.entries()) {
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
issues.push({
kind: "keybindings.invalid-entry",
index,
message: INVALID_KEYBINDING_ENTRY_MESSAGE,
});
const detail = Cause.pretty(decodedRule.cause);
issues.push(invalidEntryIssue(index, detail));
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
...keybindingsValidationLogAttributes({
stage: "entry-schema",
value: entry,
cause: decodedRule.cause,
index,
}),
index,
entry,
error: detail,
});
continue;
}
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
if (resolvedRule._tag === "Failure") {
issues.push({
kind: "keybindings.invalid-entry",
index,
message: INVALID_KEYBINDING_RULE_MESSAGE,
});
const detail = Cause.pretty(resolvedRule.cause);
issues.push(invalidEntryIssue(index, detail));
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
...keybindingsValidationLogAttributes({
stage: "resolved-rule",
value: entry,
cause: resolvedRule.cause,
index,
}),
index,
entry,
error: detail,
});
continue;
}
@@ -488,14 +425,6 @@ const make = Effect.gen(function* () {
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "encode",
cause,
}),
),
Effect.map((encoded) => `${encoded}\n`),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
@@ -504,16 +433,16 @@ const make = Effect.gen(function* () {
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "write",
cause,
}),
),
),
),
Effect.mapError(
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
detail: "failed to write keybindings config",
cause,
}),
),
);
};
@@ -558,13 +487,7 @@ const make = Effect.gen(function* () {
"skipping startup keybindings default sync because config has issues",
{
path: keybindingsConfigPath,
issueCount: runtimeConfig.issues.length,
malformedConfigIssueCount: runtimeConfig.issues.filter(
(issue) => issue.kind === "keybindings.malformed-config",
).length,
invalidEntryIssueCount: runtimeConfig.issues.filter(
(issue) => issue.kind === "keybindings.invalid-entry",
).length,
issues: runtimeConfig.issues,
},
);
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
@@ -576,7 +499,8 @@ const make = Effect.gen(function* () {
const shortcutConflictWarnings: Array<{
defaultCommand: KeybindingRule["command"];
conflictingCommand: KeybindingRule["command"];
hasWhenContext: boolean;
key: string;
when: string | null;
}> = [];
for (const defaultRule of DEFAULT_KEYBINDINGS) {
if (existingCommands.has(defaultRule.command)) {
@@ -589,7 +513,8 @@ const make = Effect.gen(function* () {
shortcutConflictWarnings.push({
defaultCommand: defaultRule.command,
conflictingCommand: conflictingEntry.command,
hasWhenContext: defaultRule.when !== undefined,
key: defaultRule.key,
when: defaultRule.when ?? null,
});
continue;
}
@@ -600,7 +525,8 @@ const make = Effect.gen(function* () {
path: keybindingsConfigPath,
defaultCommand: conflict.defaultCommand,
conflictingCommand: conflict.conflictingCommand,
hasWhenContext: conflict.hasWhenContext,
key: conflict.key,
when: conflict.when,
reason: "shortcut context already used by existing rule",
});
}
@@ -648,22 +574,13 @@ const make = Effect.gen(function* () {
(cause) =>
new KeybindingsConfigError({
configPath: keybindingsConfigPath,
operation: "prepare-directory",
detail: "failed to prepare keybindings config directory",
cause,
}),
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.void
: Effect.logWarning("keybindings config revalidation failed", {
path: keybindingsConfigPath,
...keybindingsCauseLogAttributes(cause),
}),
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
// Debounce watch events so the file is fully written before we read it.
// Editors emit multiple events per save (truncate, write, rename) and
@@ -680,14 +597,7 @@ const make = Effect.gen(function* () {
);
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.void
: Effect.logWarning("keybindings config watcher failed", {
path: keybindingsConfigPath,
...keybindingsCauseLogAttributes(cause),
}),
),
Effect.ignoreCause({ log: true }),
Effect.forkIn(watcherScope),
Effect.asVoid,
);
@@ -9,6 +9,7 @@ import * as OtlpSerialization from "effect/unstable/observability/OtlpSerializat
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
import * as ServerConfig from "../../config.ts";
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
import { ServerLoggerLive } from "../../serverLogger.ts";
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
@@ -17,6 +18,7 @@ const otlpSerializationLayer = OtlpSerialization.layerJson;
export const ObservabilityLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const attribution = yield* ResourceAttribution.ResourceAttribution;
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
@@ -31,6 +33,14 @@ export const ObservabilityLive = Layer.unwrap(
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
onFlush: (stats) =>
attribution.record({
component: "server-trace",
operation: "append",
logicalWriteBytes: stats.logicalWriteBytes,
count: stats.count,
durationMs: stats.durationMs,
}),
});
const delegate =
config.otlpTracesUrl === undefined
@@ -24,6 +24,7 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
@@ -57,7 +58,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
function isClaudeNativeCommandPath(commandPath: string): boolean {
@@ -82,6 +82,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type ClaudeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -186,7 +187,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -22,7 +22,6 @@
* @module provider/Drivers/CodexDriver
*/
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -32,6 +31,7 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
@@ -60,7 +60,6 @@ import {
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const DRIVER_KIND = ProviderDriverKind.make("codex");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makePackageManagedProviderMaintenanceResolver({
provider: DRIVER_KIND,
npmPackageName: "@openai/codex",
@@ -74,6 +73,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
* registered driver and the runtime satisfies them once.
*/
export type CodexDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -186,7 +186,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -12,7 +12,6 @@
* @module provider/Drivers/CursorDriver
*/
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -21,6 +20,7 @@ import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
@@ -53,7 +53,6 @@ import {
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
@@ -65,6 +64,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
);
export type CursorDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -157,8 +157,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
publishSnapshot,
stampIdentity,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
}).pipe(
Effect.mapError(
(cause) =>
@@ -1,5 +1,4 @@
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -8,6 +7,7 @@ import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
@@ -40,7 +40,6 @@ import {
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const DRIVER_KIND = ProviderDriverKind.make("grok");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeManualOnlyProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
@@ -49,6 +48,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
);
export type GrokDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -134,7 +134,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
publishSnapshot,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
@@ -13,7 +13,6 @@
* @module provider/Drivers/OpenCodeDriver
*/
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -23,6 +22,7 @@ import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderDriverError } from "../Errors.ts";
@@ -55,7 +55,6 @@ import {
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DRIVER_KIND = ProviderDriverKind.make("opencode");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
const normalized = normalizeCommandPath(commandPath);
@@ -78,6 +77,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type OpenCodeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -166,7 +166,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
},
).pipe(
Effect.mapError(
@@ -1354,6 +1354,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const createQuery =
options?.createQuery ??
@@ -1387,7 +1389,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
const logNativeSdkMessage = Effect.fnUntraced(function* (
context: ClaudeSessionContext,
message: SDKMessage,
) {
@@ -3843,6 +3845,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
@@ -1637,7 +1637,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
),
);
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect, it } from "vite-plus/test";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
@@ -24,7 +25,11 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const cursorCliCommandMissingMessage = [
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
});
describe("checkCursorProviderStatus", () => {
it("reports the install docs when the Cursor CLI command is missing", async () => {
const provider = await runNode(
checkCursorProviderStatus({
enabled: true,
binaryPath: missingCursorBinaryPath,
apiEndpoint: "",
customModels: [],
}),
);
expect(provider).toMatchObject({
installed: false,
status: "error",
auth: { status: "unknown" },
message: cursorCliCommandMissingMessage,
});
});
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
"Check server logs for ACP details.",
].join(" ");
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
parameterizedModelPicker: true,
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
return parts.length > 0 ? parts.join(" ") : undefined;
}
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
return [
`Cursor CLI command \`${binaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
].join(" ");
}
export function buildCursorProviderSnapshot(input: {
readonly checkedAt: string;
readonly cursorSettings: CursorSettings;
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
yield* Effect.logWarning("Cursor ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff. Show more