Compare commits

..
Author SHA1 Message Date
Cursor Agent 54bbd4877a fix: remove persistFailure from readiness timeout and gate work on host suspend
- Remove backendOutputLog.persistFailure call from onReadinessFailure handler
  since the backend process is still running during a readiness timeout and
  failure logs should only be written on actual process exit.

- Add hostPower.suspended check to isHostConstrained so background work
  (scoped and opportunistic) is paused when the host is suspended.
2026-06-19 04:28:01 +00:00
Julius Marmingeandcodex 4a875dbe51 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-18 21:20:10 -07:00
Julius Marmingeandcodex 4638de470a 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-18 21:20:09 -07:00
Julius Marmingeandcodex 4ae9d9e9f7 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-18 21:20:09 -07:00
Julius Marmingeandcodex 453e074b55 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-18 21:20:08 -07:00
Ishan 0651af92b8 fix(server): use bound host for MCP endpoint (#3114) 2026-06-18 20:41:14 -07:00
Julius Marminge 52a24c8902 Add origin-based worktree bootstrap option (#3157) 2026-06-18 20:39:52 -07:00
30034ecedc Add archived threads and mobile file viewer (#3155)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-18 20:24:48 -07:00
Mike Olson 1fcc57af13 fix(web): Remove saved environments atomically (#2917) 2026-06-18 20:20:53 -07:00
Julius Marmingeandcodex e95b57dc26 [codex] Rewrite client connection architecture (#2978)
Co-authored-by: codex <[email protected]>
2026-06-18 13:10:32 -07:00
237 changed files with 20297 additions and 3630 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
@@ -54,12 +60,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:
@@ -518,6 +531,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:
@@ -525,6 +551,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]
@@ -579,6 +612,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
@@ -54,6 +54,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,
@@ -54,6 +54,7 @@ function makeHarness(input: { readonly isDevelopment: boolean }): CloudAuthHarne
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: (protocol, path, args) =>
Effect.sync(() => {
+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)),
+147 -31
View File
@@ -21,8 +21,10 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
@@ -30,14 +32,13 @@ export interface RotatingLogFileWriter {
}
export interface DesktopBackendOutputLogShape {
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
readonly discardSession: Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
@@ -113,10 +114,84 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
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 currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
@@ -301,45 +376,86 @@ const backendOutputLogLayer = Layer.effect(
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
return Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn(
"desktop.observability.backendOutput.writeSessionBoundary",
)(function* ({ phase, details }) {
onSome: (logFile) => {
return {
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
details,
}) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
yield* Ref.set(
sessionRef,
Option.some({
runId,
phase,
details: sanitizeLogValue(details),
},
});
startDetails: sanitizeLogValue(details),
chunks: [],
byteLength: 0,
}),
);
}),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
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;
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
message: "backend child process failure output start",
level: "ERROR",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
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: output.streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
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),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
discardSession: Ref.set(sessionRef, Option.none()),
} satisfies DesktopBackendOutputLogShape;
},
});
}),
);
@@ -41,6 +41,7 @@ function makeEnvironmentLayer(
options?: {
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly resourcesPath?: string;
},
) {
return DesktopEnvironment.layer({
@@ -51,7 +52,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(
@@ -192,4 +193,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)),
);
});
@@ -56,6 +56,42 @@ const { logWarning: logBackendConfigurationWarning } = DesktopObservability.make
"desktop-backend-configuration",
);
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.Effect<
BackendObservabilitySettings,
never,
@@ -89,6 +125,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,
@@ -115,6 +152,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 }),
@@ -156,9 +199,14 @@ export const layer = Layer.effect(
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 Deferred from "effect/Deferred";
@@ -23,11 +24,15 @@ 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 encodeDesktopTelemetryControl = Schema.encodeSync(
Schema.fromJsonString(DesktopTelemetryControlMessage),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -43,6 +48,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,
@@ -59,6 +66,7 @@ function makeProcess(options?: {
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
@@ -70,7 +78,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),
});
}
@@ -107,6 +115,7 @@ function makeManagerLayer(input: {
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly desktopState?: DesktopState.DesktopStateShape;
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindowShape>;
readonly desktopTelemetryPublisher?: Partial<DesktopTelemetryPublisher.DesktopTelemetryPublisherShape>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
}) {
return DesktopBackendManager.layer.pipe(
@@ -120,12 +129,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.DesktopBackendOutputLogShape),
Layer.succeed(DesktopWindow.DesktopWindow, {
@@ -184,8 +202,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),
},
});
@@ -208,6 +225,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,
@@ -218,6 +237,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> = [];
@@ -255,8 +356,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),
},
});
@@ -289,6 +389,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,
@@ -320,6 +422,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* () {
@@ -339,6 +450,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));
@@ -352,6 +465,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(
@@ -371,6 +485,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* () {
@@ -378,6 +495,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);
@@ -434,6 +552,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);
@@ -16,17 +16,21 @@ 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 { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
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);
@@ -35,6 +39,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;
@@ -88,6 +93,10 @@ class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnErro
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
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>;
@@ -224,6 +233,7 @@ function drainBackendOutput(
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
@@ -233,6 +243,23 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
);
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"],
@@ -247,23 +274,47 @@ 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,
},
);
const handle = yield* spawner
.spawn(command)
.pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
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) {
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
outputFibers.push(
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped),
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped),
);
}
yield* waitForHttpReady(
options.httpBaseUrl,
@@ -274,7 +325,12 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.forkScoped,
);
return describeProcessExit(yield* Effect.result(handle.exitCode));
const exit = describeProcessExit(yield* Effect.result(handle.exitCode));
yield* Effect.forEach(outputFibers, Fiber.await, {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
return exit;
});
const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
@@ -283,6 +339,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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;
@@ -419,10 +476,13 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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);
}
@@ -436,13 +496,14 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
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}`,
});
}),
@@ -475,10 +536,13 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
function* (error) {
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
});
},
),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -589,7 +653,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
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
@@ -30,6 +30,7 @@ export interface ElectronAppShape {
) => 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,
@@ -101,6 +102,7 @@ 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);
+4
View File
@@ -19,6 +19,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 DesktopSecretStorage from "./electron/ElectronSafeStorage.ts";
import * as ElectronShell from "./electron/ElectronShell.ts";
@@ -45,6 +46,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 PreviewBrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -104,6 +106,7 @@ const electronLayer = Layer.mergeAll(
ElectronApp.layer,
ElectronDialog.layer,
ElectronMenu.layer,
ElectronPowerMonitor.layer,
ElectronProtocol.layer,
DesktopSecretStorage.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),
);
+52
View File
@@ -128,6 +128,58 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
const loadURL = vi.fn(async () => undefined);
const listeners = new Map<string, (...args: never[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "about:blank",
getTitle: () => "",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.navigate("tab_pending", "localhost:3200");
expect(yield* manager.automationStatus("tab_pending")).toEqual({
available: false,
visible: true,
tabId: "tab_pending",
url: "http://localhost:3200/",
title: "",
loading: true,
});
yield* manager.registerWebview("tab_pending", 42);
yield* Effect.yieldNow;
expect(loadURL).toHaveBeenCalledOnce();
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
+89 -12
View File
@@ -1195,26 +1195,103 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
Effect.ignore,
);
}
yield* update(tabId, {
webContentsId,
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor: tab.zoomFactor,
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) {
return [
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
tabs,
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const next: PreviewTabState = {
...current,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
updatedAt: registeredAt,
};
return [
Option.some({
state: next,
pendingUrl,
}),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
if (Option.isNone(registration)) {
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt("registerWebview.restoreZoom", () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt("registerWebview.sendTheme", () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
if (
pendingUrl &&
latestNavStatus?.kind === "Loading" &&
latestNavStatus.url === pendingUrl &&
wc.getURL() !== pendingUrl
) {
runFork(
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
Effect.ignore,
),
);
}
});
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
const wc = yield* requireWebContents(tabId);
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
const updatedAt = yield* currentIso;
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
const next: PreviewTabState = {
tabId,
webContentsId: current?.webContentsId ?? null,
navStatus: {
kind: "Loading",
url,
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
},
canGoBack: current?.canGoBack ?? false,
canGoForward: current?.canGoForward ?? false,
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
controller: current?.controller ?? "none",
updatedAt,
};
return [
next,
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
yield* attempt("navigate.reload", () => wc.reload());
return;
@@ -272,6 +272,26 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
withSavedEnvironments(
Effect.gen(function* () {
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
yield* savedEnvironments.setSecret({
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
});
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
assert.isTrue(
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
);
}),
),
);
it.effect("treats empty saved environment documents as empty", () =>
withSavedEnvironments(
Effect.gen(function* () {
@@ -121,6 +121,9 @@ export interface DesktopSavedEnvironmentsShape {
readonly setRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly removeEnvironment: (
environmentId: string,
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
readonly getSecret: (
environmentId: string,
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
@@ -293,6 +296,23 @@ export const layer = Layer.effect(
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
}),
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
fileSystem,
environment.savedEnvironmentRegistryPath,
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
if (!document.records.some((record) => record.environmentId === environmentId)) {
return;
}
yield* writeDocument({
version: document.version,
records: document.records.filter((record) => record.environmentId !== environmentId),
});
},
),
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
yield* Effect.annotateCurrentSpan({ environmentId });
const document = yield* readRegistryDocument(
@@ -385,6 +405,18 @@ export const layerTest = (input?: {
return DesktopSavedEnvironments.of({
getRegistry: Ref.get(recordsRef),
setRegistry: (records) => Ref.set(recordsRef, records),
removeEnvironment: (environmentId) =>
Ref.update(recordsRef, (records) =>
records.filter((record) => record.environmentId !== environmentId),
).pipe(
Effect.andThen(
Ref.update(secretsRef, (secrets) => {
const nextSecrets = new Map(secrets);
nextSecrets.delete(environmentId);
return nextSecrets;
}),
),
),
getSecret: (environmentId) =>
Ref.get(secretsRef).pipe(
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
@@ -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.ElectronAppShape);
}
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,
@@ -70,7 +70,12 @@ static void T3MarkdownTextApplyAttachments(
renderingMode:UIImageRenderingModeAlwaysOriginal];
}
attachment.image = image ?: [[UIImage alloc] init];
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -80,104 +85,6 @@ static void T3MarkdownTextApplyAttachments(
}
}
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
NSMutableAttributedString *attributedString,
const std::vector<T3MarkdownTextChipRange> &chipRanges)
{
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
for (const auto &chipRange : chipRanges) {
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
continue;
}
const NSRange range = NSMakeRange(
chipRange.location,
MIN(chipRange.length, attributedString.length - chipRange.location));
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
atIndex:range.location
effectiveRange:nil];
if (color == nil) {
continue;
}
[backgrounds addObject:@{
@"range": [NSValue valueWithRange:range],
@"color": color,
@"strokeColor": [foregroundColor
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
}];
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
return backgrounds;
}
@interface T3MarkdownTextBackingView : UITextView
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
@end
@implementation T3MarkdownTextBackingView
- (void)drawRect:(CGRect)rect
{
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
CGContextRef context = UIGraphicsGetCurrentContext();
if (context != nil) {
CGContextSaveGState(context);
CGContextResetClip(context);
CGContextClipToRect(context, self.bounds);
}
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
const NSRange characterRange = [background[@"range"] rangeValue];
UIColor *color = background[@"color"];
UIColor *strokeColor = background[@"strokeColor"];
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
continue;
}
const NSRange glyphRange =
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
[color setFill];
[self.layoutManager
enumerateEnclosingRectsForGlyphRange:glyphRange
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
inTextContainer:self.textContainer
usingBlock:^(CGRect glyphRect, BOOL *stop) {
const CGFloat chipHeight = 22;
CGRect chipRect = CGRectMake(
glyphRect.origin.x - 4,
CGRectGetMidY(glyphRect) - chipHeight / 2,
glyphRect.size.width + 8,
chipHeight);
chipRect.origin.x += self.textContainerInset.left;
chipRect.origin.y += self.textContainerInset.top;
const CGFloat minimumX = self.textContainerInset.left + 0.5;
const CGFloat maximumX =
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
if (chipRect.origin.x < minimumX) {
chipRect.size.width -= minimumX - chipRect.origin.x;
chipRect.origin.x = minimumX;
}
if (CGRectGetMaxX(chipRect) > maximumX) {
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
}
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
[path fill];
[strokeColor setStroke];
path.lineWidth = 1;
[path stroke];
}];
}
if (context != nil) {
CGContextRestoreGState(context);
}
[super drawRect:rect];
}
@end
@protocol T3MarkdownOutsideTapTarget <NSObject>
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
@end
@@ -285,7 +192,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
@implementation T3MarkdownText {
UIView * _view;
T3MarkdownTextBackingView * _textView;
UITextView * _textView;
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
__weak UIWindow * _outsideTapWindow;
BOOL _suppressSelectionChange;
@@ -308,7 +215,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
self.contentView = _view;
self.clipsToBounds = true;
_textView = [[T3MarkdownTextBackingView alloc] init];
_textView = [[UITextView alloc] init];
_attachmentImages = [[NSMutableDictionary alloc] init];
_pendingAttachmentUris = [[NSMutableSet alloc] init];
_textView.scrollEnabled = false;
@@ -405,9 +312,6 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
convertedAttrString,
_state->getData().attachmentRanges,
_attachmentImages);
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
convertedAttrString,
_state->getData().chipRanges);
[self loadAttachmentImages:_state->getData().attachmentRanges];
// Setting attributedText clears any active text selection, and re-assigning
@@ -28,18 +28,20 @@ struct T3MarkdownTextAttachmentRange {
std::string imageUri;
};
struct T3MarkdownTextChipRange {
size_t location;
size_t length;
bool isSkill;
};
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
return 14;
}
inline Float T3MarkdownTextAttachmentBaselineOffset(
const T3MarkdownTextAttachmentRange &) {
return -2;
}
class T3MarkdownTextStateReal final {
public:
AttributedString attributedString;
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
std::vector<T3MarkdownTextChipRange> chipRanges;
};
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
@@ -72,6 +74,5 @@ private:
mutable AttributedString _attributedString;
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
};
} // namespace facebook::React
@@ -9,9 +9,8 @@
namespace facebook::react {
static constexpr Float ParagraphStyleEncodingOffset = 1000;
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
static void applyParagraphStyles(
NSMutableAttributedString *attributedString,
@@ -58,7 +57,12 @@ static void applyAttachments(
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage alloc] init];
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
attachment.bounds = CGRectMake(
0,
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
attachmentSize,
attachmentSize);
const NSRange range = NSMakeRange(
attachmentRange.location,
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
@@ -91,7 +95,6 @@ Size T3MarkdownTextShadowNode::measureContent(
auto baseAttributedString = AttributedString{};
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
size_t utf16Offset = 0;
const auto &children = getChildren();
for (size_t i = 0; i < children.size(); i++) {
@@ -184,25 +187,19 @@ Size T3MarkdownTextShadowNode::measureContent(
props.shadowRadius - ParagraphStyleEncodingOffset,
});
}
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
chipRanges.push_back(T3MarkdownTextChipRange{
utf16Offset,
fragmentLength,
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
});
}
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset + 1,
utf16Offset,
1,
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
});
} else if (
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
utf16Offset + 1,
utf16Offset,
1,
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
props.nativeId.substr(
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
});
}
utf16Offset += fragmentLength;
@@ -213,7 +210,6 @@ Size T3MarkdownTextShadowNode::measureContent(
_attributedString = baseAttributedString;
_paragraphStyleRanges = paragraphStyleRanges;
_attachmentRanges = attachmentRanges;
_chipRanges = chipRanges;
NSMutableAttributedString *convertedAttributedString =
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
@@ -263,7 +259,6 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
_attributedString,
_paragraphStyleRanges,
_attachmentRanges,
_chipRanges,
});
}
}
@@ -40,11 +40,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
@@ -312,6 +314,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const rows = collectTableRows(props.node);
return (
@@ -351,6 +354,7 @@ function NativeTable(props: {
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
))}
@@ -364,10 +368,17 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const href = props.node.href;
if (!href) {
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
return (
@@ -426,6 +437,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<View style={{ gap: 8 }}>
@@ -435,9 +447,15 @@ function NativeMixedParagraph(props: {
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
<SelectableNode
key={nodeKey(child, index)}
node={child}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
),
)}
</View>
@@ -448,6 +466,7 @@ function NativeList(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth: number;
}) {
const ordered = props.node.ordered ?? false;
@@ -508,6 +527,7 @@ function NativeList(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={props.depth + 1}
compact
/>
@@ -524,6 +544,7 @@ export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
readonly depth?: number;
readonly compact?: boolean;
}) {
@@ -538,6 +559,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
))}
@@ -553,9 +575,21 @@ export function NativeMarkdownBlock(props: {
/>
);
case "table":
return <NativeTable node={props.node} textStyle={props.textStyle} />;
return (
<NativeTable
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "image":
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
return (
<NativeMarkdownImage
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "horizontal_rule":
return (
<View
@@ -583,6 +617,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -595,14 +630,23 @@ export function NativeMarkdownBlock(props: {
node={props.node}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
/>
);
case "paragraph":
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
<NativeMixedParagraph
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode node={props.node} textStyle={props.textStyle} />
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
case "html_block":
case "math_block":
@@ -618,7 +662,11 @@ export function NativeMarkdownBlock(props: {
: "transparent",
}}
>
<SelectableNode node={props.node} textStyle={props.textStyle} />
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
</View>
);
case "table_head":
@@ -635,6 +683,7 @@ export function NativeMarkdownBlock(props: {
node={child}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
depth={depth}
compact
/>
@@ -642,6 +691,12 @@ export function NativeMarkdownBlock(props: {
</View>
);
default:
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
return (
<SelectableNode
node={props.node}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
);
}
}
@@ -1,61 +1,15 @@
import { useEffect, useMemo, useState } from "react";
import { Asset } from "expo-asset";
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import { markdownFileIconSource } from "./markdownFileIcons";
import type { MarkdownFileIcon } from "./markdownLinks";
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
const EXTERNAL_LINK_PREFIX = "◉ ";
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
const CHIP_SUFFIX = "\u00A0";
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
const iconSignature = JSON.stringify(
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
);
const icons = useMemo(
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
[iconSignature],
);
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
useEffect(() => {
let cancelled = false;
void Promise.all(
icons.map(async (icon) => {
const source = markdownFileIconSource(icon);
const fallbackUri = Image.resolveAssetSource(source).uri;
if (typeof source !== "number" && typeof source !== "string") {
return [icon, fallbackUri] as const;
}
try {
const asset = Asset.fromModule(source);
await asset.downloadAsync();
return [icon, asset.localUri ?? fallbackUri] as const;
} catch {
return [icon, fallbackUri] as const;
}
}),
).then((entries) => {
if (!cancelled) {
setUris(new Map(entries));
}
});
return () => {
cancelled = true;
};
}, [icons]);
return uris;
}
function runKeySignature(run: NativeMarkdownTextRun): string {
return [
run.text,
@@ -81,13 +35,16 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
const isFile = run.fileIcon != null;
const isSkill = run.skillName != null;
const isChip = isFile || isSkill;
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
const isHeading = run.role === "heading";
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
const hasParagraphStyle = run.headIndent !== undefined;
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
const textDecorationLine = run.strikethrough
? "line-through"
: run.href && !isFile
? "underline"
: "none";
return {
color: isFile
@@ -106,20 +63,23 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? textStyle.mutedColor
: run.role === "list-marker"
? textStyle.mutedColor
: run.code || isFile
: isCodeBlock
? textStyle.codeColor
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily: isChip
? "DMSans_500Medium"
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
: run.code
? textStyle.inlineCodeColor
: run.bold
? textStyle.strongColor
: textStyle.color,
fontFamily:
isFile || isSkill
? textStyle.boldFontFamily
: run.code || isCodeBlock
? "ui-monospace"
: isHeading
? textStyle.headingFontFamily
: run.bold
? textStyle.boldFontFamily
: textStyle.fontFamily,
fontSize:
run.role === "spacer"
? (run.spacing ?? 10)
@@ -129,7 +89,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? headingFontSize
: run.role === "code-language"
? 11
: run.code || isChip || isCodeBlock
: run.code || isCodeBlock
? Math.max(12, textStyle.fontSize - 2)
: textStyle.fontSize,
lineHeight:
@@ -143,17 +103,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
? 18
: textStyle.lineHeight,
fontStyle: run.italic ? "italic" : "normal",
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
textDecorationLine,
backgroundColor: isCodeBlock
? textStyle.codeBlockBackgroundColor
: isSkill
? textStyle.skillBackgroundColor
: run.code
? textStyle.codeBackgroundColor
: isFile
? textStyle.fileBackgroundColor
: undefined,
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
...(hasParagraphStyle
? {
shadowColor: "transparent",
@@ -170,9 +122,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
export function NativeMarkdownSelectableText(props: {
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
const colorScheme = useColorScheme();
const fileIconUris = useFileIconUris(props.runs);
const occurrences = new Map<string, number>();
const prefixedExternalLinks = new Set<string>();
const keyedRuns = props.runs.map((run) => {
@@ -182,9 +134,9 @@ export function NativeMarkdownSelectableText(props: {
let text = run.text;
if (run.fileIcon) {
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
} else if (run.skillName && run.skillLabel) {
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
prefixedExternalLinks.add(run.href);
text = `${EXTERNAL_LINK_PREFIX}${text}`;
@@ -200,12 +152,11 @@ export function NativeMarkdownSelectableText(props: {
props.textStyle.strongColor,
props.textStyle.mutedColor,
props.textStyle.linkColor,
props.textStyle.inlineCodeColor,
props.textStyle.codeColor,
props.textStyle.codeBackgroundColor,
props.textStyle.codeBlockBackgroundColor,
props.textStyle.fileBackgroundColor,
props.textStyle.fileTextColor,
props.textStyle.skillBackgroundColor,
props.textStyle.skillTextColor,
props.textStyle.quoteMarkerColor,
props.textStyle.dividerColor,
@@ -217,7 +168,8 @@ export function NativeMarkdownSelectableText(props: {
uiTextView
selectable
style={{
width: "100%",
flexShrink: 1,
minWidth: 0,
color: props.textStyle.color,
fontFamily: props.textStyle.fontFamily,
fontSize: props.textStyle.fontSize,
@@ -231,19 +183,20 @@ export function NativeMarkdownSelectableText(props: {
key={key}
nativeID={
run.fileIcon
? `t3-chip-file:${
fileIconUris.get(run.fileIcon) ??
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
}`
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
: run.skillName
? "t3-chip-skill:sf:cube"
? "t3-skill:sf:cube"
: undefined
}
style={runStyle(run, props.textStyle)}
onPress={
href
? () => {
void Linking.openURL(href);
if (props.onLinkPress) {
props.onLinkPress(href);
} else {
void Linking.openURL(href);
}
}
: undefined
}
@@ -6,6 +6,7 @@ import {
nativeMarkdownChunkSpacing,
nativeMarkdownDocumentChunks,
nativeMarkdownDocumentRuns,
nativeMarkdownWithPreservedSoftBreaks,
} from "./nativeMarkdownText";
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
@@ -33,15 +34,20 @@ export function SelectableMarkdownText({
skills = EMPTY_SKILLS,
textStyle,
highlightCode,
preserveSoftBreaks = false,
onLinkPress,
marginTop = 0,
marginBottom = 0,
}: SelectableMarkdownTextProps) {
const chunks = useMemo(() => {
const document = parseMarkdownWithOptions(markdown, {
const parsedDocument = parseMarkdownWithOptions(markdown, {
gfm: true,
html: true,
math: false,
});
const document = preserveSoftBreaks
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
: parsedDocument;
return nativeMarkdownDocumentChunks(document).map((chunk) =>
chunk.kind === "selectable"
? {
@@ -50,10 +56,14 @@ export function SelectableMarkdownText({
}
: chunk,
);
}, [markdown, skills]);
}, [markdown, preserveSoftBreaks, skills]);
return (
<View style={{ width: "100%", marginTop, marginBottom }}>
// A percentage width here creates a cyclic intrinsic measurement inside
// shrink-to-fit containers such as user-message bubbles. Yoga then gives
// the native text node an unbounded second pass and the parent only clips
// the resulting single-line width instead of reflowing it.
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
{chunks.map((chunk, index) => {
const content =
chunk.kind === "rich" ? (
@@ -61,9 +71,14 @@ export function SelectableMarkdownText({
node={chunk.node}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
/>
) : (
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
<NativeMarkdownSelectableText
runs={chunk.runs}
textStyle={textStyle}
onLinkPress={onLinkPress}
/>
);
return (
@@ -3,12 +3,11 @@ export interface NativeMarkdownTextStyle {
readonly strongColor: string;
readonly mutedColor: string;
readonly linkColor: string;
readonly inlineCodeColor: string;
readonly codeColor: string;
readonly codeBackgroundColor: string;
readonly codeBlockBackgroundColor: string;
readonly fileBackgroundColor: string;
readonly fileTextColor: string;
readonly skillBackgroundColor: string;
readonly skillTextColor: string;
readonly quoteMarkerColor: string;
readonly dividerColor: string;
@@ -41,6 +40,8 @@ export interface SelectableMarkdownTextProps {
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly preserveSoftBreaks?: boolean;
readonly onLinkPress?: (href: string) => void;
readonly marginTop?: number;
readonly marginBottom?: number;
}
@@ -27,8 +27,12 @@ export type MarkdownLinkPresentation =
}
| {
readonly kind: "file";
readonly href: string;
readonly icon: MarkdownFileIcon;
readonly label: string;
readonly path: string;
readonly line?: number;
readonly column?: number;
}
| {
readonly kind: "link";
@@ -247,7 +251,7 @@ function normalizeDestination(value: string): string {
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
}
function fileUrlPath(href: string): string | null {
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
try {
const parsed = new URL(href);
if (parsed.protocol.toLowerCase() !== "file:") {
@@ -256,15 +260,44 @@ function fileUrlPath(href: string): string | null {
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
? parsed.pathname.slice(1)
: parsed.pathname;
const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
return `${safeDecode(path)}${
lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
}`;
return { path, hash: parsed.hash };
} catch {
return null;
}
}
function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
const hashIndex = value.indexOf("#");
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
const queryIndex = pathWithSearch.indexOf("?");
return {
path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
hash,
};
}
function splitFilePosition(
path: string,
hash: string,
): { readonly path: string; readonly line?: number; readonly column?: number } {
const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
const match = suffixMatch ?? hashMatch;
if (!match?.[1]) {
return { path };
}
const line = Number.parseInt(match[1], 10);
const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
return {
path: pathWithoutPosition,
...(line > 0 ? { line } : {}),
...(column !== undefined && column > 0 ? { column } : {}),
};
}
function looksLikePosixFilesystemPath(path: string): boolean {
if (!path.startsWith("/")) {
return false;
@@ -331,14 +364,31 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
// Relative paths and non-URL link destinations are handled below.
}
const fileTarget = normalized.toLowerCase().startsWith("file:")
? fileUrlPath(normalized)
: safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
if (fileTarget && looksLikeFilePath(fileTarget)) {
const source = normalized.toLowerCase().startsWith("file:")
? fileUrlTarget(normalized)
: stripSearchAndHash(normalized);
const decodedSource = source
? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
: null;
const fileTarget = decodedSource
? splitFilePosition(decodedSource.path, decodedSource.hash)
: null;
const targetWithPosition = fileTarget
? `${fileTarget.path}${
fileTarget.line
? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
: ""
}`
: null;
if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
return {
kind: "file",
icon: resolveMarkdownFileIcon(fileTarget),
label: fileLabel(fileTarget),
href: normalized,
icon: resolveMarkdownFileIcon(fileTarget.path),
label: fileLabel(targetWithPosition),
path: fileTarget.path,
...(fileTarget.line ? { line: fileTarget.line } : {}),
...(fileTarget.column ? { column: fileTarget.column } : {}),
};
}
@@ -293,6 +293,7 @@ function appendNode(
if (presentation.kind === "file") {
return appendRun(runs, presentation.label, {
...context,
href: presentation.href,
fileIcon: presentation.icon,
});
}
@@ -319,6 +320,15 @@ export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<Native
return appendChildren([], node, EMPTY_CONTEXT);
}
export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
return {
...node,
...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
...(children ? { children } : {}),
};
}
function appendBlockTerminator(
runs: NativeMarkdownTextRun[],
context: RunContext,
@@ -57,6 +57,10 @@ public class T3ReviewDiffModule: Module {
view.setContentWidth(CGFloat(contentWidth))
}
Prop("initialRowIndex") { (view: T3ReviewDiffView, initialRowIndex: Double) in
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
}
}
@@ -205,7 +205,7 @@ private struct ReviewDiffNativeStyle {
ReviewDiffNativeStyle(
rowHeight: metric(payload?.rowHeight, fallback: 24),
contentWidth: metric(payload?.contentWidth, fallback: 2800),
changeBarWidth: metric(payload?.changeBarWidth, fallback: 4),
changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
codePadding: metric(payload?.codePadding, fallback: 8),
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
@@ -243,6 +243,13 @@ private struct ReviewDiffNativeStyle {
return CGFloat(value)
}
private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
guard let value, value.isFinite, value >= 0 else {
return fallback
}
return CGFloat(value)
}
private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
switch value?.lowercased() {
case "ultralight", "ultra-light":
@@ -316,6 +323,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
private var initialRowIndex: Int?
private var hasAppliedInitialRowIndex = false
let onDebug = EventDispatcher()
let onToggleFile = EventDispatcher()
@@ -394,6 +403,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
do {
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
contentView.rows = rows
hasAppliedInitialRowIndex = false
emitDebug("rows-decoded", [
"rows": rows.count,
"firstKind": rows.first?.kind ?? "none",
@@ -402,6 +412,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
} catch {
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
@@ -561,6 +572,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
applyInitialRowIndexIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -645,6 +657,19 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyStyle()
}
func setInitialRowIndex(_ initialRowIndex: Double) {
let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
? Int(initialRowIndex.rounded(.down))
: nil
guard nextIndex != self.initialRowIndex else {
return
}
self.initialRowIndex = nextIndex
hasAppliedInitialRowIndex = false
applyInitialRowIndexIfNeeded()
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -662,6 +687,22 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
}
private func applyInitialRowIndexIfNeeded() {
guard !hasAppliedInitialRowIndex,
let initialRowIndex,
bounds.height > 0,
let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
return
}
let targetScreenY = max(0, (bounds.height - rowFrame.height) * 0.3)
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
let targetOffset = min(max(rowFrame.minY - targetScreenY, 0), maxOffset)
hasAppliedInitialRowIndex = true
scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
updateViewportFrame()
}
}
private enum ReviewDiffHorizontalPanKind {
@@ -820,6 +861,19 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return style.rowHeight
}
func frameForRow(at index: Int) -> CGRect? {
guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
return nil
}
return CGRect(
x: 0,
y: rowOffsets[index],
width: max(viewportWidth, 1),
height: height(for: rows[index])
)
}
private func rebuildRowLayout() {
var nextOffsets: [CGFloat] = []
var nextFileHeaderRowIndices: [Int] = []
+1
View File
@@ -101,6 +101,7 @@
"react-native-screens": "4.25.2",
"react-native-shiki-engine": "^0.3.12",
"react-native-svg": "15.15.4",
"react-native-webview": "^13.16.1",
"react-native-worklets": "0.8.3",
"shiki": "4.2.0",
"tailwind-merge": "^3.5.0",
+3 -2
View File
@@ -30,10 +30,11 @@ import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
const clerkRouteIsActive = pathname === "/settings/auth";
const expandedSettingsRouteIsActive =
pathname === "/settings/archive" || pathname === "/settings/auth";
return (
<ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
+88 -89
View File
@@ -1,13 +1,33 @@
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Text as RNText, View } from "react-native";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { useProjects, useThreadShells } from "../state/entities";
import { useWorkspaceState } from "../state/workspace";
import { buildThreadRoutePath } from "../lib/routes";
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
import { HomeScreen } from "../features/home/HomeScreen";
import { useThemeColor } from "../lib/useThemeColor";
import { HomeHeader } from "../features/home/HomeHeader";
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
import { useThreadListActions } from "../features/home/useThreadListActions";
interface HomeListOptions {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -18,103 +38,82 @@ export default function HomeRouteScreen() {
const { savedConnectionsById } = useSavedRemoteConnections();
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const [listOptions, setListOptions] = useState<HomeListOptions>({
selectedEnvironmentId: null,
projectSortOrder:
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
? "updated_at"
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
});
const { archiveThread, confirmDeleteThread } = useThreadListActions();
const environments = useMemo(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(
Order.String,
(environment: { readonly label: string }) => environment.label,
),
),
[savedConnectionsById],
);
const selectedEnvironmentId = environments.some(
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
)
? listOptions.selectedEnvironmentId
: null;
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
}, []);
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
setListOptions((current) => ({ ...current, projectSortOrder }));
}, []);
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
setListOptions((current) => ({ ...current, threadSortOrder }));
}, []);
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
setListOptions((current) => ({ ...current, projectGroupingMode }));
}, []);
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
allowToolbarIntegration: true,
},
}}
<HomeHeader
environments={environments}
selectedEnvironmentId={selectedEnvironmentId}
projectSortOrder={listOptions.projectSortOrder}
threadSortOrder={listOptions.threadSortOrder}
projectGroupingMode={listOptions.projectGroupingMode}
onEnvironmentChange={setSelectedEnvironmentId}
onOpenSettings={() => router.push("/settings")}
onProjectGroupingModeChange={setProjectGroupingMode}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => router.push("/new")}
onThreadSortOrderChange={setThreadSortOrder}
/>
{/* Header left: plain text, no Liquid Glass button chrome */}
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: mutedColor,
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="gearshape"
onPress={() => router.push("/settings")}
separateBackground
/>
</Stack.Toolbar>
{/* Bottom toolbar: search + compose, visually split like iMessage */}
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
icon="square.and.pencil"
onPress={() => router.push("/new")}
separateBackground
/>
</Stack.Toolbar>
<HomeScreen
projects={projects}
threads={threads}
catalogState={catalogState}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
onAddConnection={() => router.push("/connections/new")}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onOpenEnvironments={() => router.push("/settings/environments")}
onSelectThread={(thread) => {
router.push(buildThreadRoutePath(thread));
}}
projectGroupingMode={listOptions.projectGroupingMode}
projects={projects}
projectSortOrder={listOptions.projectSortOrder}
savedConnectionsById={savedConnectionsById}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
threads={threads}
threadSortOrder={listOptions.threadSortOrder}
/>
</>
);
+7 -2
View File
@@ -14,7 +14,7 @@ export default function SettingsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
const handleClerkRouteTransitionEnd = useCallback(
const handleExpandedRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
@@ -47,9 +47,14 @@ export default function SettingsLayout() {
name="waitlist"
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
<Stack.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleClerkRouteTransitionEnd }}
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
+3
View File
@@ -0,0 +1,3 @@
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
export default ArchivedThreadsRouteScreen;
+16 -2
View File
@@ -65,6 +65,8 @@ function LocalSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -374,6 +376,8 @@ function ConfiguredSettingsRouteScreen() {
/>
</SettingsSection>
<ArchivedThreadsSettingsSection />
<AppSettingsSection />
</ScrollView>
</View>
@@ -416,12 +420,20 @@ function AppSettingsSection() {
);
}
function ArchivedThreadsSettingsSection() {
return (
<SettingsSection title="Threads">
<SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
</SettingsSection>
);
}
function SettingsRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly value?: string;
readonly href?: "/settings/environments";
readonly href?: "/settings/archive" | "/settings/environments";
readonly onPress?: () => void;
}) {
const icon = useThemeColor("--color-icon");
@@ -459,7 +471,9 @@ function SettingsRow(props: {
if (props.href) {
return (
<Link href={props.href} asChild>
<Pressable>{content}</Pressable>
<Pressable accessibilityLabel={props.label} accessibilityRole="button">
{content}
</Pressable>
</Link>
);
}
@@ -55,6 +55,32 @@ export default function ThreadLayout() {
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/index"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/[...path]"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
@@ -0,0 +1,5 @@
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFileRoute() {
return <ThreadFileScreen />;
}
@@ -0,0 +1,5 @@
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFilesIndexRoute() {
return <ThreadFilesTreeScreen />;
}
@@ -0,0 +1,93 @@
import { useEffect, useState } from "react";
import { View } from "react-native";
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withRepeat,
withTiming,
} from "react-native-reanimated";
const INDICATOR_WIDTH_FRACTION = 0.3;
const MIN_INDICATOR_WIDTH = 48;
function LoadingStripFrame(props: {
readonly children: React.ReactNode;
readonly onLayout?: (width: number) => void;
}) {
return (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden"
onLayout={
props.onLayout
? (event) => {
props.onLayout?.(event.nativeEvent.layout.width);
}
: undefined
}
>
{props.children}
</View>
);
}
function IndeterminateLoadingStrip() {
const [containerWidth, setContainerWidth] = useState(0);
const travelProgress = useSharedValue(0);
const indicatorWidth = Math.max(MIN_INDICATOR_WIDTH, containerWidth * INDICATOR_WIDTH_FRACTION);
useEffect(() => {
travelProgress.value = 0;
travelProgress.value = withRepeat(
withTiming(1, {
duration: 1100,
easing: Easing.inOut(Easing.quad),
}),
-1,
false,
);
return () => {
cancelAnimation(travelProgress);
};
}, [travelProgress]);
const indicatorStyle = useAnimatedStyle(
() => ({
transform: [
{
translateX: (containerWidth + indicatorWidth) * travelProgress.value - indicatorWidth,
},
],
width: indicatorWidth,
}),
[containerWidth, indicatorWidth],
);
return (
<LoadingStripFrame onLayout={setContainerWidth}>
<Animated.View className="h-full rounded-full bg-primary" style={indicatorStyle} />
</LoadingStripFrame>
);
}
export function LoadingStrip(props: { readonly progress?: number }) {
if (props.progress === undefined) {
return <IndeterminateLoadingStrip />;
}
const clampedProgress = Math.min(1, Math.max(0, props.progress));
return (
<LoadingStripFrame>
<View
className="h-full rounded-r-full bg-primary"
style={{ width: `${clampedProgress * 100}%` }}
/>
</LoadingStripFrame>
);
}
@@ -0,0 +1,95 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { useArchivedThreadListActions } from "../home/useThreadListActions";
import {
ArchivedThreadsScreen,
type ArchivedThreadsHeaderEnvironment,
} from "./ArchivedThreadsScreen";
import { buildArchivedThreadGroups, type ArchivedThreadSortOrder } from "./archivedThreadList";
import {
refreshArchivedThreadsForEnvironment,
useArchivedThreadSnapshots,
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
const [sortOrder, setSortOrder] = useState<ArchivedThreadSortOrder>("newest");
const environments = useMemo<ReadonlyArray<ArchivedThreadsHeaderEnvironment>>(
() =>
Arr.sort(
Object.values(savedConnectionsById).map((connection) => ({
environmentId: connection.environmentId,
label: connection.environmentLabel,
})),
Order.mapInput(Order.String, (environment: ArchivedThreadsHeaderEnvironment) =>
environment.label.toLocaleLowerCase(),
),
),
[savedConnectionsById],
);
const environmentIds = useMemo(
() => environments.map((environment) => environment.environmentId),
[environments],
);
const environmentLabels = useMemo(
() =>
Object.fromEntries(
environments.map((environment) => [environment.environmentId, environment.label]),
),
[environments],
);
const { error, isLoading, refresh, snapshots } = useArchivedThreadSnapshots(environmentIds);
const groups = useMemo(
() =>
buildArchivedThreadGroups({
snapshots,
environmentLabels,
environmentId: selectedEnvironmentId,
searchQuery,
sortOrder,
}),
[environmentLabels, searchQuery, selectedEnvironmentId, snapshots, sortOrder],
);
const refreshChangedEnvironment = useCallback(
(thread: { readonly environmentId: EnvironmentId }) => {
refreshArchivedThreadsForEnvironment(thread.environmentId);
},
[],
);
const { unarchiveThread, confirmDeleteThread } =
useArchivedThreadListActions(refreshChangedEnvironment);
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [expand, refresh]),
);
return (
<ArchivedThreadsScreen
environments={environments}
error={error}
groups={groups}
isLoading={isLoading}
onDeleteThread={confirmDeleteThread}
onEnvironmentChange={setSelectedEnvironmentId}
onRefresh={refresh}
onSearchQueryChange={setSearchQuery}
onSortOrderChange={setSortOrder}
onUnarchiveThread={unarchiveThread}
searchQuery={searchQuery}
selectedEnvironmentId={selectedEnvironmentId}
sortOrder={sortOrder}
/>
);
}
@@ -0,0 +1,434 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useRef } from "react";
import {
ActivityIndicator,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "../home/thread-swipe-actions";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
export interface ArchivedThreadsHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
const THREAD_ACTIONS: MenuAction[] = [
{
id: "unarchive",
title: "Unarchive",
image: "arrow.uturn.backward",
},
{
id: "delete",
title: "Delete",
image: "trash",
attributes: { destructive: true },
},
];
function ArchivedThreadsHeader(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
}) {
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
return (
<>
<Stack.Screen
options={{
title: "Archived Threads",
headerSearchBarOptions: {
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
placement: "stacked",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Sort by archived date">
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
</>
);
}
function ProjectGroupLabel(props: {
readonly environmentLabel: string | null;
readonly project: EnvironmentProject;
}) {
return (
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
projectTitle={props.project.title}
size={18}
workspaceRoot={props.project.workspaceRoot}
/>
<Text
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
numberOfLines={1}
style={{ letterSpacing: 0.5 }}
>
{props.project.title}
</Text>
{props.environmentLabel ? (
<Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
{props.environmentLabel}
</Text>
) : null}
</View>
);
}
function ArchivedThreadRow(props: {
readonly environmentLabel: string | null;
readonly isLast: boolean;
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onUnarchive: () => void;
readonly thread: EnvironmentThreadShell;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const cardColor = useThemeColor("--color-card");
const iconColor = useThemeColor("--color-icon-subtle");
const separatorColor = useThemeColor("--color-separator");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
if (event.nativeEvent.event === "unarchive") {
props.onUnarchive();
} else if (event.nativeEvent.event === "delete") {
props.onDelete();
}
},
[props.onDelete, props.onUnarchive],
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<Text
className="min-w-0 flex-1 text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
</ReanimatedSwipeable>
);
}
function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
return (
<View className="rounded-[20px] border border-danger-border bg-danger p-4">
<Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
<Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
<Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
</Pressable>
</View>
);
}
export function ArchivedThreadsScreen(props: {
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
readonly error: string | null;
readonly groups: ReadonlyArray<ArchivedThreadGroup>;
readonly isLoading: boolean;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onRefresh: () => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const refreshTint = useThemeColor("--color-icon");
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
openSwipeableRef.current.close();
}
openSwipeableRef.current = methods;
}, []);
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current === methods) {
openSwipeableRef.current = null;
}
}, []);
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
return (
<View className="flex-1 bg-sheet">
<ArchivedThreadsHeader
environments={props.environments}
onEnvironmentChange={props.onEnvironmentChange}
onSearchQueryChange={props.onSearchQueryChange}
onSortOrderChange={props.onSortOrderChange}
selectedEnvironmentId={props.selectedEnvironmentId}
sortOrder={props.sortOrder}
/>
<ScrollView
className="flex-1"
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
thread={thread}
/>
))}
</View>
</View>
);
})
)}
</ScrollView>
</View>
);
}
@@ -0,0 +1,144 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildArchivedThreadGroups } from "./archivedThreadList";
const environmentId = EnvironmentId.make("environment-1");
function makeProject(
input: Partial<OrchestrationProjectShell> & Pick<OrchestrationProjectShell, "id" | "title">,
): OrchestrationProjectShell {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<OrchestrationThreadShell> &
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
): OrchestrationThreadShell {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: "2026-06-02T00:00:00.000Z",
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
function makeSnapshot(
projects: ReadonlyArray<OrchestrationProjectShell>,
threads: ReadonlyArray<OrchestrationThreadShell>,
targetEnvironmentId = environmentId,
): ArchivedSnapshotEntry {
return {
environmentId: targetEnvironmentId,
snapshot: {
snapshotSequence: 1,
projects,
threads,
updatedAt: "2026-06-04T00:00:00.000Z",
},
};
}
describe("buildArchivedThreadGroups", () => {
it("groups archived threads by project and sorts newest first", () => {
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const older = makeThread({
id: ThreadId.make("thread-older"),
projectId: project.id,
title: "Older",
});
const newer = makeThread({
archivedAt: "2026-06-03T00:00:00.000Z",
id: ThreadId.make("thread-newer"),
projectId: project.id,
title: "Newer",
});
const result = buildArchivedThreadGroups({
snapshots: [makeSnapshot([project], [older, newer])],
environmentLabels: { [environmentId]: "Julius's MacBook Pro" },
environmentId: null,
searchQuery: "",
sortOrder: "newest",
});
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-newer", "thread-older"]);
});
it("filters by environment and matches project, thread, and branch text", () => {
const secondEnvironmentId = EnvironmentId.make("environment-2");
const firstProject = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const secondProject = makeProject({ id: ProjectId.make("project-2"), title: "Website" });
const firstThread = makeThread({
branch: "fix/archive-screen",
id: ThreadId.make("thread-1"),
projectId: firstProject.id,
title: "Build settings route",
});
const secondThread = makeThread({
id: ThreadId.make("thread-2"),
projectId: secondProject.id,
title: "Unrelated",
});
const snapshots = [
makeSnapshot([firstProject], [firstThread]),
makeSnapshot([secondProject], [secondThread], secondEnvironmentId),
];
const result = buildArchivedThreadGroups({
snapshots,
environmentLabels: {
[environmentId]: "Local",
[secondEnvironmentId]: "Remote",
},
environmentId,
searchQuery: "archive-screen",
sortOrder: "oldest",
});
expect(result).toHaveLength(1);
expect(result[0]?.project.environmentId).toBe(environmentId);
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-1"]);
});
it("ignores non-archived entries returned in a snapshot", () => {
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
const active = makeThread({
archivedAt: null,
id: ThreadId.make("thread-active"),
projectId: project.id,
title: "Active",
});
const result = buildArchivedThreadGroups({
snapshots: [makeSnapshot([project], [active])],
environmentLabels: {},
environmentId: null,
searchQuery: "",
sortOrder: "newest",
});
expect(result).toEqual([]);
});
});
@@ -0,0 +1,106 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import {
scopeProject,
scopeThreadShell,
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
export type ArchivedThreadSortOrder = "newest" | "oldest";
export interface ArchivedThreadGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
function archiveTimestamp(thread: EnvironmentThreadShell): number {
const timestamp = Date.parse(thread.archivedAt ?? thread.updatedAt);
return Number.isNaN(timestamp) ? 0 : timestamp;
}
function matchesQuery(value: string | null, query: string): boolean {
return value?.toLocaleLowerCase().includes(query) ?? false;
}
export function buildArchivedThreadGroups(input: {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly environmentLabels: Readonly<Record<string, string>>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly sortOrder: ArchivedThreadSortOrder;
}): ReadonlyArray<ArchivedThreadGroup> {
const query = input.searchQuery.trim().toLocaleLowerCase();
const groups: ArchivedThreadGroup[] = [];
for (const entry of input.snapshots) {
if (input.environmentId !== null && input.environmentId !== entry.environmentId) {
continue;
}
const environmentLabel = input.environmentLabels[entry.environmentId] ?? null;
const threadsByProjectId = new Map<string, EnvironmentThreadShell[]>();
for (const thread of entry.snapshot.threads) {
if (thread.archivedAt === null) {
continue;
}
const threads = threadsByProjectId.get(thread.projectId) ?? [];
threads.push(scopeThreadShell(entry.environmentId, thread));
threadsByProjectId.set(thread.projectId, threads);
}
for (const rawProject of entry.snapshot.projects) {
const project = scopeProject(entry.environmentId, rawProject);
const projectThreads = threadsByProjectId.get(project.id) ?? [];
const groupMatches =
query.length === 0 ||
matchesQuery(project.title, query) ||
matchesQuery(project.workspaceRoot, query) ||
matchesQuery(environmentLabel, query);
const matchingThreads = groupMatches
? projectThreads
: projectThreads.filter(
(thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
);
if (matchingThreads.length === 0) {
continue;
}
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
groups.push({
key: scopedProjectKey(project.environmentId, project.id),
project,
threads: Arr.sort(
matchingThreads,
Order.mapInput(
Order.Struct({ timestamp: timestampOrder, title: Order.String, id: Order.String }),
(thread: EnvironmentThreadShell) => ({
timestamp: archiveTimestamp(thread),
title: thread.title,
id: thread.id,
}),
),
),
});
}
}
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
return Arr.sort(
groups,
Order.mapInput(
Order.Struct({ timestamp: timestampOrder, title: Order.String, key: Order.String }),
(group: ArchivedThreadGroup) => ({
timestamp: group.threads[0] ? archiveTimestamp(group.threads[0]) : 0,
title: group.project.title,
key: group.key,
}),
),
);
}
@@ -0,0 +1,47 @@
import { useAtomValue } from "@effect/atom-react";
import {
type ArchivedSnapshotEntry,
createArchivedThreadSnapshotsAtomFamily,
makeArchivedThreadsEnvironmentKey,
} from "@t3tools/client-runtime/state/threads";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { orchestrationEnvironment } from "../../state/orchestration";
function archivedSnapshotAtom(environmentId: EnvironmentId) {
return orchestrationEnvironment.archivedShellSnapshot({
environmentId,
input: {},
});
}
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
getSnapshotAtom: archivedSnapshotAtom,
labelPrefix: "mobile:archived-thread-snapshots",
});
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
}
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
readonly error: string | null;
readonly isLoading: boolean;
readonly refresh: () => void;
} {
const environmentKey = useMemo(
() => makeArchivedThreadsEnvironmentKey(environmentIds),
[environmentIds],
);
const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
const refresh = useCallback(() => {
for (const environmentId of environmentIds) {
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
}
}, [environmentIds]);
return { ...result, refresh };
}
@@ -110,6 +110,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly styleJson?: string;
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
@@ -0,0 +1,166 @@
import { useMemo } from "react";
import {
Markdown,
type CustomRenderers,
type NodeStyleOverrides,
type PartialMarkdownTheme,
} from "react-native-nitro-markdown";
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
type NativeMarkdownTextStyle,
} from "../../native/SelectableMarkdownText";
interface MarkdownPreviewStyles {
readonly theme: PartialMarkdownTheme;
readonly styles: NodeStyleOverrides;
readonly renderers: CustomRenderers;
readonly nativeTextStyle: NativeMarkdownTextStyle;
}
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
const body = String(useThemeColor("--color-md-body"));
const strong = String(useThemeColor("--color-md-strong"));
const link = String(useThemeColor("--color-md-link"));
const blockquoteBorder = String(useThemeColor("--color-md-blockquote-border"));
const blockquoteBackground = String(useThemeColor("--color-md-blockquote-bg"));
const codeBackground = String(useThemeColor("--color-md-code-bg"));
const codeText = String(useThemeColor("--color-md-code-text"));
const horizontalRule = String(useThemeColor("--color-md-hr"));
return useMemo(() => {
const renderers: CustomRenderers = {
link: ({ href, children }) => (
<NativeText
onPress={() => {
if (href) {
void Linking.openURL(href);
}
}}
style={{
color: link,
fontFamily: "DMSans_500Medium",
textDecorationLine: "none",
}}
>
{children}
</NativeText>
),
};
return {
theme: {
colors: {
text: body,
heading: strong,
link,
blockquote: blockquoteBorder,
border: horizontalRule,
surfaceLight: blockquoteBackground,
accent: link,
tableBorder: horizontalRule,
tableHeader: blockquoteBackground,
tableHeaderText: strong,
code: codeText,
codeBackground,
},
},
styles: {
text: {
color: body,
fontFamily: "DMSans_400Regular",
fontSize: 15,
lineHeight: 22,
},
heading: {
color: strong,
fontFamily: "DMSans_700Bold",
},
strong: {
color: strong,
fontFamily: "DMSans_700Bold",
},
link: {
color: link,
fontFamily: "DMSans_500Medium",
},
blockquote: {
backgroundColor: blockquoteBackground,
borderLeftColor: blockquoteBorder,
borderLeftWidth: 3,
paddingLeft: 12,
},
code: {
backgroundColor: codeBackground,
color: codeText,
fontFamily: "ui-monospace",
},
codeBlock: {
backgroundColor: codeBackground,
borderRadius: 12,
color: codeText,
fontFamily: "ui-monospace",
padding: 12,
},
hr: {
backgroundColor: horizontalRule,
},
},
renderers,
nativeTextStyle: {
color: body,
strongColor: strong,
mutedColor: body,
linkColor: link,
inlineCodeColor: codeText,
codeColor: codeText,
codeBackgroundColor: codeBackground,
codeBlockBackgroundColor: codeBackground,
fileTextColor: codeText,
skillTextColor: codeText,
quoteMarkerColor: blockquoteBorder,
dividerColor: horizontalRule,
fontSize: 15,
lineHeight: 22,
fontFamily: "DMSans_400Regular",
headingFontFamily: "DMSans_700Bold",
boldFontFamily: "DMSans_700Bold",
},
};
}, [
blockquoteBackground,
blockquoteBorder,
body,
codeBackground,
codeText,
horizontalRule,
link,
strong,
]);
}
export function FileMarkdownPreview(props: { readonly markdown: string }) {
const styles = useMarkdownPreviewStyles();
return (
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
<View className="mx-auto w-full max-w-[760px]">
{hasNativeSelectableMarkdownText() ? (
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
) : (
<Markdown
options={{ gfm: true }}
renderers={styles.renderers}
styles={styles.styles}
theme={styles.theme}
>
{props.markdown}
</Markdown>
)}
</View>
</ScrollView>
);
}
@@ -0,0 +1,191 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import {
buildFileTree,
defaultExpandedTreePaths,
flattenFileTree,
type VisibleFileTreeNode,
} from "./fileTree";
function ancestorPaths(path: string): ReadonlyArray<string> {
const parts = path.split("/").filter(Boolean);
const ancestors: string[] = [];
for (let index = 1; index < parts.length; index += 1) {
ancestors.push(parts.slice(0, index).join("/"));
}
return ancestors;
}
const FileTreeRow = memo(function FileTreeRow(props: {
readonly item: VisibleFileTreeNode;
readonly selectedPath: string | null;
readonly expanded: boolean;
readonly iconColor: string;
readonly onPressDirectory: (path: string) => void;
readonly onPressFile: (path: string) => void;
}) {
const { node, depth } = props.item;
const selected = node.kind === "file" && node.path === props.selectedPath;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={node.path}
onPress={() => {
if (node.kind === "directory") {
props.onPressDirectory(node.path);
return;
}
props.onPressFile(node.path);
}}
className={cn(
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
selected && "bg-subtle-strong",
)}
style={{ paddingLeft: 8 + depth * 18 }}
>
{node.kind === "directory" ? (
<SymbolView
name={props.expanded ? "chevron.down" : "chevron.right"}
size={12}
tintColor={props.iconColor}
type="monochrome"
/>
) : (
<View className="w-3" />
)}
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
<Text
className={cn(
"min-w-0 flex-1 text-[14px] leading-[19px]",
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
)}
numberOfLines={1}
>
{node.name}
</Text>
{node.kind === "directory" ? (
<Text className="text-[11px] font-t3-medium text-foreground-tertiary">
{node.children.length}
</Text>
) : null}
</Pressable>
);
});
export function FileTreeBrowser(props: {
readonly entries: ReadonlyArray<ProjectEntry>;
readonly error: string | null;
readonly isPending: boolean;
readonly searchQuery: string;
readonly selectedPath: string | null;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
}) {
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
const iconColor = String(useThemeColor("--color-icon-muted"));
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
const visibleNodes = useMemo(
() =>
flattenFileTree({
nodes: tree,
expanded: expandedPaths,
searchQuery: props.searchQuery,
}),
[expandedPaths, props.searchQuery, tree],
);
useEffect(() => {
setExpandedPaths((current) => {
if (current.size > 0 || defaultExpanded.size === 0) {
return current;
}
return new Set(defaultExpanded);
});
}, [defaultExpanded]);
useEffect(() => {
if (!props.selectedPath) {
return;
}
setExpandedPaths((current) => {
const next = new Set(current);
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
next.add(ancestor);
}
return next;
});
}, [props.selectedPath]);
const toggleDirectory = useCallback((path: string) => {
setExpandedPaths((current) => {
const next = new Set(current);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
return (
<View className="flex-1 bg-sheet">
{props.error && props.entries.length === 0 ? (
<View className="px-4 py-5">
<Text className="text-[13px] font-t3-bold text-foreground">Files unavailable</Text>
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
{props.error}
</Text>
</View>
) : (
<FlatList
data={visibleNodes}
keyExtractor={(item) => item.node.path}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingVertical: 8 }}
refreshControl={
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
}
renderItem={({ item }) => (
<FileTreeRow
item={item}
selectedPath={props.selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPressFile={props.onSelectFile}
/>
)}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
<ActivityIndicator size="small" />
) : (
<>
<Text className="text-[13px] font-t3-bold text-foreground">No files found</Text>
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
{props.searchQuery.trim().length > 0
? "Try a different search."
: "The workspace file index is empty."}
</Text>
</>
)}
</View>
}
/>
)}
</View>
);
}
@@ -0,0 +1,252 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { ComponentType } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
import {
type NativeReviewDiffViewProps,
resolveNativeReviewDiffView,
} from "../diffs/nativeReviewDiffSurface";
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
import {
REVIEW_DIFF_LINE_HEIGHT,
REVIEW_MONO_FONT_FAMILY,
renderVisibleWhitespace,
} from "../review/reviewDiffRendering";
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
NATIVE_SOURCE_CONTENT_WIDTH,
NATIVE_SOURCE_ROW_HEIGHT,
NATIVE_SOURCE_STYLE,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { sourceHighlightAtom } from "./sourceHighlightingState";
const SOURCE_LINE_HEIGHT = 24;
const SOURCE_LINE_NUMBER_WIDTH = 58;
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
interface SourceFileSurfaceProps {
readonly contents: string;
readonly path: string;
readonly initialLine?: number | null;
}
type SourceHighlightStatus = "highlighting" | "ready" | "error";
function splitSourceLines(contents: string): ReadonlyArray<string> {
return contents.replace(/\r\n?/g, "\n").split("\n");
}
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
readonly index: number;
readonly line: string;
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
readonly highlighted: boolean;
}) {
return (
<View
className={cn("flex-row", props.highlighted && "bg-primary/10")}
style={{ minHeight: SOURCE_LINE_HEIGHT }}
>
<NativeText
className="select-none pr-3 text-right text-[11px] leading-[24px] text-foreground-tertiary"
style={{
width: SOURCE_LINE_NUMBER_WIDTH,
fontFamily: REVIEW_MONO_FONT_FAMILY,
}}
>
{props.index + 1}
</NativeText>
<NativeText
selectable
numberOfLines={1}
className="text-[13px] font-medium leading-[24px] text-foreground"
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY, minWidth: 320 }}
>
{props.tokens && props.tokens.length > 0
? (() => {
let offset = 0;
return props.tokens.map((token) => {
const start = offset;
offset += token.content.length;
const fontWeight =
token.fontStyle !== null && (token.fontStyle & 2) === 2
? ("700" as const)
: ("500" as const);
const fontStyle =
token.fontStyle !== null && (token.fontStyle & 1) === 1
? ("italic" as const)
: ("normal" as const);
return (
<NativeText
key={`${start}:${token.content.length}:${token.color ?? ""}`}
selectable
style={{
color: token.color ?? undefined,
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontWeight,
fontStyle,
}}
>
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
</NativeText>
);
});
})()
: renderVisibleWhitespace(props.line || " ")}
</NativeText>
</View>
);
});
function useSourceFileModel(props: SourceFileSurfaceProps) {
const colorScheme = useColorScheme();
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
const normalizedContents = useMemo(
() => props.contents.replace(/\r\n?/g, "\n"),
[props.contents],
);
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
const targetIndex =
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
: null;
const highlightAtom = useMemo(
() => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
[normalizedContents, props.path, theme],
);
const highlightResult = useAtomValue(highlightAtom);
const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
? "error"
: AsyncResult.isSuccess(highlightResult)
? "ready"
: "highlighting";
return { lines, status, targetIndex, theme, tokens };
}
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
if (props.status === "highlighting") {
return <LoadingStrip />;
}
if (props.status === "error") {
return (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-[11px] font-t3-medium uppercase text-foreground-muted">
Plain text
</Text>
</View>
);
}
return null;
}
function NativeSourceFileSurface(
props: SourceFileSurfaceProps & {
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
},
) {
const { NativeView } = props;
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
[targetIndex],
);
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
return (
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<NativeView
key={props.path}
collapsable={false}
testID="source-native-code-view"
style={{ flex: 1 }}
appearanceScheme={theme}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
rowsJson={rowsJson}
selectedRowIdsJson={selectedRowIdsJson}
styleJson={NATIVE_SOURCE_STYLE_JSON}
themeJson={themeJson}
tokensJson={tokensJson}
/>
</View>
);
}
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
const listRef = useRef<FlatList<string>>(null);
useEffect(() => {
if (targetIndex === null) {
return;
}
const frame = requestAnimationFrame(() => {
listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
});
return () => cancelAnimationFrame(frame);
}, [props.path, targetIndex]);
const renderLine = useCallback(
({ item, index }: { item: string; index: number }) => (
<HighlightedSourceLine
index={index}
line={item}
tokens={tokens?.[index] ?? null}
highlighted={index === targetIndex}
/>
),
[targetIndex, tokens],
);
return (
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<ScrollView horizontal bounces={false} className="flex-1">
<FlatList
ref={listRef}
data={lines}
keyExtractor={(_line, index) => String(index)}
initialNumToRender={80}
maxToRenderPerBatch={80}
windowSize={12}
getItemLayout={(_data, index) => ({
length: SOURCE_LINE_HEIGHT,
offset: SOURCE_LINE_HEIGHT * index,
index,
})}
contentContainerStyle={{
minWidth: "100%",
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
paddingTop: 8,
}}
renderItem={renderLine}
/>
</ScrollView>
</View>
);
}
export function SourceFileSurface(props: SourceFileSurfaceProps) {
const NativeView = resolveNativeReviewDiffView();
return NativeView ? (
<NativeSourceFileSurface {...props} NativeView={NativeView} />
) : (
<JavaScriptSourceFileSurface {...props} />
);
}
@@ -0,0 +1,631 @@
import Stack from "expo-router/stack";
import { SymbolView } from "expo-symbols";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Linking,
Pressable,
ScrollView,
Text as RNText,
View,
} from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
type ProjectListEntriesResult,
type ProjectReadFileResult,
ThreadId,
} from "@t3tools/contracts";
import { AppText as Text } from "../../components/AppText";
import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { SourceFileSurface } from "./SourceFileSurface";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
basename,
fileBreadcrumbs,
isBrowserPreviewFile,
isImagePreviewFile,
isMarkdownPreviewFile,
isSvgImagePreviewFile,
} from "./filePath";
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
return value[0] ?? null;
}
return value ?? null;
}
function normalizeRoutePath(value: string | string[] | undefined): string | null {
const path = Array.isArray(value) ? value.join("/") : value;
if (path === undefined || path.trim().length === 0) {
return null;
}
return path;
}
function normalizeRouteLine(value: string | null): number | null {
if (value === null) {
return null;
}
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function defaultViewMode(path: string | null): FileViewMode {
return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
? "preview"
: "source";
}
function ModeButton(props: {
readonly active: boolean;
readonly icon: "doc.text" | "eye";
readonly label: string;
readonly onPress: () => void;
}) {
const iconColor = String(
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.active }}
className={cn(
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
props.active ? "bg-primary" : "bg-subtle",
)}
onPress={props.onPress}
>
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
<Text
className={cn(
"text-[12px] font-t3-bold",
props.active ? "text-primary-foreground" : "text-foreground-muted",
)}
>
{props.label}
</Text>
</Pressable>
);
}
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
const gradientId = `file-breadcrumb-${props.side}-fade`;
const isLeft = props.side === "left";
return (
<View
pointerEvents="none"
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
</Svg>
</View>
);
}
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const cardColor = String(useThemeColor("--color-card"));
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
const breadcrumbs = useMemo(
() => fileBreadcrumbs(props.projectName, props.relativePath),
[props.projectName, props.relativePath],
);
const updateFadeVisibility = useCallback(
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
Object.assign(scrollMetrics.current, metrics);
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
const maxOffset = Math.max(0, contentWidth - viewportWidth);
const next = {
left: maxOffset > 1 && offsetX > 1,
right: maxOffset > 1 && offsetX < maxOffset - 1,
};
setFadeVisibility((current) =>
current.left === next.left && current.right === next.right ? current : next,
);
},
[],
);
return (
<View className="min-w-0 flex-1">
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
onContentSizeChange={(contentWidth) => {
updateFadeVisibility({ contentWidth });
}}
onLayout={(event) => {
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
}}
onScroll={(event) => {
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
}}
scrollEventThrottle={16}
>
<View className="h-8 flex-row items-center">
{breadcrumbs.map((crumb, index) => (
<View key={crumb.path || "project"} className="flex-row items-center">
{index > 0 ? (
<SymbolView
name="chevron.right"
size={10}
tintColor={iconColor}
type="monochrome"
/>
) : null}
<Text
className={cn(
"max-w-[180px] px-1 text-[12px]",
crumb.kind === "file"
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-muted",
)}
numberOfLines={1}
>
{crumb.label}
</Text>
</View>
))}
</View>
</ScrollView>
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
</View>
);
}
function FilePreviewHeader(props: {
readonly activeMode: FileViewMode;
readonly showModeSelector: boolean;
readonly externalPreviewUri?: string | null;
readonly projectName: string;
readonly relativePath: string;
readonly onSetMode: (mode: FileViewMode) => void;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
return (
<View className="border-b border-border bg-card px-3 py-2">
<View className="flex-row items-center gap-2">
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
<CopyTextButton
accessibilityLabel="Copy file path"
text={props.relativePath}
tintColor={iconColor}
buttonSize={32}
iconSize={13}
/>
</View>
{props.showModeSelector ? (
<View className="mt-2 flex-row items-center gap-2">
<ModeButton
active={props.activeMode === "preview"}
icon="eye"
label="Preview"
onPress={() => props.onSetMode("preview")}
/>
<ModeButton
active={props.activeMode === "source"}
icon="doc.text"
label="Source"
onPress={() => props.onSetMode("source")}
/>
{props.externalPreviewUri !== undefined ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Open preview in Safari"
disabled={props.externalPreviewUri === null}
hitSlop={8}
className={cn(
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
props.externalPreviewUri === null && "opacity-40",
)}
onPress={() => {
if (typeof props.externalPreviewUri === "string") {
void Linking.openURL(props.externalPreviewUri);
}
}}
>
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
</Pressable>
) : null}
</View>
) : null}
</View>
);
}
function FileContent(props: {
readonly activeMode: FileViewMode;
readonly previewUri: string | null;
readonly fileContents: string | null;
readonly fileError: string | null;
readonly relativePath: string;
readonly initialLine: number | null;
readonly truncated: boolean;
}) {
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
const isImageFile = isImagePreviewFile(props.relativePath);
if (props.activeMode === "preview" && isImageFile) {
if (isSvgImagePreviewFile(props.relativePath)) {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
}
return (
<WorkspaceFileImagePreview
accessibilityLabel={basename(props.relativePath)}
uri={props.previewUri}
/>
);
}
if (props.activeMode === "preview" && isBrowserFile) {
return <WorkspaceFileWebPreview uri={props.previewUri} />;
}
if (props.fileError && props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<EmptyState title="File unavailable" detail={props.fileError} />
</View>
);
}
if (props.fileContents === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Loading file...</Text>
</View>
);
}
return (
<View className="flex-1 bg-card">
{props.truncated ? (
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
<Text className="text-[11px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
Partial file
</Text>
<Text className="text-[12px] leading-[17px] text-amber-800 dark:text-amber-200">
Preview limited to the first 1 MB of a truncated file.
</Text>
</View>
) : null}
{props.activeMode === "preview" && isMarkdown ? (
<FileMarkdownPreview markdown={props.fileContents} />
) : (
<SourceFileSurface
contents={props.fileContents}
path={props.relativePath}
initialLine={props.initialLine}
/>
)}
</View>
);
}
function useThreadFilesWorkspace() {
const params = useLocalSearchParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
const routeEnvironmentId = firstRouteParam(params.environmentId);
const routeThreadId = firstRouteParam(params.threadId);
const { selectedThread, selectedThreadProject } = useThreadSelection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const environmentId =
routeEnvironmentId !== null
? EnvironmentId.make(routeEnvironmentId)
: (selectedThread?.environmentId ?? null);
const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
const project = selectedThreadProject as {
readonly title?: string;
readonly workspaceRoot?: string;
} | null;
return {
cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
environmentId,
projectName: project?.title ?? "Files",
selectedThread,
threadId,
};
}
function FilesUnavailable() {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<EmptyState
title="Files unavailable"
detail="This thread does not have an active workspace path."
/>
</View>
);
}
function FilesHeaderTitle(props: { readonly projectName: string }) {
const foregroundColor = String(useThemeColor("--color-foreground"));
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
return (
<View style={{ alignItems: "center", maxWidth: 220 }}>
<RNText
numberOfLines={1}
style={{
color: foregroundColor,
fontFamily: "DMSans_700Bold",
fontSize: 18,
fontWeight: "900",
letterSpacing: -0.4,
}}
>
Files
</RNText>
<RNText
numberOfLines={1}
style={{
color: secondaryForegroundColor,
fontFamily: "DMSans_500Medium",
fontSize: 12,
fontWeight: "500",
letterSpacing: 0.2,
}}
>
{props.projectName}
</RNText>
</View>
);
}
function FilesToolbarBottomFade() {
const sheetColor = String(useThemeColor("--color-sheet"));
if (process.env.EXPO_OS !== "ios") {
return null;
}
return (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
style={{
bottom: 0,
height: 112,
left: 0,
position: "absolute",
right: 0,
zIndex: 1,
}}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
<Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
<Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
<Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
</LinearGradient>
</Defs>
<Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
</Svg>
</View>
);
}
export function ThreadFilesTreeScreen() {
const router = useRouter();
const [searchQuery, setSearchQuery] = useState("");
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null
? projectEnvironment.listEntries({
environmentId,
input: { cwd },
})
: null,
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleSelectFile = useCallback(
(path: string) => {
if (environmentId === null || threadId === null) {
return;
}
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
},
[environmentId, router, threadId],
);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
if (cwd === null) {
return <FilesUnavailable />;
}
return (
<View className="flex-1 bg-sheet">
<Stack.Screen
options={{
title: "Files",
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
headerSearchBarOptions: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
</Stack.Toolbar>
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={null}
onRefresh={entriesQuery.refresh}
onSelectFile={handleSelectFile}
/>
<FilesToolbarBottomFade />
</View>
);
}
export function ThreadFileScreen() {
const params = useLocalSearchParams<{
line?: string | string[];
path?: string | string[];
}>();
const relativePath = normalizeRoutePath(params.path);
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const [modeOverride, setModeOverride] = useState<{
readonly path: string;
readonly mode: FileViewMode;
} | null>(null);
const [previewRevision, setPreviewRevision] = useState(0);
const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
const canPreview =
relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
const activeMode =
relativePath !== null && modeOverride?.path === relativePath
? modeOverride.mode
: defaultViewMode(relativePath);
const resolvedActiveMode = canPreview ? activeMode : "source";
const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
const assetPreviewUri = useWorkspaceFileAssetUrl({
cwd,
environmentId,
relativePath: assetPreviewPath,
threadId,
});
const previewUri =
assetPreviewUri === null || previewRevision === 0
? assetPreviewUri
: `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
const needsFileContents =
relativePath !== null &&
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
const fileQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
? projectEnvironment.readFile({
environmentId,
input: { cwd, relativePath },
})
: null,
);
const fileData = fileQuery.data as ProjectReadFileResult | null;
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
if (cwd === null) {
return <FilesUnavailable />;
}
if (relativePath === null) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<EmptyState title="File unavailable" detail="This file path is invalid." />
</View>
);
}
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: basename(relativePath) }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
setPreviewRevision((current) => current + 1);
return;
}
fileQuery.refresh();
}}
/>
</Stack.Toolbar>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</View>
</ReviewHighlighterProvider>
);
}
@@ -0,0 +1,118 @@
import { useAtomValue } from "@effect/atom-react";
import { useMemo, useState } from "react";
import { ActivityIndicator, Image, Pressable, View } from "react-native";
import ImageViewing from "react-native-image-viewing";
import { AsyncResult } from "effect/unstable/reactivity";
import { AppText as Text } from "../../components/AppText";
import { EmptyState } from "../../components/EmptyState";
import { workspaceFileImageAtom } from "./workspace-file-image-cache";
function ResolvedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
}) {
const [loadError, setLoadError] = useState<string | null>(null);
const [fullScreenVisible, setFullScreenVisible] = useState(false);
const imageSource = useMemo(
() => ({ uri: props.uri, cache: "force-cache" as const }),
[props.uri],
);
const fullScreenImages = useMemo(() => [imageSource], [imageSource]);
return (
<View className="relative flex-1 bg-subtle">
<Pressable
accessibilityRole="button"
accessibilityLabel={`Open full-screen preview of ${props.accessibilityLabel}`}
disabled={loadError !== null}
className="flex-1 p-4 active:bg-subtle-strong"
onPress={() => setFullScreenVisible(true)}
>
<Image
accessible={false}
source={imageSource}
className="h-full w-full"
resizeMode="contain"
onLoadStart={() => setLoadError(null)}
onError={(event) => {
setLoadError(event.nativeEvent.error || "The image could not be rendered.");
}}
/>
</Pressable>
{loadError !== null ? (
<View className="absolute inset-0 items-center justify-center bg-card px-6">
<EmptyState title="Image unavailable" detail={loadError} />
</View>
) : null}
<ImageViewing
images={fullScreenImages}
imageIndex={0}
visible={fullScreenVisible}
onRequestClose={() => setFullScreenVisible(false)}
swipeToCloseEnabled
doubleTapToZoomEnabled
/>
</View>
);
}
function CachedWorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string;
}) {
const imageAtom = useMemo(() => workspaceFileImageAtom(props.uri), [props.uri]);
const imageResult = useAtomValue(imageAtom);
if (AsyncResult.isFailure(imageResult)) {
return (
<View className="flex-1 items-center justify-center bg-card px-6">
<EmptyState
title="Image unavailable"
detail="The image could not be loaded into the local cache."
/>
</View>
);
}
if (!AsyncResult.isSuccess(imageResult)) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Loading image...</Text>
</View>
);
}
return (
<ResolvedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={imageResult.value}
/>
);
}
export function WorkspaceFileImagePreview(props: {
readonly accessibilityLabel: string;
readonly uri: string | null;
}) {
if (props.uri === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">
Preparing image preview...
</Text>
</View>
);
}
return (
<CachedWorkspaceFileImagePreview
accessibilityLabel={props.accessibilityLabel}
uri={props.uri}
/>
);
}
@@ -0,0 +1,62 @@
import { useState } from "react";
import { ActivityIndicator, View } from "react-native";
import { WebView } from "react-native-webview";
import { AppText as Text } from "../../components/AppText";
import { LoadingStrip } from "../../components/LoadingStrip";
export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
const [loadProgress, setLoadProgress] = useState(0);
const [loadError, setLoadError] = useState<string | null>(null);
if (props.uri === null) {
return (
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
<ActivityIndicator />
<Text className="text-center text-[13px] text-foreground-muted">Preparing preview...</Text>
</View>
);
}
return (
<View className="relative flex-1 bg-card">
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
{loadError ? (
<View className="border-b border-border bg-card px-4 py-2">
<Text className="text-[12px] font-t3-bold text-foreground">Preview failed</Text>
<Text className="mt-0.5 text-[12px] leading-[17px] text-foreground-muted">
{loadError}
</Text>
</View>
) : null}
<WebView
source={{ uri: props.uri }}
originWhitelist={["*"]}
allowsBackForwardNavigationGestures
allowsFullscreenVideo
setSupportMultipleWindows={false}
startInLoadingState
onLoadProgress={(event) => {
setLoadProgress(event.nativeEvent.progress);
}}
onLoadStart={() => {
setLoadProgress(0.05);
setLoadError(null);
}}
onLoadEnd={() => {
setLoadProgress(0);
}}
onError={(event) => {
setLoadProgress(0);
setLoadError(event.nativeEvent.description || "The file could not be rendered.");
}}
renderLoading={() => (
<View className="absolute inset-0 items-center justify-center bg-card">
<ActivityIndicator />
</View>
)}
style={{ flex: 1, backgroundColor: "transparent" }}
/>
</View>
);
}
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vite-plus/test";
import {
isBrowserPreviewFile,
isImagePreviewFile,
isSvgImagePreviewFile,
resolveWorkspaceRelativeFilePath,
} from "./filePath";
describe("resolveWorkspaceRelativeFilePath", () => {
it("keeps normalized workspace-relative paths", () => {
expect(resolveWorkspaceRelativeFilePath("/repo", "./src/../src/main.ts")).toBe("src/main.ts");
});
it("converts absolute paths inside the workspace", () => {
expect(
resolveWorkspaceRelativeFilePath("/Users/julius/repo", "/Users/julius/repo/src/main.ts"),
).toBe("src/main.ts");
expect(resolveWorkspaceRelativeFilePath("C:\\repo", "c:\\repo\\src\\main.ts")).toBe(
"src/main.ts",
);
});
it("rejects paths outside the workspace", () => {
expect(resolveWorkspaceRelativeFilePath("/repo", "/other/main.ts")).toBeNull();
expect(resolveWorkspaceRelativeFilePath("/repo", "../other/main.ts")).toBeNull();
expect(resolveWorkspaceRelativeFilePath(null, "/repo/main.ts")).toBeNull();
});
});
describe("file preview types", () => {
it("recognizes browser and image previews", () => {
expect(isBrowserPreviewFile("reports/summary.html")).toBe(true);
expect(isImagePreviewFile("assets/icon.png")).toBe(true);
expect(isImagePreviewFile("assets/diagram.SVG?raw=1")).toBe(true);
expect(isImagePreviewFile("src/image.ts")).toBe(false);
});
it("identifies SVG images that need web rendering", () => {
expect(isSvgImagePreviewFile("assets/diagram.svg#icon")).toBe(true);
expect(isSvgImagePreviewFile("assets/photo.png")).toBe(false);
});
});
+116
View File
@@ -0,0 +1,116 @@
import {
isWorkspaceBrowserPreviewPath,
isWorkspaceImagePreviewPath,
} from "@t3tools/shared/filePreview";
export interface FileBreadcrumb {
readonly label: string;
readonly path: string;
readonly kind: "project" | "directory" | "file";
}
function isWindowsAbsolutePath(value: string): boolean {
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
}
function isAbsolutePath(value: string): boolean {
return value.startsWith("/") || isWindowsAbsolutePath(value);
}
function isWindowsPathStyle(value: string): boolean {
return isWindowsAbsolutePath(value) || /^[A-Za-z]:\\/.test(value);
}
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
const cleanBase = base.replace(/[\\/]+$/, "");
if (separator === "\\") {
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
}
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
}
export function basename(path: string): string {
const parts = path.split(/[\\/]/).filter(Boolean);
return parts.at(-1) ?? path;
}
export function resolveWorkspaceFilePath(cwd: string, relativePath: string): string {
if (isAbsolutePath(relativePath)) {
return relativePath;
}
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
return joinPath(cwd, relativePath, separator);
}
function normalizeRelativePath(value: string): string | null {
const segments: string[] = [];
for (const segment of value.replaceAll("\\", "/").split("/")) {
if (segment.length === 0 || segment === ".") {
continue;
}
if (segment === "..") {
if (segments.length === 0) {
return null;
}
segments.pop();
continue;
}
segments.push(segment);
}
return segments.length > 0 ? segments.join("/") : null;
}
export function resolveWorkspaceRelativeFilePath(
workspaceRoot: string | null | undefined,
targetPath: string,
): string | null {
if (!isAbsolutePath(targetPath)) {
if (targetPath.startsWith("~/") || targetPath.startsWith("~\\")) {
return null;
}
return normalizeRelativePath(targetPath);
}
if (!workspaceRoot) {
return null;
}
const normalizedTarget = targetPath.replaceAll("\\", "/");
const normalizedRoot = workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, "");
const caseInsensitive = isWindowsAbsolutePath(targetPath) || isWindowsAbsolutePath(workspaceRoot);
const comparableTarget = caseInsensitive ? normalizedTarget.toLowerCase() : normalizedTarget;
const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
if (!comparableTarget.startsWith(`${comparableRoot}/`)) {
return null;
}
return normalizeRelativePath(normalizedTarget.slice(normalizedRoot.length + 1));
}
export function isBrowserPreviewFile(path: string): boolean {
return isWorkspaceBrowserPreviewPath(path);
}
export function isImagePreviewFile(path: string): boolean {
return isWorkspaceImagePreviewPath(path);
}
export function isSvgImagePreviewFile(path: string): boolean {
return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? "");
}
export function isMarkdownPreviewFile(path: string): boolean {
return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
}
export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
const parts = relativePath.split("/").filter(Boolean);
return [
{ label: projectName, path: "", kind: "project" },
...parts.map((part, index) => ({
label: part,
path: parts.slice(0, index + 1).join("/"),
kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
})),
];
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vite-plus/test";
import type { ProjectEntry } from "@t3tools/contracts";
import {
buildFileTree,
countFileNodes,
defaultExpandedTreePaths,
firstFilePath,
flattenFileTree,
} from "./fileTree";
const entries = [
{ kind: "file", path: "README.md" },
{ kind: "directory", path: "src" },
{ kind: "file", path: "src/index.ts" },
{ kind: "file", path: "src/components/App.tsx" },
{ kind: "file", path: "package.json" },
] satisfies ReadonlyArray<ProjectEntry>;
describe("mobile file tree helpers", () => {
it("builds a deterministic hierarchy with directories before files", () => {
const tree = buildFileTree(entries);
expect(tree.map((node) => `${node.kind}:${node.path}`)).toEqual([
"directory:src",
"file:package.json",
"file:README.md",
]);
expect(tree[0]?.children.map((node) => `${node.kind}:${node.path}`)).toEqual([
"directory:src/components",
"file:src/index.ts",
]);
expect(countFileNodes(tree)).toBe(4);
expect(firstFilePath(tree)).toBe("src/components/App.tsx");
});
it("flattens expanded directories and hides collapsed descendants", () => {
const tree = buildFileTree(entries);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(["src"]),
}).map((item) => `${item.depth}:${item.node.path}`),
).toEqual(["0:src", "1:src/components", "1:src/index.ts", "0:package.json", "0:README.md"]);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
}).map((item) => item.node.path),
).toEqual(["src", "package.json", "README.md"]);
});
it("includes matching descendants and their ancestors during search", () => {
const tree = buildFileTree(entries);
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
searchQuery: "app",
}).map((item) => item.node.path),
).toEqual(["src", "src/components", "src/components/App.tsx"]);
});
it("supports fuzzy, whitespace-separated path queries", () => {
const tree = buildFileTree([
{
kind: "file",
path: ".plans/19-version-control-phase-1-vcs-driver-foundation.md",
},
{
kind: "file",
path: ".repos/alchemy-effect/examples/aws-lambda/src/JobNotifications.ts",
},
{ kind: "directory", path: "apps/web/src/components/chat" },
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.test.ts" },
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.tsx" },
{ kind: "file", path: "apps/web/src/components/chat/Composer.tsx" },
]);
const expectedPaths = [
"apps",
"apps/web",
"apps/web/src",
"apps/web/src/components",
"apps/web/src/components/chat",
"apps/web/src/components/chat/ChatHeader.test.ts",
"apps/web/src/components/chat/ChatHeader.tsx",
];
for (const searchQuery of ["chat hea", "cht hdr"]) {
expect(
flattenFileTree({
nodes: tree,
expanded: new Set(),
searchQuery,
}).map((item) => item.node.path),
).toEqual(expectedPaths);
}
});
it("expands top-level directories by default", () => {
const tree = buildFileTree(entries);
expect([...defaultExpandedTreePaths(tree)]).toEqual(["src"]);
});
});
+220
View File
@@ -0,0 +1,220 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
export interface FileTreeNode {
readonly path: string;
readonly name: string;
readonly kind: ProjectEntry["kind"];
readonly children: ReadonlyArray<FileTreeNode>;
readonly searchSegments: ReadonlyArray<string>;
readonly searchWords: ReadonlyArray<string>;
}
export interface VisibleFileTreeNode {
readonly node: FileTreeNode;
readonly depth: number;
}
interface MutableFileTreeNode {
path: string;
name: string;
kind: ProjectEntry["kind"];
children: Map<string, MutableFileTreeNode>;
}
function createMutableNode(
path: string,
name: string,
kind: ProjectEntry["kind"],
): MutableFileTreeNode {
return {
path,
name,
kind,
children: new Map(),
};
}
function splitSearchWords(value: string): ReadonlyArray<string> {
return value
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((word) => word.toLowerCase());
}
function buildNodeSearchTerms(path: string): {
readonly segments: ReadonlyArray<string>;
readonly words: ReadonlyArray<string>;
} {
const segments: string[] = [];
const words: string[] = [];
for (const segment of path.split("/")) {
if (!segment) {
continue;
}
segments.push(segment.toLowerCase());
words.push(...splitSearchWords(segment));
}
return { segments, words };
}
function freezeNode(node: MutableFileTreeNode): FileTreeNode {
const searchTerms = buildNodeSearchTerms(node.path);
return {
path: node.path,
name: node.name,
kind: node.kind,
children: [...node.children.values()].sort(compareNodes).map(freezeNode),
searchSegments: searchTerms.segments,
searchWords: searchTerms.words,
};
}
function compareNodes(
left: Pick<FileTreeNode, "kind" | "name">,
right: Pick<FileTreeNode, "kind" | "name">,
): number {
if (left.kind !== right.kind) {
return left.kind === "directory" ? -1 : 1;
}
return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
}
export function buildFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
const root = createMutableNode("", "", "directory");
for (const entry of entries) {
const parts = entry.path.split("/").filter(Boolean);
if (parts.length === 0) {
continue;
}
let current = root;
for (let index = 0; index < parts.length; index += 1) {
const part = parts[index];
if (!part) {
continue;
}
const path = parts.slice(0, index + 1).join("/");
const isLeaf = index === parts.length - 1;
const kind = isLeaf ? entry.kind : "directory";
let child = current.children.get(part);
if (!child) {
child = createMutableNode(path, part, kind);
current.children.set(part, child);
} else if (isLeaf) {
child.kind = entry.kind;
}
current = child;
}
}
return [...root.children.values()].sort(compareNodes).map(freezeNode);
}
export function countFileNodes(nodes: ReadonlyArray<FileTreeNode>): number {
let count = 0;
for (const node of nodes) {
if (node.kind === "file") {
count += 1;
} else {
count += countFileNodes(node.children);
}
}
return count;
}
export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
const expanded = new Set<string>();
for (const node of nodes) {
if (node.kind === "directory") {
expanded.add(node.path);
}
}
return expanded;
}
function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
return (
scoreQueryMatch({
value,
query: token,
exactBase: 0,
prefixBase: 2,
boundaryBase: 4,
includesBase: 6,
...(fuzzy ? { fuzzyBase: 100 } : {}),
boundaryMarkers: ["/", "-", "_", "."],
}) !== null
);
}
function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
return tokens.every(
(token) =>
node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
);
}
function flattenNode(
output: VisibleFileTreeNode[],
node: FileTreeNode,
depth: number,
expanded: ReadonlySet<string>,
searchTokens: ReadonlyArray<string>,
): boolean {
const isSearching = searchTokens.length > 0;
const matches = isSearching && nodeMatchesSearch(node, searchTokens);
let descendantMatches = false;
const childOutput: VisibleFileTreeNode[] = [];
if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
for (const child of node.children) {
if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
descendantMatches = true;
}
}
}
const visible = !isSearching || matches || descendantMatches;
if (!visible) {
return false;
}
output.push({ node, depth });
output.push(...childOutput);
return matches || descendantMatches;
}
export function flattenFileTree(input: {
readonly nodes: ReadonlyArray<FileTreeNode>;
readonly expanded: ReadonlySet<string>;
readonly searchQuery?: string;
}): ReadonlyArray<VisibleFileTreeNode> {
const output: VisibleFileTreeNode[] = [];
const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
for (const node of input.nodes) {
flattenNode(output, node, 0, input.expanded, searchTokens);
}
return output;
}
export function firstFilePath(nodes: ReadonlyArray<FileTreeNode>): string | null {
for (const node of nodes) {
if (node.kind === "file") {
return node.path;
}
const child = firstFilePath(node.children);
if (child !== null) {
return child;
}
}
return null;
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vite-plus/test";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
describe("nativeSourceFileAdapter", () => {
it("maps plain source lines onto context rows with stable line numbers", () => {
expect(buildNativeSourceRows(["const value = 1;", "\treturn value;"])).toEqual([
{
kind: "line",
id: nativeSourceRowId(0),
fileId: "source-file",
content: "const value = 1;",
change: "context",
newLineNumber: 1,
},
{
kind: "line",
id: nativeSourceRowId(1),
fileId: "source-file",
content: " return value;",
change: "context",
newLineNumber: 2,
},
]);
});
it("maps cached source tokens to the same row identifiers", () => {
expect(
buildNativeSourceTokens([
[{ content: "const", color: "#ff0000", fontStyle: 2 }],
[{ content: "\tvalue", color: null, fontStyle: null }],
]),
).toEqual({
[nativeSourceRowId(0)]: [{ content: "const", color: "#ff0000", fontStyle: 2 }],
[nativeSourceRowId(1)]: [{ content: " value", color: null, fontStyle: null }],
});
});
it("clears native tokens while highlighting is unavailable", () => {
expect(buildNativeSourceTokens(null)).toEqual({});
});
});
@@ -0,0 +1,65 @@
import type {
NativeReviewDiffRow,
NativeReviewDiffStyle,
NativeReviewDiffToken,
} from "../diffs/nativeReviewDiffSurface";
import type { SourceHighlightTokens } from "./sourceHighlightingState";
export const NATIVE_SOURCE_ROW_HEIGHT = 24;
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
changeBarWidth: 0,
gutterWidth: 58,
codePadding: 8,
codeFontSize: 13,
codeFontWeight: "medium",
lineNumberFontSize: 11,
lineNumberFontWeight: "medium",
emptyStateFontSize: 12,
emptyStateFontWeight: "medium",
};
const SOURCE_FILE_ID = "source-file";
function expandTabs(value: string): string {
return value.replace(/\t/g, " ");
}
export function nativeSourceRowId(index: number): string {
return `source-line:${index}`;
}
export function buildNativeSourceRows(
lines: ReadonlyArray<string>,
): ReadonlyArray<NativeReviewDiffRow> {
return lines.map((line, index) => ({
kind: "line",
id: nativeSourceRowId(index),
fileId: SOURCE_FILE_ID,
content: expandTabs(line),
change: "context",
newLineNumber: index + 1,
}));
}
export function buildNativeSourceTokens(
tokenLines: SourceHighlightTokens | null,
): Readonly<Record<string, ReadonlyArray<NativeReviewDiffToken>>> {
if (tokenLines === null) {
return {};
}
return Object.fromEntries(
tokenLines.map((tokens, index) => [
nativeSourceRowId(index),
tokens.map((token) => ({
content: expandTabs(token.content),
color: token.color,
fontStyle: token.fontStyle,
})),
]),
);
}
@@ -0,0 +1,123 @@
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,
type SourceHighlightTokens,
} from "./sourceHighlightingState";
const highlightedTokens: SourceHighlightTokens = [
[{ content: "const", color: "#0000ff", fontStyle: null }],
];
afterEach(() => {
vi.restoreAllMocks();
});
describe("sourceHighlightingState", () => {
it("reuses completed highlighting across equivalent route remounts", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 1_000 });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const input = {
path: "src/example.ts",
contents: "const value = 1;",
theme: "light" as const,
};
const firstAtom = sourceHighlightAtom(input);
const firstUnmount = registry.mount(firstAtom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
});
firstUnmount();
const remountedAtom = sourceHighlightAtom({ ...input });
const secondUnmount = registry.mount(remountedAtom);
expect(remountedAtom).toBe(firstAtom);
expect(AsyncResult.isSuccess(registry.get(remountedAtom))).toBe(true);
expect(highlight).toHaveBeenCalledTimes(1);
secondUnmount();
registry.dispose();
});
it("does not reuse highlighting when the source contents change", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
const registry = AtomRegistry.make();
const firstAtom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const secondAtom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 2;",
theme: "light",
});
const firstUnmount = registry.mount(firstAtom);
const secondUnmount = registry.mount(secondAtom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
expect(AsyncResult.isSuccess(registry.get(secondAtom))).toBe(true);
});
expect(secondAtom).not.toBe(firstAtom);
expect(highlight).toHaveBeenCalledTimes(2);
firstUnmount();
secondUnmount();
registry.dispose();
});
it("recomputes highlighting after the idle cache entry expires", async () => {
const highlight = vi.fn(async () => highlightedTokens);
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 5 });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const atom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const firstUnmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
firstUnmount();
await new Promise((resolve) => setTimeout(resolve, 25));
const secondUnmount = registry.mount(atom);
await vi.waitFor(() => {
expect(highlight).toHaveBeenCalledTimes(2);
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
secondUnmount();
registry.dispose();
});
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 atom = sourceHighlightAtom({
path: "src/example.ts",
contents: "const value = 1;",
theme: "light",
});
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
unmount();
registry.dispose();
});
});
@@ -0,0 +1,50 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
import {
highlightSourceFile,
type ReviewDiffTheme,
type ReviewHighlightedToken,
} from "../review/shikiReviewHighlighter";
const SOURCE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000;
export interface SourceHighlightInput {
readonly path: string;
readonly contents: string;
readonly theme: ReviewDiffTheme;
}
export type SourceHighlightTokens = ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighlightTokens>;
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
readonly cause: unknown;
}> {}
export function createSourceHighlightAtomFamily(options?: {
readonly highlight?: SourceHighlighter;
readonly idleTtlMs?: number;
}) {
const highlight = options?.highlight ?? highlightSourceFile;
const idleTtlMs = options?.idleTtlMs ?? SOURCE_HIGHLIGHT_IDLE_TTL_MS;
const family = Atom.family((request: SourceHighlightCacheKey) =>
Atom.make(
Effect.tryPromise({
try: () => highlight(request),
catch: (cause) => new SourceHighlightError({ cause }),
}),
).pipe(
Atom.setIdleTTL(idleTtlMs),
Atom.withLabel(`mobile:source-highlight:${request.theme}:${request.path}`),
),
);
return (input: SourceHighlightInput) => family(new SourceHighlightCacheKey(input));
}
export const sourceHighlightAtom = createSourceHighlightAtomFamily();
@@ -0,0 +1,64 @@
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 } from "./workspace-file-image-cache";
describe("workspaceFileImageAtom", () => {
it("reuses a prefetched image across route remounts", async () => {
const prefetch = vi.fn(async () => true);
const imageAtom = createWorkspaceFileImageAtomFamily({ idleTtlMs: 1_000, prefetch });
const registry = AtomRegistry.make({ timeoutResolution: 1 });
const first = imageAtom("https://example.test/image.png");
const firstUnmount = registry.mount(first);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
});
firstUnmount();
const remounted = imageAtom("https://example.test/image.png");
const secondUnmount = registry.mount(remounted);
expect(remounted).toBe(first);
expect(AsyncResult.isSuccess(registry.get(remounted))).toBe(true);
expect(prefetch).toHaveBeenCalledTimes(1);
secondUnmount();
registry.dispose();
});
it("prefetches different asset URLs independently", async () => {
const prefetch = vi.fn(async () => true);
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch });
const registry = AtomRegistry.make();
const first = imageAtom("https://example.test/first.png");
const second = imageAtom("https://example.test/second.png");
const firstUnmount = registry.mount(first);
const secondUnmount = registry.mount(second);
await vi.waitFor(() => {
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
expect(AsyncResult.isSuccess(registry.get(second))).toBe(true);
});
expect(prefetch).toHaveBeenCalledTimes(2);
firstUnmount();
secondUnmount();
registry.dispose();
});
it("exposes prefetch failures", async () => {
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
const registry = AtomRegistry.make();
const atom = imageAtom("https://example.test/missing.png");
const unmount = registry.mount(atom);
await vi.waitFor(() => {
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
});
unmount();
registry.dispose();
});
});
@@ -0,0 +1,48 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { Atom } from "effect/unstable/reactivity";
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
type ImagePrefetch = (uri: string) => Promise<boolean>;
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
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);
}
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) =>
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:${key.uri}`)),
);
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
}
export const workspaceFileImageAtom = createWorkspaceFileImageAtomFamily();
@@ -0,0 +1,31 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceFilePath } from "./filePath";
export function useWorkspaceFileAssetUrl(props: {
readonly cwd: string | null;
readonly environmentId: EnvironmentId | null;
readonly relativePath: string | null;
readonly threadId: ThreadId | null;
}) {
const absolutePath = useMemo(
() =>
props.cwd !== null && props.relativePath !== null
? resolveWorkspaceFilePath(props.cwd, props.relativePath)
: null,
[props.cwd, props.relativePath],
);
return useAssetUrl(
props.environmentId,
absolutePath !== null && props.threadId !== null
? {
_tag: "workspace-file",
threadId: props.threadId,
path: absolutePath,
}
: null,
);
}
@@ -0,0 +1,244 @@
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import {
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "@t3tools/contracts";
import { Stack } from "expo-router";
import { Text as RNText, View } from "react-native";
import { useThemeColor } from "../../lib/useThemeColor";
import type { HomeProjectSortOrder } from "./homeThreadList";
export interface HomeHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
}
const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const THREAD_SORT_OPTIONS: ReadonlyArray<{
readonly value: SidebarThreadSortOrder;
readonly label: string;
}> = [
{ value: "updated_at", label: "Last user message" },
{ value: "created_at", label: "Created at" },
];
const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
readonly value: SidebarProjectGroupingMode;
readonly label: string;
readonly subtitle: string;
}> = [
{
value: "repository",
label: "Group by repository",
subtitle: "Combine matching repositories across environments",
},
{
value: "repository_path",
label: "Group by repository path",
subtitle: "Combine only matching paths within a repository",
},
{
value: "separate",
label: "Keep separate",
subtitle: "Show every project path separately",
},
];
export function HomeHeader(props: {
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onSearchQueryChange: (query: string) => void;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const hasCustomListOptions =
props.selectedEnvironmentId !== null ||
props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER ||
props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE;
return (
<>
<Stack.Screen
options={{
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTintColor: iconColor,
headerTitle: "",
headerSearchBarOptions: {
placeholder: "Search threads",
hideNavigationBar: false,
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
allowToolbarIntegration: true,
},
}}
/>
<Stack.Toolbar placement="left">
<Stack.Toolbar.View hidesSharedBackground>
<View
style={{
width: 128,
height: 32,
flexDirection: "row",
alignItems: "center",
gap: 8,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 17,
color: iconColor,
letterSpacing: -0.4,
}}
>
T3 Code
</RNText>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 99,
paddingHorizontal: 8,
paddingVertical: 3,
}}
>
<RNText
style={{
fontFamily: "DMSans_700Bold",
fontSize: 10,
color: mutedColor,
letterSpacing: 1.1,
textTransform: "uppercase",
}}
>
Alpha
</RNText>
</View>
</View>
</Stack.Toolbar.View>
</Stack.Toolbar>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort threads"
icon={
hasCustomListOptions
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Thread list options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
subtitle="Show threads from every environment"
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Sort projects">
<Stack.Toolbar.Label>Sort projects</Stack.Toolbar.Label>
{PROJECT_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectSortOrder === option.value}
onPress={() => props.onProjectSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Sort threads">
<Stack.Toolbar.Label>Sort threads</Stack.Toolbar.Label>
{THREAD_SORT_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.threadSortOrder === option.value}
onPress={() => props.onThreadSortOrderChange(option.value)}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<Stack.Toolbar.Menu title="Group projects">
<Stack.Toolbar.Label>Group projects</Stack.Toolbar.Label>
{PROJECT_GROUPING_OPTIONS.map((option) => (
<Stack.Toolbar.MenuAction
key={option.value}
isOn={props.projectGroupingMode === option.value}
onPress={() => props.onProjectGroupingModeChange(option.value)}
subtitle={option.subtitle}
>
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
<Stack.Toolbar.Button
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
separateBackground
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
<Stack.Toolbar.Button
accessibilityLabel="New task"
icon="square.and.pencil"
onPress={props.onStartNewTask}
separateBackground
/>
</Stack.Toolbar>
</>
);
}
+287 -139
View File
@@ -2,12 +2,26 @@ import {
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Easing,
LinearTransition,
type ExitAnimationsValues,
withDelay,
withTiming,
} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useThemeColor } from "../../lib/useThemeColor";
import { AppText as Text } from "../../components/AppText";
@@ -15,9 +29,14 @@ import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import type { WorkspaceState } from "../../state/workspaceModel";
import type { SavedRemoteConnection } from "../../lib/connection";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { relativeTime } from "../../lib/time";
import { threadStatusTone } from "../threads/threadPresentation";
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "./thread-swipe-actions";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -27,26 +46,17 @@ interface HomeScreenProps {
readonly catalogState: WorkspaceState;
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
readonly searchQuery: string;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
}
interface ProjectGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
const projectGroupActivityOrder = Order.mapInput(
Order.Struct({
activityAt: Order.flip(Order.Number),
}),
(group: ProjectGroup) => ({
activityAt: new Date(group.threads[0]!.updatedAt ?? group.threads[0]!.createdAt).getTime(),
}),
);
/* ─── Status indicator colors ────────────────────────────────────────── */
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
@@ -65,6 +75,33 @@ function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string
}
const COLLAPSED_THREAD_LIMIT = 6;
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
function threadRowExit(values: ExitAnimationsValues) {
"worklet";
return {
initialValues: {
height: values.currentHeight,
opacity: 1,
originX: values.currentOriginX,
},
animations: {
height: withDelay(
90,
withTiming(0, {
duration: 170,
easing: Easing.inOut(Easing.cubic),
}),
),
opacity: withDelay(80, withTiming(0, { duration: 100 })),
originX: withTiming(values.currentOriginX - values.windowWidth, {
duration: 190,
easing: Easing.out(Easing.cubic),
}),
},
};
}
function deriveEmptyState(props: {
readonly catalogState: WorkspaceState;
@@ -133,6 +170,7 @@ function deriveEmptyState(props: {
function ProjectGroupLabel(props: {
readonly project: EnvironmentProject;
readonly title: string;
readonly totalThreadCount: number;
readonly isExpanded: boolean;
readonly onToggleExpand: () => void;
@@ -152,7 +190,7 @@ function ProjectGroupLabel(props: {
style={{ letterSpacing: 0.5 }}
numberOfLines={1}
>
{props.project.title}
{props.title}
</Text>
{hiddenCount > 0 ? (
@@ -175,95 +213,172 @@ function ThreadRow(props: {
readonly thread: EnvironmentThreadShell;
readonly environmentLabel: string | null;
readonly onPress: () => void;
readonly onArchive: () => void;
readonly onDelete: () => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly isLast: boolean;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const separatorColor = useThemeColor("--color-separator");
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const cardColor = useThemeColor("--color-card");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const { bg, fg } = statusColors(props.thread);
const tone = threadStatusTone(props.thread);
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
const timestamp = relativeTime(
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
);
const branch = props.thread.branch;
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
return (
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
<View
style={{
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) {
return;
}
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Archive ${props.thread.title}`,
icon: "archivebox",
label: "Archive",
onPress: props.onArchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
>
<Pressable
accessibilityHint="Swipe left for archive and delete actions"
accessibilityLabel={props.thread.title}
accessibilityRole="button"
className="bg-card"
onPress={() => {
swipeableRef.current?.close();
props.onPress();
}}
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
>
{/* Git status indicator */}
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
flexDirection: "row",
paddingLeft: 16,
paddingRight: 16,
paddingVertical: 10,
gap: 12,
borderBottomWidth: props.isLast ? 0 : 1,
borderBottomColor: separatorColor,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
{/* Content */}
<View style={{ flex: 1, gap: 3 }}>
{/* Title + Status + Timestamp */}
<View className="flex-row items-center justify-between gap-2">
<Text
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
<View
style={{
width: 30,
height: 30,
borderRadius: 9,
backgroundColor: bg,
alignItems: "center",
justifyContent: "center",
marginTop: 2,
}}
>
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
</View>
{/* Environment + branch */}
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<View style={{ flex: 1, gap: 3 }}>
<View className="flex-row items-center justify-between gap-2">
<Text
className="text-[11px] text-foreground-tertiary"
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
{props.thread.title}
</Text>
<View className="flex-row items-center gap-2">
<View
className={tone.pillClassName}
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
>
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
{tone.label}
</Text>
</View>
<Text
className="text-[12px] text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
</View>
) : null}
{subtitleParts.length > 0 ? (
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconSubtleColor}
type="monochrome"
/>
<Text
className="text-[11px] text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitleParts.join(" · ")}
</Text>
</View>
) : null}
</View>
</View>
</View>
</Pressable>
</Pressable>
</ReanimatedSwipeable>
);
}
@@ -323,6 +438,7 @@ function StaleCatalogStatusPill(props: {
export function HomeScreen(props: HomeScreenProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const insets = useSafeAreaInsets();
const accentColor = useThemeColor("--color-icon-muted");
@@ -335,51 +451,50 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, []);
/* Build project title lookup for search */
const projectTitleByKey = useMemo(() => {
const map = new Map<string, string>();
for (const p of props.projects) {
map.set(scopedProjectKey(p.environmentId, p.id), p.title);
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current !== methods) {
openSwipeableRef.current?.close();
openSwipeableRef.current = methods;
}
return map;
}, [props.projects]);
}, []);
/* Filter threads by search query */
const filteredThreads = useMemo(() => {
const q = props.searchQuery.trim().toLowerCase();
if (!q) return props.threads;
return props.threads.filter((t) => {
if (t.title.toLowerCase().includes(q)) return true;
const key = scopedProjectKey(t.environmentId, t.projectId);
return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
});
}, [props.threads, props.searchQuery, projectTitleByKey]);
/* Group filtered threads by project */
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
const byProject = new Map<string, EnvironmentThreadShell[]>();
for (const thread of filteredThreads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = byProject.get(key);
if (existing) existing.push(thread);
else byProject.set(key, [thread]);
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current === methods) {
openSwipeableRef.current = null;
}
}, []);
const groups: ProjectGroup[] = [];
for (const project of props.projects) {
const key = scopedProjectKey(project.environmentId, project.id);
const threads = byProject.get(key);
if (threads && threads.length > 0) {
groups.push({ key, project, threads });
}
}
return Arr.sort(groups, projectGroupActivityOrder);
}, [props.projects, filteredThreads]);
const projectGroups = useMemo(
() =>
buildHomeThreadGroups({
projects: props.projects,
threads: props.threads,
environmentId: props.selectedEnvironmentId,
searchQuery: props.searchQuery,
projectSortOrder: props.projectSortOrder,
threadSortOrder: props.threadSortOrder,
projectGroupingMode: props.projectGroupingMode,
}),
[
props.projectGroupingMode,
props.projects,
props.projectSortOrder,
props.searchQuery,
props.selectedEnvironmentId,
props.threadSortOrder,
props.threads,
],
);
/* Empty states */
const hasAnyThreads = props.threads.length > 0;
const hasResults = filteredThreads.length > 0;
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
const hasResults = projectGroups.length > 0;
const selectedEnvironmentLabel =
props.selectedEnvironmentId === null
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
const hasSearchQuery = props.searchQuery.trim().length > 0;
const shouldShowConnectionStatus =
props.catalogState.networkStatus === "offline" ||
props.catalogState.hasConnectingEnvironment ||
@@ -396,6 +511,7 @@ export function HomeScreen(props: HomeScreenProps) {
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
className="flex-1"
contentContainerStyle={{
paddingHorizontal: 16,
@@ -418,8 +534,18 @@ export function HomeScreen(props: HomeScreenProps) {
</View>
) : null}
</View>
) : !hasResults ? (
) : !hasResults && hasSearchQuery ? (
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
) : !hasResults && selectedEnvironmentLabel ? (
<EmptyState
title={`No threads in ${selectedEnvironmentLabel}`}
detail="Choose another environment or create a new task."
/>
) : !hasResults ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding session."
/>
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
@@ -428,30 +554,52 @@ export function HomeScreen(props: HomeScreenProps) {
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
return (
<View key={group.key}>
<Animated.View
key={group.key}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ProjectGroupLabel
project={group.project}
totalThreadCount={group.threads.length}
isExpanded={isExpanded}
onToggleExpand={() => toggleExpanded(group.key)}
project={group.representative}
title={group.title}
totalThreadCount={group.threads.length}
/>
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{visibleThreads.map((thread, i) => (
<ThreadRow
key={`${thread.environmentId}:${thread.id}`}
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
}
onPress={() => props.onSelectThread(thread)}
isLast={i === visibleThreads.length - 1}
/>
))}
{visibleThreads.map((thread, i) => {
const threadKey = `${thread.environmentId}:${thread.id}`;
return (
<Animated.View
key={threadKey}
collapsable={false}
exiting={threadRowExit}
layout={THREAD_LAYOUT_TRANSITION}
style={{ overflow: "hidden" }}
>
<ThreadRow
thread={thread}
environmentLabel={
props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
null
}
isLast={i === visibleThreads.length - 1}
onArchive={() => props.onArchiveThread(thread)}
onDelete={() => props.onDeleteThread(thread)}
onPress={() => props.onSelectThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
/>
</Animated.View>
);
})}
</View>
</View>
</Animated.View>
);
})
)}
@@ -0,0 +1,223 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildHomeThreadGroups } from "./homeThreadList";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
): EnvironmentThreadShell {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
}
function buildGroups(
projects: ReadonlyArray<EnvironmentProject>,
threads: ReadonlyArray<EnvironmentThreadShell>,
overrides: Partial<Parameters<typeof buildHomeThreadGroups>[0]> = {},
) {
return buildHomeThreadGroups({
projects,
threads,
environmentId: null,
searchQuery: "",
projectSortOrder: "updated_at",
threadSortOrder: "updated_at",
projectGroupingMode: "repository",
...overrides,
});
}
describe("buildHomeThreadGroups", () => {
it("sorts the newest thread first regardless of snapshot order", () => {
const environmentId = EnvironmentId.make("environment-1");
const project = makeProject({
environmentId,
id: ProjectId.make("project-1"),
title: "T3 Code",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("thread-old"),
projectId: project.id,
title: "Older thread",
updatedAt: "2026-06-02T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("thread-new"),
projectId: project.id,
title: "Newer thread",
updatedAt: "2026-06-03T00:00:00.000Z",
}),
];
expect(buildGroups([project], threads)[0]?.threads.map((thread) => thread.id)).toEqual([
"thread-new",
"thread-old",
]);
});
it("supports independent project and thread creation-time sorting", () => {
const environmentId = EnvironmentId.make("environment-1");
const olderProject = makeProject({
environmentId,
id: ProjectId.make("project-older"),
title: "Older project",
});
const newerProject = makeProject({
environmentId,
id: ProjectId.make("project-newer"),
title: "Newer project",
});
const threads = [
makeThread({
environmentId,
id: ThreadId.make("old-created"),
projectId: olderProject.id,
title: "Updated recently",
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-05T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("new-created"),
projectId: olderProject.id,
title: "Created recently",
createdAt: "2026-06-04T00:00:00.000Z",
updatedAt: "2026-06-04T00:00:00.000Z",
}),
makeThread({
environmentId,
id: ThreadId.make("newest-project-thread"),
projectId: newerProject.id,
title: "Newest project",
createdAt: "2026-06-06T00:00:00.000Z",
}),
];
const groups = buildGroups([olderProject, newerProject], threads, {
projectSortOrder: "created_at",
threadSortOrder: "created_at",
projectGroupingMode: "separate",
});
expect(groups.map((group) => group.representative.id)).toEqual([
"project-newer",
"project-older",
]);
expect(groups[1]?.threads.map((thread) => thread.id)).toEqual(["new-created", "old-created"]);
});
it("filters both projects and threads to one environment", () => {
const localEnvironmentId = EnvironmentId.make("environment-local");
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: ProjectId.make("project-local"),
title: "Local",
}),
makeProject({
environmentId: remoteEnvironmentId,
id: ProjectId.make("project-remote"),
title: "Remote",
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId: project.environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
const groups = buildGroups(projects, threads, { environmentId: remoteEnvironmentId });
expect(groups).toHaveLength(1);
expect(groups[0]?.representative.environmentId).toBe(remoteEnvironmentId);
expect(groups[0]?.threads.map((thread) => thread.environmentId)).toEqual([remoteEnvironmentId]);
});
it("matches web repository, repository-path, and separate grouping modes", () => {
const environmentId = EnvironmentId.make("environment-1");
const repositoryIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
rootPath: "/workspaces/t3code",
};
const projects = [
makeProject({
environmentId,
id: ProjectId.make("project-web"),
title: "Web",
workspaceRoot: "/workspaces/t3code/apps/web",
repositoryIdentity,
}),
makeProject({
environmentId,
id: ProjectId.make("project-mobile"),
title: "Mobile",
workspaceRoot: "/workspaces/t3code/apps/mobile",
repositoryIdentity,
}),
];
const threads = projects.map((project) =>
makeThread({
environmentId,
id: ThreadId.make(`thread-${project.id}`),
projectId: project.id,
title: project.title,
}),
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
});
@@ -0,0 +1,140 @@
import {
deriveLogicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { scopedProjectKey } from "../../lib/scopedEntities";
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
export interface HomeThreadGroup {
readonly key: string;
readonly title: string;
readonly representative: EnvironmentProject;
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}
interface MutableHomeThreadGroup {
readonly key: string;
readonly projects: EnvironmentProject[];
readonly threads: EnvironmentThreadShell[];
}
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
return group.threads.reduce(
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
Number.NEGATIVE_INFINITY,
);
}
export function buildHomeThreadGroups(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly environmentId: EnvironmentId | null;
readonly searchQuery: string;
readonly projectSortOrder: HomeProjectSortOrder;
readonly threadSortOrder: SidebarThreadSortOrder;
readonly projectGroupingMode: SidebarProjectGroupingMode;
}): ReadonlyArray<HomeThreadGroup> {
const groups = new Map<string, MutableHomeThreadGroup>();
const groupKeyByProjectKey = new Map<string, string>();
for (const project of input.projects) {
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
continue;
}
const groupKey = deriveLogicalProjectKey(project, {
groupingMode: input.projectGroupingMode,
});
const physicalKey = scopedProjectKey(project.environmentId, project.id);
groupKeyByProjectKey.set(physicalKey, groupKey);
const existing = groups.get(groupKey);
if (existing) {
existing.projects.push(project);
} else {
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
}
}
for (const thread of input.threads) {
if (thread.archivedAt !== null) {
continue;
}
if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
continue;
}
const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
const groupKey = groupKeyByProjectKey.get(physicalKey);
if (!groupKey) {
continue;
}
groups.get(groupKey)?.threads.push(thread);
}
const query = input.searchQuery.trim().toLocaleLowerCase();
const result: HomeThreadGroup[] = [];
for (const group of groups.values()) {
const representative = group.projects[0];
if (!representative || group.threads.length === 0) {
continue;
}
const title =
group.projects.length > 1
? deriveProjectGroupLabel({ representative, members: group.projects })
: representative.title;
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
const matchingThreads = groupMatches
? group.threads
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
if (matchingThreads.length === 0) {
continue;
}
result.push({
key: group.key,
title,
representative,
projects: group.projects,
threads: sortThreads(matchingThreads, input.threadSortOrder),
});
}
return Arr.sort(
result,
Order.mapInput(
Order.Struct({
timestamp: Order.flip(Order.Number),
title: Order.String,
key: Order.String,
}),
(group: HomeThreadGroup) => ({
timestamp: groupSortTimestamp(group, input.projectSortOrder),
title: group.title,
key: group.key,
}),
),
);
}
@@ -0,0 +1,238 @@
import { SymbolView } from "expo-symbols";
import type { ComponentProps } from "react";
import type { ColorValue } from "react-native";
import { Pressable, View } from "react-native";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
Extrapolation,
interpolate,
runOnJS,
type SharedValue,
useAnimatedReaction,
useAnimatedStyle,
} from "react-native-reanimated";
import { AppText as Text } from "../../components/AppText";
const ACTION_ITEM_WIDTH = 50;
const ACTION_CIRCLE_SIZE = 36;
const ACTION_ICON_SIZE = 15;
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
export const THREAD_SWIPE_SPRING = {
damping: 26,
mass: 0.7,
overshootClamping: true,
stiffness: 330,
};
function SwipeActionButton(props: {
readonly accessibilityLabel: string;
readonly backgroundColor: string;
readonly entryRange: readonly [number, number];
readonly fullSwipeThreshold: number;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
readonly stretchesOnFullSwipe: boolean;
readonly translation: SharedValue<number>;
}) {
const actionStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
const fullSwipeProgress = interpolate(
reveal,
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
return {
opacity: props.stretchesOnFullSwipe ? entryProgress : entryProgress * (1 - fullSwipeProgress),
transform: [
{
translateX:
interpolate(entryProgress, [0, 1], [22, 0]) -
(props.stretchesOnFullSwipe ? 0 : stretch),
},
{ scale: interpolate(entryProgress, [0, 1], [0.78, 1]) },
],
};
});
const circleStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
return {
transform: [{ translateX: -stretch }],
width: ACTION_CIRCLE_SIZE + stretch,
};
});
const iconStyle = useAnimatedStyle(() => {
const reveal = Math.max(-props.translation.value, 0);
const stretch = props.stretchesOnFullSwipe
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
: 0;
const armedProgress = interpolate(
reveal,
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
[0, 1],
Extrapolation.CLAMP,
);
return {
transform: [{ translateX: -stretch * (0.5 + armedProgress * 0.5) }],
};
});
const labelStyle = useAnimatedStyle(() => {
if (!props.stretchesOnFullSwipe) {
return { opacity: 1 };
}
const reveal = Math.max(-props.translation.value, 0);
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
return {
opacity: interpolate(
reveal,
[props.fullSwipeThreshold - 24, props.fullSwipeThreshold],
[1, 0],
Extrapolation.CLAMP,
),
transform: [{ translateX: -stretch * 0.5 }],
};
});
return (
<Animated.View
style={[
{
alignItems: "center",
height: "100%",
justifyContent: "center",
width: ACTION_ITEM_WIDTH,
zIndex: props.stretchesOnFullSwipe ? 2 : 1,
},
actionStyle,
]}
>
<Pressable
accessibilityLabel={props.accessibilityLabel}
accessibilityRole="button"
onPress={props.onPress}
style={({ pressed }) => ({
alignItems: "center",
height: "100%",
justifyContent: "center",
opacity: pressed ? 0.72 : 1,
width: "100%",
})}
>
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
<Animated.View
style={[
{
backgroundColor: props.backgroundColor,
borderRadius: 999,
height: ACTION_CIRCLE_SIZE,
left: 0,
position: "absolute",
top: 0,
},
circleStyle,
]}
/>
<Animated.View
style={[
{
alignItems: "center",
height: ACTION_CIRCLE_SIZE,
justifyContent: "center",
left: 0,
position: "absolute",
top: 0,
width: ACTION_CIRCLE_SIZE,
},
iconStyle,
]}
>
<SymbolView
name={props.icon}
size={ACTION_ICON_SIZE}
tintColor="#ffffff"
type="monochrome"
/>
</Animated.View>
</View>
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
<Text className="text-[10px] font-t3-medium text-foreground-muted">{props.label}</Text>
</Animated.View>
</Pressable>
</Animated.View>
);
}
export function ThreadSwipeActions(props: {
readonly backgroundColor: ColorValue;
readonly fullSwipeThreshold: number;
readonly onDelete: () => void;
readonly onFullSwipeArmedChange: (armed: boolean) => void;
readonly primaryAction: {
readonly accessibilityLabel: string;
readonly icon: ComponentProps<typeof SymbolView>["name"];
readonly label: string;
readonly onPress: () => void;
};
readonly swipeableMethods: SwipeableMethods;
readonly threadTitle: string;
readonly translation: SharedValue<number>;
}) {
useAnimatedReaction(
() => -props.translation.value >= props.fullSwipeThreshold,
(armed, previous) => {
if (armed !== previous) {
runOnJS(props.onFullSwipeArmedChange)(armed);
}
},
[props.fullSwipeThreshold, props.onFullSwipeArmedChange],
);
return (
<View
style={{
backgroundColor: props.backgroundColor,
flexDirection: "row",
height: "100%",
width: THREAD_SWIPE_ACTIONS_WIDTH,
}}
>
<SwipeActionButton
accessibilityLabel={props.primaryAction.accessibilityLabel}
backgroundColor="#007aff"
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon={props.primaryAction.icon}
label={props.primaryAction.label}
onPress={props.primaryAction.onPress}
stretchesOnFullSwipe={false}
translation={props.translation}
/>
<SwipeActionButton
accessibilityLabel={`Delete ${props.threadTitle}`}
backgroundColor="#ff2d55"
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
fullSwipeThreshold={props.fullSwipeThreshold}
icon="trash"
label="Delete"
onPress={() => {
props.swipeableMethods.close();
props.onDelete();
}}
stretchesOnFullSwipe
translation={props.translation}
/>
</View>
);
}
@@ -0,0 +1,142 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
import { useCallback, useRef } from "react";
import { Alert } from "react-native";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
type ThreadListAction = "archive" | "unarchive" | "delete";
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
const verb =
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
return `The thread could not be ${verb}.`;
}
function selectionHaptic(): void {
if (process.env.EXPO_OS === "ios") {
void Haptics.selectionAsync();
}
}
function actionFailureTitle(action: ThreadListAction): string {
if (action === "archive") return "Could not archive thread";
if (action === "unarchive") return "Could not unarchive thread";
return "Could not delete thread";
}
function useThreadActionExecutor(
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
) {
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
const inFlightThreadKeys = useRef(new Set<string>());
const executeAction = useCallback(
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (inFlightThreadKeys.current.has(key)) {
return;
}
inFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const mutation =
action === "archive"
? archiveMutation
: action === "unarchive"
? unarchiveMutation
: deleteMutation;
const result = await mutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
return;
}
onCompleted?.(action, thread);
} finally {
inFlightThreadKeys.current.delete(key);
}
},
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
);
return executeAction;
}
function useConfirmDeleteThread(
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
) {
return useCallback(
(thread: EnvironmentThreadShell) => {
Alert.alert(
"Delete thread?",
`“${thread.title}” will be permanently deleted, including its terminal history.`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => {
void executeAction("delete", thread);
},
},
],
);
},
[executeAction],
);
}
export function useThreadListActions(): {
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
} {
const executeAction = useThreadActionExecutor();
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
void executeAction("archive", thread);
},
[executeAction],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { archiveThread, confirmDeleteThread };
}
export function useArchivedThreadListActions(
onCompleted: (thread: EnvironmentThreadShell) => void,
): {
readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
} {
const handleCompleted = useCallback(
(_action: ThreadListAction, thread: EnvironmentThreadShell) => {
onCompleted(thread);
},
[onCompleted],
);
const executeAction = useThreadActionExecutor(handleCompleted);
const unarchiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
void executeAction("unarchive", thread);
},
[executeAction],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return { unarchiveThread, confirmDeleteThread };
}
@@ -695,6 +695,15 @@ export async function highlightCodeSnippet(input: {
return highlightLines(input.code, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
}
export async function highlightSourceFile(input: {
readonly path: string;
readonly contents: string;
readonly theme: ReviewDiffTheme;
}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
const language = await resolveLanguageFromPath(input.path);
return highlightLines(input.contents, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
}
async function highlightPatchLinesInChunks(input: {
readonly lines: ReadonlyArray<string>;
readonly language: string;
@@ -62,6 +62,7 @@ export interface ThreadDetailScreenProps {
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
readonly selectedThreadQueueCount: number;
readonly serverConfig: T3ServerConfig | null;
readonly layoutVariant?: LayoutVariant;
@@ -309,6 +310,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
+109 -194
View File
@@ -4,6 +4,7 @@ import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Markdown,
@@ -54,6 +55,7 @@ import {
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import type { LayoutVariant } from "../../lib/layout";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
@@ -64,7 +66,9 @@ import {
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const THREAD_FEED_END_THRESHOLD = 80;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -83,6 +87,7 @@ function formatMessageTime(input: string): string {
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
@@ -120,32 +125,6 @@ function MessageAttachmentImage(props: {
);
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
return (match?.[1] ?? trimmed).trim();
}
function compactActivityDetail(detail: string | null): string | null {
if (!detail) {
return null;
}
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : null;
}
function buildActivityRows(
activities: Extract<ThreadFeedEntry, { type: "activity-group" }>["activities"],
) {
return activities.map((activity) => ({
...activity,
detail: compactActivityDetail(activity.detail),
}));
}
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const MARKDOWN_COLORS = {
light: {
body: "#111111",
@@ -155,10 +134,12 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(0, 0, 0, 0.02)",
codeBackground: "rgba(0, 0, 0, 0.04)",
codeText: "#262626",
inlineCodeText: "#5f6368",
horizontalRule: "rgba(0, 0, 0, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.22)",
userCodeText: "#ffffff",
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.16)",
userFenceText: "#ffffff",
},
@@ -170,10 +151,12 @@ const MARKDOWN_COLORS = {
blockquoteBackground: "rgba(255, 255, 255, 0.03)",
codeBackground: "rgba(255, 255, 255, 0.06)",
codeText: "#e5e5e5",
inlineCodeText: "#b8bcc2",
horizontalRule: "rgba(255, 255, 255, 0.08)",
userBody: "#ffffff",
userCodeBackground: "rgba(255, 255, 255, 0.18)",
userCodeText: "#ffffff",
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
userFenceBackground: "rgba(0, 0, 0, 0.28)",
userFenceText: "#ffffff",
},
@@ -202,27 +185,18 @@ interface ReviewCommentColors {
const failedMarkdownFaviconHosts = new Set<string>();
const markdownLinkStyles = StyleSheet.create({
favicon: {
inlineIcon: {
width: 14,
height: 14,
borderRadius: 3,
marginHorizontal: 3,
transform: [{ translateY: 2 }],
},
file: {
borderRadius: 5,
borderWidth: StyleSheet.hairlineWidth,
fontFamily: "DMSans_500Medium",
fontSize: 13,
lineHeight: 20,
paddingHorizontal: 6,
paddingVertical: 2,
favicon: {
borderRadius: 3,
},
fileIcon: {
width: 15,
height: 15,
marginRight: 4,
transform: [{ translateY: 2 }],
file: {
fontFamily: "DMSans_700Bold",
fontWeight: "700",
},
});
@@ -250,7 +224,7 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
source={{
uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,
}}
style={markdownLinkStyles.favicon}
style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}
onError={() => {
failedMarkdownFaviconHosts.add(props.host);
setFailed(true);
@@ -287,11 +261,9 @@ function useReviewCommentColors(): ReviewCommentColors {
);
}
function useMarkdownStyles(): MarkdownStyleSets {
function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {
const colorScheme = useColorScheme();
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
const inlineChipBackground = String(useThemeColor("--color-subtle"));
const inlineSkillBackground = String(useThemeColor("--color-inline-skill-background"));
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
return useMemo(() => {
@@ -302,10 +274,12 @@ function useMarkdownStyles(): MarkdownStyleSets {
const markdownBlockquoteBorder = colors.blockquoteBorder;
const markdownCodeBg = colors.codeBackground;
const markdownCodeText = colors.codeText;
const markdownInlineCodeText = colors.inlineCodeText;
const markdownHrColor = colors.horizontalRule;
const markdownUserBodyColor = colors.userBody;
const markdownUserCodeBg = colors.userCodeBackground;
const markdownUserCodeText = colors.userCodeText;
const markdownUserInlineCodeText = colors.userInlineCodeText;
const markdownUserFenceBg = colors.userFenceBackground;
const markdownUserFenceText = colors.userFenceText;
@@ -394,28 +368,23 @@ function useMarkdownStyles(): MarkdownStyleSets {
};
const createMarkdownRenderers = (
inlineBackgroundColor: string,
inlineTextColor: string,
inlineCodeTextColor: string,
blockBackgroundColor: string,
blockTextColor: string,
preserveSoftBreaks: boolean,
): CustomRenderers => ({
link: ({ children, href = "" }) => {
const presentation = resolveMarkdownLinkPresentation(href);
if (presentation.kind === "file") {
return (
<NativeText
style={[
markdownLinkStyles.file,
{
backgroundColor: inlineBackgroundColor,
borderColor: markdownHrColor,
color: inlineTextColor,
},
]}
onPress={() => onLinkPress(href)}
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
>
<Image
source={markdownFileIconSource(presentation.icon)}
style={markdownLinkStyles.fileIcon}
style={markdownLinkStyles.inlineIcon}
/>
{presentation.label}
</NativeText>
@@ -492,28 +461,24 @@ function useMarkdownStyles(): MarkdownStyleSets {
),
code_inline: ({ content }) => {
const value = content ?? "";
const wrapsPoorly =
value.length > 24 || value.includes("/") || value.includes("\\") || value.includes(":");
return (
<NativeText
style={{
color: inlineTextColor,
color: inlineCodeTextColor,
fontFamily: "ui-monospace",
fontSize: 12,
lineHeight: 18,
...(wrapsPoorly
? { opacity: 0.82 }
: {
backgroundColor: inlineBackgroundColor,
borderRadius: 4,
paddingHorizontal: 3,
}),
lineHeight: 22,
}}
>
{value}
</NativeText>
);
},
...(preserveSoftBreaks
? {
soft_break: () => <NativeText>{"\n"}</NativeText>,
}
: {}),
code_block: ({ content, language }) => (
<View
style={{
@@ -619,23 +584,23 @@ function useMarkdownStyles(): MarkdownStyleSets {
theme: userTheme,
styles: userStyles,
renderers: createMarkdownRenderers(
markdownUserCodeBg,
markdownUserCodeText,
markdownUserInlineCodeText,
markdownUserFenceBg,
markdownUserFenceText,
true,
),
nativeTextStyle: {
color: markdownUserBodyColor,
strongColor: markdownUserBodyColor,
mutedColor: markdownUserBodyColor,
linkColor: markdownUserBodyColor,
inlineCodeColor: markdownUserInlineCodeText,
codeColor: markdownUserCodeText,
codeBackgroundColor: markdownUserCodeBg,
codeBlockBackgroundColor: markdownUserFenceBg,
fileBackgroundColor: "rgba(255, 255, 255, 0.12)",
fileTextColor: "#ffffff",
skillBackgroundColor: "rgba(217, 70, 239, 0.24)",
skillTextColor: "#ffffff",
skillTextColor: "#f0abfc",
quoteMarkerColor: markdownUserBodyColor,
dividerColor: markdownUserBodyColor,
fontSize: 15,
@@ -649,22 +614,22 @@ function useMarkdownStyles(): MarkdownStyleSets {
theme: assistantTheme,
styles: assistantStyles,
renderers: createMarkdownRenderers(
markdownCodeText,
markdownInlineCodeText,
markdownCodeBg,
markdownCodeText,
markdownCodeBg,
markdownCodeText,
false,
),
nativeTextStyle: {
color: markdownBodyColor,
strongColor: markdownStrongColor,
mutedColor: markdownBodyColor,
linkColor: markdownLinkColor,
inlineCodeColor: markdownInlineCodeText,
codeColor: markdownCodeText,
codeBackgroundColor: markdownCodeBg,
codeBlockBackgroundColor: markdownCodeBg,
fileBackgroundColor: inlineChipBackground,
fileTextColor: markdownCodeText,
skillBackgroundColor: inlineSkillBackground,
skillTextColor: inlineSkillForeground,
quoteMarkerColor: markdownBlockquoteBorder,
dividerColor: markdownHrColor,
@@ -676,7 +641,7 @@ function useMarkdownStyles(): MarkdownStyleSets {
},
},
};
}, [colors, inlineChipBackground, inlineSkillBackground, inlineSkillForeground]);
}, [colors, inlineSkillForeground, onLinkPress]);
}
function renderFeedEntry(
@@ -692,11 +657,13 @@ function renderFeedEntry(
readonly onToggleWorkRow: (rowId: string) => void;
readonly onToggleTurnFold: (turnId: TurnId) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
readonly onMarkdownLinkPress: (href: string) => void;
readonly iconSubtleColor: string | import("react-native").ColorValue;
readonly userBubbleColor: string | import("react-native").ColorValue;
readonly markdownStyles: MarkdownStyleSets;
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
},
) {
const entry = info.item;
@@ -745,9 +712,10 @@ function renderFeedEntry(
return (
<View className="mb-5 items-end">
<View
className="max-w-[85%] gap-2 rounded-[20px] px-3.5 py-2.5"
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
backgroundColor: userBubbleColor,
maxWidth: props.userBubbleMaxWidth,
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
}}
>
@@ -757,6 +725,7 @@ function renderFeedEntry(
markdownStyles={styles}
reviewCommentColors={props.reviewCommentColors}
skills={props.skills}
onLinkPress={props.onMarkdownLinkPress}
/>
) : null}
{attachments.map((attachment) => {
@@ -803,6 +772,7 @@ function renderFeedEntry(
markdown={message.text}
skills={props.skills}
textStyle={styles.nativeTextStyle}
onLinkPress={props.onMarkdownLinkPress}
/>
) : (
<Markdown
@@ -868,123 +838,17 @@ function renderFeedEntry(
);
}
const rows = buildActivityRows(entry.activities).filter(
(activity) => !(activity.toolLike && activity.status === "neutral"),
);
if (rows.length === 0) {
return null;
}
const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
const headerTitle = onlyToolRows
? rows.length === 1
? "1 tool call"
: `${rows.length} tool calls`
: "Work log";
return (
<View className="mb-3 rounded-[16px] border border-neutral-300/70 bg-background px-2 py-2.5 dark:border-white/[0.1] dark:bg-white/[0.035]">
<View className="mb-1.5 flex-row items-center justify-between gap-3 px-2">
<Text className="font-t3-medium text-xs text-foreground">{headerTitle}</Text>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: isExpanded }}
onPress={() => props.onToggleWorkGroup(entry.id)}
className="flex-row items-center gap-1"
>
<Text className="font-t3-medium text-xs text-foreground-muted">
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</Text>
<SymbolView
name={isExpanded ? "chevron.up" : "chevron.down"}
size={12}
tintColor={iconSubtleColor}
type="monochrome"
/>
</Pressable>
) : null}
</View>
{visibleRows.map((row, index) => (
<Pressable
key={row.id}
accessibilityRole={row.fullDetail ? "button" : undefined}
accessibilityState={
row.fullDetail ? { expanded: props.expandedWorkRows[row.id] ?? false } : undefined
}
onPress={() => {
if (row.fullDetail) {
props.onToggleWorkRow(row.id);
}
}}
onLongPress={() => props.onCopyWorkRow(row.id, row.copyText)}
className={cn(
"rounded-lg px-2 py-1.5",
index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
)}
>
<View className="flex-row items-center gap-2">
<View className="w-4 items-center justify-center">
<SymbolView
name={
row.status === "failure"
? "xmark"
: row.status === "success"
? "checkmark"
: row.status === "neutral"
? "minus"
: "terminal"
}
size={row.status ? 11 : 13}
tintColor={row.status === "failure" ? "#e11d48" : iconSubtleColor}
type="monochrome"
/>
</View>
<Text
className="min-w-0 flex-1 text-[12px] leading-[18px] text-neutral-700 dark:text-neutral-300"
numberOfLines={props.expandedWorkRows[row.id] ? undefined : 1}
>
{row.detail ? `${row.summary} - ${row.detail}` : row.summary}
</Text>
{row.fullDetail ? (
<SymbolView
name={props.expandedWorkRows[row.id] ? "chevron.up" : "chevron.down"}
size={11}
tintColor={iconSubtleColor}
type="monochrome"
/>
) : null}
{props.copiedRowId === row.id ? (
<Text className="shrink-0 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
</View>
{row.fullDetail && props.expandedWorkRows[row.id] ? (
<ScrollView
horizontal
nestedScrollEnabled
directionalLockEnabled
showsHorizontalScrollIndicator
bounces={false}
className="mt-2 rounded-lg bg-neutral-100 dark:bg-black/20"
contentContainerStyle={{ paddingHorizontal: 10, paddingVertical: 8 }}
>
<Text
selectable
className="text-[11px] leading-[17px] text-neutral-600 dark:text-neutral-400"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
</ScrollView>
) : null}
</Pressable>
))}
</View>
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={props.onToggleWorkRow}
/>
);
}
@@ -993,6 +857,7 @@ function UserMessageContent(props: {
readonly markdownStyles: MarkdownStyleSet;
readonly reviewCommentColors: ReviewCommentColors;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
readonly onLinkPress: (href: string) => void;
}) {
const segments = parseReviewCommentMessageSegments(props.text);
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
@@ -1003,6 +868,8 @@ function UserMessageContent(props: {
markdown={props.text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
preserveSoftBreaks
onLinkPress={props.onLinkPress}
/>
);
}
@@ -1042,6 +909,8 @@ function UserMessageContent(props: {
markdown={text}
skills={props.skills}
textStyle={props.markdownStyles.nativeTextStyle}
preserveSoftBreaks
onLinkPress={props.onLinkPress}
/>
) : (
<Markdown
@@ -1254,6 +1123,7 @@ function ThreadFeedPlaceholder(props: {
}
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const router = useRouter();
const listRef = useRef<LegendListRef>(null);
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const scrollFrameRef = useRef<number | null>(null);
@@ -1283,6 +1153,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
} | null>(null);
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
const userBubbleMaxWidth = contentWidth * 0.85;
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
const insets = useSafeAreaInsets();
const topContentInset = props.contentTopInset ?? insets.top + 44;
@@ -1290,16 +1161,56 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const iconSubtleColor = useThemeColor("--color-icon-subtle");
const userBubbleColor = useThemeColor("--color-user-bubble");
const markdownStyles = useMarkdownStyles();
const onMarkdownLinkPress = useCallback(
(href: string) => {
const presentation = resolveMarkdownLinkPresentation(href);
if (presentation.kind === "file") {
const relativePath = resolveWorkspaceRelativeFilePath(
props.workspaceRoot,
presentation.path,
);
if (relativePath) {
void Haptics.selectionAsync();
router.push(
buildThreadFilesNavigation(
{ environmentId: props.environmentId, threadId: props.threadId },
relativePath,
presentation.line,
),
);
}
return;
}
if (presentation.href) {
void Linking.openURL(presentation.href);
}
},
[props.environmentId, props.threadId, props.workspaceRoot, router],
);
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
const reviewCommentColors = useReviewCommentColors();
// LegendList does not invalidate visible rows when only the renderItem closure changes.
// Keep row-local interaction props in extraData so disclosures and copy feedback repaint.
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
reviewCommentColors,
userBubbleColor,
}),
[iconSubtleColor, markdownStyles, reviewCommentColors, userBubbleColor],
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
reviewCommentColors,
userBubbleColor,
],
);
const presentedFeed = useMemo(
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
@@ -1490,11 +1401,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkRow,
onToggleTurnFold,
onPressImage,
onMarkdownLinkPress,
iconSubtleColor,
userBubbleColor,
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
skills: props.skills,
}),
[
@@ -1508,7 +1421,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
markdownStyles,
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
onCopyWorkRow,
onMarkdownLinkPress,
onPressImage,
onToggleTurnFold,
onToggleWorkGroup,
@@ -14,7 +14,7 @@ import { useLocalSearchParams, useRouter } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback, useMemo } from "react";
import { Alert, Linking } from "react-native";
import { buildThreadReviewRoutePath } from "../../lib/routes";
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
import {
basename,
getTerminalStatusLabel,
@@ -69,6 +69,7 @@ export function ThreadGitControls(props: {
readonly gitStatus: VcsStatusResult | null;
readonly gitOperationLabel: string | null;
readonly canOpenTerminal: boolean;
readonly canOpenFiles: boolean;
readonly projectScripts: ReadonlyArray<ProjectScript>;
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
readonly onOpenTerminal: (terminalId?: string | null) => void;
@@ -259,6 +260,14 @@ export function ThreadGitControls(props: {
>
<Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="folder"
disabled={!props.canOpenFiles}
onPress={() => router.push(buildThreadFilesNavigation({ environmentId, threadId }))}
subtitle="Browse this workspace"
>
<Stack.Toolbar.Label>Files</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
icon="ellipsis.circle"
onPress={() =>
@@ -420,6 +420,7 @@ export function ThreadRouteScreen() {
gitStatus={gitStatus.data}
gitOperationLabel={gitState.gitOperationLabel}
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
canOpenFiles={Boolean(selectedThreadProject?.workspaceRoot)}
projectScripts={selectedThreadProject?.scripts ?? []}
terminalSessions={terminalMenuSessions}
onOpenTerminal={handleOpenTerminal}
@@ -452,6 +453,7 @@ export function ThreadRouteScreen() {
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
selectedThreadQueueCount={composer.selectedThreadQueueCount}
onOpenDrawer={handleOpenDrawer}
onOpenConnectionEditor={handleOpenConnectionEditor}
@@ -0,0 +1,261 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: { type: LayoutAnimation.Types.easeInEaseOut },
delete: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
} as const;
function triggerDisclosureFeedback() {
LayoutAnimation.configureNext(WORK_LOG_LAYOUT_ANIMATION);
void Haptics.selectionAsync();
}
function stripShellWrapper(value: string): string {
const trimmed = value.trim();
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
return (match?.[1] ?? trimmed).trim();
}
function compactActivityDetail(detail: string | null): string | null {
if (!detail) {
return null;
}
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
return cleaned.length > 0 ? cleaned : null;
}
function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
switch (icon) {
case "agent":
return "sparkles";
case "alert":
return "exclamationmark.triangle";
case "check":
return "checkmark";
case "command":
return "terminal";
case "edit":
return "square.and.pencil";
case "eye":
return "eye";
case "globe":
return "globe";
case "hammer":
return "hammer";
case "message":
return "bubble.left";
case "warning":
return "xmark";
case "wrench":
return "wrench";
case "zap":
return "bolt";
}
}
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const rows = props.activities
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
if (rows.length === 0) {
return null;
}
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows =
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
return (
<View className="-mx-1 mb-3 px-1 py-0.5">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-[11px] text-foreground-muted opacity-60">
work log
</Text>
) : null}
<View className="gap-px">
{visibleRows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
return (
<View key={row.id}>
<Pressable
accessibilityRole={canExpand ? "button" : undefined}
accessibilityLabel={displayText}
accessibilityHint={
canExpand
? "Double tap to show full details. Long press to copy."
: "Long press to copy."
}
accessibilityState={canExpand ? { expanded } : undefined}
hitSlop={4}
onPress={() => {
if (canExpand) {
triggerDisclosureFeedback();
props.onToggleRow(row.id);
}
}}
onLongPress={() => props.onCopyRow(row.id, row.copyText)}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="rounded-md px-0.5 py-0.5"
>
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={14}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
numberOfLines={1}
>
<Text
className={cn(
"font-t3-medium text-foreground",
iconIsDestructive && "text-rose-600 dark:text-rose-400",
)}
>
{row.summary}
</Text>
{row.detail ? (
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
) : null}
</Text>
<View className="shrink-0 flex-row items-center gap-px">
{props.copiedRowId === row.id ? (
<Text className="pr-1 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
Copied
</Text>
) : null}
<View className="h-4 w-4 items-center justify-center">
{canExpand ? (
<SymbolView
name={expanded ? "chevron.up" : "chevron.down"}
size={11}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
) : null}
</View>
<View className="h-4 w-4 items-center justify-center">
{row.status ? (
<SymbolView
name={
row.status === "failure"
? "xmark"
: row.status === "success"
? "checkmark"
: "minus"
}
size={11}
tintColor={row.status === "failure" ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
) : null}
</View>
</View>
</View>
</Pressable>
{expanded && row.fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-[11px] leading-[17px] text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
</ScrollView>
</View>
) : null}
</View>
);
})}
</View>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? "Show fewer tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
}
hitSlop={4}
onPress={() => {
triggerDisclosureFeedback();
props.onToggleGroup();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
>
<View className="h-5 w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={13}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? "Show fewer tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
</Text>
</Pressable>
) : null}
</View>
);
}
+21
View File
@@ -16,26 +16,47 @@ describe("resolveMarkdownLinkPresentation", () => {
resolveMarkdownLinkPresentation("file:///Users/julius/project/src/main.ts#L42C7"),
).toEqual({
kind: "file",
href: "file:///Users/julius/project/src/main.ts#L42C7",
icon: "typescript",
label: "main.ts:42:7",
path: "/Users/julius/project/src/main.ts",
line: 42,
column: 7,
});
});
it("recognizes relative source paths and bare filenames", () => {
expect(resolveMarkdownLinkPresentation("apps/mobile/src/index.ts:10")).toEqual({
kind: "file",
href: "apps/mobile/src/index.ts:10",
icon: "typescript",
label: "index.ts:10",
path: "apps/mobile/src/index.ts",
line: 10,
});
expect(resolveMarkdownLinkPresentation("AGENTS.md")).toEqual({
kind: "file",
href: "AGENTS.md",
icon: "agents",
label: "AGENTS.md",
path: "AGENTS.md",
});
expect(resolveMarkdownLinkPresentation("package.json")).toEqual({
kind: "file",
href: "package.json",
icon: "package",
label: "package.json",
path: "package.json",
});
});
it("extracts line fragments from relative file links", () => {
expect(resolveMarkdownLinkPresentation("src/main.ts#L18C2")).toMatchObject({
kind: "file",
path: "src/main.ts",
line: 18,
column: 2,
label: "main.ts:18:2",
});
});
+22 -2
View File
@@ -7,6 +7,7 @@ import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
nativeMarkdownWithPreservedSoftBreaks,
} from "@t3tools/mobile-markdown-text/markdown";
describe("nativeMarkdownTextRuns", () => {
@@ -54,7 +55,11 @@ describe("nativeMarkdownTextRuns", () => {
externalHost: "example.com",
},
{ text: " " },
{ text: "README.md:12", fileIcon: "readme" },
{
text: "README.md:12",
href: "file:///repo/README.md#L12",
fileIcon: "readme",
},
]);
});
@@ -73,6 +78,21 @@ describe("nativeMarkdownTextRuns", () => {
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: "first second\nthird" }]);
});
it("can preserve soft breaks for authored user messages", () => {
const node: MarkdownNode = {
type: "paragraph",
children: [
{ type: "text", content: "first" },
{ type: "soft_break" },
{ type: "text", content: "second" },
],
};
expect(nativeMarkdownTextRuns(nativeMarkdownWithPreservedSoftBreaks(node))).toEqual([
{ text: "first\nsecond" },
]);
});
it("normalizes common inline HTML and entities", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -130,7 +150,7 @@ describe("nativeMarkdownTextRuns", () => {
});
describe("nativeMarkdownDocumentRuns", () => {
it("decorates known skill references as selectable skill chips", () => {
it("decorates known skill references as selectable skill links", () => {
const node: MarkdownNode = {
type: "document",
children: [
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { buildThreadFilesNavigation, buildThreadFilesRoutePath } from "./routes";
const thread = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
};
describe("thread file routes", () => {
it("includes an optional source line in string routes", () => {
expect(buildThreadFilesRoutePath(thread, "src/main.ts", 42)).toBe(
"/threads/environment-1/thread-1/files/src/main.ts?line=42",
);
});
it("encodes each file path segment without encoding separators", () => {
expect(buildThreadFilesRoutePath(thread, "docs/My File#1.md")).toBe(
"/threads/environment-1/thread-1/files/docs/My%20File%231.md",
);
});
it("builds typed navigation params for a file and source line", () => {
expect(buildThreadFilesNavigation(thread, "src/main.ts", 42)).toEqual({
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
params: {
environmentId: "environment-1",
threadId: "thread-1",
path: ["src", "main.ts"],
line: "42",
},
});
});
it("targets the files index when no file path is provided", () => {
expect(buildThreadFilesNavigation(thread)).toEqual({
pathname: "/threads/[environmentId]/[threadId]/files",
params: {
environmentId: "environment-1",
threadId: "thread-1",
},
});
});
});
+53
View File
@@ -32,6 +32,27 @@ export function buildThreadReviewRoutePath(
return `${buildThreadRoutePath(input)}/review`;
}
export function buildThreadFilesRoutePath(
input: ThreadRouteInput | PlainThreadRouteInput,
relativePath?: string | null,
line?: number | null,
): string {
const basePath = `${buildThreadRoutePath(input)}/files`;
if (!relativePath) {
return basePath;
}
const pathSegments = relativePath.split("/").filter((segment) => segment.length > 0);
if (pathSegments.length === 0) {
return basePath;
}
const encodedPath = pathSegments.map(encodeURIComponent).join("/");
const lineParam =
Number.isFinite(line) && Number(line) > 0 ? `?line=${Math.floor(Number(line))}` : "";
return `${basePath}/${encodedPath}${lineParam}`;
}
export function buildThreadTerminalRoutePath(
input: ThreadRouteInput | PlainThreadRouteInput,
terminalId?: string | null,
@@ -71,6 +92,38 @@ export function buildThreadTerminalNavigation(
};
}
export function buildThreadFilesNavigation(
input: ThreadRouteInput | PlainThreadRouteInput,
relativePath?: string | null,
line?: number | null,
): Href {
const environmentId = String(input.environmentId);
const threadId = String("threadId" in input ? input.threadId : input.id);
const path = relativePath?.split("/").filter((segment) => segment.length > 0) ?? [];
if (path.length === 0) {
return {
pathname: "/threads/[environmentId]/[threadId]/files",
params: { environmentId, threadId },
};
}
const params: {
environmentId: string;
threadId: string;
path: string[];
line?: string;
} = { environmentId, threadId, path };
if (Number.isFinite(line) && Number(line) > 0) {
params.line = String(Math.floor(Number(line)));
}
return {
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
params,
};
}
export function dismissRoute(router: Router) {
if (router.canGoBack()) {
router.back();
+53 -2
View File
@@ -161,14 +161,65 @@ describe("buildThreadFeed", () => {
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
fullDetail: null,
copyText: "Run tests\nbun run test",
fullDetail: "/bin/zsh -lc 'bun run test'",
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
icon: "command",
toolLike: true,
status: "success",
},
]);
});
it("keeps MCP inputs available to expanded mobile work rows", () => {
const turnId = TurnId.make("turn-mcp");
const thread = makeThread({
id: ThreadId.make("thread-mcp"),
projectId: ProjectId.make("project-1"),
title: "Expandable MCP call",
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: "2026-04-01T00:00:03.000Z",
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("mcp-completed"),
kind: "tool.completed",
tone: "tool",
summary: "Call repository tool",
createdAt: "2026-04-01T00:00:02.000Z",
turnId,
payload: {
title: "Call repository tool",
itemType: "mcp_tool_call",
detail: "repository.search",
status: "completed",
data: {
item: {
server: "repository",
tool: "search",
arguments: { query: "work log" },
},
},
},
}),
],
});
const group = buildThreadFeed(thread, [], null)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities[0]?.icon).toBe("wrench");
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
expect(group.activities[0]?.fullDetail).toContain("repository.search");
});
it("folds settled turn work while leaving the terminal answer visible", () => {
const turnId = TurnId.make("turn-1");
const thread = makeThread({
+72 -9
View File
@@ -40,6 +40,19 @@ export interface ThreadFeedActivity {
readonly detail: string | null;
readonly fullDetail: string | null;
readonly copyText: string;
readonly icon:
| "agent"
| "alert"
| "check"
| "command"
| "edit"
| "eye"
| "globe"
| "hammer"
| "message"
| "warning"
| "wrench"
| "zap";
readonly toolLike: boolean;
readonly status: "success" | "failure" | "neutral" | null;
}
@@ -60,6 +73,7 @@ interface WorkLogEntry {
itemType?: ToolLifecycleItemType;
requestKind?: PendingApproval["requestKind"];
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
toolData?: unknown;
}
interface DerivedWorkLogEntry extends WorkLogEntry {
@@ -214,7 +228,7 @@ function resolvePendingUserInputAnswer(
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): WorkLogEntry[] {
): DerivedWorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
@@ -225,9 +239,7 @@ function deriveWorkLogEntries(
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries).map(
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
);
return collapseDerivedWorkLogEntries(entries);
}
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
@@ -301,6 +313,12 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (title) {
entry.toolTitle = title;
}
if (itemType === "mcp_tool_call") {
const data = asRecord(payload?.data);
if (data?.item !== undefined) {
entry.toolData = data.item;
}
}
if (itemType) {
entry.itemType = itemType;
}
@@ -365,6 +383,7 @@ function mergeDerivedWorkLogEntries(
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
const toolData = next.toolData ?? previous.toolData;
return {
...previous,
...next,
@@ -377,6 +396,7 @@ function mergeDerivedWorkLogEntries(
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
...(toolData !== undefined ? { toolData } : {}),
};
}
@@ -480,6 +500,52 @@ function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
return "neutral";
}
function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
if (
entry.activityKind === "user-input.requested" ||
entry.activityKind === "user-input.resolved"
) {
return "message";
}
if (entry.activityKind === "runtime.warning") return "warning";
if (entry.requestKind === "command") return "command";
if (entry.requestKind === "file-read") return "eye";
if (entry.requestKind === "file-change") return "edit";
if (entry.itemType === "command_execution" || entry.command) return "command";
if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
if (entry.itemType === "web_search") return "globe";
if (entry.itemType === "image_view") return "eye";
if (entry.itemType === "mcp_tool_call") return "wrench";
if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
return "hammer";
}
if (entry.tone === "error") return "alert";
if (entry.tone === "thinking") return "agent";
if (entry.tone === "info") return "check";
return "zap";
}
function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
const blocks: string[] = [];
const appendUniqueBlock = (value: string | null | undefined) => {
const trimmed = value?.trim();
if (trimmed && !blocks.includes(trimmed)) {
blocks.push(trimmed);
}
};
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
}
appendUniqueBlock(entry.rawCommand ?? entry.command);
appendUniqueBlock(entry.detail);
if ((entry.changedFiles?.length ?? 0) > 0) {
appendUniqueBlock(entry.changedFiles!.join("\n"));
}
return blocks.length > 0 ? blocks.join("\n\n") : null;
}
function workEntryPreview(
workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
): string | null {
@@ -1226,11 +1292,7 @@ export function buildThreadFeed(
.map<RawThreadFeedEntry>((entry) => {
const summary = workEntryHeading(entry);
const detail = workEntryPreview(entry);
const normalizedFullDetail = entry.detail
? unwrapKnownShellCommandWrapper(entry.detail)
: null;
const fullDetail =
normalizedFullDetail && normalizedFullDetail !== detail ? normalizedFullDetail : null;
const fullDetail = buildWorkEntryExpandedBody(entry);
return {
type: "activity",
id: entry.id,
@@ -1243,6 +1305,7 @@ export function buildThreadFeed(
summary,
detail,
fullDetail,
icon: workEntryIcon(entry),
copyText: [summary, detail, fullDetail]
.filter((value, index, values): value is string => {
return Boolean(value) && values.indexOf(value) === index;
@@ -89,6 +89,42 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact workspace URLs for image previews", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-image-workspace-",
});
const assetsDirectory = path.join(root, "assets");
const imagePath = path.join(assetsDirectory, "icon.png");
const siblingPath = path.join(assetsDirectory, "other.png");
yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
const result = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: imagePath,
},
workspaceRoot: root,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "icon.png")).toEqual({
kind: "file",
path: canonicalImagePath,
});
expect(yield* resolveAsset(token, "other.png")).toBeNull();
expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
+45 -21
View File
@@ -1,5 +1,11 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -24,22 +30,14 @@ export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
const PREVIEW_ASSET_EXTENSIONS = new Set([
...PREVIEWABLE_EXTENSIONS,
".avif",
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
".css",
".gif",
".ico",
".jpeg",
".jpg",
".js",
".mjs",
".otf",
".png",
".svg",
".ttf",
".webp",
".woff",
".woff2",
]);
@@ -52,6 +50,13 @@ const AssetClaimsSchema = Schema.Union([
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file-exact"),
workspaceRoot: Schema.String,
relativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
@@ -144,8 +149,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
return yield* failAccess("Only HTML and PDF files can open in the browser.");
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* failAccess("Only browser documents and images can be previewed.");
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
@@ -154,15 +159,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
}
claims = {
version: 1,
kind: "workspace-file",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
const canonicalWorkspaceRoot = yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
? {
version: 1,
kind: "workspace-file-exact",
workspaceRoot: canonicalWorkspaceRoot,
relativePath: resolved.relativePath,
expiresAt,
}
: {
version: 1,
kind: "workspace-file",
workspaceRoot: canonicalWorkspaceRoot,
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
fileName = path.basename(resolved.relativePath);
break;
}
@@ -268,6 +282,16 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return exactWorkspaceFile
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
: null;
}
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
@@ -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,275 @@
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 (hostPower.suspended) return true;
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
@@ -91,7 +91,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),
@@ -298,6 +298,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),
@@ -370,6 +373,9 @@ export const resolveServerConfig = (
noBrowser,
startupPresentation,
desktopBootstrapToken,
desktopTelemetryFd,
desktopTelemetryControlFd,
resourceMonitorPath,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
+6
View File
@@ -69,6 +69,9 @@ export interface ServerConfigShape extends ServerDerivedPaths {
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;
@@ -171,6 +174,9 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
desktopTelemetryFd: undefined,
desktopTelemetryControlFd: undefined,
resourceMonitorPath: undefined,
staticDir: undefined,
devUrl,
noBrowser: false,
@@ -1,243 +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 * 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("does not allow signaling the diagnostics query process", () =>
it.effect("rejects stale process identities before signaling", () =>
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),
);
@@ -245,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."),
});
}),
);
+139 -415
View File
@@ -1,40 +1,23 @@
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
export interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
readonly status: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly elapsed: string;
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
readonly signal: (input: {
readonly pid: number;
readonly startTimeMs: number;
readonly signal: ServerProcessSignal;
}) => Effect.Effect<ServerSignalProcessResult>;
}
@@ -44,420 +27,161 @@ export class ProcessDiagnostics extends Context.Service<
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
"ProcessDiagnosticsError",
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
"ProcessIdentityChanged",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
pid: Schema.Number,
startTimeMs: Schema.Number,
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
message,
...(cause === undefined ? {} : { cause }),
});
}
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
for (const line of output.split(/\r?\n/)) {
if (line.trim().length === 0) continue;
const match = rowPattern.exec(line);
if (!match) continue;
const pidText = match[1];
const ppidText = match[2];
const pgidText = match[3];
const status = match[4];
const cpuText = match[5];
const rssText = match[6];
const elapsed = match[7];
const command = match[8];
if (
pidText === undefined ||
ppidText === undefined ||
pgidText === undefined ||
status === undefined ||
cpuText === undefined ||
rssText === undefined ||
elapsed === undefined ||
command === undefined
) {
continue;
}
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid,
ppid,
pgid,
status,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
}
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 [];
) {
override get message(): string {
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
}
}
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);
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
"ProcessSignalFailed",
{
pid: Schema.Number,
signal: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to signal process ${this.pid} with ${this.signal}.`;
}
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;
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
const command = row.command.trim();
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 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))
);
}
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 exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const runProcess = Effect.fn("runProcess")(
function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly errorMessage: string;
}) {
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: process.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 {
exitCode,
stdout: stdout.text,
stderr: stderr.text,
} satisfies ProcessOutput;
},
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
),
);
function readPosixProcessRows(): Effect.Effect<
ReadonlyArray<ProcessRow>,
ProcessDiagnosticsError,
ChildProcessSpawner.ChildProcessSpawner
> {
return runProcess({
command: "ps",
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
: 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],
errorMessage: "Failed to query process diagnostics.",
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
)
: 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(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
}
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(
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
);
}),
category === "server-child" || category === "provider-root" || category === "terminal-root"
);
}
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const read: ProcessDiagnosticsShape["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 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,
}),
);
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 })),
};
}),
);
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) =>
toProcessDiagnosticsError(
`Failed to signal process ${input.pid} with ${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.",
),
}),
),
);
},
);
@@ -1,231 +1,132 @@
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 {
aggregateProcessResourceHistory,
collectMonitoredSamples,
} from "./ProcessResourceMonitor.ts";
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 = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
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 history: ResourceTelemetryHistory = {
readAt,
windowMs: 60_000,
bucketMs: 10_000,
sampleIntervalMs: 1_000,
retainedSampleCount: 2,
buckets: [
{
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",
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,
},
],
});
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 = [
...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",
},
],
}),
...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 = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: 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 = [
...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",
},
],
}),
...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 = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: 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 = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
topProcesses: [
{
pid: 100,
identity: { pid: process.pid, startTimeMs: 100 },
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
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,
},
...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}`,
})),
],
});
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),
),
),
);
const result = aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
Effect.flatMap((monitor) =>
monitor.readHistory({
windowMs: 60_000,
bucketMs: 10_000,
}),
),
Effect.provide(layer),
);
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
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(result.error).toEqual(Option.some({ message: "collector stalled" }));
}),
);
});
@@ -1,45 +1,13 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
} 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 { ChildProcessSpawner } from "effect/unstable/process";
import {
buildDescendantEntries,
isDiagnosticsQueryProcess,
type ProcessRow,
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
}
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
export interface ProcessResourceMonitorShape {
readonly readHistory: (
@@ -52,246 +20,51 @@ export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const root = findServerRootRow(rows, input.serverPid);
const descendants = 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 lastError: string | 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.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* 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),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
const readHistory: ProcessResourceMonitorShape["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,
lastError: current.lastError,
});
});
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) => ({ message }))),
};
}),
);
return ProcessResourceMonitor.of({ readHistory });
});
+20
View File
@@ -61,6 +61,18 @@ export interface GitWorkflowServiceShape {
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly fetchRemote: (input: {
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<void, GitCommandError>;
readonly resolveRemoteTrackingCommit: (input: {
readonly cwd: string;
readonly refName: string;
readonly fallbackRemoteName: string;
}) => Effect.Effect<
{ readonly commitSha: string; readonly remoteRefName: string },
GitCommandError
>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
@@ -295,6 +307,14 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
fetchRemote: (input) =>
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
),
resolveRemoteTrackingCommit: (input) =>
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
),
removeWorktree: (input) =>
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
Effect.andThen(git.removeWorktree(input)),
+28 -6
View File
@@ -8,16 +8,18 @@ import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
const environmentId = EnvironmentId.make("environment-1");
const fakeHttpServer = HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const makeFakeHttpServer = (hostname: string, port = 43123) =>
HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname, port },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const fakeHttpServer = makeFakeHttpServer("127.0.0.1");
const fakeEnvironment = ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.die("unused"),
});
const makeRegistry = (now: () => number) =>
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
McpSessionRegistry.__testing
.make({
now,
@@ -25,7 +27,7 @@ const makeRegistry = (now: () => number) =>
maximumLifetimeMs: 1_000,
})
.pipe(
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
Effect.provideService(HttpServer.HttpServer, httpServer),
Effect.provideService(ServerEnvironment, fakeEnvironment),
Effect.provide(NodeServices.layer),
);
@@ -53,6 +55,26 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
}),
);
it.effect("builds MCP endpoints from the bound server host", () =>
Effect.gen(function* () {
const cases = [
["100.64.0.40", "http://100.64.0.40:43123/mcp"],
["0.0.0.0", "http://127.0.0.1:43123/mcp"],
["localhost", "http://localhost:43123/mcp"],
["127.0.0.1", "http://127.0.0.1:43123/mcp"],
] as const;
for (const [hostname, expectedEndpoint] of cases) {
const registry = yield* makeRegistry(() => 1_000, makeFakeHttpServer(hostname));
const issued = yield* registry.issue({
threadId: ThreadId.make(`thread-${hostname}`),
providerInstanceId: ProviderInstanceId.make("codex"),
});
expect(issued.config.endpoint).toBe(expectedEndpoint);
}
}),
);
it.effect("expires credentials after inactivity", () =>
Effect.gen(function* () {
let timestamp = 1_000;
+12 -1
View File
@@ -60,6 +60,17 @@ const bytesToHex = (bytes: Uint8Array): string =>
const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
const getHttpMcpEndpointHost = (hostname: string): string => {
const normalized = hostname.toLowerCase();
const endpointHostname =
normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]"
? "127.0.0.1"
: hostname;
return endpointHostname.includes(":") && !endpointHostname.startsWith("[")
? `[${endpointHostname}]`
: endpointHostname;
};
const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
options: McpSessionRegistryOptions = {},
) {
@@ -73,7 +84,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
const endpoint =
httpServer.address._tag === "TcpAddress"
? `http://127.0.0.1:${httpServer.address.port}/mcp`
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
: "http://127.0.0.1/mcp";
const hashToken = (token: string) =>
@@ -7,6 +7,7 @@ import * as Tracer from "effect/Tracer";
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { ServerConfig } from "../../config.ts";
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
import { ServerLoggerLive } from "../../serverLogger.ts";
import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts";
@@ -15,6 +16,7 @@ const otlpSerializationLayer = OtlpSerialization.layerJson;
export const ObservabilityLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
const attribution = yield* ResourceAttribution.ResourceAttribution;
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
@@ -29,6 +31,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
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more