Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bed9031f02 |
No files matched your search
@@ -1,191 +0,0 @@
|
||||
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" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,276 +0,0 @@
|
||||
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());
|
||||
@@ -1,209 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -10,6 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const encodeJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
@@ -41,7 +43,7 @@ describe("ProcessDiagnostics", () => {
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
assert.deepEqual(rows, [
|
||||
{
|
||||
pid: 10,
|
||||
ppid: 1,
|
||||
@@ -125,15 +127,21 @@ describe("ProcessDiagnostics", () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
assert.equal(diagnostics.serverPid, 100);
|
||||
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
|
||||
assert.equal(diagnostics.processCount, 2);
|
||||
assert.equal(diagnostics.totalRssBytes, 6_000);
|
||||
assert.equal(diagnostics.totalCpuPercent, 4.75);
|
||||
assert.deepEqual(
|
||||
diagnostics.processes.map((process) => process.pid),
|
||||
[101, 102],
|
||||
);
|
||||
assert.deepEqual(
|
||||
diagnostics.processes.map((process) => process.depth),
|
||||
[0, 1],
|
||||
);
|
||||
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
|
||||
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -176,7 +184,10 @@ describe("ProcessDiagnostics", () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
assert.deepEqual(
|
||||
diagnostics.processes.map((process) => process.pid),
|
||||
[101, 102, 103],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -184,9 +195,8 @@ describe("ProcessDiagnostics", () => {
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -200,8 +210,8 @@ describe("ProcessDiagnostics", () => {
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
@@ -209,8 +219,11 @@ describe("ProcessDiagnostics", () => {
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
assert.deepEqual(
|
||||
diagnostics.processes.map((process) => process.pid),
|
||||
[4242],
|
||||
);
|
||||
assert.deepEqual(commands, [
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
@@ -219,11 +232,64 @@ describe("ProcessDiagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes Windows process rows through Schema JSON parsing", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: (command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: encodeJsonString([
|
||||
{
|
||||
ProcessId: 4242,
|
||||
ParentProcessId: 100,
|
||||
Name: "node.exe",
|
||||
CommandLine: "node server.js",
|
||||
Status: "Running",
|
||||
WorkingSetSize: 2048,
|
||||
PercentProcessorTime: 12.5,
|
||||
},
|
||||
{
|
||||
ProcessId: 0,
|
||||
ParentProcessId: 100,
|
||||
Name: "invalid.exe",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows("win32").pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
);
|
||||
|
||||
assert.deepEqual(rows, [
|
||||
{
|
||||
pid: 4242,
|
||||
ppid: 100,
|
||||
pgid: null,
|
||||
status: "Running",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 2048,
|
||||
elapsed: "",
|
||||
command: "node server.js",
|
||||
},
|
||||
]);
|
||||
assert.equal(commands[0]?.command, "powershell.exe");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
|
||||
spawn: () =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
@@ -232,8 +298,7 @@ describe("ProcessDiagnostics", () => {
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
@@ -241,7 +306,7 @@ describe("ProcessDiagnostics", () => {
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
assert.deepEqual(result, {
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface ProcessRow {
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
@@ -43,17 +43,73 @@ export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
class ProcessQueryError extends Schema.TaggedErrorClass<ProcessQueryError>()("ProcessQueryError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
class ProcessQueryTimeoutError extends Schema.TaggedErrorClass<ProcessQueryTimeoutError>()(
|
||||
"ProcessQueryTimeoutError",
|
||||
{
|
||||
message: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessCommandExitError extends Schema.TaggedErrorClass<ProcessCommandExitError>()(
|
||||
"ProcessCommandExitError",
|
||||
{
|
||||
message: Schema.String,
|
||||
command: Schema.String,
|
||||
exitCode: Schema.Number,
|
||||
stderr: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessSignalRejectedError extends Schema.TaggedErrorClass<ProcessSignalRejectedError>()(
|
||||
"ProcessSignalRejectedError",
|
||||
{
|
||||
message: Schema.String,
|
||||
pid: Schema.Number,
|
||||
reason: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
class ProcessSignalFailedError extends Schema.TaggedErrorClass<ProcessSignalFailedError>()(
|
||||
"ProcessSignalFailedError",
|
||||
{
|
||||
message: Schema.String,
|
||||
pid: Schema.Number,
|
||||
signal: Schema.Literals(["SIGINT", "SIGKILL"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
type ProcessDiagnosticsError =
|
||||
| ProcessQueryError
|
||||
| ProcessQueryTimeoutError
|
||||
| ProcessCommandExitError
|
||||
| ProcessSignalRejectedError
|
||||
| ProcessSignalFailedError;
|
||||
|
||||
const isProcessQueryError = Schema.is(ProcessQueryError);
|
||||
const isProcessQueryTimeoutError = Schema.is(ProcessQueryTimeoutError);
|
||||
const isProcessCommandExitError = Schema.is(ProcessCommandExitError);
|
||||
const isProcessSignalRejectedError = Schema.is(ProcessSignalRejectedError);
|
||||
const isProcessSignalFailedError = Schema.is(ProcessSignalFailedError);
|
||||
|
||||
function isProcessDiagnosticsError(error: unknown): error is ProcessDiagnosticsError {
|
||||
return (
|
||||
isProcessQueryError(error) ||
|
||||
isProcessQueryTimeoutError(error) ||
|
||||
isProcessCommandExitError(error) ||
|
||||
isProcessSignalRejectedError(error) ||
|
||||
isProcessSignalFailedError(error)
|
||||
);
|
||||
}
|
||||
|
||||
function makeProcessQueryError(message: string, cause?: unknown): ProcessQueryError {
|
||||
return new ProcessQueryError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
@@ -74,6 +130,22 @@ function parseNumber(value: string): number | null {
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
const WindowsProcessRowSchema = Schema.Struct({
|
||||
ProcessId: Schema.optional(Schema.Number),
|
||||
ParentProcessId: Schema.optional(Schema.Number),
|
||||
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
Name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
Status: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
WorkingSetSize: Schema.optional(Schema.Number),
|
||||
PercentProcessorTime: Schema.optional(Schema.Number),
|
||||
});
|
||||
type WindowsProcessRow = typeof WindowsProcessRowSchema.Type;
|
||||
|
||||
const WindowsProcessRowsJsonSchema = Schema.fromJsonString(
|
||||
Schema.Union([Schema.Array(WindowsProcessRowSchema), WindowsProcessRowSchema]),
|
||||
);
|
||||
const decodeWindowsProcessRowsJsonOption = Schema.decodeUnknownOption(WindowsProcessRowsJsonSchema);
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
@@ -139,9 +211,7 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
function normalizeWindowsProcessRow(record: WindowsProcessRow): ProcessRow | null {
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
@@ -174,16 +244,15 @@ function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
const decoded = decodeWindowsProcessRowsJsonOption(output);
|
||||
if (Option.isNone(decoded)) return [];
|
||||
|
||||
const records = Array.isArray(decoded.value) ? decoded.value : [decoded.value];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildDescendantEntries(
|
||||
@@ -309,17 +378,21 @@ const runProcess = Effect.fn("runProcess")(
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessQueryTimeoutError({
|
||||
message: `${input.errorMessage} timed out.`,
|
||||
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
isProcessDiagnosticsError(cause) ? cause : makeProcessQueryError(input.errorMessage, cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -336,7 +409,14 @@ function readPosixProcessRows(): Effect.Effect<
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
? Effect.fail(
|
||||
new ProcessCommandExitError({
|
||||
message: result.stderr.trim() || "ps failed.",
|
||||
command: "ps",
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
@@ -363,7 +443,12 @@ function readWindowsProcessRows(): Effect.Effect<
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
new ProcessCommandExitError({
|
||||
message: result.stderr.trim() || "PowerShell process query failed.",
|
||||
command: "powershell.exe",
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
@@ -385,7 +470,13 @@ function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
return Effect.fail(
|
||||
new ProcessSignalRejectedError({
|
||||
message: "Refusing to signal the T3 server process.",
|
||||
pid,
|
||||
reason: "self",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows().pipe(
|
||||
@@ -397,7 +488,11 @@ function assertDescendantPid(
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
new ProcessSignalRejectedError({
|
||||
message: `Process ${pid} is not a live descendant of the T3 server.`,
|
||||
pid,
|
||||
reason: "not-descendant",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -438,10 +533,12 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
new ProcessSignalFailedError({
|
||||
message: `Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
|
||||
@@ -5,9 +5,12 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
const encodeTraceRecordJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
function ns(ms: number): string {
|
||||
return String(BigInt(ms) * 1_000_000n);
|
||||
}
|
||||
@@ -21,7 +24,7 @@ function record(input: {
|
||||
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
|
||||
readonly events?: ReadonlyArray<unknown>;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
return encodeTraceRecordJson({
|
||||
type: "effect-span",
|
||||
name: input.name,
|
||||
traceId: input.traceId,
|
||||
|
||||
@@ -14,23 +14,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
interface TraceRecordLike {
|
||||
readonly name?: unknown;
|
||||
readonly traceId?: unknown;
|
||||
readonly spanId?: unknown;
|
||||
readonly startTimeUnixNano?: unknown;
|
||||
readonly endTimeUnixNano?: unknown;
|
||||
readonly durationMs?: unknown;
|
||||
readonly exit?: unknown;
|
||||
readonly events?: unknown;
|
||||
}
|
||||
|
||||
interface TraceEventLike {
|
||||
readonly name?: unknown;
|
||||
readonly timeUnixNano?: unknown;
|
||||
readonly attributes?: unknown;
|
||||
}
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export interface TraceDiagnosticsOptions {
|
||||
readonly traceFilePath: string;
|
||||
@@ -65,6 +49,35 @@ interface TraceDiagnosticsErrorSummary {
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
|
||||
const TraceExitSchema = Schema.Struct({
|
||||
_tag: Schema.optional(Schema.Unknown),
|
||||
cause: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
type TraceExit = typeof TraceExitSchema.Type;
|
||||
const decodeTraceExitOption = Schema.decodeUnknownOption(TraceExitSchema);
|
||||
|
||||
const TraceEventSchema = Schema.Struct({
|
||||
name: Schema.optional(Schema.Unknown),
|
||||
timeUnixNano: Schema.optional(Schema.Unknown),
|
||||
attributes: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
});
|
||||
const decodeTraceEventOption = Schema.decodeUnknownOption(TraceEventSchema);
|
||||
|
||||
const TraceRecordJsonSchema = Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(Schema.Unknown),
|
||||
traceId: Schema.optional(Schema.Unknown),
|
||||
spanId: Schema.optional(Schema.Unknown),
|
||||
startTimeUnixNano: Schema.optional(Schema.Unknown),
|
||||
endTimeUnixNano: Schema.optional(Schema.Unknown),
|
||||
durationMs: Schema.optional(Schema.Unknown),
|
||||
exit: Schema.optional(Schema.Unknown),
|
||||
events: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
}),
|
||||
);
|
||||
const decodeTraceRecordJsonOption = Schema.decodeUnknownOption(TraceRecordJsonSchema);
|
||||
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
const backups = Array.from(
|
||||
@@ -74,47 +87,55 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
|
||||
function isRecordObject(value: unknown): value is TraceRecordLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
function toStringOption(value: unknown): Option.Option<string> {
|
||||
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
|
||||
}
|
||||
|
||||
function toStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
function toNumberOption(value: unknown): Option.Option<number> {
|
||||
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
|
||||
}
|
||||
|
||||
function toNumberValue(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
|
||||
const text = toStringValue(value);
|
||||
if (!text) return null;
|
||||
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
|
||||
const text = toStringOption(value);
|
||||
if (Option.isNone(text)) return Option.none();
|
||||
try {
|
||||
const millis = Number(BigInt(text) / 1_000_000n);
|
||||
return Option.getOrNull(DateTime.make(millis));
|
||||
const millis = Number(BigInt(text.value) / 1_000_000n);
|
||||
return DateTime.make(millis);
|
||||
} catch {
|
||||
return null;
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): string | null {
|
||||
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
|
||||
return toStringValue(exit._tag);
|
||||
function decodeTraceExit(exit: unknown): Option.Option<TraceExit> {
|
||||
return decodeTraceExitOption(exit);
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): Option.Option<string> {
|
||||
return Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit._tag));
|
||||
}
|
||||
|
||||
function readExitCause(exit: unknown): string {
|
||||
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
|
||||
return toStringValue(exit.cause)?.trim() ?? "Failure";
|
||||
return Option.getOrElse(
|
||||
Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit.cause)),
|
||||
() => "Failure",
|
||||
).trim();
|
||||
}
|
||||
|
||||
function isTraceEvent(value: unknown): value is TraceEventLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
function minDateTimeOption(
|
||||
current: Option.Option<DateTime.Utc>,
|
||||
candidate: Option.Option<DateTime.Utc>,
|
||||
): Option.Option<DateTime.Utc> {
|
||||
if (Option.isNone(candidate)) return current;
|
||||
if (Option.isNone(current)) return candidate;
|
||||
return DateTime.isLessThan(candidate.value, current.value) ? candidate : current;
|
||||
}
|
||||
|
||||
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
|
||||
return typeof event.attributes === "object" && event.attributes !== null
|
||||
? (event.attributes as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
function maxDateTime(
|
||||
current: Option.Option<DateTime.Utc>,
|
||||
candidate: DateTime.Utc,
|
||||
): Option.Option<DateTime.Utc> {
|
||||
if (Option.isNone(current)) return Option.some(candidate);
|
||||
return DateTime.isGreaterThan(candidate, current.value) ? Option.some(candidate) : current;
|
||||
}
|
||||
|
||||
function makeEmptyDiagnostics(input: {
|
||||
@@ -199,8 +220,8 @@ export function aggregateTraceDiagnostics(
|
||||
let failureCount = 0;
|
||||
let interruptionCount = 0;
|
||||
let slowSpanCount = 0;
|
||||
let firstSpanAt: DateTime.Utc | null = null;
|
||||
let lastSpanAt: DateTime.Utc | null = null;
|
||||
let firstSpanAt = Option.none<DateTime.Utc>();
|
||||
let lastSpanAt = Option.none<DateTime.Utc>();
|
||||
|
||||
const spansByName = new Map<
|
||||
string,
|
||||
@@ -217,42 +238,42 @@ export function aggregateTraceDiagnostics(
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
const decodedRecord = decodeTraceRecordJsonOption(line);
|
||||
if (Option.isNone(decodedRecord)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
const parsed = decodedRecord.value;
|
||||
|
||||
if (!isRecordObject(parsed)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = toStringValue(parsed.name);
|
||||
const traceId = toStringValue(parsed.traceId);
|
||||
const spanId = toStringValue(parsed.spanId);
|
||||
const durationMs = toNumberValue(parsed.durationMs);
|
||||
const nameOption = toStringOption(parsed.name);
|
||||
const traceIdOption = toStringOption(parsed.traceId);
|
||||
const spanIdOption = toStringOption(parsed.spanId);
|
||||
const durationMsOption = toNumberOption(parsed.durationMs);
|
||||
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
|
||||
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
|
||||
|
||||
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
|
||||
if (
|
||||
Option.isNone(nameOption) ||
|
||||
Option.isNone(traceIdOption) ||
|
||||
Option.isNone(spanIdOption) ||
|
||||
Option.isNone(durationMsOption) ||
|
||||
Option.isNone(endedAt)
|
||||
) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
const name = nameOption.value;
|
||||
const traceId = traceIdOption.value;
|
||||
const spanId = spanIdOption.value;
|
||||
const durationMs = durationMsOption.value;
|
||||
|
||||
recordCount += 1;
|
||||
firstSpanAt =
|
||||
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
|
||||
? startedAt
|
||||
: firstSpanAt;
|
||||
lastSpanAt =
|
||||
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
|
||||
firstSpanAt = minDateTimeOption(firstSpanAt, startedAt);
|
||||
lastSpanAt = maxDateTime(lastSpanAt, endedAt.value);
|
||||
|
||||
const exitTag = readExitTag(parsed.exit);
|
||||
const isFailure = exitTag === "Failure";
|
||||
const isInterrupted = exitTag === "Interrupted";
|
||||
const isFailure = Option.contains(exitTag, "Failure");
|
||||
const isInterrupted = Option.contains(exitTag, "Interrupted");
|
||||
if (isFailure) failureCount += 1;
|
||||
if (isInterrupted) interruptionCount += 1;
|
||||
|
||||
@@ -268,7 +289,7 @@ export function aggregateTraceDiagnostics(
|
||||
if (isFailure) spanSummary.failureCount += 1;
|
||||
spansByName.set(name, spanSummary);
|
||||
|
||||
const spanItem = { name, durationMs, endedAt, traceId, spanId };
|
||||
const spanItem = { name, durationMs, endedAt: endedAt.value, traceId, spanId };
|
||||
if (durationMs >= slowSpanThresholdMs) {
|
||||
slowSpanCount += 1;
|
||||
}
|
||||
@@ -280,12 +301,13 @@ export function aggregateTraceDiagnostics(
|
||||
|
||||
const failureKey = `${name}\0${cause}`;
|
||||
const existing = failuresByKey.get(failureKey);
|
||||
const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
|
||||
const isLatestFailure =
|
||||
!existing || DateTime.isGreaterThan(endedAt.value, existing.lastSeenAt);
|
||||
failuresByKey.set(failureKey, {
|
||||
name,
|
||||
cause,
|
||||
count: (existing?.count ?? 0) + 1,
|
||||
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
|
||||
lastSeenAt: isLatestFailure ? endedAt.value : existing!.lastSeenAt,
|
||||
traceId: isLatestFailure ? traceId : existing!.traceId,
|
||||
spanId: isLatestFailure ? spanId : existing!.spanId,
|
||||
});
|
||||
@@ -293,10 +315,15 @@ export function aggregateTraceDiagnostics(
|
||||
|
||||
if (Array.isArray(parsed.events)) {
|
||||
for (const rawEvent of parsed.events) {
|
||||
if (!isTraceEvent(rawEvent)) continue;
|
||||
const attributes = readEventAttributes(rawEvent);
|
||||
const level = toStringValue(attributes["effect.logLevel"]);
|
||||
if (!level) continue;
|
||||
const event = decodeTraceEventOption(rawEvent);
|
||||
if (Option.isNone(event)) continue;
|
||||
const attributes = Option.getOrElse(
|
||||
Option.fromUndefinedOr(event.value.attributes),
|
||||
() => ({}) as Readonly<Record<string, unknown>>,
|
||||
);
|
||||
const levelOption = toStringOption(attributes["effect.logLevel"]);
|
||||
if (Option.isNone(levelOption)) continue;
|
||||
const level = levelOption.value;
|
||||
|
||||
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
|
||||
const normalizedLevel = level.toLowerCase();
|
||||
@@ -309,8 +336,14 @@ export function aggregateTraceDiagnostics(
|
||||
continue;
|
||||
}
|
||||
|
||||
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
|
||||
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
|
||||
const seenAt = Option.getOrElse(
|
||||
unixNanoToDateTime(event.value.timeUnixNano),
|
||||
() => endedAt.value,
|
||||
);
|
||||
const message = Option.getOrElse(
|
||||
Option.map(toStringOption(event.value.name), (name) => name.trim()),
|
||||
() => "Log event",
|
||||
);
|
||||
latestWarningAndErrorLogs.push({
|
||||
spanName: name,
|
||||
level,
|
||||
@@ -342,8 +375,8 @@ export function aggregateTraceDiagnostics(
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
firstSpanAt,
|
||||
lastSpanAt,
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
|
||||
@@ -24,9 +24,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
@@ -53,6 +51,7 @@ 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 {
|
||||
@@ -77,14 +76,12 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -177,6 +174,7 @@ 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,6 +22,7 @@
|
||||
* @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";
|
||||
@@ -31,9 +32,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
@@ -55,6 +54,7 @@ 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,14 +68,12 @@ 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
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
/**
|
||||
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
|
||||
@@ -176,6 +174,7 @@ 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,6 +13,7 @@
|
||||
* @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";
|
||||
@@ -22,8 +23,6 @@ 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";
|
||||
@@ -49,6 +48,7 @@ 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,14 +60,12 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -153,6 +151,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* @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";
|
||||
@@ -22,9 +23,7 @@ import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
@@ -50,6 +49,7 @@ 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,15 +72,13 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
| ServerConfig;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -155,6 +153,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -33,15 +33,11 @@ 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";
|
||||
@@ -57,37 +53,6 @@ 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",
|
||||
@@ -133,8 +98,6 @@ 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)),
|
||||
);
|
||||
@@ -272,8 +235,6 @@ 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,6 +1,5 @@
|
||||
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";
|
||||
@@ -33,7 +32,6 @@ 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";
|
||||
@@ -66,7 +64,6 @@ 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,
|
||||
@@ -75,35 +72,6 @@ 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,
|
||||
@@ -767,7 +735,6 @@ 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));
|
||||
@@ -862,7 +829,6 @@ 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));
|
||||
@@ -967,7 +933,6 @@ 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));
|
||||
@@ -1064,7 +1029,6 @@ 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
|
||||
@@ -1145,7 +1109,6 @@ 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),
|
||||
@@ -1245,7 +1208,6 @@ 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),
|
||||
@@ -1296,7 +1258,6 @@ 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") {
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
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: [
|
||||
{
|
||||
@@ -93,43 +87,6 @@ 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",
|
||||
@@ -182,38 +139,7 @@ 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", () =>
|
||||
@@ -258,7 +184,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", () =>
|
||||
@@ -296,7 +222,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", () =>
|
||||
@@ -357,6 +283,6 @@ describe("makeManagedServerProvider", () => {
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
|
||||
type ServerProvider,
|
||||
ServerSettingsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
@@ -14,9 +9,8 @@ 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;
|
||||
@@ -39,13 +33,7 @@ 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 | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
|
||||
> {
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
@@ -146,45 +134,13 @@ 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(
|
||||
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.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot()),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
@@ -53,7 +53,6 @@ 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";
|
||||
@@ -710,36 +709,6 @@ 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),
|
||||
|
||||
@@ -3,8 +3,6 @@ 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,
|
||||
@@ -105,11 +103,6 @@ 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;
|
||||
@@ -250,7 +243,6 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
@@ -278,6 +270,7 @@ 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),
|
||||
@@ -287,7 +280,6 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(BackgroundLayerLive),
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(ProcessResourceMonitor.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
|
||||
@@ -460,14 +460,6 @@ 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,17 +135,13 @@ export class ServerSettingsService extends Context.Service<
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
|
||||
overrides;
|
||||
const { automaticGitFetchInterval, ...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);
|
||||
|
||||
@@ -219,9 +215,7 @@ 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",
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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";
|
||||
@@ -12,7 +11,6 @@ import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type {
|
||||
BackgroundScope,
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
@@ -20,11 +18,8 @@ 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: {
|
||||
@@ -61,7 +56,6 @@ function makeTestLayer(state: {
|
||||
}) {
|
||||
return VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: () =>
|
||||
@@ -87,37 +81,6 @@ 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 = {
|
||||
@@ -233,7 +196,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
};
|
||||
const testLayer = VcsStatusBroadcaster.layer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(makeBackgroundPolicyLayer(() => true)),
|
||||
Layer.provide(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
localStatus: (input) =>
|
||||
@@ -371,57 +333,6 @@ describe("VcsStatusBroadcaster", () => {
|
||||
);
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -435,7 +346,6 @@ 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: () =>
|
||||
|
||||
@@ -21,7 +21,6 @@ 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);
|
||||
@@ -99,7 +98,6 @@ 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>(),
|
||||
@@ -271,14 +269,6 @@ export const layer = Layer.effect(
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
const shouldRun = yield* backgroundPolicy.shouldRunScopeWork({
|
||||
type: "vcs-status",
|
||||
cwd,
|
||||
});
|
||||
if (!shouldRun) {
|
||||
return activeInterval;
|
||||
}
|
||||
|
||||
const exit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(exit)) {
|
||||
yield* Ref.set(consecutiveFailuresRef, 0);
|
||||
|
||||
+1
-36
@@ -28,13 +28,11 @@ 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";
|
||||
@@ -67,7 +65,6 @@ 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 ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
@@ -184,12 +181,9 @@ 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) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
|
||||
),
|
||||
Effect.map((settings) => settings.automaticGitFetchInterval),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to read automatic Git fetch interval setting", {
|
||||
detail: cause.message,
|
||||
@@ -929,26 +923,6 @@ 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,
|
||||
@@ -1261,15 +1235,6 @@ 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" },
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -18,7 +18,6 @@ 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";
|
||||
@@ -762,41 +761,6 @@ 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,19 +1,9 @@
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArchiveX,
|
||||
InfoIcon,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SettingsIcon,
|
||||
} from "lucide-react";
|
||||
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } 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,
|
||||
@@ -23,11 +13,6 @@ 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";
|
||||
@@ -64,23 +49,7 @@ 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";
|
||||
@@ -130,128 +99,7 @@ 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";
|
||||
type BackgroundActivityOverridePatch = Partial<{
|
||||
[K in keyof BackgroundActivitySettings["overrides"]]:
|
||||
| BackgroundActivitySettings["overrides"][K]
|
||||
| undefined;
|
||||
}>;
|
||||
|
||||
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 durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
}
|
||||
|
||||
function normalizeIntervalSeconds(value: number | null): number {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
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 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"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function PolicyTooltip({ 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>
|
||||
);
|
||||
}
|
||||
|
||||
function withoutProviderInstanceKey<V>(
|
||||
record: Readonly<Record<ProviderInstanceId, V>> | undefined,
|
||||
@@ -560,8 +408,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
|
||||
? ["Assistant output"]
|
||||
: []),
|
||||
...(!Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity)
|
||||
? ["Background activity"]
|
||||
...(Duration.toMillis(settings.automaticGitFetchInterval) !==
|
||||
Duration.toMillis(DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval)
|
||||
? ["Automatic Git fetch interval"]
|
||||
: []),
|
||||
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
|
||||
? ["New thread mode"]
|
||||
@@ -586,7 +435,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.backgroundActivity,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
@@ -612,7 +461,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
@@ -628,255 +477,10 @@ 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({
|
||||
@@ -909,21 +513,6 @@ 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>
|
||||
@@ -1080,88 +669,6 @@ 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."
|
||||
@@ -1437,14 +944,6 @@ 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(
|
||||
@@ -1724,61 +1223,6 @@ 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(
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { ChevronDownIcon, GitPullRequestIcon, InfoIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Option from "effect/Option";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import type {
|
||||
BackgroundActivitySettings,
|
||||
SourceControlProviderKind,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlProviderAuth,
|
||||
@@ -11,11 +10,7 @@ import type {
|
||||
VcsDriverKind,
|
||||
VcsDiscoveryItem,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
@@ -75,11 +70,6 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
|
||||
|
||||
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
const GIT_FETCH_INTERVAL_STEP_SECONDS = 5;
|
||||
type BackgroundActivityOverridePatch = Partial<{
|
||||
[K in keyof BackgroundActivitySettings["overrides"]]:
|
||||
| BackgroundActivitySettings["overrides"][K]
|
||||
| undefined;
|
||||
}>;
|
||||
|
||||
function durationToSeconds(duration: Duration.Duration): number {
|
||||
return Math.round(Duration.toMillis(duration) / 1_000);
|
||||
@@ -92,27 +82,6 @@ function normalizeFetchIntervalSeconds(value: number | null): number {
|
||||
return Math.max(0, Math.round(value));
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
function optionLabel(value: Option.Option<string>): string | null {
|
||||
return Option.getOrNull(value);
|
||||
}
|
||||
@@ -322,41 +291,14 @@ function DiscoveryItemRow({
|
||||
}
|
||||
|
||||
function GitFetchIntervalSettings() {
|
||||
const settings = useSettings();
|
||||
const automaticGitFetchInterval = useSettings((settings) => settings.automaticGitFetchInterval);
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
);
|
||||
const automaticGitFetchIntervalSeconds = durationToSeconds(automaticGitFetchInterval);
|
||||
const defaultAutomaticGitFetchIntervalSeconds = durationToSeconds(
|
||||
getBackgroundActivityPresetSettings(
|
||||
getBackgroundActivityBaseProfile(settings.backgroundActivity),
|
||||
).automaticGitFetchInterval,
|
||||
DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
);
|
||||
const canResetFetchInterval =
|
||||
automaticGitFetchIntervalSeconds !== defaultAutomaticGitFetchIntervalSeconds;
|
||||
const 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"],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
@@ -364,11 +306,6 @@ 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",
|
||||
@@ -380,11 +317,9 @@ function GitFetchIntervalSettings() {
|
||||
<SettingResetButton
|
||||
label="fetch interval"
|
||||
onClick={() =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: undefined,
|
||||
}),
|
||||
)
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
@@ -403,11 +338,9 @@ function GitFetchIntervalSettings() {
|
||||
size="sm"
|
||||
className="w-32"
|
||||
onValueChange={(value) =>
|
||||
updateSettings(
|
||||
backgroundActivityOverrideSettings(settings.backgroundActivity, {
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
}),
|
||||
)
|
||||
updateSettings({
|
||||
automaticGitFetchInterval: Duration.seconds(normalizeFetchIntervalSeconds(value)),
|
||||
})
|
||||
}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
|
||||
@@ -73,7 +73,6 @@ import {
|
||||
derivePhysicalProjectKey,
|
||||
} from "../../logicalProject";
|
||||
import { getClientSettings } from "~/hooks/useSettings";
|
||||
import { startBackgroundActivityReporter } from "~/lib/backgroundActivityReporter";
|
||||
|
||||
type EnvironmentServiceState = {
|
||||
readonly queryClient: QueryClient;
|
||||
@@ -1787,10 +1786,6 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
.catch(() => undefined);
|
||||
|
||||
const unsubscribeBrowserResumeReconnects = subscribeBrowserResumeReconnects();
|
||||
const stopBackgroundActivityReporter = startBackgroundActivityReporter({
|
||||
getConnections: listEnvironmentConnections,
|
||||
subscribeConnections: subscribeEnvironmentConnections,
|
||||
});
|
||||
|
||||
activeService = {
|
||||
queryClient,
|
||||
@@ -1799,7 +1794,6 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
|
||||
stop: () => {
|
||||
unsubscribeSavedEnvironments();
|
||||
unsubscribeBrowserResumeReconnects();
|
||||
stopBackgroundActivityReporter();
|
||||
queryInvalidationThrottler.cancel();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
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]);
|
||||
});
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -22,7 +22,6 @@ 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]";
|
||||
|
||||
@@ -31,13 +30,6 @@ 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) {
|
||||
@@ -151,10 +143,6 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
};
|
||||
}
|
||||
|
||||
function enqueueServerSettingsUpdate(serverPatch: ServerSettingsPatch): void {
|
||||
serverSettingsWriteQueue.enqueue(serverPatch);
|
||||
}
|
||||
|
||||
// ── Hooks ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -213,7 +201,8 @@ export function useUpdateSettings() {
|
||||
if (currentServerConfig) {
|
||||
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
|
||||
}
|
||||
enqueueServerSettingsUpdate(serverPatch);
|
||||
// Fire-and-forget RPC — push will reconcile on success
|
||||
void ensureLocalApi().server.updateSettings(serverPatch);
|
||||
}
|
||||
|
||||
if (Object.keys(clientPatch).length > 0) {
|
||||
@@ -238,7 +227,6 @@ export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationPromise = null;
|
||||
serverSettingsWriteQueue.reset();
|
||||
clientSettingsListeners.clear();
|
||||
clientSettingsHydrationListeners.clear();
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
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,7 +14,6 @@ import {
|
||||
subscribeEnvironmentConnections,
|
||||
} from "../environments/runtime";
|
||||
import type { WsRpcClient } from "~/rpc/wsRpcClient";
|
||||
import { retainBackgroundScope } from "./backgroundActivityReporter";
|
||||
|
||||
interface GitStatusState {
|
||||
readonly data: VcsStatusResult | null;
|
||||
@@ -203,7 +202,6 @@ 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
|
||||
@@ -238,7 +236,6 @@ function subscribeToGitStatusTarget(
|
||||
syncClientSubscription();
|
||||
|
||||
return () => {
|
||||
releaseScope();
|
||||
unsubscribeRegistry();
|
||||
currentUnsubscribe();
|
||||
};
|
||||
|
||||
@@ -139,15 +139,9 @@ export interface WsRpcClient {
|
||||
typeof WS_METHODS.serverGetProcessResourceHistory
|
||||
>;
|
||||
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>;
|
||||
@@ -285,12 +279,6 @@ 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,
|
||||
@@ -306,15 +294,6 @@ 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) =>
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
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,8 +43,6 @@ 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;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export * from "./baseSchemas.ts";
|
||||
export * from "./background.ts";
|
||||
export * from "./auth.ts";
|
||||
export * from "./environment.ts";
|
||||
export * from "./desktopBootstrap.ts";
|
||||
|
||||
@@ -4,11 +4,6 @@ import * as RpcGroup from "effect/unstable/rpc/RpcGroup";
|
||||
|
||||
import { ExternalLauncherError, LaunchEditorInput } from "./editor.ts";
|
||||
import { AuthAccessStreamEvent } from "./auth.ts";
|
||||
import {
|
||||
BackgroundPolicySnapshot,
|
||||
ClientActivityReportInput,
|
||||
HostPowerSnapshot,
|
||||
} from "./background.ts";
|
||||
import {
|
||||
FilesystemBrowseInput,
|
||||
FilesystemBrowseResult,
|
||||
@@ -154,9 +149,6 @@ export const WS_METHODS = {
|
||||
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
|
||||
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
|
||||
serverSignalProcess: "server.signalProcess",
|
||||
serverReportClientActivity: "server.reportClientActivity",
|
||||
serverReportHostPowerState: "server.reportHostPowerState",
|
||||
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
|
||||
|
||||
// Source control methods
|
||||
sourceControlLookupRepository: "sourceControl.lookupRepository",
|
||||
@@ -169,7 +161,6 @@ export const WS_METHODS = {
|
||||
subscribeServerConfig: "subscribeServerConfig",
|
||||
subscribeServerLifecycle: "subscribeServerLifecycle",
|
||||
subscribeAuthAccess: "subscribeAuthAccess",
|
||||
subscribeBackgroundPolicy: "subscribeBackgroundPolicy",
|
||||
} as const;
|
||||
|
||||
export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {
|
||||
@@ -249,19 +240,6 @@ 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,
|
||||
{
|
||||
@@ -494,12 +472,6 @@ 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,
|
||||
@@ -513,9 +485,6 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetProcessDiagnosticsRpc,
|
||||
WsServerGetProcessResourceHistoryRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsServerReportClientActivityRpc,
|
||||
WsServerReportHostPowerStateRpc,
|
||||
WsServerGetBackgroundPolicyRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
WsSourceControlPublishRepositoryRpc,
|
||||
@@ -545,7 +514,6 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeServerConfigRpc,
|
||||
WsSubscribeServerLifecycleRpc,
|
||||
WsSubscribeAuthAccessRpc,
|
||||
WsSubscribeBackgroundPolicyRpc,
|
||||
WsOrchestrationDispatchCommandRpc,
|
||||
WsOrchestrationGetTurnDiffRpc,
|
||||
WsOrchestrationGetFullThreadDiffRpc,
|
||||
|
||||
@@ -338,65 +338,14 @@ 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)),
|
||||
),
|
||||
@@ -499,17 +448,7 @@ 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),
|
||||
|
||||
@@ -63,10 +63,6 @@
|
||||
"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"
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
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,9 +3,7 @@ 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,
|
||||
@@ -196,80 +194,4 @@ 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: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,6 @@ import * as Schema from "effect/Schema";
|
||||
import { deepMerge } from "./Struct.ts";
|
||||
import { fromLenientJson } from "./schemaJson.ts";
|
||||
import { createModelSelection } from "./model.ts";
|
||||
import {
|
||||
getBackgroundActivityBaseProfile,
|
||||
normalizeBackgroundActivitySettings,
|
||||
resolveBackgroundActivitySettings,
|
||||
} from "./backgroundActivitySettings.ts";
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
|
||||
@@ -81,61 +76,14 @@ export function applyServerSettingsPatch(
|
||||
patch: ServerSettingsPatch,
|
||||
): ServerSettings {
|
||||
const selectionPatch = patch.textGenerationModelSelection;
|
||||
const {
|
||||
automaticGitFetchInterval,
|
||||
providerHealthRefreshInterval,
|
||||
backgroundActivityProfile,
|
||||
backgroundActivity,
|
||||
...patchForMerge
|
||||
} = patch;
|
||||
const backgroundActivityPatch =
|
||||
backgroundActivityProfile !== undefined
|
||||
? {
|
||||
schemaVersion: 1 as const,
|
||||
profile: backgroundActivityProfile,
|
||||
overrides: {},
|
||||
}
|
||||
: automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
|
||||
? {
|
||||
schemaVersion: 1 as const,
|
||||
profile: "custom" as const,
|
||||
baseProfile: getBackgroundActivityBaseProfile(current.backgroundActivity),
|
||||
overrides: {
|
||||
...current.backgroundActivity.overrides,
|
||||
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
|
||||
...(providerHealthRefreshInterval !== undefined
|
||||
? { providerHealthRefreshInterval }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: undefined;
|
||||
const { automaticGitFetchInterval, ...patchForMerge } = patch;
|
||||
const next = deepMerge(current, patchForMerge);
|
||||
const nextWithReplacementsBase = {
|
||||
const nextWithReplacements = {
|
||||
...next,
|
||||
...(backgroundActivity !== undefined
|
||||
? { backgroundActivity: deepMerge(current.backgroundActivity, backgroundActivity) }
|
||||
: {}),
|
||||
...(backgroundActivityPatch !== undefined
|
||||
? { backgroundActivity: backgroundActivityPatch }
|
||||
: {}),
|
||||
...(patch.providerInstances !== undefined
|
||||
? { providerInstances: patch.providerInstances }
|
||||
: {}),
|
||||
...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
|
||||
...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
|
||||
};
|
||||
const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
|
||||
nextWithReplacementsBase.backgroundActivity,
|
||||
);
|
||||
const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
|
||||
normalizedBackgroundActivity,
|
||||
);
|
||||
const nextWithReplacements = {
|
||||
...nextWithReplacementsBase,
|
||||
backgroundActivity: normalizedBackgroundActivity,
|
||||
automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
|
||||
providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
|
||||
backgroundActivityProfile: resolvedBackgroundActivity.profile,
|
||||
};
|
||||
if (!selectionPatch) {
|
||||
return nextWithReplacements;
|
||||
|
||||
Reference in new issue
Block a user