Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d184f0660 | ||
|
|
038e209ece | ||
|
|
a41f4895ce | ||
|
|
d15909af15 | ||
|
|
447236d51f | ||
|
|
5165b8c333 | ||
|
|
8fc317939f | ||
|
|
16c69ba7ff | ||
|
|
e64c19f1af | ||
|
|
6ab8f93a23 | ||
|
|
b793401aee |
No files matched your search
@@ -625,6 +625,9 @@ jobs:
|
||||
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
|
||||
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
|
||||
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
|
||||
router_domain="${router_url#http://}"
|
||||
router_domain="${router_domain#https://}"
|
||||
router_domain="${router_domain%%/*}"
|
||||
|
||||
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
|
||||
channel_domain="$latest_domain"
|
||||
@@ -655,6 +658,13 @@ jobs:
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}"
|
||||
|
||||
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
|
||||
echo "Aliasing $deployment_url to router domain $router_domain."
|
||||
bunx [email protected] alias set "$deployment_url" "$router_domain" \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}"
|
||||
fi
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -73,7 +73,6 @@ import {
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
@@ -311,8 +310,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.succeed({ branch: input.newBranch }),
|
||||
});
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -31,8 +31,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
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),
|
||||
setDemandActive: () => Effect.void,
|
||||
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" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
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 (
|
||||
(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.catch(() => Effect.succeed(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.tap((next) => hostPowerMonitor.setDemandActive(next.activeForegroundLeaseCount > 0)),
|
||||
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,209 @@
|
||||
import {
|
||||
type BackgroundBooleanState,
|
||||
type HostPowerSnapshot,
|
||||
type HostPowerThermalState,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly setDemandActive: (active: boolean) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
|
||||
"t3/background/HostPowerMonitor",
|
||||
) {}
|
||||
|
||||
const COMMAND_TIMEOUT = Duration.seconds(3);
|
||||
|
||||
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 boolState(value: boolean | null): BackgroundBooleanState {
|
||||
if (value === null) return "unknown";
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function parseIdleSeconds(ioregOutput: string): number | null {
|
||||
const match = /"HIDIdleTime"\s*=\s*(\d+)/u.exec(ioregOutput);
|
||||
if (!match) return null;
|
||||
const nanoseconds = Number(match[1]);
|
||||
return Number.isFinite(nanoseconds) ? Math.floor(nanoseconds / 1_000_000_000) : null;
|
||||
}
|
||||
|
||||
function parseOnBattery(pmsetBatteryOutput: string): boolean | null {
|
||||
if (/Now drawing from 'Battery Power'/iu.test(pmsetBatteryOutput)) return true;
|
||||
if (/Now drawing from 'AC Power'/iu.test(pmsetBatteryOutput)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseLowPowerMode(pmsetOutput: string): boolean | null {
|
||||
const match = /^\s*lowpowermode\s+([01])\s*$/imu.exec(pmsetOutput);
|
||||
if (!match) return null;
|
||||
return match[1] === "1";
|
||||
}
|
||||
|
||||
function parseThermalState(_output: string): HostPowerThermalState {
|
||||
// The stable shell adapter intentionally does not parse `pmset thermlog`;
|
||||
// native adapters can provide this without depending on human-formatted text.
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function runOptional(
|
||||
runner: ProcessRunner.ProcessRunnerShape,
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) {
|
||||
return runner
|
||||
.run({
|
||||
command,
|
||||
args,
|
||||
timeout: COMMAND_TIMEOUT,
|
||||
timeoutBehavior: "timedOutResult",
|
||||
outputMode: "truncate",
|
||||
maxOutputBytes: 32_000,
|
||||
})
|
||||
.pipe(Effect.option);
|
||||
}
|
||||
|
||||
const readMacShellSnapshot = Effect.fn("background.hostPower.readMacShellSnapshot")(function* () {
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const updatedAt = yield* DateTime.now;
|
||||
const [idleOutput, batteryOutput, pmsetOutput] = yield* Effect.all(
|
||||
[
|
||||
runOptional(runner, "ioreg", ["-c", "IOHIDSystem"]),
|
||||
runOptional(runner, "pmset", ["-g", "batt"]),
|
||||
runOptional(runner, "pmset", ["-g"]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const idleSeconds = idleOutput._tag === "Some" ? parseIdleSeconds(idleOutput.value.stdout) : null;
|
||||
const onBattery =
|
||||
batteryOutput._tag === "Some" ? parseOnBattery(batteryOutput.value.stdout) : null;
|
||||
const lowPowerMode =
|
||||
pmsetOutput._tag === "Some" ? parseLowPowerMode(pmsetOutput.value.stdout) : null;
|
||||
|
||||
return {
|
||||
source: "node-macos-shell",
|
||||
idle: boolState(idleSeconds === null ? null : idleSeconds >= 60),
|
||||
idleSeconds,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: boolState(onBattery),
|
||||
lowPowerMode: boolState(lowPowerMode),
|
||||
thermalState: parseThermalState(""),
|
||||
stale: false,
|
||||
updatedAt,
|
||||
} satisfies HostPowerSnapshot;
|
||||
});
|
||||
|
||||
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 demandActiveRef = yield* Ref.make(false);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitorShape["report"] = (snapshot) =>
|
||||
Ref.set(latestRef, snapshot).pipe(
|
||||
Effect.andThen(PubSub.publish(changes, snapshot)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
setDemandActive: (active) => Ref.set(demandActiveRef, active),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
|
||||
const unknownLayer = Layer.effect(HostPowerMonitor, make("unknown"));
|
||||
const linuxLayer = Layer.effect(HostPowerMonitor, make("node-linux"));
|
||||
const windowsLayer = Layer.effect(HostPowerMonitor, make("node-windows"));
|
||||
|
||||
const macShellLayer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const monitor = yield* make("node-macos-shell");
|
||||
const demandActiveRef = yield* Ref.make(true);
|
||||
const setDemandActive: HostPowerMonitorShape["setDemandActive"] = (active) =>
|
||||
Ref.set(demandActiveRef, active);
|
||||
const getPollInterval = Effect.gen(function* () {
|
||||
const demandActive = yield* Ref.get(demandActiveRef);
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.catch(() => Effect.succeed(getBackgroundActivityPresetSettings("balanced"))),
|
||||
);
|
||||
return demandActive
|
||||
? settings.hostPowerMonitorActiveInterval
|
||||
: settings.hostPowerMonitorIdleInterval;
|
||||
});
|
||||
const adaptiveMonitor = HostPowerMonitor.of({
|
||||
snapshot: monitor.snapshot,
|
||||
report: monitor.report,
|
||||
setDemandActive,
|
||||
streamChanges: monitor.streamChanges,
|
||||
});
|
||||
yield* readMacShellSnapshot().pipe(
|
||||
Effect.flatMap(adaptiveMonitor.report),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
yield* Effect.forever(
|
||||
getPollInterval.pipe(
|
||||
Effect.flatMap((interval) => Effect.sleep(Duration.max(interval, Duration.seconds(5)))),
|
||||
Effect.andThen(readMacShellSnapshot()),
|
||||
Effect.flatMap(adaptiveMonitor.report),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
return adaptiveMonitor;
|
||||
}),
|
||||
).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
export const layer = Layer.unwrap(
|
||||
Effect.sync(() => {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return macShellLayer;
|
||||
case "linux":
|
||||
return linuxLayer;
|
||||
case "win32":
|
||||
return windowsLayer;
|
||||
default:
|
||||
return unknownLayer;
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -41,11 +41,110 @@ function makeThreadCheckpointContext(input: {
|
||||
}
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("uses the narrow full-thread context lookup for all-turns diffs", async () => {
|
||||
const projectId = ProjectId.make("project-full-thread");
|
||||
const threadId = ThreadId.make("thread-full-thread");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
|
||||
let getThreadCheckpointContextCalls = 0;
|
||||
let getFullThreadDiffContextCalls = 0;
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () =>
|
||||
Effect.sync(() => {
|
||||
getThreadCheckpointContextCalls += 1;
|
||||
return Option.none();
|
||||
}),
|
||||
getFullThreadDiffContext: () =>
|
||||
Effect.sync(() => {
|
||||
getFullThreadDiffContextCalls += 1;
|
||||
return Option.some({
|
||||
threadId,
|
||||
projectId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: "/tmp/worktree",
|
||||
latestCheckpointTurnCount: 4,
|
||||
toCheckpointRef,
|
||||
});
|
||||
}),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getFullThreadDiff({
|
||||
threadId,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(getThreadCheckpointContextCalls).toBe(0);
|
||||
expect(getFullThreadDiffContextCalls).toBe(1);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/worktree",
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 4,
|
||||
diff: "full thread diff patch",
|
||||
});
|
||||
});
|
||||
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
@@ -65,11 +164,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: ({ checkpointRef }) =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCalls.push(checkpointRef);
|
||||
return true;
|
||||
}),
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
@@ -102,6 +197,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
@@ -121,7 +217,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
);
|
||||
|
||||
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/workspace",
|
||||
@@ -184,6 +279,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
@@ -204,6 +300,74 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
});
|
||||
|
||||
it("does not preflight checkpoint refs before diffing", async () => {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
const threadId = ThreadId.make("thread-no-preflight");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
let hasCheckpointRefCallCount = 0;
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCallCount += 1;
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(hasCheckpointRefCallCount).toBe(0);
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
@@ -234,6 +398,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
type CheckpointRef,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
type OrchestrationGetFullThreadDiffInput,
|
||||
type ThreadId,
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -20,6 +21,22 @@ import {
|
||||
|
||||
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
|
||||
|
||||
function buildTurnDiffResult(
|
||||
input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly fromTurnCount: number;
|
||||
readonly toTurnCount: number;
|
||||
},
|
||||
diff: string,
|
||||
): OrchestrationGetTurnDiffResultType {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
@@ -28,6 +45,12 @@ const make = Effect.gen(function* () {
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"checkpoint.thread_id": input.threadId,
|
||||
"checkpoint.from_turn_count": input.fromTurnCount,
|
||||
"checkpoint.to_turn_count": input.toTurnCount,
|
||||
"checkpoint.ignore_whitespace": ignoreWhitespace,
|
||||
});
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -45,9 +68,9 @@ const make = Effect.gen(function* () {
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
||||
input.threadId,
|
||||
);
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(input.threadId)
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
@@ -100,50 +123,17 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const [fromExists, toExists] = yield* Effect.all(
|
||||
[
|
||||
checkpointStore.hasCheckpointRef({
|
||||
cwd: workspaceCwd,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
}),
|
||||
checkpointStore.hasCheckpointRef({
|
||||
cwd: workspaceCwd,
|
||||
checkpointRef: toCheckpointRef,
|
||||
}),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
|
||||
|
||||
if (!fromExists) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!toExists) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
const turnDiff = buildTurnDiffResult(input, diff);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
@@ -155,15 +145,99 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) =>
|
||||
getTurnDiff({
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = Effect.fn(
|
||||
"CheckpointDiffQuery.getFullThreadDiff",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getFullThreadDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"checkpoint.thread_id": input.threadId,
|
||||
"checkpoint.from_turn_count": 0,
|
||||
"checkpoint.to_turn_count": input.toTurnCount,
|
||||
"checkpoint.ignore_whitespace": ignoreWhitespace,
|
||||
"checkpoint.diff_kind": "full-thread",
|
||||
});
|
||||
|
||||
if (input.toTurnCount === 0) {
|
||||
const emptyDiff = buildTurnDiffResult(
|
||||
{
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 0,
|
||||
},
|
||||
"",
|
||||
);
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
}
|
||||
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
|
||||
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!threadContext.value.toCheckpointRef) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
|
||||
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
diff,
|
||||
);
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: "Computed full thread diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
});
|
||||
|
||||
return {
|
||||
getTurnDiff,
|
||||
|
||||
@@ -1,304 +1,79 @@
|
||||
/**
|
||||
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
|
||||
*
|
||||
* Implements hidden Git-ref checkpoint capture/restore directly with
|
||||
* Effect-native child process execution (`effect/unstable/process`).
|
||||
*
|
||||
* This layer owns filesystem/Git interactions only; it does not persist
|
||||
* checkpoint metadata and does not coordinate provider rollback semantics.
|
||||
* Resolves the active VCS driver once per checkpoint operation and delegates
|
||||
* checkpoint-specific behavior to the driver's optional checkpoint capability.
|
||||
*
|
||||
* @module CheckpointStoreLive
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import type { VcsCheckpointOps } from "../../vcs/VcsDriver.ts";
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
const vcs = {
|
||||
execute: (input: {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) =>
|
||||
vcsRegistry
|
||||
.resolve({ cwd: input.cwd, requestedKind: "git" })
|
||||
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
|
||||
};
|
||||
|
||||
const resolveHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const hasHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
.execute({
|
||||
operation: "CheckpointStore.hasHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
||||
|
||||
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
|
||||
vcs
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveCheckpointCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd });
|
||||
if (!handle.driver.checkpoints) {
|
||||
return yield* new VcsUnsupportedOperationError({
|
||||
operation,
|
||||
kind: handle.kind,
|
||||
detail: `${handle.kind} driver does not implement checkpoint operations.`,
|
||||
});
|
||||
}
|
||||
return handle.driver.checkpoints satisfies VcsCheckpointOps;
|
||||
});
|
||||
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
vcs
|
||||
.execute({
|
||||
operation: "CheckpointStore.isGitRepository",
|
||||
cwd,
|
||||
args: ["rev-parse", "--is-inside-work-tree"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
|
||||
return yield* checkpoints.captureCheckpoint(input);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||
Effect.map((commit) => commit !== null),
|
||||
);
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = Effect.fn("hasCheckpointRef")(
|
||||
function* (input) {
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
|
||||
return yield* checkpoints.hasCheckpointRef(input);
|
||||
},
|
||||
);
|
||||
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
|
||||
return yield* checkpoints.restoreCheckpoint(input);
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointStore.diffCheckpoints";
|
||||
|
||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
|
||||
|
||||
if (!fromCommitOid && input.fallbackFromToHead === true) {
|
||||
const headCommit = yield* resolveHeadCommit(input.cwd);
|
||||
if (headCommit) {
|
||||
fromCommitOid = headCommit;
|
||||
}
|
||||
}
|
||||
|
||||
if (!fromCommitOid || !toCommitOid) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
exitCode: 1,
|
||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
];
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: diffArgs,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
|
||||
return yield* checkpoints.diffCheckpoints(input);
|
||||
},
|
||||
);
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
const checkpoints = yield* resolveCheckpoints(
|
||||
"CheckpointStore.deleteCheckpointRefs",
|
||||
input.cwd,
|
||||
);
|
||||
return yield* checkpoints.deleteCheckpointRefs(input);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as Path from "effect/Path";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
|
||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
@@ -93,4 +94,6 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
} satisfies ServerEnvironmentShape;
|
||||
});
|
||||
|
||||
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
|
||||
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
|
||||
Layer.provide(ProcessRunnerLive),
|
||||
);
|
||||
@@ -1,20 +1,36 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { vi } from "vitest";
|
||||
|
||||
vi.mock("../../processRunner.ts", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const runMock = vi.fn<ProcessRunnerShape["run"]>();
|
||||
|
||||
const ProcessRunnerTest = Layer.succeed(
|
||||
ProcessRunner,
|
||||
ProcessRunner.of({
|
||||
run: (input) => runMock(input),
|
||||
}),
|
||||
);
|
||||
const NoopFileSystemLayer = FileSystem.layerNoop({});
|
||||
const TestLayer = Layer.merge(NoopFileSystemLayer, ProcessRunnerTest);
|
||||
const LinuxMachineInfoLayer = Layer.merge(
|
||||
ProcessRunnerTest,
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
||||
readFileString: (path) =>
|
||||
path === "/etc/machine-info"
|
||||
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
||||
: Effect.succeed(""),
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
mockedRunProcess.mockReset();
|
||||
runMock.mockReset();
|
||||
});
|
||||
|
||||
describe("resolveServerEnvironmentLabel", () => {
|
||||
@@ -24,7 +40,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
@@ -32,25 +48,30 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
it.effect("prefers the macOS ComputerName", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " Julius's MacBook Pro \n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.succeed({
|
||||
stdout: " Julius's MacBook Pro \n",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("Julius's MacBook Pro");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"scutil",
|
||||
["--get", "ComputerName"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
expect(runMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "scutil",
|
||||
args: ["--get", "ComputerName"],
|
||||
timeoutBehavior: "timedOutResult",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -61,44 +82,39 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "buildbox",
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
||||
readFileString: (path) =>
|
||||
path === "/etc/machine-info"
|
||||
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
||||
: Effect.succeed(""),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(LinuxMachineInfoLayer));
|
||||
|
||||
expect(result).toBe("Build Agent 01");
|
||||
expect(mockedRunProcess).not.toHaveBeenCalled();
|
||||
expect(runMock).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: "CI Runner\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.succeed({
|
||||
stdout: "CI Runner\n",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: "runner-01",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("CI Runner");
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"hostnamectl",
|
||||
["--pretty"],
|
||||
expect.objectContaining({ allowNonZeroExit: true }),
|
||||
expect(runMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "hostnamectl",
|
||||
args: ["--pretty"],
|
||||
timeoutBehavior: "timedOutResult",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -109,7 +125,7 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
cwdBaseName: "t3code",
|
||||
platform: "win32",
|
||||
hostname: "JULIUS-LAPTOP",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("JULIUS-LAPTOP");
|
||||
}),
|
||||
@@ -117,13 +133,21 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new ProcessSpawnError({
|
||||
command: "scutil",
|
||||
args: ["--get", "ComputerName"],
|
||||
cause: new Error("spawn scutil ENOENT"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "darwin",
|
||||
hostname: "macbook-pro",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("macbook-pro");
|
||||
}),
|
||||
@@ -131,19 +155,22 @@ describe("resolveServerEnvironmentLabel", () => {
|
||||
|
||||
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: " ",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
runMock.mockReturnValueOnce(
|
||||
Effect.succeed({
|
||||
stdout: " ",
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName: "t3code",
|
||||
platform: "linux",
|
||||
hostname: " ",
|
||||
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||
}).pipe(Effect.provide(TestLayer));
|
||||
|
||||
expect(result).toBe("t3code");
|
||||
}),
|
||||
|
||||
@@ -2,8 +2,9 @@ import * as OS from "node:os";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { ProcessRunner } from "../../processRunner.ts";
|
||||
|
||||
interface ResolveServerEnvironmentLabelInput {
|
||||
readonly cwdBaseName: string;
|
||||
@@ -52,19 +53,21 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
catch: () => null,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
const processRunner = yield* ProcessRunner;
|
||||
const result = yield* processRunner
|
||||
.run({
|
||||
command,
|
||||
args,
|
||||
timeoutBehavior: "timedOutResult",
|
||||
shell: process.platform === "win32",
|
||||
})
|
||||
.pipe(Effect.option);
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
if (Option.isNone(result) || result.value.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeLabel(result.stdout);
|
||||
return normalizeLabel(result.value.stdout);
|
||||
});
|
||||
|
||||
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
||||
|
||||
@@ -1,241 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser and workspace
|
||||
* paths in a configured editor.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { OpenError };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
|
||||
function parseTargetPathAndPosition(target: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} | null {
|
||||
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
|
||||
if (!match?.[1] || !match[2]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
path: match[1],
|
||||
line: match[2],
|
||||
column: match[3],
|
||||
};
|
||||
}
|
||||
|
||||
function resolveCommandEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const parsedTarget = parseTargetPathAndPosition(target);
|
||||
|
||||
switch (editor.launchStyle) {
|
||||
case "direct-path":
|
||||
return [target];
|
||||
case "goto":
|
||||
return parsedTarget ? ["--goto", target] : [target];
|
||||
case "line-column": {
|
||||
if (!parsedTarget) {
|
||||
return [target];
|
||||
}
|
||||
|
||||
const { path, line, column } = parsedTarget;
|
||||
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): string | null {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
return command;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.commands === null) {
|
||||
const command = fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const command = resolveAvailableCommand(editor.commands, { platform, env });
|
||||
if (command !== null) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface OpenShape {
|
||||
/**
|
||||
* Open a URL target in the default browser.
|
||||
*/
|
||||
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
|
||||
|
||||
/**
|
||||
* Open a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"open.editor": input.editor,
|
||||
"open.cwd": input.cwd,
|
||||
"open.platform": platform,
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
const command =
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
export const OpenLive = Layer.effect(Open, make);
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
@@ -37,7 +38,6 @@ import {
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
@@ -197,6 +197,7 @@ describe("OrchestrationEngine", () => {
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
@@ -785,6 +786,7 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
@@ -927,6 +929,7 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -29,6 +30,7 @@ const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
CheckpointRef,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
@@ -49,6 +50,7 @@ import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIde
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionFullThreadDiffContext,
|
||||
type ProjectionSnapshotCounts,
|
||||
type ProjectionThreadCheckpointContext,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
@@ -122,6 +124,18 @@ const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
|
||||
workspaceRoot: Schema.String,
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
const FullThreadDiffContextLookupInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
checkpointTurnCount: NonNegativeInt,
|
||||
});
|
||||
const ProjectionFullThreadDiffContextRowSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
workspaceRoot: Schema.String,
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),
|
||||
toCheckpointRef: Schema.NullOr(CheckpointRef),
|
||||
});
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
@@ -882,6 +896,38 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
|
||||
Request: FullThreadDiffContextLookupInput,
|
||||
Result: ProjectionFullThreadDiffContextRowSchema,
|
||||
execute: ({ threadId, checkpointTurnCount }) =>
|
||||
sql`
|
||||
SELECT
|
||||
threads.thread_id AS "threadId",
|
||||
threads.project_id AS "projectId",
|
||||
projects.workspace_root AS "workspaceRoot",
|
||||
threads.worktree_path AS "worktreePath",
|
||||
(
|
||||
SELECT MAX(turns.checkpoint_turn_count)
|
||||
FROM projection_turns AS turns
|
||||
WHERE turns.thread_id = threads.thread_id
|
||||
AND turns.checkpoint_turn_count IS NOT NULL
|
||||
) AS "latestCheckpointTurnCount",
|
||||
(
|
||||
SELECT turns.checkpoint_ref
|
||||
FROM projection_turns AS turns
|
||||
WHERE turns.thread_id = threads.thread_id
|
||||
AND turns.checkpoint_turn_count = ${checkpointTurnCount}
|
||||
LIMIT 1
|
||||
) AS "toCheckpointRef"
|
||||
FROM projection_threads AS threads
|
||||
INNER JOIN projection_projects AS projects
|
||||
ON projects.project_id = threads.project_id
|
||||
WHERE threads.thread_id = ${threadId}
|
||||
AND threads.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
});
|
||||
|
||||
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
@@ -1759,6 +1805,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const getFullThreadDiffContext: NonNullable<
|
||||
ProjectionSnapshotQueryShape["getFullThreadDiffContext"]
|
||||
> = (threadId, toTurnCount) =>
|
||||
Effect.gen(function* () {
|
||||
const row = yield* getFullThreadDiffContextRow({
|
||||
threadId,
|
||||
checkpointTurnCount: toTurnCount,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getFullThreadDiffContext:query",
|
||||
"ProjectionSnapshotQuery.getFullThreadDiffContext:decodeRow",
|
||||
),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return Option.none<ProjectionFullThreadDiffContext>();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
threadId: row.value.threadId,
|
||||
projectId: row.value.projectId,
|
||||
workspaceRoot: row.value.workspaceRoot,
|
||||
worktreePath: row.value.worktreePath,
|
||||
latestCheckpointTurnCount: row.value.latestCheckpointTurnCount ?? 0,
|
||||
toCheckpointRef: row.value.toCheckpointRef,
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
@@ -1963,6 +2038,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getThreadCheckpointContext,
|
||||
getFullThreadDiffContext,
|
||||
getThreadShellById,
|
||||
getThreadDetailById,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module ProjectionSnapshotQuery
|
||||
*/
|
||||
import type {
|
||||
CheckpointRef,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationProject,
|
||||
OrchestrationProjectShell,
|
||||
@@ -40,6 +41,15 @@ export interface ProjectionThreadCheckpointContext {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
}
|
||||
|
||||
export interface ProjectionFullThreadDiffContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly latestCheckpointTurnCount: number;
|
||||
readonly toCheckpointRef: CheckpointRef | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||
*/
|
||||
@@ -125,6 +135,15 @@ export interface ProjectionSnapshotQueryShape {
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read only the narrow context needed to compute a full-thread diff from
|
||||
* checkpoint 0 to a specific turn count.
|
||||
*/
|
||||
readonly getFullThreadDiffContext: (
|
||||
threadId: ThreadId,
|
||||
toTurnCount: number,
|
||||
) => Effect.Effect<Option.Option<ProjectionFullThreadDiffContext>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a single active thread shell row by id.
|
||||
*/
|
||||
|
||||
@@ -2,16 +2,52 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
launchBrowser,
|
||||
launchEditorProcess,
|
||||
resolveAvailableEditors,
|
||||
resolveBrowserLaunch,
|
||||
resolveEditorLaunch,
|
||||
} from "./open.ts";
|
||||
} from "./externalLauncher.ts";
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const code = input.charCodeAt(index);
|
||||
bytes[index * 2] = code & 0xff;
|
||||
bytes[index * 2 + 1] = code >>> 8;
|
||||
}
|
||||
return Encoding.encodeBase64(bytes);
|
||||
}
|
||||
|
||||
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(true),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.sync(() => {
|
||||
onUnref();
|
||||
return Effect.void;
|
||||
}),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
@@ -216,70 +252,70 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const traeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLineAndColumn, {
|
||||
command: "trae",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
args: ["/tmp/workspace/src/process/externalLauncher.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineOnly = yield* resolveEditorLaunch(
|
||||
@@ -302,102 +338,102 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
});
|
||||
|
||||
const ideaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "idea" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(ideaLineAndColumn, {
|
||||
command: "idea",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const aquaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLineAndColumn, {
|
||||
command: "aqua",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const clionLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLineAndColumn, {
|
||||
command: "clion",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const datagripLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLineAndColumn, {
|
||||
command: "datagrip",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const dataspellLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLineAndColumn, {
|
||||
command: "dataspell",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const golandLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLineAndColumn, {
|
||||
command: "goland",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const phpstormLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLineAndColumn, {
|
||||
command: "phpstorm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const pycharmLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLineAndColumn, {
|
||||
command: "pycharm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const riderLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLineAndColumn, {
|
||||
command: "rider",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rubymineLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLineAndColumn, {
|
||||
command: "rubymine",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const rustroverLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
|
||||
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLineAndColumn, {
|
||||
command: "rustrover",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
|
||||
});
|
||||
|
||||
const webstormLineOnly = yield* resolveEditorLaunch(
|
||||
@@ -415,7 +451,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
|
||||
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
|
||||
|
||||
@@ -477,23 +513,147 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchDetached", (it) => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
it("resolveBrowserLaunch maps default browser launchers by platform", () => {
|
||||
const target = "https://example.com/some path?name=o'hara";
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").command, "open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").args, [target]);
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "darwin").options, {
|
||||
detached: true,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).command, "xdg-open");
|
||||
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).args, [target]);
|
||||
|
||||
const windows = resolveBrowserLaunch(target, "win32", {
|
||||
SYSTEMROOT: "C:\\Windows",
|
||||
});
|
||||
assert.equal(windows.command, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
|
||||
assert.deepEqual(windows.args, [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
encodeUtf16LeBase64(
|
||||
"$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path?name=o''hara'",
|
||||
),
|
||||
]);
|
||||
assert.deepEqual(windows.options, {
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch opens through Windows from WSL when not remote", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
});
|
||||
assert.equal(launch.command, "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
assert.equal(launch.options.detached, true);
|
||||
});
|
||||
|
||||
it("resolveBrowserLaunch keeps xdg-open for WSL over SSH", () => {
|
||||
const launch = resolveBrowserLaunch("https://example.com", "linux", {
|
||||
WSL_DISTRO_NAME: "Ubuntu",
|
||||
SSH_CONNECTION: "client server",
|
||||
});
|
||||
assert.equal(launch.command, "xdg-open");
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchBrowser", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* launchBrowser("https://example.com").pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
const expectedLaunch = resolveBrowserLaunch("https://example.com");
|
||||
assert.equal(spawnedCommand.command, expectedLaunch.command);
|
||||
assert.deepEqual(spawnedCommand.args, expectedLaunch.args);
|
||||
assert.deepEqual(spawnedCommand.options, expectedLaunch.options);
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
|
||||
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnedCommand: ChildProcess.StandardCommand | undefined;
|
||||
let didUnref = false;
|
||||
const expectedArgs = ["-e", "process.exit(0)"];
|
||||
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) =>
|
||||
Effect.sync(() => {
|
||||
assert.equal(ChildProcess.isStandardCommand(command), true);
|
||||
if (!ChildProcess.isStandardCommand(command)) {
|
||||
throw new Error("Expected a standard command");
|
||||
}
|
||||
spawnedCommand = command;
|
||||
return makeMockDetachedHandle(() => {
|
||||
didUnref = true;
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const result = yield* launchEditorProcess({
|
||||
command: process.execPath,
|
||||
args: expectedArgs,
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
|
||||
assertSuccess(result, undefined);
|
||||
assert.ok(spawnedCommand);
|
||||
assert.equal(spawnedCommand.command, process.execPath);
|
||||
assert.deepEqual(
|
||||
spawnedCommand.args,
|
||||
process.platform === "win32" ? expectedArgs.map((arg) => `"${arg}"`) : expectedArgs,
|
||||
);
|
||||
assert.deepEqual(spawnedCommand.options, {
|
||||
detached: true,
|
||||
shell: process.platform === "win32",
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
});
|
||||
assert.equal(didUnref, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
|
||||
const result = yield* launchEditorProcess({
|
||||
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
@@ -504,7 +664,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -526,7 +686,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -540,7 +700,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
@@ -554,8 +714,8 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
|
||||
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
|
||||
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
|
||||
const env = {
|
||||
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* ExternalLauncher - external application launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for browser URLs and workspace paths
|
||||
* in configured editor integrations.
|
||||
*
|
||||
* @module ExternalLauncher
|
||||
*/
|
||||
import {
|
||||
EDITORS,
|
||||
ExternalLauncherError,
|
||||
type EditorId,
|
||||
type LaunchEditorInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { ExternalLauncherError };
|
||||
export type { LaunchEditorInput };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface ProcessLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: ChildProcess.CommandOptions;
|
||||
}
|
||||
|
||||
interface TargetPathAndPosition {
|
||||
readonly path: string;
|
||||
readonly line: string;
|
||||
readonly column: Option.Option<string>;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
const POWERSHELL_ARGUMENTS_PREFIX = [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-EncodedCommand",
|
||||
] as const;
|
||||
|
||||
const DETACHED_IGNORE_STDIO_OPTIONS = {
|
||||
detached: true,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
} as const satisfies ChildProcess.CommandOptions;
|
||||
|
||||
function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
|
||||
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
|
||||
if (!match?.[1] || !match[2]) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
return Option.some({
|
||||
path: match[1],
|
||||
line: match[2],
|
||||
column: Option.fromUndefinedOr(match[3]),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCommandEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const parsedTarget = parseTargetPathAndPosition(target);
|
||||
|
||||
switch (editor.launchStyle) {
|
||||
case "direct-path":
|
||||
return [target];
|
||||
case "goto":
|
||||
return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
|
||||
case "line-column":
|
||||
return Option.match(parsedTarget, {
|
||||
onNone: () => [target],
|
||||
onSome: ({ path, line, column }) => [
|
||||
"--line",
|
||||
line,
|
||||
...Option.match(column, {
|
||||
onNone: () => [],
|
||||
onSome: (value) => ["--column", value],
|
||||
}),
|
||||
path,
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): Option.Option<string> {
|
||||
for (const command of commands) {
|
||||
if (isCommandAvailable(command, options)) {
|
||||
return Option.some(command);
|
||||
}
|
||||
}
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
function encodeUtf16LeBase64(input: string): string {
|
||||
const bytes = new Uint8Array(input.length * 2);
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
const code = input.charCodeAt(index);
|
||||
bytes[index * 2] = code & 0xff;
|
||||
bytes[index * 2 + 1] = code >>> 8;
|
||||
}
|
||||
return Encoding.encodeBase64(bytes);
|
||||
}
|
||||
|
||||
function escapePowerShellStringLiteral(input: string): string {
|
||||
return `'${input.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
|
||||
}
|
||||
|
||||
function resolveWslPowerShellPath(): string {
|
||||
return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
|
||||
}
|
||||
|
||||
function shouldUseWindowsBrowserFromWsl(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): boolean {
|
||||
return (
|
||||
platform === "linux" &&
|
||||
(env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
|
||||
env.SSH_CONNECTION === undefined &&
|
||||
env.SSH_TTY === undefined &&
|
||||
env.container === undefined
|
||||
);
|
||||
}
|
||||
|
||||
function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
|
||||
const encodedCommand = encodeUtf16LeBase64(
|
||||
`$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
|
||||
);
|
||||
return {
|
||||
command,
|
||||
args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
|
||||
options: {
|
||||
detached: true,
|
||||
shell: false,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ProcessLaunch {
|
||||
if (platform === "darwin") {
|
||||
return {
|
||||
command: "open",
|
||||
args: [target],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "win32") {
|
||||
return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
|
||||
}
|
||||
|
||||
if (shouldUseWindowsBrowserFromWsl(platform, env)) {
|
||||
return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
|
||||
}
|
||||
|
||||
return {
|
||||
command: "xdg-open",
|
||||
args: [target],
|
||||
options: DETACHED_IGNORE_STDIO_OPTIONS,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
if (editor.commands === null) {
|
||||
const command = fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const command = resolveAvailableCommand(editor.commands, { platform, env });
|
||||
if (Option.isSome(command)) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalLauncherShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface ExternalLauncherShape {
|
||||
/**
|
||||
* Launch a URL target in the default browser.
|
||||
*/
|
||||
readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
|
||||
|
||||
/**
|
||||
* Launch a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalLauncher - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
|
||||
"t3/process/ExternalLauncher",
|
||||
) {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
input: LaunchEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"externalLauncher.editor": input.editor,
|
||||
"externalLauncher.cwd": input.cwd,
|
||||
"externalLauncher.platform": platform,
|
||||
});
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new ExternalLauncherError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.commands) {
|
||||
const command = Option.getOrElse(
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }),
|
||||
() => editorDef.commands[0],
|
||||
);
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new ExternalLauncherError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
|
||||
launch: ProcessLaunch,
|
||||
errorMessage: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make(launch.command, launch.args, launch.options);
|
||||
|
||||
yield* spawner.spawn(command).pipe(
|
||||
Effect.flatMap((handle) => handle.unref),
|
||||
Effect.asVoid,
|
||||
Effect.scoped,
|
||||
Effect.mapError((cause) => new ExternalLauncherError({ message: errorMessage, cause })),
|
||||
);
|
||||
});
|
||||
|
||||
export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
|
||||
target: string,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
|
||||
});
|
||||
|
||||
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
|
||||
launch: EditorLaunch,
|
||||
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new ExternalLauncherError({
|
||||
message: `Editor command not found: ${launch.command}`,
|
||||
});
|
||||
}
|
||||
|
||||
const isWin32 = process.platform === "win32";
|
||||
yield* launchAndUnref(
|
||||
{
|
||||
command: launch.command,
|
||||
args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
|
||||
options: {
|
||||
detached: true,
|
||||
shell: isWin32,
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
},
|
||||
"failed to spawn detached process",
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
return {
|
||||
launchBrowser: (target) =>
|
||||
launchBrowser(target).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
launchEditor: (input) =>
|
||||
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
|
||||
launchEditorProcess(launch).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
),
|
||||
} satisfies ExternalLauncherShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ExternalLauncher, make);
|
||||
@@ -1,25 +1,282 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
|
||||
import {
|
||||
isWindowsCommandNotFound,
|
||||
ProcessOutputLimitError,
|
||||
ProcessRunner,
|
||||
ProcessTimeoutError,
|
||||
layer as ProcessRunnerLive,
|
||||
type ProcessRunInput,
|
||||
} from "./processRunner.ts";
|
||||
|
||||
type ChildProcessCommand = {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
// Accesses private properties of ChildProcessCommand for testing purposes
|
||||
function asChildProcessCommand(command: unknown): ChildProcessCommand {
|
||||
return command as ChildProcessCommand;
|
||||
}
|
||||
|
||||
function makeHandle(input: {
|
||||
readonly stdout?: string | Stream.Stream<Uint8Array>;
|
||||
readonly stderr?: string | Stream.Stream<Uint8Array>;
|
||||
readonly code?: number;
|
||||
readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: input.stdin ?? Sink.drain,
|
||||
stdout:
|
||||
typeof input.stdout === "string"
|
||||
? Stream.encodeText(Stream.make(input.stdout))
|
||||
: (input.stdout ?? Stream.empty),
|
||||
stderr:
|
||||
typeof input.stderr === "string"
|
||||
? Stream.encodeText(Stream.make(input.stderr))
|
||||
: (input.stderr ?? Stream.empty),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function makeSpawner(
|
||||
f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
|
||||
) {
|
||||
return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
|
||||
}
|
||||
|
||||
const runWith =
|
||||
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
|
||||
Effect.service(ProcessRunner).pipe(
|
||||
Effect.flatMap((runner) =>
|
||||
runner.run({
|
||||
...input,
|
||||
shell: input.shell ?? false,
|
||||
}),
|
||||
),
|
||||
Effect.provide(
|
||||
ProcessRunnerLive.pipe(
|
||||
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
await expect(
|
||||
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
|
||||
).rejects.toThrow("exceeded stdout buffer limit");
|
||||
it.effect("collects stdout through an injected ChildProcessSpawner", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner((command) =>
|
||||
Effect.sync(() => {
|
||||
expect(command.command).toBe("fake");
|
||||
expect(command.args).toEqual(["stdout-bytes", "32"]);
|
||||
return makeHandle({ stdout: "x".repeat(32) });
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["stdout-bytes", "32"],
|
||||
});
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(result.stdout).toBe("x".repeat(32));
|
||||
expect(result.timedOut).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runs through the ProcessRunner service", () => {
|
||||
const spawner = makeSpawner((command) =>
|
||||
Effect.sync(() => {
|
||||
expect(command.command).toBe("fake");
|
||||
expect(command.args).toEqual(["--service"]);
|
||||
return makeHandle({ stdout: "service ok" });
|
||||
}),
|
||||
);
|
||||
const layer = ProcessRunnerLive.pipe(
|
||||
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProcessRunner;
|
||||
const result = yield* runner.run({
|
||||
command: "fake",
|
||||
args: ["--service"],
|
||||
});
|
||||
|
||||
expect(result.stdout).toBe("service ok");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it("truncates output when outputMode is truncate", async () => {
|
||||
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
|
||||
maxBufferBytes: 128,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
it.effect("fails when output exceeds max buffer in default mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
const error = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["stdout-bytes", "2048"],
|
||||
maxOutputBytes: 128,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessOutputLimitError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails fast on output limit before timeout for long-running output", () =>
|
||||
Effect.gen(function* () {
|
||||
const textChunk = "x".repeat(64);
|
||||
const spawner = makeSpawner(() =>
|
||||
Effect.succeed(
|
||||
makeHandle({
|
||||
stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
|
||||
Stream.encodeText,
|
||||
),
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["spam-stdout"],
|
||||
maxOutputBytes: 128,
|
||||
timeout: "2 seconds",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessOutputLimitError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("truncates output when outputMode is truncate", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
|
||||
|
||||
const result = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["stdout-bytes", "2048"],
|
||||
maxOutputBytes: 128,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("writes stdin before waiting for exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const stdinWritten = yield* Deferred.make<void>();
|
||||
const decoder = new TextDecoder();
|
||||
const spawner = makeSpawner(() =>
|
||||
Effect.succeed(
|
||||
makeHandle({
|
||||
stdout: "stdin payload",
|
||||
stdin: Sink.forEach((chunk: Uint8Array) => {
|
||||
const text = decoder.decode(chunk, { stream: true });
|
||||
return text.includes("stdin payload")
|
||||
? Deferred.succeed(stdinWritten, undefined)
|
||||
: Effect.void;
|
||||
}),
|
||||
exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["stdin-echo"],
|
||||
stdin: "stdin payload",
|
||||
});
|
||||
|
||||
expect(result.stdout).toBe("stdin payload");
|
||||
expect(result.code).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns output for non-zero exit codes", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
|
||||
|
||||
const result = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["stderr-exit", "boom", "2"],
|
||||
});
|
||||
|
||||
expect(result.code).toBe(2);
|
||||
expect(result.stderr).toBe("boom");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails on timeout", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() =>
|
||||
Effect.succeed(
|
||||
makeHandle({
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const errorFiber = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["sleep"],
|
||||
timeout: "50 millis",
|
||||
}).pipe(Effect.flip, Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(errorFiber);
|
||||
|
||||
expect(error).toBeInstanceOf(ProcessTimeoutError);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = makeSpawner(() =>
|
||||
Effect.succeed(
|
||||
makeHandle({
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const resultFiber = yield* runWith(spawner)({
|
||||
command: "fake",
|
||||
args: ["sleep"],
|
||||
timeout: "50 millis",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const result = yield* Fiber.join(resultFiber);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("isWindowsCommandNotFound", () => {
|
||||
|
||||
+295
-245
@@ -1,42 +1,100 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
import * as NodeTimers from "node:timers";
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
stdin?: string | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
import * as Data from "effect/Data";
|
||||
import * as Context from "effect/Context";
|
||||
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 PlatformError from "effect/PlatformError";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
collectUint8StreamText,
|
||||
type CollectedUint8StreamText,
|
||||
} from "./stream/collectUint8StreamText.ts";
|
||||
|
||||
export interface ProcessRunInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly spawnCwd?: string | undefined;
|
||||
readonly timeout?: Duration.Input | undefined;
|
||||
readonly env?: NodeJS.ProcessEnv | undefined;
|
||||
readonly stdin?: string | undefined;
|
||||
readonly maxOutputBytes?: number | undefined;
|
||||
readonly outputMode?: "error" | "truncate" | undefined;
|
||||
readonly truncatedMarker?: string | undefined;
|
||||
readonly shell?: boolean | string | undefined;
|
||||
/**
|
||||
* On timeout, return a synthetic timedOut result.
|
||||
* Partial stdout/stderr are not preserved.
|
||||
*/
|
||||
readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
timedOut: boolean;
|
||||
stdoutTruncated?: boolean | undefined;
|
||||
stderrTruncated?: boolean | undefined;
|
||||
export interface ProcessRunOutput {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: ChildProcessSpawner.ExitCode | null;
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly stream: "stdout" | "stderr";
|
||||
readonly maxBytes: number;
|
||||
}> {}
|
||||
|
||||
export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly stream: "stdout" | "stderr" | "exitCode";
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly timeoutMs: number;
|
||||
}> {}
|
||||
|
||||
export type ProcessRunError =
|
||||
| ProcessSpawnError
|
||||
| ProcessStdinError
|
||||
| ProcessOutputLimitError
|
||||
| ProcessReadError
|
||||
| ProcessTimeoutError;
|
||||
|
||||
export interface ProcessRunnerShape {
|
||||
readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
|
||||
}
|
||||
|
||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
}
|
||||
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
|
||||
"t3/process/ProcessRunner",
|
||||
) {}
|
||||
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
if (maybeCode === "ENOENT") {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
const DEFAULT_TIMEOUT = "60 seconds";
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
|
||||
/is not recognized as an internal or external command/i,
|
||||
@@ -57,230 +115,222 @@ export function isWindowsCommandNotFound(code: number | null, stderr: string): b
|
||||
return hasWindowsCommandNotFoundMessage(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
const collectText = Effect.fn("processRunner.collectText")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string | undefined;
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly maxOutputBytes: number;
|
||||
readonly outputMode: "error" | "truncate";
|
||||
readonly truncatedMarker: string;
|
||||
}) {
|
||||
const stream = input.stream.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new ProcessReadError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
stream: input.streamName,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (input.outputMode === "truncate") {
|
||||
return yield* collectUint8StreamText({
|
||||
stream,
|
||||
maxBytes: input.maxOutputBytes,
|
||||
truncatedMarker: input.truncatedMarker,
|
||||
});
|
||||
}
|
||||
|
||||
const reason = result.timedOut
|
||||
? "timed out"
|
||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||
const stderr = result.stderr.trim();
|
||||
const detail = stderr.length > 0 ? ` ${stderr}` : "";
|
||||
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
|
||||
}
|
||||
return yield* stream.pipe(
|
||||
Stream.runFoldEffect<
|
||||
{
|
||||
readonly chunks: Uint8Array<ArrayBufferLike>[];
|
||||
readonly bytes: number;
|
||||
},
|
||||
Uint8Array<ArrayBufferLike>,
|
||||
ProcessOutputLimitError | ProcessReadError,
|
||||
never
|
||||
>(
|
||||
() => ({ chunks: [], bytes: 0 }),
|
||||
(state, chunk) => {
|
||||
const remainingBytes = input.maxOutputBytes - state.bytes;
|
||||
if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
|
||||
return Effect.fail(
|
||||
new ProcessOutputLimitError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
stream: input.streamName,
|
||||
maxBytes: input.maxOutputBytes,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
|
||||
}
|
||||
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
state.chunks.push(chunk);
|
||||
return Effect.succeed({
|
||||
chunks: state.chunks,
|
||||
bytes: state.bytes + chunk.byteLength,
|
||||
});
|
||||
},
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
|
||||
bytes: state.bytes,
|
||||
truncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function normalizeBufferError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
stream: "stdout" | "stderr",
|
||||
maxBufferBytes: number,
|
||||
): Error {
|
||||
return new Error(
|
||||
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
|
||||
function finalizeRunProcess<R>(
|
||||
effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
|
||||
input: ProcessRunInput,
|
||||
): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
|
||||
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
|
||||
const timeoutBehavior = input.timeoutBehavior ?? "error";
|
||||
|
||||
return effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.flatMap((result) => {
|
||||
if (Option.isSome(result)) {
|
||||
return Effect.succeed(result.value);
|
||||
}
|
||||
if (timeoutBehavior === "timedOutResult") {
|
||||
return Effect.succeed({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
} satisfies ProcessRunOutput);
|
||||
}
|
||||
return Effect.fail(
|
||||
new ProcessTimeoutError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
|
||||
spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
|
||||
input: ProcessRunInput,
|
||||
): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const outputMode = input.outputMode ?? "error";
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill(signal);
|
||||
}
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.command, [...input.args], {
|
||||
...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
|
||||
...(input.env !== undefined
|
||||
? {
|
||||
env: input.env,
|
||||
extendEnv: true,
|
||||
}
|
||||
: {}),
|
||||
...(input.shell !== undefined ? { shell: input.shell } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProcessSpawnError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const writeStdin =
|
||||
input.stdin === undefined
|
||||
? Effect.void
|
||||
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProcessStdinError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr] = yield* Effect.all(
|
||||
[
|
||||
collectText({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
streamName: "stdout",
|
||||
stream: child.stdout,
|
||||
maxOutputBytes,
|
||||
outputMode,
|
||||
truncatedMarker,
|
||||
}),
|
||||
collectText({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
streamName: "stderr",
|
||||
stream: child.stderr,
|
||||
maxOutputBytes,
|
||||
outputMode,
|
||||
truncatedMarker,
|
||||
}),
|
||||
writeStdin,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const exitCode = yield* child.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProcessReadError({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
stream: "exitCode",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
chunk: Buffer,
|
||||
maxBytes: number,
|
||||
): {
|
||||
next: string;
|
||||
nextBytes: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
const remaining = maxBytes - currentBytes;
|
||||
if (remaining <= 0) {
|
||||
return { next: target, nextBytes: currentBytes, truncated: true };
|
||||
}
|
||||
if (chunk.length <= remaining) {
|
||||
return {
|
||||
next: `${target}${chunk.toString()}`,
|
||||
nextBytes: currentBytes + chunk.length,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
next: `${target}${chunk.subarray(0, remaining).toString()}`,
|
||||
nextBytes: currentBytes + remaining,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
code: exitCode,
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProcessRunOutput;
|
||||
});
|
||||
|
||||
export async function runProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessRunOptions = {},
|
||||
): Promise<ProcessRunResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 60_000;
|
||||
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
export const make = Effect.fn("makeProcessRunner")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const run: ProcessRunnerShape["run"] = (input) =>
|
||||
finalizeRunProcess(runProcessCore(spawner, input), input);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let stdoutTruncated = false;
|
||||
let stderrTruncated = false;
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
let forceKillTimer: ReturnType<typeof NodeTimers.setTimeout> | null = null;
|
||||
|
||||
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; moving this runner to Effect timers is a separate refactor.
|
||||
const timeoutTimer = NodeTimers.setTimeout(() => {
|
||||
timedOut = true;
|
||||
killChild(child, "SIGTERM");
|
||||
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; see timeout timer above.
|
||||
forceKillTimer = NodeTimers.setTimeout(() => {
|
||||
killChild(child, "SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
const finalize = (callback: () => void): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
NodeTimers.clearTimeout(timeoutTimer);
|
||||
if (forceKillTimer) {
|
||||
NodeTimers.clearTimeout(forceKillTimer);
|
||||
}
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killChild(child, "SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
};
|
||||
|
||||
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
|
||||
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
||||
const text = chunkBuffer.toString();
|
||||
const byteLength = chunkBuffer.length;
|
||||
if (stream === "stdout") {
|
||||
if (outputMode === "truncate") {
|
||||
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
|
||||
stdout = appended.next;
|
||||
stdoutBytes = appended.nextBytes;
|
||||
stdoutTruncated = stdoutTruncated || appended.truncated;
|
||||
return null;
|
||||
}
|
||||
stdout += text;
|
||||
stdoutBytes += byteLength;
|
||||
if (stdoutBytes > maxBufferBytes) {
|
||||
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
|
||||
}
|
||||
} else {
|
||||
if (outputMode === "truncate") {
|
||||
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
|
||||
stderr = appended.next;
|
||||
stderrBytes = appended.nextBytes;
|
||||
stderrTruncated = stderrTruncated || appended.truncated;
|
||||
return null;
|
||||
}
|
||||
stderr += text;
|
||||
stderrBytes += byteLength;
|
||||
if (stderrBytes > maxBufferBytes) {
|
||||
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer | string) => {
|
||||
const error = appendOutput("stdout", chunk);
|
||||
if (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
const error = appendOutput("stderr", chunk);
|
||||
if (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", (error) => {
|
||||
finalize(() => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
|
||||
child.once("close", (code, signal) => {
|
||||
const result: ProcessRunResult = {
|
||||
stdout,
|
||||
stderr,
|
||||
code,
|
||||
signal,
|
||||
timedOut,
|
||||
stdoutTruncated,
|
||||
stderrTruncated,
|
||||
};
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
});
|
||||
});
|
||||
|
||||
child.stdin.once("error", (error) => {
|
||||
fail(normalizeStdinError(command, args, error));
|
||||
});
|
||||
|
||||
if (options.stdin !== undefined) {
|
||||
child.stdin.write(options.stdin, (error) => {
|
||||
if (error) {
|
||||
fail(normalizeStdinError(command, args, error));
|
||||
return;
|
||||
}
|
||||
child.stdin.end();
|
||||
});
|
||||
return;
|
||||
}
|
||||
child.stdin.end();
|
||||
return ProcessRunner.of({
|
||||
run,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessRunner, make());
|
||||
@@ -36,6 +36,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
});
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Path from "effect/Path";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import * as ProcessRunner from "../../processRunner.ts";
|
||||
import { RepositoryIdentityResolver } from "../Services/RepositoryIdentityResolver.ts";
|
||||
import {
|
||||
makeRepositoryIdentityResolver,
|
||||
@@ -17,11 +15,17 @@ import {
|
||||
} from "./RepositoryIdentityResolver.ts";
|
||||
|
||||
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
|
||||
const normalizeResolvedPath = (value: string) =>
|
||||
normalizePathSeparators(realpathSync.native(value));
|
||||
const normalizeResolvedPath = (value: string) => normalizePathSeparators(value);
|
||||
|
||||
const git = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
|
||||
Effect.gen(function* () {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
return yield* processRunner.run({
|
||||
command: "git",
|
||||
args: ["-C", cwd, ...args],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
}).pipe(Effect.provide(ProcessRunner.layer));
|
||||
|
||||
const makeRepositoryIdentityResolverTestLayer = (options: {
|
||||
readonly positiveCacheTtl?: Duration.Input;
|
||||
@@ -33,7 +37,7 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
|
||||
cacheCapacity: 16,
|
||||
...options,
|
||||
}),
|
||||
);
|
||||
).pipe(Layer.provide(ProcessRunner.layer));
|
||||
|
||||
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () =>
|
||||
@@ -48,10 +52,13 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
|
||||
const resolver = yield* RepositoryIdentityResolver;
|
||||
const identity = yield* resolver.resolve(cwd);
|
||||
const resolvedIdentityRoot =
|
||||
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
|
||||
const resolvedCwd = yield* fileSystem.realPath(cwd);
|
||||
|
||||
expect(identity).not.toBeNull();
|
||||
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
|
||||
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
|
||||
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(normalizeResolvedPath(resolvedCwd));
|
||||
expect(identity?.displayName).toBe("t3tools/t3code");
|
||||
expect(identity?.provider).toBe("github");
|
||||
expect(identity?.owner).toBe("t3tools");
|
||||
@@ -62,10 +69,11 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-repository-identity-nested-root-test-",
|
||||
});
|
||||
const nestedWorkspace = `${repoRoot}/packages/web`;
|
||||
const nestedWorkspace = path.join(repoRoot, "packages", "web");
|
||||
|
||||
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
|
||||
yield* git(repoRoot, ["init"]);
|
||||
@@ -73,10 +81,15 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
|
||||
|
||||
const resolver = yield* RepositoryIdentityResolver;
|
||||
const identity = yield* resolver.resolve(nestedWorkspace);
|
||||
const resolvedIdentityRoot =
|
||||
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
|
||||
const resolvedRepoRoot = yield* fileSystem.realPath(repoRoot);
|
||||
|
||||
expect(identity).not.toBeNull();
|
||||
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
|
||||
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
|
||||
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(
|
||||
normalizeResolvedPath(resolvedRepoRoot),
|
||||
);
|
||||
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
normalizeGitRemoteUrl,
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import * as ProcessRunner from "../../processRunner.ts";
|
||||
import {
|
||||
RepositoryIdentityResolver,
|
||||
type RepositoryIdentityResolverShape,
|
||||
@@ -83,50 +83,63 @@ interface RepositoryIdentityResolverOptions {
|
||||
readonly negativeCacheTtl?: Duration.Input;
|
||||
}
|
||||
|
||||
async function resolveRepositoryIdentityCacheKey(cwd: string): Promise<string> {
|
||||
const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCacheKey")(function* (
|
||||
cwd: string,
|
||||
) {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
let cacheKey = cwd;
|
||||
|
||||
try {
|
||||
const topLevelResult = await runProcess("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (topLevelResult.code !== 0) {
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
const candidate = topLevelResult.stdout.trim();
|
||||
if (candidate.length > 0) {
|
||||
cacheKey = candidate;
|
||||
}
|
||||
} catch {
|
||||
const topLevelResult = yield* processRunner
|
||||
.run({
|
||||
command: "git",
|
||||
args: ["-C", cwd, "rev-parse", "--show-toplevel"],
|
||||
timeoutBehavior: "timedOutResult",
|
||||
shell: process.platform === "win32",
|
||||
})
|
||||
.pipe(Effect.option);
|
||||
if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
return cacheKey;
|
||||
}
|
||||
const candidate = topLevelResult.value.stdout.trim();
|
||||
if (candidate.length > 0) {
|
||||
cacheKey = candidate;
|
||||
}
|
||||
|
||||
async function resolveRepositoryIdentityFromCacheKey(
|
||||
cacheKey: string,
|
||||
): Promise<RepositoryIdentity | null> {
|
||||
try {
|
||||
const remoteResult = await runProcess("git", ["-C", cacheKey, "remote", "-v"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (remoteResult.code !== 0) {
|
||||
return cacheKey;
|
||||
});
|
||||
|
||||
const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdentityFromCacheKey")(
|
||||
function* (
|
||||
cacheKey: string,
|
||||
): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const remoteResult = yield* processRunner
|
||||
.run({
|
||||
command: "git",
|
||||
args: ["-C", cacheKey, "remote", "-v"],
|
||||
timeoutBehavior: "timedOutResult",
|
||||
shell: process.platform === "win32",
|
||||
})
|
||||
.pipe(Effect.option);
|
||||
if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
|
||||
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
|
||||
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
|
||||
function* (options: RepositoryIdentityResolverOptions = {}) {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
|
||||
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
|
||||
(cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
|
||||
(cacheKey) =>
|
||||
resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
|
||||
),
|
||||
{
|
||||
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
|
||||
timeToLive: Exit.match({
|
||||
@@ -142,7 +155,9 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
|
||||
const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
|
||||
"RepositoryIdentityResolver.resolve",
|
||||
)(function* (cwd) {
|
||||
const cacheKey = yield* Effect.promise(() => resolveRepositoryIdentityCacheKey(cwd));
|
||||
const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
|
||||
);
|
||||
return yield* Cache.get(repositoryIdentityCache, cacheKey);
|
||||
});
|
||||
|
||||
@@ -155,4 +170,4 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
|
||||
export const RepositoryIdentityResolverLive = Layer.effect(
|
||||
RepositoryIdentityResolver,
|
||||
makeRepositoryIdentityResolver(),
|
||||
);
|
||||
).pipe(Layer.provide(ProcessRunner.layer));
|
||||
@@ -24,7 +24,9 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
@@ -51,7 +53,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
@@ -76,12 +77,14 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -174,7 +177,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
* @module provider/Drivers/CodexDriver
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -32,7 +31,9 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
@@ -54,7 +55,6 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
@@ -68,12 +68,14 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
* registered driver and the runtime satisfies them once.
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
/**
|
||||
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
|
||||
@@ -174,7 +176,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
* @module provider/Drivers/CursorDriver
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -23,6 +22,8 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
@@ -48,7 +49,6 @@ import {
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -60,12 +60,14 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -151,7 +153,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
* @module provider/Drivers/OpenCodeDriver
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -23,7 +22,9 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
@@ -49,7 +50,6 @@ import {
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
@@ -72,13 +72,15 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -153,7 +155,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Types from "effect/Types";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
@@ -22,13 +23,15 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import {
|
||||
AUTH_PROBE_TIMEOUT_MS,
|
||||
buildServerProvider,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
|
||||
|
||||
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
|
||||
const CODEX_PRESENTATION = {
|
||||
displayName: "Codex",
|
||||
showInteractionModeToggle: true,
|
||||
@@ -245,12 +248,6 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
|
||||
};
|
||||
}
|
||||
|
||||
// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
|
||||
// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
|
||||
// `ChildProcess.kill` throwing because the `codex app-server` child exited
|
||||
// early) cannot override a successful probe body. Without this guard the
|
||||
// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
|
||||
// `refreshOneSource`, and `providersRef` never receives the snapshot.
|
||||
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
@@ -320,7 +317,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
models: appendCustomCodexModels(models, input.customModels ?? []),
|
||||
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
}, scopedSafeTeardown("codex-probe"));
|
||||
});
|
||||
|
||||
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
|
||||
codexSettings.customModels
|
||||
@@ -413,7 +410,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
}) => Effect.Effect<
|
||||
CodexAppServerProviderSnapshot,
|
||||
CodexErrors.CodexAppServerError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
> = probeCodexAppServerProvider,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): Effect.fn.Return<
|
||||
@@ -447,7 +444,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
|
||||
cwd: process.cwd(),
|
||||
customModels: codexSettings.customModels,
|
||||
environment,
|
||||
}).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(probeResult)) {
|
||||
const error = probeResult.failure;
|
||||
|
||||
@@ -53,6 +53,7 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
|
||||
"state db missing rollout path for thread",
|
||||
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
|
||||
];
|
||||
const CODEX_APP_SERVER_FORCE_KILL_AFTER = "2 seconds" as const;
|
||||
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"not found",
|
||||
"missing thread",
|
||||
@@ -721,6 +722,7 @@ export const makeCodexSessionRuntime = (
|
||||
ChildProcess.make(options.binaryPath, ["app-server"], {
|
||||
cwd: options.cwd,
|
||||
env,
|
||||
forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -34,7 +34,6 @@ const runtimeMock = {
|
||||
runVersionError: null as Error | null,
|
||||
versionStdout: DEFAULT_VERSION_STDOUT,
|
||||
inventoryError: null as Error | null,
|
||||
closeError: null as Error | null,
|
||||
closeCalls: 0,
|
||||
inventory: {
|
||||
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
|
||||
@@ -45,7 +44,6 @@ const runtimeMock = {
|
||||
this.state.runVersionError = null;
|
||||
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
|
||||
this.state.inventoryError = null;
|
||||
this.state.closeError = null;
|
||||
this.state.closeCalls = 0;
|
||||
this.state.inventory = {
|
||||
providerList: { connected: [], all: [] as unknown[], default: {} },
|
||||
@@ -66,9 +64,6 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls += 1;
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -206,41 +201,6 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
assert.equal(runtimeMock.state.closeCalls, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves a successful provider refresh when probe teardown throws", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventory = {
|
||||
providerList: {
|
||||
connected: ["openai"],
|
||||
all: [
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
models: {
|
||||
"gpt-5": {
|
||||
id: "gpt-5",
|
||||
name: "GPT-5",
|
||||
variants: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
default: {},
|
||||
},
|
||||
agents: [],
|
||||
};
|
||||
runtimeMock.state.closeError = new Error("close failed");
|
||||
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
|
||||
assert.equal(runtimeMock.state.closeCalls, 1);
|
||||
assert.equal(snapshot.status, "ready");
|
||||
assert.equal(
|
||||
snapshot.models.some((model) => model.slug === "openai/gpt-5"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
@@ -407,34 +406,38 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
return yield* openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(isExternalServer && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
}).pipe(scopedSafeTeardown("opencode-provider-probe")),
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
return yield* openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(isExternalServer && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
|
||||
@@ -33,11 +33,15 @@ import {
|
||||
type ProviderInstanceConfigMap,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
@@ -53,6 +57,37 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -98,6 +133,8 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
@@ -235,6 +272,8 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -31,6 +33,7 @@ import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
@@ -63,6 +66,7 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -71,6 +75,35 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -209,6 +242,31 @@ function failingSpawnerLayer(description: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function hangingScopedSpawnerLayer(killCalls: Ref.Ref<number>) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.gen(function* () {
|
||||
const handle = ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.never,
|
||||
isRunning: Effect.succeed(true),
|
||||
kill: () => Ref.update(killCalls, (current) => current + 1),
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.never,
|
||||
stderr: Stream.never,
|
||||
all: Stream.never,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
|
||||
return handle;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const codexModelCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoningEffort", "Reasoning", [
|
||||
@@ -421,6 +479,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("closes the app-server probe scope when provider status times out", () =>
|
||||
Effect.gen(function* () {
|
||||
const killCalls = yield* Ref.make(0);
|
||||
const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe(
|
||||
Effect.provide(hangingScopedSpawnerLayer(killCalls)),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust("11 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const status = yield* Fiber.join(statusFiber);
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Timed out while checking Codex app-server provider status.",
|
||||
);
|
||||
assert.strictEqual(yield* Ref.get(killCalls), 1);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderRegistryLive", () => {
|
||||
@@ -687,6 +767,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -781,6 +862,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-refresh-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -885,6 +967,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-sync-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -981,6 +1064,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
// outer `NodeServices.layer` on `it.layer(...)` and will
|
||||
// genuinely spawn a subprocess. The missing-binary ENOENT is
|
||||
@@ -1061,6 +1145,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// same real `ChildProcessSpawner` + `FileSystem` + `Path`
|
||||
// services that production uses.
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1160,6 +1245,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1210,6 +1296,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
|
||||
@@ -202,6 +202,7 @@ describe("ProviderSessionReaper", () => {
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
|
||||
describe("scopedSafeTeardown", () => {
|
||||
it.effect("returns the body's value when teardown is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const finalizers: string[] = [];
|
||||
const wrapped = Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
finalizers.push("clean");
|
||||
}),
|
||||
);
|
||||
return "body-ok";
|
||||
}).pipe(scopedSafeTeardown("test"));
|
||||
|
||||
const value = yield* wrapped;
|
||||
expect(value).toBe("body-ok");
|
||||
expect(finalizers).toEqual(["clean"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves body success when a finalizer dies", () =>
|
||||
// The production failure mode: `Layer.build(...)` registers a finalizer
|
||||
// that kills a subprocess; if the kill fails, the defect would otherwise
|
||||
// override a successful probe body.
|
||||
Effect.gen(function* () {
|
||||
const finalizers: string[] = [];
|
||||
const wrapped = Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
finalizers.push("ran-before-die");
|
||||
}),
|
||||
);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.die(new Error("simulated subprocess kill failure")),
|
||||
);
|
||||
return "body-ok";
|
||||
}).pipe(scopedSafeTeardown("test"));
|
||||
|
||||
const value = yield* wrapped;
|
||||
expect(value).toBe("body-ok");
|
||||
// The clean finalizer still ran; teardown defect was logged + swallowed.
|
||||
expect(finalizers).toEqual(["ran-before-die"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves typed body failures even when teardown is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
class BodyError {
|
||||
readonly _tag = "BodyError" as const;
|
||||
}
|
||||
const wrapped = Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() => Effect.void);
|
||||
return yield* Effect.fail(new BodyError());
|
||||
}).pipe(scopedSafeTeardown("test"));
|
||||
|
||||
const exit = yield* Effect.exit(wrapped);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
// Body's typed failure should surface, not a defect.
|
||||
const squashed = Cause.squash(exit.cause);
|
||||
expect(squashed).toBeInstanceOf(BodyError);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers the body's typed failure over a teardown defect", () =>
|
||||
// Even when both the body fails AND teardown defects, the body's typed
|
||||
// failure is what callers see. This matters because `Effect.result` /
|
||||
// `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die.
|
||||
Effect.gen(function* () {
|
||||
class BodyError {
|
||||
readonly _tag = "BodyError" as const;
|
||||
}
|
||||
const wrapped = Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.die(new Error("simulated subprocess kill failure")),
|
||||
);
|
||||
return yield* Effect.fail(new BodyError());
|
||||
}).pipe(scopedSafeTeardown("test"));
|
||||
|
||||
const exit = yield* Effect.exit(wrapped);
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
const squashed = Cause.squash(exit.cause);
|
||||
expect(squashed).toBeInstanceOf(BodyError);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* scopedSafeTeardown — run a scope-requiring effect so that finalizer
|
||||
* failures during scope close cannot override the body's Exit.
|
||||
*
|
||||
* Motivation
|
||||
* ----------
|
||||
* The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh
|
||||
* Scope, run the body, close the scope with the body's Exit. If a
|
||||
* finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server
|
||||
* spawn) dies during that close, the combined Exit becomes the
|
||||
* finalizer's defect — even when the body already succeeded.
|
||||
*
|
||||
* Concretely this bit us in the Codex provider probe: a successful
|
||||
* `initialize` → `account/read` → `skills/list` → `model/list`
|
||||
* round-trip produced a `CodexAppServerProviderSnapshot`, but the
|
||||
* `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to
|
||||
* kill the `codex app-server` subprocess with a `PlatformError`. The
|
||||
* defect bubbled past `Effect.result` in `checkCodexProviderStatus`,
|
||||
* died `refreshOneSource`, and `providersRef` never saw the snapshot.
|
||||
*
|
||||
* Strategy
|
||||
* --------
|
||||
* 1. Make a fresh scope manually.
|
||||
* 2. Run the body against that scope, capturing its Exit via
|
||||
* `Effect.exit`.
|
||||
* 3. Close the scope, catching any cause (typed failure *or* defect)
|
||||
* with a log.
|
||||
* 4. Replay the captured Exit so typed body failures still surface and
|
||||
* successes still return their value.
|
||||
*
|
||||
* The helper deliberately logs teardown causes at `Warning` level —
|
||||
* silently swallowing them is dangerous because they usually indicate a
|
||||
* real bug in a downstream Layer's finalizer.
|
||||
*
|
||||
* @module provider/Layers/scopedSafeTeardown
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
|
||||
* teardown failures cannot override the body's Exit.
|
||||
*
|
||||
* Shape matches `Effect.scoped`: takes an effect whose env includes
|
||||
* `Scope.Scope`, returns one whose env excludes it.
|
||||
*
|
||||
* @param label Short label for the warning log emitted when teardown
|
||||
* fails. Use something like `"codex-probe"`.
|
||||
*/
|
||||
export const scopedSafeTeardown =
|
||||
(label: string) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make();
|
||||
const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit);
|
||||
yield* Scope.close(scope, Exit.void).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning(`${label} teardown errored; preserving body result`, cause),
|
||||
),
|
||||
);
|
||||
return yield* bodyExit;
|
||||
}) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
|
||||
@@ -1,16 +1,22 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
|
||||
|
||||
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
const fastModeCapabilities = createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
@@ -87,6 +93,43 @@ const refreshedSnapshotSecond: ServerProvider = {
|
||||
message: "Refreshed provider availability again.",
|
||||
};
|
||||
|
||||
function makeBackgroundPolicyLayer(shouldRunScopeWork: boolean) {
|
||||
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunScopeWork: () => Effect.succeed(shouldRunScopeWork),
|
||||
shouldRunOpportunisticWork: Effect.succeed(shouldRunScopeWork),
|
||||
});
|
||||
}
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = makeBackgroundPolicyLayer(true);
|
||||
const BackgroundPolicyNeverRunLayer = makeBackgroundPolicyLayer(false);
|
||||
const ServerSettingsTestLayer = ServerSettingsService.layerTest();
|
||||
const AlwaysRunTestLayer = Layer.merge(BackgroundPolicyAlwaysRunLayer, ServerSettingsTestLayer);
|
||||
const NeverRunTestLayer = Layer.merge(BackgroundPolicyNeverRunLayer, ServerSettingsTestLayer);
|
||||
|
||||
const enrichedSnapshotSecond: ServerProvider = {
|
||||
...refreshedSnapshotSecond,
|
||||
checkedAt: "2026-04-10T00:00:04.000Z",
|
||||
@@ -139,7 +182,38 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshot);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("skips periodic provider refreshes without foreground provider-status demand", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => Effect.succeed(initialSnapshot),
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.tap((count) =>
|
||||
count === 1
|
||||
? Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: "1 second",
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(NeverRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("reruns the provider check when streamed settings change", () =>
|
||||
@@ -184,7 +258,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
|
||||
@@ -222,7 +296,7 @@ describe("makeManagedServerProvider", () => {
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshot);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
|
||||
@@ -283,6 +357,6 @@ describe("makeManagedServerProvider", () => {
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
type ServerProvider,
|
||||
ServerSettingsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -9,8 +14,9 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
interface ProviderSnapshotState {
|
||||
readonly snapshot: ServerProvider;
|
||||
@@ -33,7 +39,13 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
}): Effect.fn.Return<
|
||||
ServerProviderShape,
|
||||
ServerSettingsError,
|
||||
Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
|
||||
> {
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
@@ -134,13 +146,45 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
|
||||
const hasProviderStatusDemand = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(snapshotStateRef);
|
||||
const instanceId = state.snapshot.instanceId;
|
||||
const [genericDemand, instanceDemand] = yield* Effect.all([
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
|
||||
backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
|
||||
]);
|
||||
return genericDemand || instanceDemand;
|
||||
});
|
||||
|
||||
const getRefreshInterval = input.refreshInterval
|
||||
? Effect.succeed(input.refreshInterval)
|
||||
: serverSettings.getSettings.pipe(
|
||||
Effect.map(
|
||||
(settings) =>
|
||||
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot()),
|
||||
getRefreshInterval.pipe(
|
||||
Effect.flatMap((refreshInterval) =>
|
||||
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
|
||||
? Effect.sleep("60 seconds")
|
||||
: Effect.sleep(refreshInterval).pipe(
|
||||
Effect.flatMap(() =>
|
||||
hasProviderStatusDemand.pipe(
|
||||
Effect.flatMap((shouldRefresh) =>
|
||||
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
@@ -273,100 +273,10 @@ function ensureRuntimeError(
|
||||
: new OpenCodeRuntimeError({ operation, detail, cause });
|
||||
}
|
||||
|
||||
function commandBasename(commandPath: string): string {
|
||||
return commandPath.split(/[\\/]/).at(-1) ?? commandPath;
|
||||
}
|
||||
|
||||
function isMatchingOpenCodeServeCommand(input: {
|
||||
readonly command: string;
|
||||
readonly binaryPath: string;
|
||||
readonly hostname: string;
|
||||
readonly port: number;
|
||||
}): boolean {
|
||||
const executable = commandBasename(input.binaryPath);
|
||||
const command = input.command;
|
||||
return (
|
||||
command.includes(executable) &&
|
||||
/\bserve\b/.test(command) &&
|
||||
command.includes(`--hostname=${input.hostname}`) &&
|
||||
command.includes(`--port=${input.port}`)
|
||||
);
|
||||
}
|
||||
|
||||
const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const netService = yield* NetService.NetService;
|
||||
|
||||
const listProcessCommands: Effect.Effect<
|
||||
ReadonlyArray<{ readonly pid: number; readonly command: string }>
|
||||
> = Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(ChildProcess.make("ps", ["-axo", "pid=,command="]));
|
||||
const [stdout, code] = yield* Effect.all(
|
||||
[collectStreamAsString(child.stdout), child.exitCode],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
if (Number(code) !== 0) {
|
||||
return [];
|
||||
}
|
||||
return stdout
|
||||
.split("\n")
|
||||
.flatMap((line) => {
|
||||
const match = line.trim().match(/^(\d+)\s+(.+)$/);
|
||||
const command = match?.[2];
|
||||
if (!match || command === undefined) {
|
||||
return [];
|
||||
}
|
||||
return [{ pid: Number(match[1]), command }];
|
||||
})
|
||||
.filter((entry) => Number.isInteger(entry.pid) && entry.pid > 0);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.catch(() => Effect.succeed([])),
|
||||
);
|
||||
|
||||
const terminateMatchingOpenCodeServeProcesses = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly hostname: string;
|
||||
readonly port: number;
|
||||
readonly signal: NodeJS.Signals;
|
||||
}): Effect.Effect<void> => {
|
||||
if (process.platform === "win32") {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return listProcessCommands.pipe(
|
||||
Effect.flatMap((processes) =>
|
||||
Effect.forEach(
|
||||
processes,
|
||||
(entry) => {
|
||||
if (
|
||||
entry.pid === process.pid ||
|
||||
!isMatchingOpenCodeServeCommand({
|
||||
command: entry.command,
|
||||
binaryPath: input.binaryPath,
|
||||
hostname: input.hostname,
|
||||
port: input.port,
|
||||
})
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.sync(() => {
|
||||
try {
|
||||
process.kill(entry.pid, input.signal);
|
||||
} catch {
|
||||
// The process may have exited between `ps` and `kill`.
|
||||
}
|
||||
});
|
||||
},
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
};
|
||||
|
||||
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(
|
||||
@@ -460,34 +370,9 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
// any serve process left in that group.
|
||||
}
|
||||
});
|
||||
const killDirectChild = (signal: NodeJS.Signals) =>
|
||||
child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid);
|
||||
const killMatchingServeProcesses = (signal: NodeJS.Signals) =>
|
||||
terminateMatchingOpenCodeServeProcesses({
|
||||
binaryPath: input.binaryPath,
|
||||
hostname,
|
||||
port,
|
||||
signal,
|
||||
});
|
||||
const terminateChild = Effect.all(
|
||||
[
|
||||
killOpenCodeProcessGroup("SIGTERM"),
|
||||
killDirectChild("SIGTERM"),
|
||||
killMatchingServeProcesses("SIGTERM"),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(
|
||||
const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
|
||||
Effect.andThen(Effect.sleep("1 second")),
|
||||
Effect.andThen(
|
||||
Effect.all(
|
||||
[
|
||||
killOpenCodeProcessGroup("SIGKILL"),
|
||||
killDirectChild("SIGKILL"),
|
||||
killMatchingServeProcesses("SIGKILL"),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
),
|
||||
),
|
||||
Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
|
||||
Effect.ignore,
|
||||
);
|
||||
yield* Scope.addFinalizer(runtimeScope, terminateChild);
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
GitCommandError,
|
||||
KeybindingRule,
|
||||
MessageId,
|
||||
OpenError,
|
||||
ExternalLauncherError,
|
||||
type OrchestrationThreadShell,
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
@@ -53,6 +53,7 @@ import { vi } from "vitest";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import type { ServerConfigShape } from "./config.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "./config.ts";
|
||||
import { makeRoutesLayer } from "./server.ts";
|
||||
@@ -63,7 +64,7 @@ import {
|
||||
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { GitManager, type GitManagerShape } from "./git/GitManager.ts";
|
||||
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
|
||||
import { Open, type OpenShape } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
@@ -319,7 +320,7 @@ const buildAppUnderTest = (options?: {
|
||||
keybindings?: Partial<KeybindingsShape>;
|
||||
providerRegistry?: Partial<ProviderRegistryShape>;
|
||||
serverSettings?: Partial<ServerSettingsShape>;
|
||||
open?: Partial<OpenShape>;
|
||||
externalLauncher?: Partial<ExternalLauncher.ExternalLauncherShape>;
|
||||
vcsDriver?: Partial<VcsDriver.VcsDriverShape>;
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
@@ -540,8 +541,8 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(Open)({
|
||||
...options?.layers?.open,
|
||||
Layer.mock(ExternalLauncher.ExternalLauncher)({
|
||||
...options?.layers?.externalLauncher,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
@@ -692,6 +693,36 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.serverRuntimeStartup,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: false,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(false),
|
||||
shouldRunScopeWork: () => Effect.succeed(false),
|
||||
shouldRunOpportunisticWork: Effect.succeed(false),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ServerEnvironment)({
|
||||
getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId),
|
||||
@@ -2517,8 +2548,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
let openedInput: { cwd: string; editor: EditorId } | null = null;
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
open: {
|
||||
openInEditor: (input) =>
|
||||
externalLauncher: {
|
||||
launchEditor: (input) =>
|
||||
Effect.sync(() => {
|
||||
openedInput = input;
|
||||
}),
|
||||
@@ -2542,11 +2573,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
it.effect("routes websocket rpc shell.openInEditor errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const openError = new OpenError({ message: "Editor command not found: cursor" });
|
||||
const externalLauncherError = new ExternalLauncherError({
|
||||
message: "Editor command not found: cursor",
|
||||
});
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
open: {
|
||||
openInEditor: () => Effect.fail(openError),
|
||||
externalLauncher: {
|
||||
launchEditor: () => Effect.fail(externalLauncherError),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2561,7 +2594,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
).pipe(Effect.result),
|
||||
);
|
||||
|
||||
assertFailure(result, openError);
|
||||
assertFailure(result, externalLauncherError);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
|
||||
import {
|
||||
attachmentsRouteLayer,
|
||||
otlpTracesProxyRouteLayer,
|
||||
@@ -13,7 +15,7 @@ import {
|
||||
} from "./http.ts";
|
||||
import { fixPath } from "./os-jank.ts";
|
||||
import { websocketRpcRouteLayer } from "./ws.ts";
|
||||
import { OpenLive } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";
|
||||
@@ -102,6 +104,11 @@ const PtyAdapterLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(HostPowerMonitor.layer),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
);
|
||||
|
||||
const HttpServerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
@@ -242,6 +249,7 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
@@ -269,7 +277,6 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// no longer transitively provides it. Exposing it at the runtime level
|
||||
// keeps a single Live for all opencode consumers.
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
@@ -279,10 +286,11 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(BackgroundLayerLive),
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ExternalLauncher.layer),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
|
||||
@@ -98,6 +98,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
@@ -159,6 +160,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
@@ -200,6 +202,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
|
||||
@@ -23,7 +23,7 @@ import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { Keybindings } from "./keybindings.ts";
|
||||
import { Open } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts";
|
||||
@@ -261,9 +261,9 @@ const maybeOpenBrowser = (target: string) =>
|
||||
if (serverConfig.noBrowser) {
|
||||
return;
|
||||
}
|
||||
const { openBrowser } = yield* Open;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
|
||||
yield* openBrowser(target).pipe(
|
||||
yield* externalLauncher.launchBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
|
||||
@@ -460,6 +460,14 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: 10_000,
|
||||
},
|
||||
},
|
||||
automaticGitFetchInterval: 10_000,
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
|
||||
@@ -135,13 +135,17 @@ export class ServerSettingsService extends Context.Service<
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
|
||||
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
|
||||
overrides;
|
||||
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
|
||||
const initialSettings = yield* normalizeServerSettings({
|
||||
...merged,
|
||||
...(automaticGitFetchInterval !== undefined
|
||||
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
|
||||
: {}),
|
||||
...(providerHealthRefreshInterval !== undefined
|
||||
? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
|
||||
: {}),
|
||||
});
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
|
||||
|
||||
@@ -215,7 +219,9 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"backgroundActivity",
|
||||
"automaticGitFetchInterval",
|
||||
"providerHealthRefreshInterval",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export const layer = Layer.effect(
|
||||
cwd: config.cwd,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
|
||||
@@ -139,7 +139,7 @@ function probeCli(input: {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
@@ -216,7 +216,7 @@ export function probeSourceControlProvider(input: {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
|
||||
@@ -8,7 +8,7 @@ export interface CollectedUint8StreamText {
|
||||
}
|
||||
|
||||
interface CollectState {
|
||||
readonly text: string;
|
||||
chunks: Uint8Array[];
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
@@ -18,18 +18,21 @@ export const collectUint8StreamText = <E>(input: {
|
||||
readonly maxBytes?: number | undefined;
|
||||
readonly truncatedMarker?: string | null | undefined;
|
||||
}): Effect.Effect<CollectedUint8StreamText, E> => {
|
||||
const decoder = new TextDecoder();
|
||||
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
|
||||
return input.stream.pipe(
|
||||
Stream.runFold(
|
||||
(): CollectState => ({
|
||||
text: "",
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk): CollectState => {
|
||||
/*
|
||||
* keep draining after truncation so the child process can exit normally.
|
||||
* its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance
|
||||
*/
|
||||
if (state.truncated) {
|
||||
return state;
|
||||
}
|
||||
@@ -38,30 +41,30 @@ export const collectUint8StreamText = <E>(input: {
|
||||
if (remainingBytes <= 0) {
|
||||
return {
|
||||
...state,
|
||||
text: `${state.text}${truncatedMarker}`,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextChunk =
|
||||
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
|
||||
state.chunks.push(nextChunk);
|
||||
const bytes = state.bytes + nextChunk.byteLength;
|
||||
const truncated = chunk.byteLength > remainingBytes;
|
||||
|
||||
return {
|
||||
text: truncated ? `${text}${truncatedMarker}` : text,
|
||||
chunks: state.chunks,
|
||||
bytes,
|
||||
truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
|
||||
Effect.map((state): CollectedUint8StreamText => {
|
||||
const text = Buffer.concat(state.chunks, state.bytes).toString("utf8");
|
||||
return {
|
||||
text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,
|
||||
bytes: state.bytes,
|
||||
truncated: state.truncated,
|
||||
}),
|
||||
),
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -6,21 +6,24 @@ import {
|
||||
type TerminalOpenInput,
|
||||
type TerminalRestartInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import * as ProcessRunner from "../../processRunner.ts";
|
||||
import type { TerminalManagerShape } from "../Services/Manager.ts";
|
||||
import {
|
||||
type PtyAdapterShape,
|
||||
@@ -31,6 +34,10 @@ import {
|
||||
} from "../Services/PTY.ts";
|
||||
import { makeTerminalManagerWithOptions } from "./Manager.ts";
|
||||
|
||||
class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
readonly writes: string[] = [];
|
||||
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
|
||||
@@ -127,11 +134,21 @@ class FakePtyAdapter implements PtyAdapterShape {
|
||||
const waitFor = <E, R>(
|
||||
predicate: Effect.Effect<boolean, E, R>,
|
||||
timeout: Duration.Input = 800,
|
||||
): Effect.Effect<void, E | Cause.TimeoutError, R> =>
|
||||
): Effect.Effect<void, WaitForConditionError | E, R> =>
|
||||
predicate.pipe(
|
||||
Effect.filter((done) => done),
|
||||
Effect.filterOrFail(
|
||||
(done) => done,
|
||||
() => new WaitForConditionError({ message: "Condition not met" }),
|
||||
),
|
||||
Effect.retry(Schedule.spaced("15 millis")),
|
||||
Effect.timeout(timeout),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
|
||||
@@ -156,33 +173,27 @@ function restartInput(overrides: Partial<TerminalRestartInput> = {}): TerminalRe
|
||||
};
|
||||
}
|
||||
|
||||
function historyLogName(threadId: string): string {
|
||||
return `terminal_${Encoding.encodeBase64Url(threadId)}.log`;
|
||||
}
|
||||
const historyLogPath = (logsDir: string, threadId = "thread-1") =>
|
||||
Effect.service(Path.Path).pipe(
|
||||
Effect.map(({ join }) => join(logsDir, `terminal_${Encoding.encodeBase64Url(threadId)}.log`)),
|
||||
);
|
||||
|
||||
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
|
||||
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
return `${threadPart}.log`;
|
||||
}
|
||||
return `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`;
|
||||
}
|
||||
|
||||
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
|
||||
return joinPath(logsDir, historyLogName(threadId));
|
||||
}
|
||||
|
||||
function multiTerminalHistoryLogPath(
|
||||
const multiTerminalHistoryLogPath = (
|
||||
logsDir: string,
|
||||
threadId = "thread-1",
|
||||
terminalId = "default",
|
||||
): string {
|
||||
return joinPath(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
|
||||
}
|
||||
|
||||
function joinPath(...segments: ReadonlyArray<string>): string {
|
||||
return segments.join("/");
|
||||
}
|
||||
terminalId = DEFAULT_TERMINAL_ID,
|
||||
) =>
|
||||
Effect.service(Path.Path).pipe(
|
||||
Effect.map(({ join }) => {
|
||||
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
|
||||
return join(
|
||||
logsDir,
|
||||
terminalId === DEFAULT_TERMINAL_ID
|
||||
? `${threadPart}.log`
|
||||
: `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
interface CreateManagerOptions {
|
||||
shellResolver?: () => string;
|
||||
@@ -209,13 +220,13 @@ const createManager = (
|
||||
): Effect.Effect<
|
||||
ManagerFixture,
|
||||
PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope
|
||||
FileSystem.FileSystem | Path.Path | Scope.Scope | ProcessRunner.ProcessRunner
|
||||
> =>
|
||||
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
|
||||
Effect.gen(function* () {
|
||||
const pathService = yield* Path.Path;
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
|
||||
const logsDir = pathService.join(baseDir, "userdata", "logs", "terminals");
|
||||
const logsDir = join(baseDir, "userdata", "logs", "terminals");
|
||||
const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
|
||||
|
||||
const manager = yield* makeTerminalManagerWithOptions({
|
||||
@@ -246,6 +257,7 @@ const createManager = (
|
||||
return {
|
||||
baseDir,
|
||||
logsDir,
|
||||
join,
|
||||
ptyAdapter,
|
||||
manager,
|
||||
getEvents: Ref.get(eventsRef),
|
||||
@@ -253,7 +265,12 @@ const createManager = (
|
||||
}),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
|
||||
it.layer(
|
||||
Layer.merge(NodeServices.layer, ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
{ excludeTestServices: true },
|
||||
)("TerminalManager", (it) => {
|
||||
const itEffectSkipOnWindows = process.platform === "win32" ? it.effect.skip : it.effect;
|
||||
|
||||
it.effect("spawns lazily and reuses running terminal per thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager();
|
||||
@@ -290,13 +307,13 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
fs.writeFileString(filePath, contents),
|
||||
);
|
||||
|
||||
it.effect("preserves non-notFound cwd stat failures", () =>
|
||||
itEffectSkipOnWindows("preserves non-notFound cwd stat failures", () =>
|
||||
Effect.gen(function* () {
|
||||
if (process.platform === "win32") return;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const { manager, baseDir } = yield* createManager();
|
||||
const blockedRoot = joinPath(baseDir, "blocked-root");
|
||||
const blockedCwd = joinPath(blockedRoot, "cwd");
|
||||
const blockedRoot = path.join(baseDir, "blocked-root");
|
||||
const blockedCwd = path.join(blockedRoot, "cwd");
|
||||
yield* makeDirectory(blockedCwd);
|
||||
yield* chmod(blockedRoot, 0o000);
|
||||
|
||||
@@ -390,15 +407,27 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
it.effect("clears transcript and emits cleared event", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
|
||||
const path = yield* Path.Path;
|
||||
yield* manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
|
||||
process.emitData("hello\n");
|
||||
yield* waitFor(pathExists(historyLogPath(logsDir)));
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
|
||||
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(readFileString),
|
||||
Effect.map((text) => text === ""),
|
||||
),
|
||||
);
|
||||
|
||||
const events = yield* getEvents;
|
||||
expect(events.some((event) => event.type === "cleared")).toBe(true);
|
||||
@@ -421,21 +450,34 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
expect(firstProcess).toBeDefined();
|
||||
if (!firstProcess) return;
|
||||
firstProcess.emitData("before restart\n");
|
||||
yield* waitFor(pathExists(historyLogPath(logsDir)));
|
||||
const path = yield* Path.Path;
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
|
||||
const snapshot = yield* manager.restart(restartInput());
|
||||
assert.equal(snapshot.history, "");
|
||||
assert.equal(snapshot.status, "running");
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(2);
|
||||
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(readFileString),
|
||||
Effect.map((text) => text === ""),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, getEvents, baseDir } = yield* createManager();
|
||||
const firstWorktreePath = joinPath(baseDir, "worktrees", "feature-a");
|
||||
const secondWorktreePath = joinPath(baseDir, "worktrees", "feature-b");
|
||||
const path = yield* Path.Path;
|
||||
const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
|
||||
const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
|
||||
yield* makeDirectory(firstWorktreePath);
|
||||
yield* makeDirectory(secondWorktreePath);
|
||||
const startedSnapshot = yield* manager.open(
|
||||
@@ -471,7 +513,8 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
it.effect("preserves worktree metadata when reopening an exited session", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
|
||||
const worktreePath = joinPath(baseDir, "worktrees", "feature-a");
|
||||
const path = yield* Path.Path;
|
||||
const worktreePath = path.join(baseDir, "worktrees", "feature-a");
|
||||
yield* makeDirectory(worktreePath);
|
||||
|
||||
yield* manager.open(
|
||||
@@ -513,12 +556,18 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
it.effect("emits exited event and reopens with clean transcript after exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
|
||||
const path = yield* Path.Path;
|
||||
yield* manager.open(openInput());
|
||||
const process = ptyAdapter.processes[0];
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
process.emitData("old data\n");
|
||||
yield* waitFor(pathExists(historyLogPath(logsDir)));
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
process.emitExit({ exitCode: 0, signal: 0 });
|
||||
|
||||
yield* waitFor(
|
||||
@@ -528,7 +577,12 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
|
||||
assert.equal(reopened.history, "");
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(2);
|
||||
expect(yield* readFileString(historyLogPath(logsDir))).toBe("");
|
||||
expect(
|
||||
yield* historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(readFileString),
|
||||
),
|
||||
).toBe("");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -715,10 +769,21 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
expect(process).toBeDefined();
|
||||
if (!process) return;
|
||||
process.emitData("bye\n");
|
||||
yield* waitFor(pathExists(historyLogPath(logsDir)));
|
||||
const path = yield* Path.Path;
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
|
||||
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
|
||||
expect(yield* pathExists(historyLogPath(logsDir))).toBe(false);
|
||||
expect(
|
||||
yield* historyLogPath(logsDir).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -735,19 +800,36 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
|
||||
defaultProcess.emitData("default\n");
|
||||
sidecarProcess.emitData("sidecar\n");
|
||||
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
|
||||
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
|
||||
const path = yield* Path.Path;
|
||||
yield* waitFor(
|
||||
multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
yield* waitFor(
|
||||
multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
|
||||
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
|
||||
|
||||
assert.equal(defaultProcess.killed, true);
|
||||
assert.equal(sidecarProcess.killed, true);
|
||||
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -786,7 +868,13 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
|
||||
first.emitData("first-history\n");
|
||||
second.emitData("second-history\n");
|
||||
yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1")));
|
||||
const path = yield* Path.Path;
|
||||
yield* waitFor(
|
||||
historyLogPath(logsDir, "thread-1").pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.flatMap(pathExists),
|
||||
),
|
||||
);
|
||||
first.emitExit({ exitCode: 0, signal: 0 });
|
||||
yield* Effect.sleep(Duration.millis(5));
|
||||
second.emitExit({ exitCode: 0, signal: 0 });
|
||||
@@ -809,8 +897,9 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, logsDir } = yield* createManager();
|
||||
const legacyPath = joinPath(logsDir, "thread-1.log");
|
||||
const nextPath = historyLogPath(logsDir);
|
||||
const path = yield* Path.Path;
|
||||
const legacyPath = path.join(logsDir, "thread-1.log");
|
||||
const nextPath = yield* historyLogPath(logsDir);
|
||||
yield* writeFileString(legacyPath, "legacy-line\n");
|
||||
|
||||
const snapshot = yield* manager.open(openInput());
|
||||
|
||||
@@ -5,13 +5,13 @@ import {
|
||||
type TerminalSessionStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
terminalRestartsTotal,
|
||||
terminalSessionsTotal,
|
||||
} from "../../observability/Metrics.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import * as ProcessRunner from "../../processRunner.ts";
|
||||
import {
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
@@ -51,6 +51,7 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(
|
||||
"TerminalSubprocessCheckError",
|
||||
@@ -72,7 +73,9 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
|
||||
) {}
|
||||
|
||||
interface TerminalSubprocessChecker {
|
||||
(terminalPid: number): Effect.Effect<boolean, TerminalSubprocessCheckError>;
|
||||
(
|
||||
terminalPid: number,
|
||||
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner>;
|
||||
}
|
||||
|
||||
interface ShellCandidate {
|
||||
@@ -211,17 +214,23 @@ function normalizeShellCommand(
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function basename(command: string, platform: NodeJS.Platform): string {
|
||||
const normalized = platform === "win32" ? command.replaceAll("/", "\\") : command;
|
||||
const separator = platform === "win32" ? "\\" : "/";
|
||||
return normalized.slice(normalized.lastIndexOf(separator) + 1);
|
||||
function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
|
||||
const normalized =
|
||||
platform === "win32" ? command.replaceAll("/", "\\") : command.replaceAll("\\", "/");
|
||||
const parts = normalized
|
||||
.split(platform === "win32" ? /\\+/ : /\/+/)
|
||||
.filter((part) => part.length > 0);
|
||||
return parts.at(-1) ?? normalized;
|
||||
}
|
||||
|
||||
function joinWindowsPath(...segments: ReadonlyArray<string>): string {
|
||||
return segments
|
||||
.filter((segment) => segment.length > 0)
|
||||
.join("\\")
|
||||
.replace(/\\+/g, "\\");
|
||||
function joinWindowsPath(...parts: ReadonlyArray<string>): string {
|
||||
return parts
|
||||
.map((part, index) => {
|
||||
if (index === 0) return part.replace(/[\\/]+$/g, "");
|
||||
return part.replace(/^[\\/]+|[\\/]+$/g, "");
|
||||
})
|
||||
.filter((part) => part.length > 0)
|
||||
.join("\\");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(
|
||||
@@ -229,7 +238,7 @@ function shellCandidateFromCommand(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = basename(command, platform).toLowerCase();
|
||||
const shellName = basenameForPlatform(command, platform).toLowerCase();
|
||||
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
|
||||
return { shell: command, args: ["-NoLogo"] };
|
||||
}
|
||||
@@ -357,66 +366,82 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
|
||||
|
||||
function checkWindowsSubprocessActivity(
|
||||
terminalPid: number,
|
||||
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
|
||||
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
].join("; ");
|
||||
return Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to check Windows terminal subprocess activity.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "powershell",
|
||||
}),
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
return Effect.gen(function* () {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
return yield* processRunner.run({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeout: "1500 millis",
|
||||
maxOutputBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
shell: process.platform === "win32",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.map((result) => result.code === 0),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to check Windows terminal subprocess activity.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "powershell",
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
const runPgrep = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with pgrep.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "pgrep",
|
||||
}),
|
||||
});
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const runPgrep = processRunner
|
||||
.run({
|
||||
command: "pgrep",
|
||||
args: ["-P", String(terminalPid)],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with pgrep.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "pgrep",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runPs = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with ps.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
}),
|
||||
});
|
||||
const runPs = processRunner
|
||||
.run({
|
||||
command: "ps",
|
||||
args: ["-eo", "pid=,ppid="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with ps.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const pgrepResult = yield* Effect.exit(runPgrep);
|
||||
if (pgrepResult._tag === "Success") {
|
||||
@@ -447,7 +472,7 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct
|
||||
|
||||
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -725,14 +750,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
const path = yield* Path.Path;
|
||||
const context = yield* Effect.context<never>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const logsDir = options.logsDir;
|
||||
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
const platform = options.platform ?? process.platform;
|
||||
const baseEnv = options.env ?? process.env;
|
||||
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
|
||||
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const subprocessChecker =
|
||||
options.subprocessChecker ??
|
||||
((terminalPid) =>
|
||||
defaultSubprocessChecker(terminalPid).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
|
||||
));
|
||||
const subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -1419,22 +1449,23 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
runFork(drainProcessEvents(session, processPid));
|
||||
});
|
||||
|
||||
const startedAt = yield* nowIso;
|
||||
const runningAt = yield* nowIso;
|
||||
yield* modifyManagerState((state) => {
|
||||
session.process = ptyProcess;
|
||||
session.pid = processPid;
|
||||
session.status = "running";
|
||||
session.updatedAt = startedAt;
|
||||
session.updatedAt = runningAt;
|
||||
session.unsubscribeData = unsubscribeData;
|
||||
session.unsubscribeExit = unsubscribeExit;
|
||||
return [undefined, state] as const;
|
||||
});
|
||||
|
||||
const createdAt = yield* nowIso;
|
||||
yield* publishEvent({
|
||||
type: eventType,
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: startedAt,
|
||||
createdAt,
|
||||
snapshot: snapshot(session),
|
||||
});
|
||||
}),
|
||||
@@ -1451,8 +1482,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
if (ptyProcess) {
|
||||
yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
|
||||
}
|
||||
const erroredAt = yield* nowIso;
|
||||
|
||||
const failedAt = yield* nowIso;
|
||||
yield* modifyManagerState((state) => {
|
||||
session.status = "error";
|
||||
session.pid = null;
|
||||
@@ -1463,18 +1494,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
session.updatedAt = failedAt;
|
||||
session.updatedAt = erroredAt;
|
||||
return [undefined, state] as const;
|
||||
});
|
||||
|
||||
yield* evictInactiveSessionsIfNeeded();
|
||||
|
||||
const message = error.message;
|
||||
const createdAt = yield* nowIso;
|
||||
yield* publishEvent({
|
||||
type: "error",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: failedAt,
|
||||
createdAt,
|
||||
message,
|
||||
});
|
||||
yield* Effect.logError("failed to start terminal", {
|
||||
@@ -1547,6 +1579,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
}
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
const createdAt = yield* nowIso;
|
||||
const event = yield* modifyManagerState((state) => {
|
||||
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
|
||||
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
|
||||
@@ -1568,7 +1601,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
type: "activity" as const,
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
createdAt: updatedAt,
|
||||
createdAt,
|
||||
hasRunningSubprocess: hasRunningSubprocess.value,
|
||||
}),
|
||||
state,
|
||||
@@ -1797,19 +1830,20 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
Effect.gen(function* () {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const session = yield* requireSession(input.threadId, terminalId);
|
||||
const updatedAt = yield* nowIso;
|
||||
session.history = "";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
const clearedAt = yield* nowIso;
|
||||
session.updatedAt = clearedAt;
|
||||
session.updatedAt = updatedAt;
|
||||
yield* persistHistory(input.threadId, terminalId, session.history);
|
||||
const createdAt = yield* nowIso;
|
||||
yield* publishEvent({
|
||||
type: "cleared",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: clearedAt,
|
||||
createdAt,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1933,4 +1967,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
},
|
||||
);
|
||||
|
||||
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager());
|
||||
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()).pipe(
|
||||
Layer.provide(ProcessRunner.layer),
|
||||
);
|
||||
@@ -67,6 +67,7 @@ runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
|
||||
|
||||
it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
|
||||
let observedEnv: NodeJS.ProcessEnv | undefined;
|
||||
let observedAppendTruncationMarker: boolean | undefined;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.makeVcsDriverShape();
|
||||
@@ -78,26 +79,32 @@ it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
|
||||
env: {
|
||||
GIT_INDEX_FILE: "/tmp/t3-index",
|
||||
},
|
||||
appendTruncationMarker: true,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(observedEnv, {
|
||||
GIT_INDEX_FILE: "/tmp/t3-index",
|
||||
});
|
||||
assert.strictEqual(observedAppendTruncationMarker, true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedEnv = input.env;
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
observedEnv = input.env;
|
||||
observedAppendTruncationMarker = input.appendTruncationMarker;
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
@@ -35,7 +39,7 @@ export interface ExecuteGitInput {
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly appendTruncationMarker?: boolean;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
@@ -218,6 +222,7 @@ export class GitVcsDriver extends Context.Service<GitVcsDriver, GitVcsDriverShap
|
||||
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
@@ -318,14 +323,15 @@ const gitCommand = (
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly appendTruncationMarker?: boolean;
|
||||
},
|
||||
) =>
|
||||
process.run({
|
||||
operation,
|
||||
command: "git",
|
||||
args,
|
||||
args: ["-C", cwd, ...args],
|
||||
cwd,
|
||||
spawnCwd: globalThis.process.cwd(),
|
||||
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
|
||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
||||
...(options?.allowNonZeroExit !== undefined
|
||||
@@ -333,13 +339,15 @@ const gitCommand = (
|
||||
: {}),
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
...(options?.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
|
||||
...(options?.appendTruncationMarker !== undefined
|
||||
? { appendTruncationMarker: options.appendTruncationMarker }
|
||||
: {}),
|
||||
});
|
||||
|
||||
export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const vcsProcess = yield* VcsProcess.VcsProcess;
|
||||
const capabilities = {
|
||||
kind: "git" as const,
|
||||
supportsWorktrees: true,
|
||||
@@ -351,7 +359,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
|
||||
const isInsideWorkTree: VcsDriver.VcsDriverShape["isInsideWorkTree"] = (cwd) =>
|
||||
gitCommand(
|
||||
process,
|
||||
vcsProcess,
|
||||
"GitVcsDriver.isInsideWorkTree",
|
||||
cwd,
|
||||
["rev-parse", "--is-inside-work-tree"],
|
||||
@@ -363,14 +371,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
|
||||
|
||||
const execute: VcsDriver.VcsDriverShape["execute"] = (input) =>
|
||||
gitCommand(process, input.operation, input.cwd, input.args, {
|
||||
gitCommand(vcsProcess, input.operation, input.cwd, input.args, {
|
||||
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
|
||||
...(input.env !== undefined ? { env: input.env } : {}),
|
||||
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
|
||||
...(input.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
|
||||
...(input.appendTruncationMarker !== undefined
|
||||
? { appendTruncationMarker: input.appendTruncationMarker }
|
||||
: {}),
|
||||
});
|
||||
|
||||
@@ -381,12 +389,12 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
|
||||
const root = yield* gitCommand(vcsProcess, "GitVcsDriver.detectRepository.root", cwd, [
|
||||
"rev-parse",
|
||||
"--show-toplevel",
|
||||
]);
|
||||
const gitCommonDir = yield* gitCommand(
|
||||
process,
|
||||
vcsProcess,
|
||||
"GitVcsDriver.detectRepository.commonDir",
|
||||
cwd,
|
||||
["rev-parse", "--git-common-dir"],
|
||||
@@ -402,7 +410,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
|
||||
const listWorkspaceFiles: VcsDriver.VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
|
||||
gitCommand(
|
||||
process,
|
||||
vcsProcess,
|
||||
"GitVcsDriver.listWorkspaceFiles",
|
||||
cwd,
|
||||
[
|
||||
@@ -417,7 +425,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
@@ -444,11 +452,17 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
|
||||
const listRemotes: VcsDriver.VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(
|
||||
function* (cwd) {
|
||||
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
});
|
||||
const result = yield* gitCommand(
|
||||
vcsProcess,
|
||||
"GitVcsDriver.listRemotes",
|
||||
cwd,
|
||||
["remote", "-v"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
@@ -494,7 +508,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const result = yield* gitCommand(
|
||||
process,
|
||||
vcsProcess,
|
||||
"GitVcsDriver.filterIgnoredPaths",
|
||||
cwd,
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
@@ -503,7 +517,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -530,14 +544,266 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
|
||||
});
|
||||
|
||||
const initRepository: VcsDriver.VcsDriverShape["initRepository"] = (input) =>
|
||||
gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
|
||||
gitCommand(vcsProcess, "GitVcsDriver.initRepository", input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
maxOutputBytes: 64 * 1024,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const resolveHeadCommit = (cwd: string) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.resolveHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const hasHeadCommit = (cwd: string) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.hasHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => result.exitCode === 0));
|
||||
|
||||
const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.resolveCheckpointCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveGitCommonDir = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* execute({
|
||||
operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
|
||||
cwd,
|
||||
args: ["rev-parse", "--git-common-dir"],
|
||||
});
|
||||
const gitCommonDir = result.stdout.trim();
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const checkpoints: VcsDriver.VcsCheckpointOps = {
|
||||
captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
|
||||
const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
|
||||
const gitCommonDir = yield* resolveGitCommonDir(input.cwd);
|
||||
const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const cleanupTempIndex = fileSystem
|
||||
.remove(tempIndexPath, { force: true })
|
||||
.pipe(Effect.ignore);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}).pipe(Effect.ensuring(cleanupTempIndex));
|
||||
}),
|
||||
|
||||
hasCheckpointRef: (input) =>
|
||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||
Effect.map((commit) => commit !== null),
|
||||
),
|
||||
|
||||
restoreCheckpoint: Effect.fn("GitVcsDriver.checkpoints.restoreCheckpoint")(function* (input) {
|
||||
const operation = "GitVcsDriver.checkpoints.restoreCheckpoint";
|
||||
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}),
|
||||
|
||||
diffCheckpoints: Effect.fn("GitVcsDriver.checkpoints.diffCheckpoints")(function* (input) {
|
||||
const operation = "GitVcsDriver.checkpoints.diffCheckpoints";
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"checkpoint.cwd": input.cwd,
|
||||
"checkpoint.from_ref": input.fromCheckpointRef,
|
||||
"checkpoint.to_ref": input.toCheckpointRef,
|
||||
"checkpoint.ignore_whitespace": input.ignoreWhitespace,
|
||||
"checkpoint.fallback_from_to_head": input.fallbackFromToHead,
|
||||
});
|
||||
|
||||
let fromRevision: string = input.fromCheckpointRef;
|
||||
if (input.fallbackFromToHead === true) {
|
||||
const resolvedFromCommit = yield* resolveCheckpointCommit(
|
||||
input.cwd,
|
||||
input.fromCheckpointRef,
|
||||
);
|
||||
if (resolvedFromCommit) {
|
||||
fromRevision = resolvedFromCommit;
|
||||
} else {
|
||||
const headCommit = yield* resolveHeadCommit(input.cwd);
|
||||
if (!headCommit) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
exitCode: 1,
|
||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
fromRevision = headCommit;
|
||||
}
|
||||
}
|
||||
|
||||
const result = yield* execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
"--no-textconv",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
`${fromRevision}^{commit}`,
|
||||
`${input.toCheckpointRef}^{commit}`,
|
||||
],
|
||||
allowNonZeroExit: true,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
exitCode: result.exitCode,
|
||||
detail: result.stderr.trim() || "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
|
||||
return result.stdout;
|
||||
}),
|
||||
|
||||
deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")(
|
||||
function* (input) {
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
execute({
|
||||
operation: "GitVcsDriver.checkpoints.deleteCheckpointRefs",
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
return VcsDriver.VcsDriver.of({
|
||||
capabilities,
|
||||
execute,
|
||||
checkpoints,
|
||||
detectRepository,
|
||||
isInsideWorkTree,
|
||||
listWorkspaceFiles,
|
||||
|
||||
@@ -77,7 +77,7 @@ interface ExecuteGitOptions {
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
maxOutputBytes?: number | undefined;
|
||||
truncateOutputAtMaxBytes?: boolean | undefined;
|
||||
appendTruncationMarker?: boolean | undefined;
|
||||
progress?: GitVcsDriver.ExecuteGitProgress | undefined;
|
||||
}
|
||||
|
||||
@@ -535,7 +535,7 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
truncateOutputAtMaxBytes: boolean,
|
||||
appendTruncationMarker: boolean,
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
@@ -565,11 +565,11 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
});
|
||||
|
||||
const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
|
||||
if (truncateOutputAtMaxBytes && truncated) {
|
||||
if (appendTruncationMarker && truncated) {
|
||||
return;
|
||||
}
|
||||
const nextBytes = bytes + chunk.byteLength;
|
||||
if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) {
|
||||
if (!appendTruncationMarker && nextBytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
@@ -579,11 +579,11 @@ const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
}
|
||||
|
||||
const chunkToDecode =
|
||||
truncateOutputAtMaxBytes && nextBytes > maxOutputBytes
|
||||
appendTruncationMarker && nextBytes > maxOutputBytes
|
||||
? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))
|
||||
: chunk;
|
||||
bytes += chunkToDecode.byteLength;
|
||||
truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes;
|
||||
truncated = appendTruncationMarker && nextBytes > maxOutputBytes;
|
||||
|
||||
const decoded = decoder.decode(chunkToDecode, { stream: !truncated });
|
||||
text += decoded;
|
||||
@@ -619,7 +619,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
} as const;
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
|
||||
const appendTruncationMarker = input.appendTruncationMarker ?? false;
|
||||
|
||||
const runGitCommand = Effect.fn("runGitCommand")(function* () {
|
||||
const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
|
||||
@@ -646,14 +646,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
commandInput,
|
||||
child.stdout,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes,
|
||||
appendTruncationMarker,
|
||||
input.progress?.onStdoutLine,
|
||||
),
|
||||
collectOutput(
|
||||
commandInput,
|
||||
child.stderr,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes,
|
||||
appendTruncationMarker,
|
||||
input.progress?.onStderrLine,
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
@@ -746,8 +746,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
|
||||
...(options.truncateOutputAtMaxBytes !== undefined
|
||||
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
|
||||
...(options.appendTruncationMarker !== undefined
|
||||
? { appendTruncationMarker: options.appendTruncationMarker }
|
||||
: {}),
|
||||
...(options.progress ? { progress: options.progress } : {}),
|
||||
}).pipe(
|
||||
@@ -1379,7 +1379,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
["diff", "--cached", "--patch", "--minimal"],
|
||||
{
|
||||
maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1598,7 +1598,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
["log", "--oneline", range],
|
||||
{
|
||||
maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
),
|
||||
runGitStdoutWithOptions(
|
||||
@@ -1607,7 +1607,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
["diff", "--stat", range],
|
||||
{
|
||||
maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
),
|
||||
runGitStdoutWithOptions(
|
||||
@@ -1616,7 +1616,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
["diff", "--patch", "--minimal", range],
|
||||
{
|
||||
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
|
||||
truncateOutputAtMaxBytes: true,
|
||||
appendTruncationMarker: true,
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
@@ -9,13 +9,53 @@ import type {
|
||||
VcsListWorkspaceFilesResult,
|
||||
VcsRepositoryIdentity,
|
||||
} from "@t3tools/contracts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
export interface VcsCaptureCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
export interface VcsRestoreCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly fallbackToHead?: boolean;
|
||||
}
|
||||
|
||||
export interface VcsDiffCheckpointsInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface VcsDeleteCheckpointRefsInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
export interface VcsCheckpointOps {
|
||||
readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;
|
||||
readonly hasCheckpointRef: (
|
||||
input: Omit<VcsRestoreCheckpointInput, "fallbackToHead">,
|
||||
) => Effect.Effect<boolean, VcsError>;
|
||||
readonly restoreCheckpoint: (
|
||||
input: VcsRestoreCheckpointInput,
|
||||
) => Effect.Effect<boolean, VcsError>;
|
||||
readonly diffCheckpoints: (input: VcsDiffCheckpointsInput) => Effect.Effect<string, VcsError>;
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: VcsDeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export interface VcsDriverShape {
|
||||
readonly capabilities: VcsDriverCapabilities;
|
||||
readonly execute: (
|
||||
input: Omit<VcsProcess.VcsProcessInput, "command">,
|
||||
) => Effect.Effect<VcsProcess.VcsProcessOutput, VcsError>;
|
||||
readonly checkpoints?: VcsCheckpointOps;
|
||||
readonly detectRepository: (cwd: string) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;
|
||||
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;
|
||||
readonly listWorkspaceFiles: (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -15,9 +16,13 @@ const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const normalizeGitArgs = (args: ReadonlyArray<string>): ReadonlyArray<string> =>
|
||||
args[0] === "-C" && args.length >= 2 ? args.slice(2) : args;
|
||||
|
||||
describe("VcsDriverRegistry", () => {
|
||||
it.effect("routes directly by VCS driver kind for non-repository workflows", () => {
|
||||
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
@@ -41,6 +46,7 @@ describe("VcsDriverRegistry", () => {
|
||||
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
|
||||
const calls: VcsProcess.VcsProcessInput[] = [];
|
||||
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
|
||||
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
|
||||
@@ -51,7 +57,9 @@ describe("VcsDriverRegistry", () => {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push(input);
|
||||
const command = input.args.join(" ");
|
||||
const normalizedArgs =
|
||||
input.args[0] === "-C" && input.args.length >= 2 ? input.args.slice(2) : input.args;
|
||||
const command = normalizedArgs.join(" ");
|
||||
if (command === "rev-parse --is-inside-work-tree") {
|
||||
return processOutput("true\n");
|
||||
}
|
||||
@@ -75,7 +83,7 @@ describe("VcsDriverRegistry", () => {
|
||||
assert.equal(first.repository.rootPath, "/repo");
|
||||
assert.equal(second.repository.rootPath, "/repo");
|
||||
assert.deepStrictEqual(
|
||||
calls.map((call) => call.args.join(" ")),
|
||||
calls.map((call) => normalizeGitArgs(call.args).join(" ")),
|
||||
[
|
||||
"rev-parse --is-inside-work-tree",
|
||||
"rev-parse --show-toplevel",
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, 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 { TestClock } from "effect/testing";
|
||||
|
||||
import { VcsProcessExitError, VcsProcessTimeoutError } from "@t3tools/contracts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
const run = (input: VcsProcess.VcsProcessInput) =>
|
||||
Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
return yield* process.run(input);
|
||||
});
|
||||
|
||||
const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
|
||||
effect.pipe(Effect.provide(liveLayer));
|
||||
|
||||
describe("VcsProcess.run", () => {
|
||||
it.effect("collects stdout", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
operation: "test.stdout",
|
||||
command: "node",
|
||||
args: ["-e", "process.stdout.write('hello')"],
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
expect(result.stdout).toBe("hello");
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdoutTruncated).toBe(false);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("writes stdin before waiting for exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
operation: "test.stdin",
|
||||
command: "node",
|
||||
args: [
|
||||
"-e",
|
||||
[
|
||||
"process.stdin.setEncoding('utf8');",
|
||||
"let data='';",
|
||||
"process.stdin.on('data', chunk => { data += chunk; });",
|
||||
"process.stdin.on('end', () => { process.stdout.write(data); });",
|
||||
].join(""),
|
||||
],
|
||||
cwd: process.cwd(),
|
||||
stdin: "stdin payload",
|
||||
});
|
||||
|
||||
expect(result.stdout).toBe("stdin payload");
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* run({
|
||||
operation: "test.exit",
|
||||
command: "node",
|
||||
args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
|
||||
cwd: process.cwd(),
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(VcsProcessExitError);
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("returns output when non-zero exits are allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
operation: "test.allowed-exit",
|
||||
command: "node",
|
||||
args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
|
||||
cwd: process.cwd(),
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toBe("boom");
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("truncates output and appends the marker when requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
operation: "test.truncate-marker",
|
||||
command: "node",
|
||||
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
|
||||
cwd: process.cwd(),
|
||||
maxOutputBytes: 128,
|
||||
appendTruncationMarker: true,
|
||||
});
|
||||
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stdout).toContain("[truncated]");
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("truncates without the marker when truncation markers are disabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
operation: "test.truncate-silent",
|
||||
command: "node",
|
||||
args: ["-e", "process.stdout.write('x'.repeat(2048))"],
|
||||
cwd: process.cwd(),
|
||||
maxOutputBytes: 128,
|
||||
});
|
||||
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stdout).not.toContain("[truncated]");
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("fails with VcsProcessTimeoutError on timeout", () =>
|
||||
Effect.gen(function* () {
|
||||
const errorFiber = yield* run({
|
||||
operation: "test.timeout",
|
||||
command: "node",
|
||||
args: ["-e", "setTimeout(() => {}, 5000)"],
|
||||
cwd: process.cwd(),
|
||||
timeoutMs: 50,
|
||||
}).pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
const error = yield* Fiber.join(errorFiber);
|
||||
|
||||
expect(error).toBeInstanceOf(VcsProcessTimeoutError);
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
});
|
||||
@@ -1,12 +1,7 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
VcsOutputDecodeError,
|
||||
@@ -15,19 +10,21 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
import { ProcessRunner, layer as ProcessRunnerLive } from "../processRunner.ts";
|
||||
import * as Match from "effect/Match";
|
||||
|
||||
export interface VcsProcessInput {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd: string;
|
||||
readonly spawnCwd?: string;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
readonly appendTruncationMarker?: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessOutput {
|
||||
@@ -38,25 +35,7 @@ export interface VcsProcessOutput {
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessCollectedText {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export interface VcsProcessHandle {
|
||||
readonly pid: ChildProcessSpawner.ProcessId;
|
||||
readonly stdin: Sink.Sink<void, Uint8Array, never, VcsError>;
|
||||
readonly stdout: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly stderr: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, VcsError>;
|
||||
readonly writeStdin: (input: string) => Effect.Effect<void, VcsError>;
|
||||
}
|
||||
|
||||
export interface VcsProcessShape {
|
||||
readonly withProcess: <A, E, R>(
|
||||
input: VcsProcessInput,
|
||||
use: (handle: VcsProcessHandle) => Effect.Effect<A, E, R>,
|
||||
) => Effect.Effect<A, E | VcsError, R>;
|
||||
readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
|
||||
}
|
||||
|
||||
@@ -72,164 +51,72 @@ function commandLabel(command: string, args: ReadonlyArray<string>): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function outputDecodeError(
|
||||
input: VcsProcessInput,
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): VcsOutputDecodeError {
|
||||
return new VcsOutputDecodeError({
|
||||
operation: input.operation,
|
||||
command: commandLabel(input.command, input.args),
|
||||
cwd: input.cwd,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
export const collectText = Effect.fn("VcsProcess.collectText")(function* (input: {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly cwd: string;
|
||||
readonly stream: Stream.Stream<Uint8Array, VcsError>;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) {
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
return yield* collectUint8StreamText({
|
||||
stream: input.stream,
|
||||
maxBytes: maxOutputBytes,
|
||||
truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
|
||||
});
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeVcsProcess")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const spawn = Effect.fn("VcsProcess.spawn")(function* (input: VcsProcessInput) {
|
||||
const label = commandLabel(input.command, input.args);
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.command, [...input.args], {
|
||||
cwd: input.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...input.env,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new VcsProcessSpawnError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const mapStreamError = (streamName: "stdout" | "stderr") =>
|
||||
Stream.mapError((cause: PlatformError.PlatformError) =>
|
||||
outputDecodeError(input, `failed to read process ${streamName}`, cause),
|
||||
);
|
||||
const mapEffectError = (detail: string) =>
|
||||
Effect.mapError((cause: PlatformError.PlatformError) =>
|
||||
outputDecodeError(input, detail, cause),
|
||||
);
|
||||
const writeStdin = (stdin: string) =>
|
||||
Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
|
||||
mapEffectError("failed to write process stdin"),
|
||||
);
|
||||
|
||||
return {
|
||||
pid: child.pid,
|
||||
stdin: child.stdin.pipe(
|
||||
Sink.mapError((cause) => outputDecodeError(input, "failed to write process stdin", cause)),
|
||||
),
|
||||
stdout: child.stdout.pipe(mapStreamError("stdout")),
|
||||
stderr: child.stderr.pipe(mapStreamError("stderr")),
|
||||
exitCode: child.exitCode.pipe(mapEffectError("failed to read process exit code")),
|
||||
writeStdin,
|
||||
} satisfies VcsProcessHandle;
|
||||
});
|
||||
|
||||
const withProcess: VcsProcessShape["withProcess"] = (input, use) =>
|
||||
Effect.scoped(spawn(input).pipe(Effect.flatMap(use)));
|
||||
const processRunner = yield* ProcessRunner;
|
||||
|
||||
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const label = commandLabel(input.command, input.args);
|
||||
const baseError = {
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
};
|
||||
|
||||
const runProcess = Effect.gen(function* () {
|
||||
const [stdout, stderr, exitCode] = yield* withProcess(input, (child) =>
|
||||
Effect.all(
|
||||
[
|
||||
collectText({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
stream: child.stdout,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
|
||||
}),
|
||||
collectText({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
stream: child.stderr,
|
||||
maxOutputBytes,
|
||||
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
|
||||
}),
|
||||
child.exitCode,
|
||||
input.stdin === undefined ? Effect.void : child.writeStdin(input.stdin),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
const result = yield* processRunner
|
||||
.run({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
|
||||
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
|
||||
...(input.env !== undefined ? { env: input.env } : {}),
|
||||
timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
|
||||
timeoutBehavior: "error",
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
Match.valueTags({
|
||||
ProcessSpawnError: (error) =>
|
||||
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
|
||||
ProcessOutputLimitError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
|
||||
ProcessTimeoutError: (error) =>
|
||||
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
|
||||
ProcessStdinError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
|
||||
ProcessReadError: (error) =>
|
||||
VcsOutputDecodeError.fromProcessReadError(baseError, error),
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
exitCode,
|
||||
detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
if (result.code === null) {
|
||||
return yield* VcsOutputDecodeError.missingExitCode(baseError);
|
||||
}
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies VcsProcessOutput;
|
||||
});
|
||||
if (!input.allowNonZeroExit && result.code !== 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
exitCode: result.code,
|
||||
detail: result.stderr.trim() || `${label} exited with code ${result.code}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return yield* runProcess.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new VcsProcessTimeoutError({
|
||||
operation: input.operation,
|
||||
command: label,
|
||||
cwd: input.cwd,
|
||||
timeoutMs,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
exitCode: result.code,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
} satisfies VcsProcessOutput;
|
||||
});
|
||||
|
||||
return VcsProcess.of({ withProcess, run });
|
||||
return VcsProcess.of({ run });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(VcsProcess, make());
|
||||
export const layer = Layer.effect(VcsProcess, make()).pipe(Layer.provide(ProcessRunnerLive));
|
||||
@@ -1,6 +1,7 @@
|
||||
import { assert, it, describe } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -11,6 +12,7 @@ import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type {
|
||||
BackgroundScope,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
@@ -18,8 +20,11 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const baseLocalStatus: VcsStatusLocalResult = {
|
||||
isRepo: true,
|
||||
sourceControlProvider: {
|
||||
@@ -56,6 +61,7 @@ function makeTestLayer(state: {
|
||||
}) {
|
||||
return VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
@@ -81,6 +87,37 @@ function makeTestLayer(state: {
|
||||
);
|
||||
}
|
||||
|
||||
function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
|
||||
return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: false,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
}
|
||||
|
||||
describe("VcsStatusBroadcaster", () => {
|
||||
it.effect("reuses the cached VCS status across repeated reads", () => {
|
||||
const state = {
|
||||
@@ -196,6 +233,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
@@ -310,6 +348,57 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("does not start automatic remote refreshes without foreground client demand", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => false)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localStatusCalls += 1;
|
||||
return state.currentLocalStatus;
|
||||
}),
|
||||
remoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteStatusCalls += 1;
|
||||
return state.currentRemoteStatus;
|
||||
}),
|
||||
invalidateLocalStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.localInvalidationCalls += 1;
|
||||
}),
|
||||
invalidateRemoteStatus: () =>
|
||||
Effect.sync(() => {
|
||||
state.remoteInvalidationCalls += 1;
|
||||
}),
|
||||
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const snapshot = yield* Stream.runHead(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isSome(snapshot));
|
||||
assert.equal(state.remoteStatusCalls, 0);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
@@ -323,6 +412,7 @@ describe("VcsStatusBroadcaster", () => {
|
||||
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
|
||||
|
||||
const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
|
||||
@@ -81,6 +82,7 @@ export const layer = Layer.effect(
|
||||
VcsStatusBroadcaster,
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<VcsStatusChange>(),
|
||||
@@ -247,9 +249,18 @@ export const layer = Layer.effect(
|
||||
detail: error.message,
|
||||
});
|
||||
const refreshRemoteStatusIfEnabled = automaticRemoteRefreshInterval.pipe(
|
||||
Effect.flatMap((interval) =>
|
||||
Duration.isZero(interval) ? Effect.void : refreshRemoteStatus(cwd).pipe(Effect.asVoid),
|
||||
),
|
||||
Effect.flatMap((interval) => {
|
||||
if (Duration.isZero(interval)) {
|
||||
return Effect.void;
|
||||
}
|
||||
return backgroundPolicy
|
||||
.shouldRunScopeWork({ type: "vcs-status", cwd })
|
||||
.pipe(
|
||||
Effect.flatMap((shouldRun) =>
|
||||
shouldRun ? refreshRemoteStatus(cwd).pipe(Effect.asVoid) : Effect.void,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const sleepForConfiguredInterval = automaticRemoteRefreshInterval.pipe(
|
||||
Effect.flatMap((interval) =>
|
||||
|
||||
@@ -11,6 +11,10 @@ import * as Option from "effect/Option";
|
||||
import type { VcsDriverKind } from "@t3tools/contracts";
|
||||
import * as VcsDriver from "../VcsDriver.ts";
|
||||
|
||||
function normalizePathForComparison(value: string): string {
|
||||
return value.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
export interface VcsDriverFixture<R, E> {
|
||||
readonly createRepo: (cwd: string) => Effect.Effect<void, E, R>;
|
||||
readonly writeFile: (
|
||||
@@ -67,7 +71,11 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
|
||||
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
|
||||
const identity = yield* driver.detectRepository(cwd);
|
||||
assert.equal(identity?.kind, input.kind);
|
||||
assert.isTrue(identity?.rootPath.endsWith(cwd));
|
||||
assert.isTrue(
|
||||
normalizePathForComparison(identity?.rootPath ?? "").endsWith(
|
||||
normalizePathForComparison(cwd),
|
||||
),
|
||||
);
|
||||
assert.equal(identity?.freshness.source, "live-local");
|
||||
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
|
||||
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
|
||||
|
||||
+40
-5
@@ -28,11 +28,13 @@ import {
|
||||
ProjectWriteFileError,
|
||||
OrchestrationReplayEventsError,
|
||||
FilesystemBrowseError,
|
||||
RpcClientId,
|
||||
ThreadId,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { clamp } from "effect/Number";
|
||||
import { HttpRouter, HttpServerRequest } from "effect/unstable/http";
|
||||
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
@@ -40,7 +42,7 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { Keybindings } from "./keybindings.ts";
|
||||
import { Open, resolveAvailableEditors } from "./open.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -65,6 +67,7 @@ import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptR
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
@@ -163,7 +166,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings;
|
||||
const open = yield* Open;
|
||||
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
@@ -180,9 +183,12 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
|
||||
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.automaticGitFetchInterval),
|
||||
Effect.map(
|
||||
(settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
|
||||
detail: cause.message,
|
||||
@@ -583,7 +589,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors: resolveAvailableEditors(),
|
||||
availableEditors: ExternalLauncher.resolveAvailableEditors(),
|
||||
observability: {
|
||||
logsDirectoryPath: config.logsDir,
|
||||
localTracingEnabled: true,
|
||||
@@ -913,6 +919,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverReportClientActivity]: (input, metadata) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverReportClientActivity,
|
||||
backgroundPolicy.reportClientActivity(
|
||||
currentSessionId,
|
||||
RpcClientId.make(metadata.client.id),
|
||||
input,
|
||||
),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverReportHostPowerState]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverReportHostPowerState,
|
||||
backgroundPolicy.reportHostPowerState(input),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverGetBackgroundPolicy]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
@@ -970,7 +996,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.filesystemBrowse]: (input) =>
|
||||
@@ -1225,6 +1251,15 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "auth" },
|
||||
),
|
||||
[WS_METHODS.subscribeBackgroundPolicy]: (_input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeBackgroundPolicy,
|
||||
Stream.concat(
|
||||
Stream.unwrap(Effect.map(backgroundPolicy.snapshot, Stream.make)),
|
||||
backgroundPolicy.streamChanges,
|
||||
),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -42,6 +42,8 @@ describe("branding", () => {
|
||||
|
||||
expect(branding.HOSTED_APP_CHANNEL).toBe("nightly");
|
||||
expect(branding.HOSTED_APP_CHANNEL_LABEL).toBe("Nightly");
|
||||
expect(branding.APP_STAGE_LABEL).toBe("Nightly");
|
||||
expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)");
|
||||
});
|
||||
|
||||
it("ignores unknown hosted app channels", async () => {
|
||||
|
||||
@@ -11,13 +11,15 @@ function readInjectedDesktopAppBranding(): DesktopAppBranding | null {
|
||||
const injectedDesktopAppBranding = readInjectedDesktopAppBranding();
|
||||
const hostedAppChannel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
|
||||
|
||||
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
|
||||
export const APP_STAGE_LABEL =
|
||||
injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Alpha");
|
||||
export const APP_DISPLAY_NAME =
|
||||
injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
|
||||
export const HOSTED_APP_CHANNEL =
|
||||
hostedAppChannel === "latest" || hostedAppChannel === "nightly" ? hostedAppChannel : null;
|
||||
export const HOSTED_APP_CHANNEL_LABEL =
|
||||
HOSTED_APP_CHANNEL === "nightly" ? "Nightly" : HOSTED_APP_CHANNEL === "latest" ? "Latest" : null;
|
||||
export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code";
|
||||
export const APP_STAGE_LABEL =
|
||||
injectedDesktopAppBranding?.stageLabel ??
|
||||
HOSTED_APP_CHANNEL_LABEL ??
|
||||
(import.meta.env.DEV ? "Dev" : "Alpha");
|
||||
export const APP_DISPLAY_NAME =
|
||||
injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;
|
||||
export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
|
||||
@@ -119,7 +119,10 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import {
|
||||
reconnectSavedEnvironment,
|
||||
useSavedEnvironmentRegistryStore,
|
||||
@@ -942,10 +945,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
},
|
||||
[],
|
||||
);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
|
||||
const logicalProjectEnvironments = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
|
||||
@@ -1434,7 +1434,6 @@ export default function GitActionsControl({
|
||||
description: result.toast.description,
|
||||
timeout: 0,
|
||||
actionProps: toastActionProps,
|
||||
actionVariant: "outline",
|
||||
data: successToastData,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -183,6 +183,7 @@ import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupingOverrideKey,
|
||||
getProjectOrderKey,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
@@ -940,10 +941,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const defaultThreadEnvMode = useSettings<ThreadEnvMode>(
|
||||
(settings) => settings.defaultThreadEnvMode,
|
||||
);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const sidebarThreadPreviewCount = useSettings<SidebarThreadPreviewCount>(
|
||||
(settings) => settings.sidebarThreadPreviewCount,
|
||||
@@ -2800,10 +2798,7 @@ export default function Sidebar() {
|
||||
const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
|
||||
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
|
||||
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
|
||||
const sidebarThreadPreviewCount = useSettings((s) => s.sidebarThreadPreviewCount);
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const { handleNewThread } = useNewThreadHandler();
|
||||
|
||||
@@ -268,6 +268,59 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
|
||||
});
|
||||
|
||||
it("marks only the active assistant turn as streaming for copy controls", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "assistant-one-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-one" as never,
|
||||
role: "assistant",
|
||||
text: "Earlier response.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
completedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-two-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-two" as never,
|
||||
role: "assistant",
|
||||
text: "Active response.",
|
||||
turnId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: "assistant-two-entry",
|
||||
completionSummary: "done",
|
||||
isWorking: false,
|
||||
activeTurnInProgress: true,
|
||||
activeTurnId: "turn-2" as never,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRows = rows.filter(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(assistantRows[0]?.assistantCopyStreaming).toBe(false);
|
||||
expect(assistantRows[0]?.completionSummary).toBeNull();
|
||||
expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
|
||||
expect(assistantRows[1]?.completionSummary).toBe("done");
|
||||
});
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
|
||||
@@ -26,7 +26,9 @@ export type MessagesTimelineRow =
|
||||
message: ChatMessage;
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
completionSummary: string | null;
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantCopyStreaming: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
@@ -111,7 +113,10 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary?: string | null;
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress?: boolean;
|
||||
activeTurnId?: TurnId | null;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
|
||||
@@ -157,6 +162,16 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const assistantTurnStillInProgress =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.activeTurnInProgress === true &&
|
||||
input.activeTurnId != null &&
|
||||
timelineEntry.message.turnId === input.activeTurnId;
|
||||
|
||||
const showCompletionDivider =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id;
|
||||
|
||||
nextRows.push({
|
||||
kind: "message",
|
||||
id: timelineEntry.id,
|
||||
@@ -164,12 +179,12 @@ export function deriveMessagesTimelineRows(input: {
|
||||
message: timelineEntry.message,
|
||||
durationStart:
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
|
||||
showCompletionDivider:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id,
|
||||
showCompletionDivider,
|
||||
completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null,
|
||||
showAssistantCopyButton:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id),
|
||||
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
|
||||
assistantTurnDiffSummary:
|
||||
timelineEntry.message.role === "assistant"
|
||||
? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
|
||||
@@ -232,7 +247,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
a.message === bm.message &&
|
||||
a.durationStart === bm.durationStart &&
|
||||
a.showCompletionDivider === bm.showCompletionDivider &&
|
||||
a.completionSummary === bm.completionSummary &&
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
a.revertTurnCount === bm.revertTurnCount
|
||||
);
|
||||
|
||||
@@ -89,11 +89,8 @@ interface TimelineRowSharedState {
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnId: TurnId | null;
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
completionSummary: string | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
@@ -164,7 +161,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
revertTurnCountByUserMessageId,
|
||||
@@ -172,7 +172,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnId,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
revertTurnCountByUserMessageId,
|
||||
@@ -233,13 +236,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
);
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
() => ({
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
completionSummary,
|
||||
}),
|
||||
[activeTurnInProgress, activeTurnId, completionSummary, isRevertingCheckpoint, isWorking],
|
||||
[isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -412,7 +412,9 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
|
||||
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && <AssistantCompletionDivider />}
|
||||
{row.showCompletionDivider && (
|
||||
<AssistantCompletionDivider completionSummary={row.completionSummary} />
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
@@ -449,14 +451,12 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantCompletionDivider() {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
function AssistantCompletionDivider({ completionSummary }: { completionSummary: string | null }) {
|
||||
return (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{activity.completionSummary ? `Response • ${activity.completionSummary}` : "Response"}
|
||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
@@ -464,15 +464,10 @@ function AssistantCompletionDivider() {
|
||||
}
|
||||
|
||||
function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const assistantTurnStillInProgress =
|
||||
activity.activeTurnInProgress &&
|
||||
activity.activeTurnId !== null &&
|
||||
row.message.turnId === activity.activeTurnId;
|
||||
const assistantCopyState = resolveAssistantMessageCopyState({
|
||||
text: row.message.text ?? null,
|
||||
showCopyButton: row.showAssistantCopyButton,
|
||||
streaming: row.message.streaming || assistantTurnStillInProgress,
|
||||
streaming: row.assistantCopyStreaming,
|
||||
});
|
||||
|
||||
if (!assistantCopyState.visible) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type SourceControlDiscoveryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Option from "effect/Option";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -743,6 +744,41 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows advanced background activity controls when background intervals are customized", async () => {
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mounted = await renderWithTestRouter(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("Advanced", { exact: true })).toBeInTheDocument();
|
||||
|
||||
await page.getByRole("button", { name: "Configure advanced background activity" }).click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Background Activity" });
|
||||
await expect.element(dialog).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Shared policy")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Git fetch interval")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Provider health interval")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Host power monitor")).toBeInTheDocument();
|
||||
await expect.element(dialog.getByText("Idle host monitor")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates and shows a pairing link when network access is enabled", async () => {
|
||||
window.desktopBridge = createDesktopBridgeStub({
|
||||
serverExposureState: {
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArchiveX,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SettingsIcon,
|
||||
} from "lucide-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
type BackgroundActivityProfile,
|
||||
type BackgroundActivitySettings,
|
||||
type DesktopUpdateChannel,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
ProviderDriverKind,
|
||||
@@ -13,6 +22,11 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -49,7 +63,23 @@ import { selectProjectsAcrossEnvironments, useStore } from "../../store";
|
||||
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
|
||||
import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldGroup,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from "../ui/number-field";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
@@ -75,6 +105,12 @@ import {
|
||||
SettingsSection,
|
||||
useRelativeTimeTick,
|
||||
} from "./settingsLayout";
|
||||
import {
|
||||
BackgroundPolicyTooltip as PolicyTooltip,
|
||||
backgroundActivityOverrideSettings,
|
||||
durationToSeconds,
|
||||
normalizeIntervalSeconds,
|
||||
} from "./backgroundActivityUtils";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import { useServerObservability, useServerProviders } from "../../rpc/serverState";
|
||||
|
||||
@@ -99,7 +135,68 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, string> = {
|
||||
balanced: "Balanced",
|
||||
performance: "Performance",
|
||||
"battery-saver": "Battery saver",
|
||||
};
|
||||
|
||||
type BackgroundActivityProfileOption = BackgroundActivityProfile | "advanced";
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS: Record<BackgroundActivityProfileOption, string> = {
|
||||
...BACKGROUND_ACTIVITY_PROFILE_LABELS,
|
||||
advanced: "Advanced",
|
||||
};
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS: Record<BackgroundActivityProfile, string> = {
|
||||
balanced:
|
||||
"Pauses background probes when clients are idle, the host is locked, or low power mode is active.",
|
||||
performance: "Allows scoped background probes while any subscribed client remains connected.",
|
||||
"battery-saver": "Also pauses background probes when the host or client is on battery.",
|
||||
};
|
||||
|
||||
const ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION =
|
||||
"Uses custom background intervals with the selected shared power policy.";
|
||||
|
||||
const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
|
||||
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES: ReadonlyArray<{
|
||||
readonly key:
|
||||
| "pauseWhenHostLocked"
|
||||
| "pauseWhenHostLowPower"
|
||||
| "pauseWhenClientLowPower"
|
||||
| "pauseWhenOnBattery";
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ key: "pauseWhenHostLocked", label: "Pause when host is locked" },
|
||||
{ key: "pauseWhenHostLowPower", label: "Pause on host low power" },
|
||||
{ key: "pauseWhenClientLowPower", label: "Pause on client low power" },
|
||||
{ key: "pauseWhenOnBattery", label: "Pause on battery" },
|
||||
];
|
||||
|
||||
function resolveBackgroundActivityProfileOption(settings: {
|
||||
readonly backgroundActivity: BackgroundActivitySettings;
|
||||
}): BackgroundActivityProfileOption {
|
||||
return settings.backgroundActivity.profile === "custom"
|
||||
? "advanced"
|
||||
: settings.backgroundActivity.profile;
|
||||
}
|
||||
|
||||
function resetBackgroundActivitySettings() {
|
||||
return {
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
};
|
||||
}
|
||||
|
||||
function backgroundActivityProfileSettings(profile: BackgroundActivityProfile) {
|
||||
return {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1 as const,
|
||||
profile,
|
||||
overrides: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function withoutProviderInstanceKey<V>(
|
||||
record: Readonly<Record<ProviderInstanceId, V>> | undefined,
|
||||
@@ -408,9 +505,8 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
|
||||
? ["Assistant output"]
|
||||
: []),
|
||||
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
|
||||
? ["Automatic Git fetch interval"]
|
||||
...(!Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity)
|
||||
? ["Background activity"]
|
||||
: []),
|
||||
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
|
||||
? ["New thread mode"]
|
||||
@@ -435,7 +531,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.backgroundActivity,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
@@ -461,7 +557,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
@@ -477,10 +573,255 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
};
|
||||
}
|
||||
|
||||
function BackgroundActivityAdvancedDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
readonly open: boolean;
|
||||
readonly onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const activeProfile = getBackgroundActivityBaseProfile(settings.backgroundActivity);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
);
|
||||
const providerHealthRefreshIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.providerHealthRefreshInterval,
|
||||
);
|
||||
const hostPowerMonitorActiveIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.hostPowerMonitorActiveInterval,
|
||||
);
|
||||
const hostPowerMonitorIdleIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.hostPowerMonitorIdleInterval,
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Background Activity</DialogTitle>
|
||||
<DialogDescription>
|
||||
Tune the shared power policy and the background intervals that feed it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-0 px-6 pb-5">
|
||||
<div className="overflow-hidden rounded-xl border bg-card text-card-foreground">
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Shared policy</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Controls whether background work may run after a subscribed interval fires.
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={activeProfile}
|
||||
onValueChange={(value) => {
|
||||
if (
|
||||
value === "balanced" ||
|
||||
value === "performance" ||
|
||||
value === "battery-saver"
|
||||
) {
|
||||
updateSettings(backgroundActivityProfileSettings(value));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Shared background policy">
|
||||
<SelectValue>{BACKGROUND_ACTIVITY_PROFILE_LABELS[activeProfile]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="balanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="performance">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="battery-saver">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Git fetch interval</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh remote branch status in the background.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={automaticGitFetchIntervalSeconds}
|
||||
min={0}
|
||||
step={5}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease Git fetch interval" />
|
||||
<NumberFieldInput aria-label="Git fetch interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase Git fetch interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Provider health interval</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Refresh provider availability, versions, auth state, and model metadata.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={providerHealthRefreshIntervalSeconds}
|
||||
min={0}
|
||||
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease provider health interval" />
|
||||
<NumberFieldInput aria-label="Provider health interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase provider health interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Host power monitor</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Poll host power state while clients are active.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={hostPowerMonitorActiveIntervalSeconds}
|
||||
min={5}
|
||||
step={5}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
hostPowerMonitorActiveInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease active host power interval" />
|
||||
<NumberFieldInput aria-label="Active host power interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase active host power interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="text-sm font-medium">Idle host monitor</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
Poll host power state when no foreground client is active.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={hostPowerMonitorIdleIntervalSeconds}
|
||||
min={5}
|
||||
step={30}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
hostPowerMonitorIdleInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease idle host power interval" />
|
||||
<NumberFieldInput aria-label="Idle host power interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase idle host power interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-0 border-t sm:grid-cols-2">
|
||||
{BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES.map(({ key, label }) => (
|
||||
<label
|
||||
key={key}
|
||||
className="flex items-center justify-between gap-3 border-b px-4 py-3 last:border-b-0 sm:border-r sm:even:border-r-0"
|
||||
>
|
||||
<span className="text-sm font-medium">{label}</span>
|
||||
<Switch
|
||||
checked={resolvedBackgroundActivity[key]}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
[key]: Boolean(checked),
|
||||
}),
|
||||
)
|
||||
}
|
||||
aria-label={label}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => updateSettings(resetBackgroundActivitySettings())}
|
||||
>
|
||||
Reset all
|
||||
</Button>
|
||||
<Button onClick={() => onOpenChange(false)}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
|
||||
const observability = useServerObservability();
|
||||
const serverProviders = useServerProviders();
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
@@ -513,6 +854,21 @@ export function GeneralSettingsPanel() {
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const activeBackgroundActivityProfile = getBackgroundActivityBaseProfile(
|
||||
settings.backgroundActivity,
|
||||
);
|
||||
const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
|
||||
const backgroundActivityDescription =
|
||||
backgroundActivityProfileOption === "advanced"
|
||||
? `${ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION} Current shared policy: ${
|
||||
BACKGROUND_ACTIVITY_PROFILE_LABELS[activeBackgroundActivityProfile]
|
||||
}.`
|
||||
: BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS[resolvedBackgroundActivity.profile];
|
||||
const canResetBackgroundActivity = !Equal.equals(
|
||||
settings.backgroundActivity,
|
||||
DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
@@ -669,6 +1025,88 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
Background activity
|
||||
<PolicyTooltip>
|
||||
This shared policy gates background work such as Git refreshes and provider health
|
||||
probes after their individual intervals elapse.
|
||||
</PolicyTooltip>
|
||||
</span>
|
||||
}
|
||||
description={backgroundActivityDescription}
|
||||
resetAction={
|
||||
canResetBackgroundActivity ? (
|
||||
<SettingResetButton
|
||||
label="background activity"
|
||||
onClick={() => updateSettings(resetBackgroundActivitySettings())}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<>
|
||||
<Select
|
||||
value={backgroundActivityProfileOption}
|
||||
onValueChange={(value) => {
|
||||
if (value === "advanced") {
|
||||
setBackgroundActivityDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
value === "balanced" ||
|
||||
value === "performance" ||
|
||||
value === "battery-saver"
|
||||
) {
|
||||
updateSettings(backgroundActivityProfileSettings(value));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Background activity profile">
|
||||
<SelectValue>
|
||||
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[backgroundActivityProfileOption]}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="balanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="performance">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="battery-saver">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="advanced">
|
||||
{BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced}
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
{backgroundActivityProfileOption === "advanced" ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
aria-label="Configure advanced background activity"
|
||||
onClick={() => setBackgroundActivityDialogOpen(true)}
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Configure background activity</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<BackgroundActivityAdvancedDialog
|
||||
open={backgroundActivityDialogOpen}
|
||||
onOpenChange={setBackgroundActivityDialogOpen}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Auto-open task panel"
|
||||
description="Open the right-side plan and task panel automatically when steps appear."
|
||||
@@ -892,7 +1330,7 @@ export function GeneralSettingsPanel() {
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="About">
|
||||
{isElectron ? (
|
||||
{isElectron || HOSTED_APP_CHANNEL ? (
|
||||
<AboutVersionSection />
|
||||
) : (
|
||||
<SettingsRow
|
||||
@@ -944,6 +1382,14 @@ export function ProviderSettingsPanel() {
|
||||
);
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const providerHealthPreset = getBackgroundActivityPresetSettings(
|
||||
getBackgroundActivityBaseProfile(settings.backgroundActivity),
|
||||
).providerHealthRefreshInterval;
|
||||
const providerHealthRefreshIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.providerHealthRefreshInterval,
|
||||
);
|
||||
const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
@@ -1223,6 +1669,61 @@ export function ProviderSettingsPanel() {
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<SettingsRow
|
||||
title={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
Health check interval
|
||||
<PolicyTooltip>
|
||||
This interval is configured here, then the shared Background activity policy decides
|
||||
whether provider probes may run when the timer fires. Custom intervals appear as
|
||||
Advanced in General settings.
|
||||
</PolicyTooltip>
|
||||
</span>
|
||||
}
|
||||
description="Refresh provider availability, versions, auth state, and model metadata in the background. Set this to 0 seconds to rely on manual refreshes."
|
||||
resetAction={
|
||||
providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
|
||||
<SettingResetButton
|
||||
label="provider health check interval"
|
||||
onClick={() =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: undefined,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<NumberField
|
||||
value={providerHealthRefreshIntervalSeconds}
|
||||
min={0}
|
||||
step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
providerHealthRefreshInterval: Duration.seconds(
|
||||
normalizeIntervalSeconds(value),
|
||||
),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldDecrement aria-label="Decrease provider health check interval" />
|
||||
<NumberFieldInput aria-label="Provider health check interval in seconds" />
|
||||
<NumberFieldIncrement aria-label="Increase provider health check interval" />
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
<span className="text-xs text-muted-foreground">seconds</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{rows.map((row) => {
|
||||
const driverOption = getDriverOption(row.driver);
|
||||
const liveProvider = serverProviders.find(
|
||||
|
||||
@@ -10,7 +10,11 @@ import type {
|
||||
VcsDriverKind,
|
||||
VcsDiscoveryItem,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
|
||||
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
@@ -50,6 +54,12 @@ import {
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
import {
|
||||
BackgroundPolicyTooltip,
|
||||
backgroundActivityOverrideSettings,
|
||||
durationToSeconds,
|
||||
normalizeIntervalSeconds as normalizeFetchIntervalSeconds,
|
||||
} from "./backgroundActivityUtils";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
versionControlSystems: [],
|
||||
@@ -71,17 +81,6 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
|
||||
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
|
||||
|
||||
function durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
}
|
||||
|
||||
function normalizeFetchIntervalSeconds(value: number | null): number {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
function optionLabel(value: Option.Option<string>): string | null {
|
||||
return Option.getOrNull(value);
|
||||
}
|
||||
@@ -291,11 +290,16 @@ function DiscoveryItemRow({
|
||||
}
|
||||
|
||||
function GitFetchIntervalSettings() {
|
||||
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
);
|
||||
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
getBackgroundActivityPresetSettings(
|
||||
getBackgroundActivityBaseProfile(settings.backgroundActivity),
|
||||
).automaticGitFetchInterval,
|
||||
);
|
||||
const canResetFetchInterval =
|
||||
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
|
||||
@@ -306,6 +310,11 @@ function GitFetchIntervalSettings() {
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
<span className="text-xs font-medium text-foreground">Fetch interval</span>
|
||||
<BackgroundPolicyTooltip>
|
||||
This interval is configured for Git only. The shared Background activity policy still
|
||||
decides whether Git refreshes may run when the timer fires. Custom intervals appear as
|
||||
Advanced in General settings.
|
||||
</BackgroundPolicyTooltip>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 items-center justify-center transition-opacity",
|
||||
@@ -317,9 +326,11 @@ function GitFetchIntervalSettings() {
|
||||
<SettingResetButton
|
||||
label="fetch interval"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
})
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: undefined,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
@@ -338,9 +349,11 @@ function GitFetchIntervalSettings() {
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
})
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import * as Duration from "effect/Duration";
|
||||
import type { BackgroundActivitySettings } from "@t3tools/contracts";
|
||||
import { getBackgroundActivityBaseProfile } from "@t3tools/shared/backgroundActivitySettings";
|
||||
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
export type BackgroundActivityOverridePatch = Partial<{
|
||||
[K in keyof BackgroundActivitySettings["overrides"]]:
|
||||
| BackgroundActivitySettings["overrides"][K]
|
||||
| undefined;
|
||||
}>;
|
||||
|
||||
export function durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
}
|
||||
|
||||
export function normalizeIntervalSeconds(value: number | null): number {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
export function backgroundActivityOverrideSettings(
|
||||
current: BackgroundActivitySettings,
|
||||
overrides: BackgroundActivityOverridePatch,
|
||||
) {
|
||||
const nextOverrides: BackgroundActivityOverridePatch = {
|
||||
...current.overrides,
|
||||
...overrides,
|
||||
};
|
||||
for (const [key, value] of Object.entries(nextOverrides)) {
|
||||
if (value === undefined) {
|
||||
delete nextOverrides[key as keyof typeof nextOverrides];
|
||||
}
|
||||
}
|
||||
return {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1 as const,
|
||||
profile: "custom" as const,
|
||||
baseProfile: getBackgroundActivityBaseProfile(current),
|
||||
overrides: nextOverrides as BackgroundActivitySettings["overrides"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function BackgroundPolicyTooltip({ children }: { readonly children: string }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground"
|
||||
aria-label="Background policy details"
|
||||
>
|
||||
<InfoIcon className="size-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-72">
|
||||
{children}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -73,6 +73,7 @@ import {
|
||||
derivePhysicalProjectKey,
|
||||
} from "../../logicalProject";
|
||||
import { getClientSettings } from "~/hooks/useSettings";
|
||||
import { startBackgroundActivityReporter } from "~/lib/backgroundActivityReporter";
|
||||
|
||||
type EnvironmentServiceState = {
|
||||
readonly queryClient: QueryClient;
|
||||
@@ -1783,6 +1784,10 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
.catch(() => undefined);
|
||||
|
||||
const unsubscribeBrowserResumeReconnects = subscribeBrowserResumeReconnects();
|
||||
const stopBackgroundActivityReporter = startBackgroundActivityReporter({
|
||||
getConnections: listEnvironmentConnections,
|
||||
subscribeConnections: subscribeEnvironmentConnections,
|
||||
});
|
||||
|
||||
activeService = {
|
||||
queryClient,
|
||||
@@ -1791,6 +1796,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
stop: () => {
|
||||
unsubscribeSavedEnvironments();
|
||||
unsubscribeBrowserResumeReconnects();
|
||||
stopBackgroundActivityReporter();
|
||||
queryInvalidationThrottler.cancel();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createServerSettingsWriteQueue } from "./serverSettingsWriteQueue";
|
||||
|
||||
describe("serverSettingsWriteQueue", () => {
|
||||
it("serializes server settings writes so later calls cannot be overtaken", async () => {
|
||||
const applied: Array<number> = [];
|
||||
const updateSettings = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(async () => ({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
automaticGitFetchInterval: Duration.seconds(10),
|
||||
}))
|
||||
.mockImplementationOnce(async () => ({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
automaticGitFetchInterval: Duration.seconds(25),
|
||||
}));
|
||||
const queue = createServerSettingsWriteQueue({
|
||||
updateSettings,
|
||||
applySettings: (settings) => {
|
||||
applied.push(Duration.toMillis(settings.automaticGitFetchInterval));
|
||||
},
|
||||
onError: vi.fn(),
|
||||
});
|
||||
|
||||
queue.enqueue({ automaticGitFetchInterval: Duration.seconds(10) });
|
||||
queue.enqueue({ automaticGitFetchInterval: Duration.seconds(25) });
|
||||
await queue.drain();
|
||||
|
||||
expect(updateSettings).toHaveBeenNthCalledWith(1, {
|
||||
automaticGitFetchInterval: Duration.seconds(10),
|
||||
});
|
||||
expect(updateSettings).toHaveBeenNthCalledWith(2, {
|
||||
automaticGitFetchInterval: Duration.seconds(25),
|
||||
});
|
||||
expect(applied).toEqual([10_000, 25_000]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
|
||||
|
||||
export interface ServerSettingsWriteQueue {
|
||||
readonly enqueue: (patch: ServerSettingsPatch) => void;
|
||||
readonly reset: () => void;
|
||||
readonly drain: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function createServerSettingsWriteQueue(input: {
|
||||
readonly updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||
readonly applySettings: (settings: ServerSettings) => void;
|
||||
readonly onError: (error: unknown) => void;
|
||||
}): ServerSettingsWriteQueue {
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
|
||||
return {
|
||||
enqueue: (patch) => {
|
||||
queue = queue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
const settings = await input.updateSettings(patch);
|
||||
input.applySettings(settings);
|
||||
})
|
||||
.catch(input.onError);
|
||||
},
|
||||
reset: () => {
|
||||
queue = Promise.resolve();
|
||||
},
|
||||
drain: () => queue,
|
||||
};
|
||||
}
|
||||
@@ -10,7 +10,11 @@ import {
|
||||
} from "../composerDraftStore";
|
||||
import { newDraftId, newThreadId } from "../lib/utils";
|
||||
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
|
||||
import { deriveLogicalProjectKeyFromSettings, getProjectOrderKey } from "../logicalProject";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
getProjectOrderKey,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { selectProjectsAcrossEnvironments, useStore } from "../store";
|
||||
import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { resolveThreadRouteTarget } from "../threadRoutes";
|
||||
@@ -19,10 +23,7 @@ import { useSettings } from "./useSettings";
|
||||
|
||||
function useNewThreadState() {
|
||||
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
|
||||
const router = useRouter();
|
||||
const getCurrentRouteTarget = useCallback(() => {
|
||||
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ensureLocalApi } from "~/localApi";
|
||||
import * as Struct from "effect/Struct";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
|
||||
import { createServerSettingsWriteQueue } from "./serverSettingsWriteQueue";
|
||||
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
@@ -30,6 +31,13 @@ const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
let clientSettingsHydrated = false;
|
||||
let clientSettingsHydrationPromise: Promise<void> | null = null;
|
||||
const serverSettingsWriteQueue = createServerSettingsWriteQueue({
|
||||
updateSettings: (patch) => ensureLocalApi().server.updateSettings(patch),
|
||||
applySettings: applySettingsUpdated,
|
||||
onError: (error) => {
|
||||
console.error("[SERVER_SETTINGS] update failed", error);
|
||||
},
|
||||
});
|
||||
|
||||
function emitClientSettingsChange() {
|
||||
for (const listener of clientSettingsListeners) {
|
||||
@@ -143,6 +151,10 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
};
|
||||
}
|
||||
|
||||
function enqueueServerSettingsUpdate(serverPatch: ServerSettingsPatch): void {
|
||||
serverSettingsWriteQueue.enqueue(serverPatch);
|
||||
}
|
||||
|
||||
// ── Hooks ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -201,8 +213,7 @@ export function useUpdateSettings() {
|
||||
if (currentServerConfig) {
|
||||
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
|
||||
}
|
||||
// Fire-and-forget RPC — push will reconcile on success
|
||||
void ensureLocalApi().server.updateSettings(serverPatch);
|
||||
enqueueServerSettingsUpdate(serverPatch);
|
||||
}
|
||||
|
||||
if (Object.keys(clientPatch).length > 0) {
|
||||
@@ -227,6 +238,7 @@ export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationPromise = null;
|
||||
serverSettingsWriteQueue.reset();
|
||||
clientSettingsListeners.clear();
|
||||
clientSettingsHydrationListeners.clear();
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { BackgroundScope, ClientActivityReportInput } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { EnvironmentConnection } from "../environments/runtime/connection";
|
||||
|
||||
const CLIENT_ID_STORAGE_KEY = "t3.backgroundActivity.clientId";
|
||||
const REPORT_INTERVAL_MS = 25_000;
|
||||
const LEASE_TTL_MS = 45_000;
|
||||
const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
|
||||
|
||||
interface RetainedScope {
|
||||
readonly scope: BackgroundScope;
|
||||
refCount: number;
|
||||
}
|
||||
|
||||
interface BackgroundActivityReporterOptions {
|
||||
readonly getConnections: () => ReadonlyArray<EnvironmentConnection>;
|
||||
readonly subscribeConnections: (listener: () => void) => () => void;
|
||||
}
|
||||
|
||||
const retainedScopes = new Map<string, RetainedScope>();
|
||||
const retainedScopeListeners = new Set<() => void>();
|
||||
|
||||
function notifyRetainedScopesChanged(): void {
|
||||
for (const listener of retainedScopeListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function stableScopeKey(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 getClientId(): string {
|
||||
try {
|
||||
const existing = window.localStorage.getItem(CLIENT_ID_STORAGE_KEY);
|
||||
if (existing) return existing;
|
||||
const next = crypto.randomUUID();
|
||||
window.localStorage.setItem(CLIENT_ID_STORAGE_KEY, next);
|
||||
return next;
|
||||
} catch {
|
||||
return "ephemeral-browser-client";
|
||||
}
|
||||
}
|
||||
|
||||
function resolveClientKind(): ClientActivityReportInput["clientKind"] {
|
||||
return window.desktopBridge ? "desktop-renderer" : "web";
|
||||
}
|
||||
|
||||
function createActivityReport(): ClientActivityReportInput {
|
||||
return {
|
||||
clientId: getClientId(),
|
||||
clientKind: resolveClientKind(),
|
||||
visible: document.visibilityState === "visible",
|
||||
focused: document.hasFocus(),
|
||||
recentlyInteracted: document.hasFocus(),
|
||||
appState: document.visibilityState === "visible" ? "active" : "background",
|
||||
scopes: [...BASELINE_SCOPES, ...[...retainedScopes.values()].map((entry) => entry.scope)],
|
||||
ttlMs: LEASE_TTL_MS,
|
||||
observedAt: DateTime.makeUnsafe(new Date().toISOString()),
|
||||
};
|
||||
}
|
||||
|
||||
async function reportToConnections(
|
||||
connections: ReadonlyArray<EnvironmentConnection>,
|
||||
): Promise<void> {
|
||||
if (connections.length === 0) return;
|
||||
const report = createActivityReport();
|
||||
await Promise.allSettled(
|
||||
connections.map((connection) => connection.client.server.reportClientActivity(report)),
|
||||
);
|
||||
}
|
||||
|
||||
export function startBackgroundActivityReporter(
|
||||
options: BackgroundActivityReporterOptions,
|
||||
): () => void {
|
||||
if (
|
||||
typeof window === "undefined" ||
|
||||
typeof document === "undefined" ||
|
||||
typeof window.setInterval !== "function"
|
||||
) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
let reportTimer: number | null = null;
|
||||
|
||||
const report = () => {
|
||||
if (disposed) return;
|
||||
void reportToConnections(options.getConnections());
|
||||
};
|
||||
|
||||
const scheduleReport = () => {
|
||||
if (disposed) return;
|
||||
if (reportTimer !== null) {
|
||||
window.clearTimeout(reportTimer);
|
||||
}
|
||||
reportTimer = window.setTimeout(() => {
|
||||
reportTimer = null;
|
||||
report();
|
||||
}, 250);
|
||||
};
|
||||
|
||||
const interval = window.setInterval(report, REPORT_INTERVAL_MS);
|
||||
const unsubscribeConnections = options.subscribeConnections(scheduleReport);
|
||||
retainedScopeListeners.add(scheduleReport);
|
||||
document.addEventListener("visibilitychange", scheduleReport);
|
||||
window.addEventListener("focus", scheduleReport);
|
||||
window.addEventListener("blur", scheduleReport);
|
||||
window.addEventListener("online", scheduleReport);
|
||||
|
||||
scheduleReport();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (reportTimer !== null) {
|
||||
window.clearTimeout(reportTimer);
|
||||
}
|
||||
window.clearInterval(interval);
|
||||
unsubscribeConnections();
|
||||
retainedScopeListeners.delete(scheduleReport);
|
||||
document.removeEventListener("visibilitychange", scheduleReport);
|
||||
window.removeEventListener("focus", scheduleReport);
|
||||
window.removeEventListener("blur", scheduleReport);
|
||||
window.removeEventListener("online", scheduleReport);
|
||||
};
|
||||
}
|
||||
|
||||
export function retainBackgroundScope(scope: BackgroundScope): () => void {
|
||||
const key = stableScopeKey(scope);
|
||||
const existing = retainedScopes.get(key);
|
||||
if (existing) {
|
||||
existing.refCount += 1;
|
||||
} else {
|
||||
retainedScopes.set(key, { scope, refCount: 1 });
|
||||
notifyRetainedScopesChanged();
|
||||
}
|
||||
|
||||
return () => {
|
||||
const current = retainedScopes.get(key);
|
||||
if (!current) return;
|
||||
current.refCount -= 1;
|
||||
if (current.refCount <= 0) {
|
||||
retainedScopes.delete(key);
|
||||
notifyRetainedScopesChanged();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
subscribeEnvironmentConnections,
|
||||
} from "../environments/runtime";
|
||||
import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
import { retainBackgroundScope } from "./backgroundActivityReporter";
|
||||
|
||||
interface GitStatusState {
|
||||
readonly data: VcsStatusResult | null;
|
||||
@@ -202,6 +203,7 @@ function subscribeToGitStatusTarget(
|
||||
const cwd = target.cwd;
|
||||
let currentClientIdentity: string | null = null;
|
||||
let currentUnsubscribe = NOOP;
|
||||
const releaseScope = retainBackgroundScope({ type: "vcs-status", cwd });
|
||||
|
||||
const syncClientSubscription = () => {
|
||||
const resolved = providedClient
|
||||
@@ -236,6 +238,7 @@ function subscribeToGitStatusTarget(
|
||||
syncClientSubscription();
|
||||
|
||||
return () => {
|
||||
releaseScope();
|
||||
unsubscribeRegistry();
|
||||
currentUnsubscribe();
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
|
||||
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import type { UnifiedSettings } from "@t3tools/contracts/settings";
|
||||
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
|
||||
import type { Project } from "./types";
|
||||
|
||||
@@ -10,6 +11,13 @@ export interface ProjectGroupingSettings {
|
||||
|
||||
export type ProjectGroupingMode = SidebarProjectGroupingMode;
|
||||
|
||||
export function selectProjectGroupingSettings(settings: UnifiedSettings): ProjectGroupingSettings {
|
||||
return {
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
};
|
||||
}
|
||||
|
||||
function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
|
||||
const seen = new Set<string>();
|
||||
const unique: string[] = [];
|
||||
|
||||
@@ -33,6 +33,7 @@ import { useSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
derivePhysicalProjectKeyFromPath,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import {
|
||||
getServerConfigUpdatedNotification,
|
||||
@@ -281,10 +282,7 @@ function EventRouter() {
|
||||
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useSettings(selectProjectGroupingSettings);
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
|
||||
|
||||
@@ -135,9 +135,15 @@ export interface WsRpcClient {
|
||||
typeof WS_METHODS.serverGetProcessDiagnostics
|
||||
>;
|
||||
readonly signalProcess: RpcUnaryMethod<typeof WS_METHODS.serverSignalProcess>;
|
||||
readonly reportClientActivity: RpcUnaryMethod<typeof WS_METHODS.serverReportClientActivity>;
|
||||
readonly reportHostPowerState: RpcUnaryMethod<typeof WS_METHODS.serverReportHostPowerState>;
|
||||
readonly getBackgroundPolicy: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetBackgroundPolicy>;
|
||||
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
|
||||
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
|
||||
readonly subscribeAuthAccess: RpcStreamMethod<typeof WS_METHODS.subscribeAuthAccess>;
|
||||
readonly subscribeBackgroundPolicy: RpcStreamMethod<
|
||||
typeof WS_METHODS.subscribeBackgroundPolicy
|
||||
>;
|
||||
};
|
||||
readonly orchestration: {
|
||||
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
|
||||
@@ -268,6 +274,12 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverSignalProcess](input).pipe(Effect.withTracerEnabled(false)),
|
||||
),
|
||||
reportClientActivity: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverReportClientActivity](input)),
|
||||
reportHostPowerState: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverReportHostPowerState](input)),
|
||||
getBackgroundPolicy: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverGetBackgroundPolicy]({})),
|
||||
subscribeConfig: (listener, options) =>
|
||||
transport.subscribe((client) => client[WS_METHODS.subscribeServerConfig]({}), listener, {
|
||||
...options,
|
||||
@@ -283,6 +295,15 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
|
||||
...options,
|
||||
tag: WS_METHODS.subscribeAuthAccess,
|
||||
}),
|
||||
subscribeBackgroundPolicy: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeBackgroundPolicy]({}),
|
||||
listener,
|
||||
{
|
||||
...options,
|
||||
tag: WS_METHODS.subscribeBackgroundPolicy,
|
||||
},
|
||||
),
|
||||
},
|
||||
orchestration: {
|
||||
dispatchCommand: (input) =>
|
||||
|
||||
+10
-1
@@ -1,9 +1,16 @@
|
||||
import { matchers, routes, type VercelConfig } from "@vercel/config/v1";
|
||||
import { matchers, routes, type Transform, type VercelConfig } from "@vercel/config/v1";
|
||||
|
||||
const ROUTER_HOST = "app.t3.codes";
|
||||
const HOSTED_WEB_CHANNEL_COOKIE = "t3code_web_channel";
|
||||
const LATEST_ORIGIN = "https://latest.app.t3.codes";
|
||||
const NIGHTLY_ORIGIN = "https://nightly.app.t3.codes";
|
||||
const CLEAN_CHANNEL_QUERY_TRANSFORMS = [
|
||||
{
|
||||
type: "request.query",
|
||||
op: "delete",
|
||||
target: { key: "channel" },
|
||||
},
|
||||
] satisfies Transform[];
|
||||
|
||||
function channelCookie(channel: "latest" | "nightly"): string {
|
||||
return [
|
||||
@@ -28,6 +35,7 @@ export const config: VercelConfig = {
|
||||
{
|
||||
src: "/__t3code/channel",
|
||||
has: [matchers.query("channel", "nightly")],
|
||||
transforms: CLEAN_CHANNEL_QUERY_TRANSFORMS,
|
||||
headers: {
|
||||
Location: "/",
|
||||
"Set-Cookie": channelCookie("nightly"),
|
||||
@@ -36,6 +44,7 @@ export const config: VercelConfig = {
|
||||
},
|
||||
{
|
||||
src: "/__t3code/channel",
|
||||
transforms: CLEAN_CHANNEL_QUERY_TRANSFORMS,
|
||||
headers: {
|
||||
Location: "/",
|
||||
"Set-Cookie": channelCookie("latest"),
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
@@ -52,7 +52,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"bin": {
|
||||
"t3": "./dist/bin.mjs",
|
||||
},
|
||||
@@ -65,7 +65,6 @@
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -85,7 +84,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.4.1",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -167,7 +166,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
@@ -1038,8 +1037,6 @@
|
||||
|
||||
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
|
||||
|
||||
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
|
||||
"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
|
||||
|
||||
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
|
||||
@@ -1126,16 +1123,10 @@
|
||||
|
||||
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
|
||||
|
||||
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
|
||||
|
||||
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
|
||||
|
||||
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
|
||||
|
||||
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
|
||||
|
||||
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
|
||||
|
||||
"defu": ["[email protected]", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="],
|
||||
@@ -1664,8 +1655,6 @@
|
||||
|
||||
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
|
||||
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
||||
|
||||
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
|
||||
@@ -1820,8 +1809,6 @@
|
||||
|
||||
"router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
|
||||
|
||||
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
|
||||
|
||||
"safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
|
||||
|
||||
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
|
||||
@@ -2110,8 +2097,6 @@
|
||||
|
||||
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
|
||||
|
||||
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
|
||||
|
||||
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
|
||||
|
||||
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
|
||||
|
||||
+11
-9
@@ -51,7 +51,7 @@ Optional GitHub Actions variables:
|
||||
|
||||
Required Vercel domains:
|
||||
|
||||
- `app.t3.codes`: the stable router domain users open.
|
||||
- `app.t3.codes`: the router domain users open, updated by stable releases.
|
||||
- `latest.app.t3.codes`: channel alias updated by stable releases.
|
||||
- `nightly.app.t3.codes`: channel alias updated by nightly releases.
|
||||
|
||||
@@ -62,11 +62,13 @@ visiting `/__t3code/channel?channel=latest` or
|
||||
the matching channel alias.
|
||||
|
||||
The release deploy job rewrites release package versions before upload so the
|
||||
hosted app's About panel renders the release version. It also passes
|
||||
`VITE_HOSTED_APP_CHANNEL=latest|nightly`, which renders the hosted update track
|
||||
selector in the About panel. Changing the selector navigates through
|
||||
`/__t3code/channel` on the router domain so the user's channel cookie is updated
|
||||
before redirecting to the hosted app root.
|
||||
hosted app's About panel renders the release version. Stable deploys alias the
|
||||
same deployment to both the `latest` channel and the router domain so the router
|
||||
rules stay current. Nightly deploys only alias the `nightly` channel. The job
|
||||
also passes `VITE_HOSTED_APP_CHANNEL=latest|nightly`, which renders the hosted
|
||||
update track selector in the About panel. Changing the selector navigates
|
||||
through `/__t3code/channel` on the router domain so the user's channel cookie is
|
||||
updated before redirecting to the hosted app root.
|
||||
|
||||
One-time Vercel dashboard setup:
|
||||
|
||||
@@ -75,9 +77,9 @@ One-time Vercel dashboard setup:
|
||||
3. Disable automatic Git deployments in the dashboard if desired; the committed
|
||||
`vercel.ts` setting is the source-of-truth, but disconnecting Git in the
|
||||
dashboard is also safe.
|
||||
4. Promote or alias one deployment containing the router rules in `apps/web/vercel.ts` to
|
||||
`app.t3.codes` once. Future release jobs should only update the channel
|
||||
aliases.
|
||||
4. Run one stable release deployment, or manually alias the current stable
|
||||
deployment, so `app.t3.codes` points at a deployment containing the router
|
||||
rules in `apps/web/vercel.ts`. Future stable releases keep this alias current.
|
||||
|
||||
## Nightly builds
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.23",
|
||||
"private": true,
|
||||
"files": [
|
||||
"dist"
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { AuthSessionId, EnvironmentId, RpcClientId, ThreadId } from "./baseSchemas.ts";
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
export const BackgroundBooleanState = Schema.Literals(["true", "false", "unknown"]);
|
||||
export type BackgroundBooleanState = typeof BackgroundBooleanState.Type;
|
||||
|
||||
export const HostPowerThermalState = Schema.Literals([
|
||||
"unknown",
|
||||
"nominal",
|
||||
"fair",
|
||||
"serious",
|
||||
"critical",
|
||||
]);
|
||||
export type HostPowerThermalState = typeof HostPowerThermalState.Type;
|
||||
|
||||
export const HostPowerSource = Schema.Literals([
|
||||
"unknown",
|
||||
"node-macos-shell",
|
||||
"node-macos-native",
|
||||
"node-linux",
|
||||
"node-windows",
|
||||
"electron-main",
|
||||
]);
|
||||
export type HostPowerSource = typeof HostPowerSource.Type;
|
||||
|
||||
export const HostPowerSnapshot = Schema.Struct({
|
||||
source: HostPowerSource,
|
||||
idle: BackgroundBooleanState,
|
||||
idleSeconds: Schema.NullOr(Schema.Number),
|
||||
locked: BackgroundBooleanState,
|
||||
suspended: Schema.Boolean,
|
||||
onBattery: BackgroundBooleanState,
|
||||
lowPowerMode: BackgroundBooleanState,
|
||||
thermalState: HostPowerThermalState,
|
||||
stale: Schema.Boolean,
|
||||
updatedAt: Schema.DateTimeUtc,
|
||||
});
|
||||
export type HostPowerSnapshot = typeof HostPowerSnapshot.Type;
|
||||
|
||||
export const BackgroundScope = Schema.Union([
|
||||
Schema.Struct({ type: Schema.Literal("server-config") }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("provider-status"),
|
||||
instanceId: Schema.optionalKey(ProviderInstanceId),
|
||||
}),
|
||||
Schema.Struct({ type: Schema.Literal("vcs-status"), cwd: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("git-refs"), cwd: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("diagnostics") }),
|
||||
Schema.Struct({ type: Schema.Literal("thread"), threadId: ThreadId }),
|
||||
]);
|
||||
export type BackgroundScope = typeof BackgroundScope.Type;
|
||||
|
||||
export const ClientKind = Schema.Literals(["web", "desktop-renderer", "mobile", "unknown"]);
|
||||
export type ClientKind = typeof ClientKind.Type;
|
||||
|
||||
export const ClientActivityReportInput = Schema.Struct({
|
||||
environmentId: Schema.optionalKey(EnvironmentId),
|
||||
clientId: Schema.String,
|
||||
clientKind: ClientKind,
|
||||
visible: Schema.Boolean,
|
||||
focused: Schema.Boolean,
|
||||
recentlyInteracted: Schema.Boolean,
|
||||
appState: Schema.optionalKey(Schema.Literals(["active", "inactive", "background", "unknown"])),
|
||||
lowPowerMode: Schema.optionalKey(BackgroundBooleanState),
|
||||
batteryState: Schema.optionalKey(Schema.Literals(["unknown", "unplugged", "charging", "full"])),
|
||||
networkType: Schema.optionalKey(Schema.String),
|
||||
scopes: Schema.Array(BackgroundScope),
|
||||
ttlMs: Schema.optionalKey(Schema.Number),
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
});
|
||||
export type ClientActivityReportInput = typeof ClientActivityReportInput.Type;
|
||||
|
||||
export const ClientActivityLease = Schema.Struct({
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
clientId: Schema.String,
|
||||
clientKind: ClientKind,
|
||||
visible: Schema.Boolean,
|
||||
focused: Schema.Boolean,
|
||||
recentlyInteracted: Schema.Boolean,
|
||||
appState: Schema.optionalKey(Schema.Literals(["active", "inactive", "background", "unknown"])),
|
||||
lowPowerMode: Schema.optionalKey(BackgroundBooleanState),
|
||||
batteryState: Schema.optionalKey(Schema.Literals(["unknown", "unplugged", "charging", "full"])),
|
||||
networkType: Schema.optionalKey(Schema.String),
|
||||
scopes: Schema.Array(BackgroundScope),
|
||||
updatedAt: Schema.DateTimeUtc,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
});
|
||||
export type ClientActivityLease = typeof ClientActivityLease.Type;
|
||||
|
||||
export const BackgroundPolicySnapshot = Schema.Struct({
|
||||
hostPower: HostPowerSnapshot,
|
||||
leases: Schema.Array(ClientActivityLease),
|
||||
activeForegroundLeaseCount: Schema.Number,
|
||||
activeScopeKeys: Schema.Array(Schema.String),
|
||||
shouldRunOpportunisticWork: Schema.Boolean,
|
||||
updatedAt: Schema.DateTimeUtc,
|
||||
});
|
||||
export type BackgroundPolicySnapshot = typeof BackgroundPolicySnapshot.Type;
|
||||
@@ -43,6 +43,8 @@ export const TurnId = makeEntityId("TurnId");
|
||||
export type TurnId = typeof TurnId.Type;
|
||||
export const AuthSessionId = makeEntityId("AuthSessionId");
|
||||
export type AuthSessionId = typeof AuthSessionId.Type;
|
||||
export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
|
||||
export type RpcClientId = typeof RpcClientId.Type;
|
||||
|
||||
export const ProviderItemId = makeEntityId("ProviderItemId");
|
||||
export type ProviderItemId = typeof ProviderItemId.Type;
|
||||
|
||||
@@ -44,13 +44,16 @@ export const EDITORS = [
|
||||
export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
|
||||
export type EditorId = typeof EditorId.Type;
|
||||
|
||||
export const OpenInEditorInput = Schema.Struct({
|
||||
export const LaunchEditorInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
editor: EditorId,
|
||||
});
|
||||
export type OpenInEditorInput = typeof OpenInEditorInput.Type;
|
||||
export type LaunchEditorInput = typeof LaunchEditorInput.Type;
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
export class ExternalLauncherError extends Schema.TaggedErrorClass<ExternalLauncherError>()(
|
||||
"ExternalLauncherError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./baseSchemas.ts";
|
||||
export * from "./background.ts";
|
||||
export * from "./auth.ts";
|
||||
export * from "./environment.ts";
|
||||
export * from "./desktopBootstrap.ts";
|
||||
|
||||
@@ -2,8 +2,13 @@ import * as Schema from "effect/Schema";
|
||||
import * as Rpc from "effect/unstable/rpc/Rpc";
|
||||
import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
|
||||
|
||||
import { OpenError, OpenInEditorInput } from "./editor.ts";
|
||||
import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";
|
||||
import { AuthAccessStreamEvent } from "./auth.ts";
|
||||
import {
|
||||
BackgroundPolicySnapshot,
|
||||
ClientActivityReportInput,
|
||||
HostPowerSnapshot,
|
||||
} from "./background.ts";
|
||||
import {
|
||||
FilesystemBrowseInput,
|
||||
FilesystemBrowseResult,
|
||||
@@ -146,6 +151,9 @@ export const WS_METHODS = {
|
||||
serverGetTraceDiagnostics: "server.getTraceDiagnostics",
|
||||
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
|
||||
serverSignalProcess: "server.signalProcess",
|
||||
serverReportClientActivity: "server.reportClientActivity",
|
||||
serverReportHostPowerState: "server.reportHostPowerState",
|
||||
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
|
||||
|
||||
// Source control methods
|
||||
sourceControlLookupRepository: "sourceControl.lookupRepository",
|
||||
@@ -158,6 +166,7 @@ export const WS_METHODS = {
|
||||
subscribeServerConfig: "subscribeServerConfig",
|
||||
subscribeServerLifecycle: "subscribeServerLifecycle",
|
||||
subscribeAuthAccess: "subscribeAuthAccess",
|
||||
subscribeBackgroundPolicy: "subscribeBackgroundPolicy",
|
||||
} as const;
|
||||
|
||||
export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {
|
||||
@@ -229,6 +238,19 @@ export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess,
|
||||
success: ServerSignalProcessResult,
|
||||
});
|
||||
|
||||
export const WsServerReportClientActivityRpc = Rpc.make(WS_METHODS.serverReportClientActivity, {
|
||||
payload: ClientActivityReportInput,
|
||||
});
|
||||
|
||||
export const WsServerReportHostPowerStateRpc = Rpc.make(WS_METHODS.serverReportHostPowerState, {
|
||||
payload: HostPowerSnapshot,
|
||||
});
|
||||
|
||||
export const WsServerGetBackgroundPolicyRpc = Rpc.make(WS_METHODS.serverGetBackgroundPolicy, {
|
||||
payload: Schema.Struct({}),
|
||||
success: BackgroundPolicySnapshot,
|
||||
});
|
||||
|
||||
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
{
|
||||
@@ -266,8 +288,8 @@ export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {
|
||||
});
|
||||
|
||||
export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
|
||||
payload: OpenInEditorInput,
|
||||
error: OpenError,
|
||||
payload: LaunchEditorInput,
|
||||
error: ExternalLauncherError,
|
||||
});
|
||||
|
||||
export const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {
|
||||
@@ -461,6 +483,12 @@ export const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsSubscribeBackgroundPolicyRpc = Rpc.make(WS_METHODS.subscribeBackgroundPolicy, {
|
||||
payload: Schema.Struct({}),
|
||||
success: BackgroundPolicySnapshot,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetConfigRpc,
|
||||
WsServerRefreshProvidersRpc,
|
||||
@@ -473,6 +501,9 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetTraceDiagnosticsRpc,
|
||||
WsServerGetProcessDiagnosticsRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsServerReportClientActivityRpc,
|
||||
WsServerReportHostPowerStateRpc,
|
||||
WsServerGetBackgroundPolicyRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
WsSourceControlPublishRepositoryRpc,
|
||||
@@ -502,6 +533,7 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeServerConfigRpc,
|
||||
WsSubscribeServerLifecycleRpc,
|
||||
WsSubscribeAuthAccessRpc,
|
||||
WsSubscribeBackgroundPolicyRpc,
|
||||
WsOrchestrationDispatchCommandRpc,
|
||||
WsOrchestrationGetTurnDiffRpc,
|
||||
WsOrchestrationGetFullThreadDiffRpc,
|
||||
|
||||
@@ -338,14 +338,65 @@ export const ObservabilitySettings = Schema.Struct({
|
||||
export type ObservabilitySettings = typeof ObservabilitySettings.Type;
|
||||
|
||||
export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
|
||||
export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
export const BackgroundActivityProfile = Schema.Literals([
|
||||
"balanced",
|
||||
"performance",
|
||||
"battery-saver",
|
||||
]);
|
||||
export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
|
||||
export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
|
||||
|
||||
export const BackgroundActivityProfileSelection = Schema.Literals([
|
||||
"balanced",
|
||||
"performance",
|
||||
"battery-saver",
|
||||
"custom",
|
||||
]);
|
||||
export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
|
||||
|
||||
export const BackgroundActivityOverrides = Schema.Struct({
|
||||
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
|
||||
pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
|
||||
pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
|
||||
pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
|
||||
|
||||
export const BackgroundActivitySettings = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
|
||||
profile: BackgroundActivityProfileSelection.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
|
||||
),
|
||||
baseProfile: Schema.optionalKey(BackgroundActivityProfile),
|
||||
overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
|
||||
export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
backgroundActivity: BackgroundActivitySettings,
|
||||
// Legacy flat fields retained for old settings files and old clients. New
|
||||
// consumers should resolve `backgroundActivity` instead.
|
||||
automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
|
||||
Schema.withDecodingDefault(
|
||||
Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
|
||||
),
|
||||
),
|
||||
providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
|
||||
Schema.withDecodingDefault(
|
||||
Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
|
||||
),
|
||||
),
|
||||
backgroundActivityProfile: BackgroundActivityProfile.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
|
||||
),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
|
||||
),
|
||||
@@ -448,7 +499,17 @@ const OpenCodeSettingsPatch = Schema.Struct({
|
||||
export const ServerSettingsPatch = Schema.Struct({
|
||||
// Server settings
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
backgroundActivity: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
schemaVersion: Schema.optionalKey(Schema.Literal(1)),
|
||||
profile: Schema.optionalKey(BackgroundActivityProfileSelection),
|
||||
baseProfile: Schema.optionalKey(BackgroundActivityProfile),
|
||||
overrides: Schema.optionalKey(BackgroundActivityOverrides),
|
||||
}),
|
||||
),
|
||||
automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
|
||||
backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
|
||||
@@ -58,6 +58,34 @@ export const VcsListRemotesResult = Schema.Struct({
|
||||
});
|
||||
export type VcsListRemotesResult = typeof VcsListRemotesResult.Type;
|
||||
|
||||
export interface VcsProcessErrorContext {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly cwd: string;
|
||||
}
|
||||
|
||||
export interface VcsProcessSpawnFailure {
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
export interface VcsProcessStdinFailure {
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
export interface VcsProcessReadFailure {
|
||||
readonly stream: "stdout" | "stderr" | "exitCode";
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
export interface VcsProcessOutputLimitFailure {
|
||||
readonly stream: "stdout" | "stderr";
|
||||
readonly maxBytes: number;
|
||||
}
|
||||
|
||||
export interface VcsProcessTimeoutFailure {
|
||||
readonly timeoutMs: number;
|
||||
}
|
||||
|
||||
export class VcsProcessSpawnError extends Schema.TaggedErrorClass<VcsProcessSpawnError>()(
|
||||
"VcsProcessSpawnError",
|
||||
{
|
||||
@@ -70,6 +98,13 @@ export class VcsProcessSpawnError extends Schema.TaggedErrorClass<VcsProcessSpaw
|
||||
override get message(): string {
|
||||
return `VCS process failed to spawn in ${this.operation}: ${this.command} (${this.cwd})`;
|
||||
}
|
||||
|
||||
static fromProcessSpawnError(context: VcsProcessErrorContext, error: VcsProcessSpawnFailure) {
|
||||
return new VcsProcessSpawnError({
|
||||
...context,
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class VcsProcessExitError extends Schema.TaggedErrorClass<VcsProcessExitError>()(
|
||||
@@ -99,6 +134,13 @@ export class VcsProcessTimeoutError extends Schema.TaggedErrorClass<VcsProcessTi
|
||||
override get message(): string {
|
||||
return `VCS process timed out in ${this.operation}: ${this.command} (${this.cwd}) after ${this.timeoutMs}ms`;
|
||||
}
|
||||
|
||||
static fromProcessTimeoutError(context: VcsProcessErrorContext, error: VcsProcessTimeoutFailure) {
|
||||
return new VcsProcessTimeoutError({
|
||||
...context,
|
||||
timeoutMs: error.timeoutMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class VcsOutputDecodeError extends Schema.TaggedErrorClass<VcsOutputDecodeError>()(
|
||||
@@ -114,6 +156,42 @@ export class VcsOutputDecodeError extends Schema.TaggedErrorClass<VcsOutputDecod
|
||||
override get message(): string {
|
||||
return `VCS output decode failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromProcessStdinError(context: VcsProcessErrorContext, error: VcsProcessStdinFailure) {
|
||||
return new VcsOutputDecodeError({
|
||||
...context,
|
||||
detail: "failed to write process stdin",
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromProcessReadError(context: VcsProcessErrorContext, error: VcsProcessReadFailure) {
|
||||
return new VcsOutputDecodeError({
|
||||
...context,
|
||||
detail:
|
||||
error.stream === "exitCode"
|
||||
? "failed to read process exit code"
|
||||
: `failed to read process ${error.stream}`,
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
|
||||
static fromProcessOutputLimitError(
|
||||
context: VcsProcessErrorContext,
|
||||
error: VcsProcessOutputLimitFailure,
|
||||
) {
|
||||
return new VcsOutputDecodeError({
|
||||
...context,
|
||||
detail: `process ${error.stream} exceeded ${error.maxBytes} bytes`,
|
||||
});
|
||||
}
|
||||
|
||||
static missingExitCode(context: VcsProcessErrorContext) {
|
||||
return new VcsOutputDecodeError({
|
||||
...context,
|
||||
detail: "process completed without an exit code",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class VcsRepositoryDetectionError extends Schema.TaggedErrorClass<VcsRepositoryDetectionError>()(
|
||||
|
||||
@@ -60,6 +60,10 @@
|
||||
"types": "./src/serverSettings.ts",
|
||||
"import": "./src/serverSettings.ts"
|
||||
},
|
||||
"./backgroundActivitySettings": {
|
||||
"types": "./src/backgroundActivitySettings.ts",
|
||||
"import": "./src/backgroundActivitySettings.ts"
|
||||
},
|
||||
"./String": {
|
||||
"types": "./src/String.ts",
|
||||
"import": "./src/String.ts"
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import {
|
||||
type BackgroundActivityProfile,
|
||||
type BackgroundActivitySettings,
|
||||
DEFAULT_BACKGROUND_ACTIVITY_PROFILE,
|
||||
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
|
||||
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
|
||||
export interface ResolvedBackgroundActivitySettings {
|
||||
readonly profile: BackgroundActivityProfile;
|
||||
readonly automaticGitFetchInterval: Duration.Duration;
|
||||
readonly providerHealthRefreshInterval: Duration.Duration;
|
||||
readonly hostPowerMonitorActiveInterval: Duration.Duration;
|
||||
readonly hostPowerMonitorIdleInterval: Duration.Duration;
|
||||
readonly idleClientTtl: Duration.Duration;
|
||||
readonly pauseWhenHostLocked: boolean;
|
||||
readonly pauseWhenHostLowPower: boolean;
|
||||
readonly pauseWhenClientLowPower: boolean;
|
||||
readonly pauseWhenOnBattery: boolean;
|
||||
}
|
||||
|
||||
const PRESET_SETTINGS: Record<BackgroundActivityProfile, ResolvedBackgroundActivitySettings> = {
|
||||
performance: {
|
||||
profile: "performance",
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
providerHealthRefreshInterval: Duration.minutes(1),
|
||||
hostPowerMonitorActiveInterval: Duration.seconds(30),
|
||||
hostPowerMonitorIdleInterval: Duration.minutes(2),
|
||||
idleClientTtl: Duration.seconds(45),
|
||||
pauseWhenHostLocked: true,
|
||||
pauseWhenHostLowPower: false,
|
||||
pauseWhenClientLowPower: false,
|
||||
pauseWhenOnBattery: false,
|
||||
},
|
||||
balanced: {
|
||||
profile: "balanced",
|
||||
automaticGitFetchInterval: DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
|
||||
providerHealthRefreshInterval: DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
hostPowerMonitorActiveInterval: Duration.seconds(30),
|
||||
hostPowerMonitorIdleInterval: Duration.minutes(5),
|
||||
idleClientTtl: Duration.seconds(45),
|
||||
pauseWhenHostLocked: true,
|
||||
pauseWhenHostLowPower: true,
|
||||
pauseWhenClientLowPower: true,
|
||||
pauseWhenOnBattery: false,
|
||||
},
|
||||
"battery-saver": {
|
||||
profile: "battery-saver",
|
||||
automaticGitFetchInterval: Duration.seconds(0),
|
||||
providerHealthRefreshInterval: Duration.minutes(15),
|
||||
hostPowerMonitorActiveInterval: Duration.minutes(1),
|
||||
hostPowerMonitorIdleInterval: Duration.minutes(10),
|
||||
idleClientTtl: Duration.seconds(45),
|
||||
pauseWhenHostLocked: true,
|
||||
pauseWhenHostLowPower: true,
|
||||
pauseWhenClientLowPower: true,
|
||||
pauseWhenOnBattery: true,
|
||||
},
|
||||
};
|
||||
|
||||
export function getBackgroundActivityPresetSettings(
|
||||
profile: BackgroundActivityProfile,
|
||||
): ResolvedBackgroundActivitySettings {
|
||||
return PRESET_SETTINGS[profile];
|
||||
}
|
||||
|
||||
export function getBackgroundActivityBaseProfile(
|
||||
backgroundActivity: BackgroundActivitySettings,
|
||||
): BackgroundActivityProfile {
|
||||
if (backgroundActivity.profile === "custom") {
|
||||
return backgroundActivity.baseProfile ?? DEFAULT_BACKGROUND_ACTIVITY_PROFILE;
|
||||
}
|
||||
return backgroundActivity.profile;
|
||||
}
|
||||
|
||||
export function resolveBackgroundActivitySettings(
|
||||
backgroundActivity: BackgroundActivitySettings,
|
||||
): ResolvedBackgroundActivitySettings {
|
||||
const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);
|
||||
const preset = PRESET_SETTINGS[baseProfile];
|
||||
const { overrides } = backgroundActivity;
|
||||
return {
|
||||
profile: baseProfile,
|
||||
automaticGitFetchInterval:
|
||||
overrides.automaticGitFetchInterval ?? preset.automaticGitFetchInterval,
|
||||
providerHealthRefreshInterval:
|
||||
overrides.providerHealthRefreshInterval ?? preset.providerHealthRefreshInterval,
|
||||
hostPowerMonitorActiveInterval:
|
||||
overrides.hostPowerMonitorActiveInterval ?? preset.hostPowerMonitorActiveInterval,
|
||||
hostPowerMonitorIdleInterval:
|
||||
overrides.hostPowerMonitorIdleInterval ?? preset.hostPowerMonitorIdleInterval,
|
||||
idleClientTtl: overrides.idleClientTtl ?? preset.idleClientTtl,
|
||||
pauseWhenHostLocked: overrides.pauseWhenHostLocked ?? preset.pauseWhenHostLocked,
|
||||
pauseWhenHostLowPower: overrides.pauseWhenHostLowPower ?? preset.pauseWhenHostLowPower,
|
||||
pauseWhenClientLowPower: overrides.pauseWhenClientLowPower ?? preset.pauseWhenClientLowPower,
|
||||
pauseWhenOnBattery: overrides.pauseWhenOnBattery ?? preset.pauseWhenOnBattery,
|
||||
};
|
||||
}
|
||||
|
||||
function durationsEqual(a: Duration.Duration, b: Duration.Duration): boolean {
|
||||
return Duration.toMillis(a) === Duration.toMillis(b);
|
||||
}
|
||||
|
||||
function resolvedSettingsEqual(
|
||||
a: ResolvedBackgroundActivitySettings,
|
||||
b: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
return (
|
||||
durationsEqual(a.automaticGitFetchInterval, b.automaticGitFetchInterval) &&
|
||||
durationsEqual(a.providerHealthRefreshInterval, b.providerHealthRefreshInterval) &&
|
||||
durationsEqual(a.hostPowerMonitorActiveInterval, b.hostPowerMonitorActiveInterval) &&
|
||||
durationsEqual(a.hostPowerMonitorIdleInterval, b.hostPowerMonitorIdleInterval) &&
|
||||
durationsEqual(a.idleClientTtl, b.idleClientTtl) &&
|
||||
a.pauseWhenHostLocked === b.pauseWhenHostLocked &&
|
||||
a.pauseWhenHostLowPower === b.pauseWhenHostLowPower &&
|
||||
a.pauseWhenClientLowPower === b.pauseWhenClientLowPower &&
|
||||
a.pauseWhenOnBattery === b.pauseWhenOnBattery
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeBackgroundActivitySettings(
|
||||
backgroundActivity: BackgroundActivitySettings,
|
||||
): BackgroundActivitySettings {
|
||||
if (backgroundActivity.profile !== "custom") {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
profile: backgroundActivity.profile,
|
||||
overrides: {},
|
||||
};
|
||||
}
|
||||
|
||||
const resolved = resolveBackgroundActivitySettings(backgroundActivity);
|
||||
const profiles: ReadonlyArray<BackgroundActivityProfile> = [
|
||||
getBackgroundActivityBaseProfile(backgroundActivity),
|
||||
"balanced",
|
||||
"performance",
|
||||
"battery-saver",
|
||||
];
|
||||
for (const profile of profiles) {
|
||||
if (resolvedSettingsEqual(resolved, PRESET_SETTINGS[profile])) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
profile,
|
||||
overrides: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);
|
||||
const preset = PRESET_SETTINGS[baseProfile];
|
||||
const overrides: BackgroundActivitySettings["overrides"] = {
|
||||
...(!durationsEqual(resolved.automaticGitFetchInterval, preset.automaticGitFetchInterval)
|
||||
? { automaticGitFetchInterval: resolved.automaticGitFetchInterval }
|
||||
: {}),
|
||||
...(!durationsEqual(
|
||||
resolved.providerHealthRefreshInterval,
|
||||
preset.providerHealthRefreshInterval,
|
||||
)
|
||||
? { providerHealthRefreshInterval: resolved.providerHealthRefreshInterval }
|
||||
: {}),
|
||||
...(!durationsEqual(
|
||||
resolved.hostPowerMonitorActiveInterval,
|
||||
preset.hostPowerMonitorActiveInterval,
|
||||
)
|
||||
? { hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval }
|
||||
: {}),
|
||||
...(!durationsEqual(resolved.hostPowerMonitorIdleInterval, preset.hostPowerMonitorIdleInterval)
|
||||
? { hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval }
|
||||
: {}),
|
||||
...(!durationsEqual(resolved.idleClientTtl, preset.idleClientTtl)
|
||||
? { idleClientTtl: resolved.idleClientTtl }
|
||||
: {}),
|
||||
...(resolved.pauseWhenHostLocked !== preset.pauseWhenHostLocked
|
||||
? { pauseWhenHostLocked: resolved.pauseWhenHostLocked }
|
||||
: {}),
|
||||
...(resolved.pauseWhenHostLowPower !== preset.pauseWhenHostLowPower
|
||||
? { pauseWhenHostLowPower: resolved.pauseWhenHostLowPower }
|
||||
: {}),
|
||||
...(resolved.pauseWhenClientLowPower !== preset.pauseWhenClientLowPower
|
||||
? { pauseWhenClientLowPower: resolved.pauseWhenClientLowPower }
|
||||
: {}),
|
||||
...(resolved.pauseWhenOnBattery !== preset.pauseWhenOnBattery
|
||||
? { pauseWhenOnBattery: resolved.pauseWhenOnBattery }
|
||||
: {}),
|
||||
};
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile,
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveServerBackgroundActivitySettings(
|
||||
settings: ServerSettings,
|
||||
): ResolvedBackgroundActivitySettings {
|
||||
const defaultBackgroundActivity: BackgroundActivitySettings = {
|
||||
schemaVersion: 1,
|
||||
profile: DEFAULT_BACKGROUND_ACTIVITY_PROFILE,
|
||||
overrides: {},
|
||||
};
|
||||
const backgroundActivityIsDefault =
|
||||
settings.backgroundActivity.profile === defaultBackgroundActivity.profile &&
|
||||
settings.backgroundActivity.baseProfile === undefined &&
|
||||
Object.keys(settings.backgroundActivity.overrides).length === 0;
|
||||
const legacyProfile = settings.backgroundActivityProfile;
|
||||
const hasLegacyOverrides =
|
||||
legacyProfile !== DEFAULT_BACKGROUND_ACTIVITY_PROFILE ||
|
||||
Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) ||
|
||||
Duration.toMillis(settings.providerHealthRefreshInterval) !==
|
||||
Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL);
|
||||
if (backgroundActivityIsDefault && hasLegacyOverrides) {
|
||||
return resolveBackgroundActivitySettings({
|
||||
schemaVersion: 1,
|
||||
profile:
|
||||
Duration.toMillis(settings.automaticGitFetchInterval) ===
|
||||
Duration.toMillis(
|
||||
getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,
|
||||
) &&
|
||||
Duration.toMillis(settings.providerHealthRefreshInterval) ===
|
||||
Duration.toMillis(
|
||||
getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,
|
||||
)
|
||||
? legacyProfile
|
||||
: "custom",
|
||||
baseProfile: legacyProfile,
|
||||
overrides: {
|
||||
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(
|
||||
getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,
|
||||
)
|
||||
? { automaticGitFetchInterval: settings.automaticGitFetchInterval }
|
||||
: {}),
|
||||
...(Duration.toMillis(settings.providerHealthRefreshInterval) !==
|
||||
Duration.toMillis(
|
||||
getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,
|
||||
)
|
||||
? { providerHealthRefreshInterval: settings.providerHealthRefreshInterval }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
return resolveBackgroundActivitySettings(settings.backgroundActivity);
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveServerBackgroundActivitySettings } from "./backgroundActivitySettings.ts";
|
||||
import { createModelSelection } from "./model.ts";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
@@ -194,4 +196,80 @@ describe("serverSettings helpers", () => {
|
||||
config: { homePath: "~/.codex" },
|
||||
});
|
||||
});
|
||||
|
||||
it("stores background activity profiles as a versioned object and syncs legacy aliases", () => {
|
||||
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "battery-saver",
|
||||
overrides: {},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.backgroundActivity).toEqual({
|
||||
schemaVersion: 1,
|
||||
profile: "battery-saver",
|
||||
overrides: {},
|
||||
});
|
||||
expect(next.backgroundActivityProfile).toBe("battery-saver");
|
||||
expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(0);
|
||||
expect(Duration.toMillis(next.providerHealthRefreshInterval)).toBe(
|
||||
Duration.toMillis(Duration.minutes(15)),
|
||||
);
|
||||
});
|
||||
|
||||
it("turns legacy interval patches into custom background activity overrides", () => {
|
||||
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
});
|
||||
|
||||
expect(next.backgroundActivity).toEqual({
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
},
|
||||
});
|
||||
expect(resolveServerBackgroundActivitySettings(next).profile).toBe("balanced");
|
||||
expect(
|
||||
Duration.toMillis(resolveServerBackgroundActivitySettings(next).automaticGitFetchInterval),
|
||||
).toBe(15_000);
|
||||
});
|
||||
|
||||
it("reconciles custom background activity back to a preset when overrides match the preset", () => {
|
||||
const custom = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
|
||||
automaticGitFetchInterval: Duration.seconds(15),
|
||||
});
|
||||
const next = applyServerSettingsPatch(custom, {
|
||||
automaticGitFetchInterval: Duration.seconds(30),
|
||||
});
|
||||
|
||||
expect(next.backgroundActivity).toEqual({
|
||||
schemaVersion: 1,
|
||||
profile: "balanced",
|
||||
overrides: {},
|
||||
});
|
||||
expect(next.backgroundActivityProfile).toBe("balanced");
|
||||
expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(30_000);
|
||||
});
|
||||
|
||||
it("drops custom overrides that duplicate the base profile", () => {
|
||||
const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
|
||||
backgroundActivity: {
|
||||
schemaVersion: 1,
|
||||
profile: "custom",
|
||||
baseProfile: "balanced",
|
||||
overrides: {
|
||||
automaticGitFetchInterval: Duration.seconds(30),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.backgroundActivity).toEqual({
|
||||
schemaVersion: 1,
|
||||
profile: "balanced",
|
||||
overrides: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user