Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f168ed1885 | ||
|
|
d40b758c4f | ||
|
|
bfd9e2c3b3 | ||
|
|
2b89c4b85d | ||
|
|
1ef83c8595 | ||
|
|
f5b4f51023 | ||
|
|
a6c922200e |
No files matched your search
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 295 KiB |
|
After Width: | Height: | Size: 310 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
@@ -63,7 +63,6 @@ export interface AuthenticatedSession {
|
||||
readonly subject: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly proofKeyThumbprint?: string;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
}
|
||||
@@ -584,7 +583,6 @@ export const make = Effect.gen(function* () {
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
scopes: session.scopes,
|
||||
client: session.client,
|
||||
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
@@ -952,7 +950,6 @@ export const make = Effect.gen(function* () {
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
scopes: session.scopes,
|
||||
client: session.client,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
mapSessionVerificationErrors,
|
||||
|
||||
@@ -100,7 +100,6 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,
|
||||
[WS_METHODS.subscribeBackgroundPolicy]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.clientReportDesktopFocus]: AuthOrchestrationReadScope,
|
||||
} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;
|
||||
|
||||
export function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as FocusedDesktopClients from "./FocusedDesktopClients.ts";
|
||||
|
||||
describe("FocusedDesktopClients", () => {
|
||||
it.effect("stays focused until the last scoped desktop lease is released", () =>
|
||||
Effect.gen(function* () {
|
||||
const presence = yield* FocusedDesktopClients.FocusedDesktopClients;
|
||||
expect(yield* presence.anyFocused).toBe(false);
|
||||
|
||||
const first = yield* Scope.make();
|
||||
const second = yield* Scope.make();
|
||||
yield* presence.acquire.pipe(Scope.provide(first));
|
||||
yield* presence.acquire.pipe(Scope.provide(second));
|
||||
expect(yield* presence.anyFocused).toBe(true);
|
||||
|
||||
yield* Scope.close(first, Exit.void);
|
||||
expect(yield* presence.anyFocused).toBe(true);
|
||||
|
||||
yield* Scope.close(second, Exit.void);
|
||||
expect(yield* presence.anyFocused).toBe(false);
|
||||
}).pipe(Effect.provide(FocusedDesktopClients.layer)),
|
||||
);
|
||||
|
||||
it.effect("emits only aggregate focus transitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const presence = yield* FocusedDesktopClients.FocusedDesktopClients;
|
||||
const observed: boolean[] = [];
|
||||
const observer = yield* presence.changes.pipe(
|
||||
Stream.take(3),
|
||||
Stream.runForEach((focused) =>
|
||||
Effect.sync(() => {
|
||||
observed.push(focused);
|
||||
}),
|
||||
),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
|
||||
const first = yield* Scope.make();
|
||||
const second = yield* Scope.make();
|
||||
yield* presence.acquire.pipe(Scope.provide(first));
|
||||
yield* presence.acquire.pipe(Scope.provide(second));
|
||||
yield* Scope.close(first, Exit.void);
|
||||
yield* Scope.close(second, Exit.void);
|
||||
yield* Fiber.join(observer);
|
||||
|
||||
expect(observed).toEqual([false, true, false]);
|
||||
}).pipe(Effect.provide(FocusedDesktopClients.layer)),
|
||||
);
|
||||
|
||||
it.effect("holds a focus lease for the full lifetime of the RPC stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const presence = yield* FocusedDesktopClients.FocusedDesktopClients;
|
||||
const stream = yield* FocusedDesktopClients.holdFocusLease(presence).pipe(
|
||||
Stream.runDrain,
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
|
||||
for (let iteration = 0; iteration < 100 && !(yield* presence.anyFocused); iteration++) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* presence.anyFocused).toBe(true);
|
||||
|
||||
yield* Fiber.interrupt(stream);
|
||||
expect(yield* presence.anyFocused).toBe(false);
|
||||
}).pipe(Effect.provide(FocusedDesktopClients.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
|
||||
export class FocusedDesktopClients extends Context.Reference<{
|
||||
/** True while at least one authenticated desktop focus stream is alive. */
|
||||
readonly anyFocused: Effect.Effect<boolean>;
|
||||
/** Current focus state followed by transitions of the aggregate state. */
|
||||
readonly changes: Stream.Stream<boolean>;
|
||||
/** A scope-bound lease held by one focused desktop WebSocket stream. */
|
||||
readonly acquire: Effect.Effect<void, never, Scope.Scope>;
|
||||
}>("t3/presence/FocusedDesktopClients", {
|
||||
defaultValue: () => ({
|
||||
anyFocused: Effect.succeed(false),
|
||||
changes: Stream.empty,
|
||||
acquire: Effect.void,
|
||||
}),
|
||||
}) {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const focusedCount = yield* SubscriptionRef.make(0);
|
||||
const anyFocused = SubscriptionRef.get(focusedCount).pipe(Effect.map((count) => count > 0));
|
||||
const changes = SubscriptionRef.changes(focusedCount).pipe(
|
||||
Stream.map((count) => count > 0),
|
||||
Stream.changes,
|
||||
);
|
||||
const acquire = Effect.acquireRelease(
|
||||
SubscriptionRef.update(focusedCount, (count) => count + 1),
|
||||
() => SubscriptionRef.update(focusedCount, (count) => Math.max(0, count - 1)),
|
||||
);
|
||||
|
||||
return FocusedDesktopClients.of({
|
||||
anyFocused,
|
||||
changes,
|
||||
acquire,
|
||||
});
|
||||
});
|
||||
|
||||
export function holdFocusLease(presence: {
|
||||
readonly acquire: Effect.Effect<void, never, Scope.Scope>;
|
||||
}): Stream.Stream<never> {
|
||||
return Stream.fromEffect(presence.acquire).pipe(
|
||||
Stream.drain,
|
||||
Stream.concat(Stream.never),
|
||||
Stream.scoped,
|
||||
);
|
||||
}
|
||||
|
||||
export const layer = Layer.effect(FocusedDesktopClients, make);
|
||||
@@ -22,18 +22,14 @@ import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/rela
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as FocusedDesktopClients from "../presence/FocusedDesktopClients.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
@@ -248,34 +244,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
).toHaveLength(160);
|
||||
});
|
||||
|
||||
it("restores only non-terminal activity after desktop focus ends", () => {
|
||||
expect(
|
||||
AgentAwarenessRelay.isAgentAwarenessResumableAfterDesktopFocus({
|
||||
...state,
|
||||
phase: "running",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
AgentAwarenessRelay.isAgentAwarenessResumableAfterDesktopFocus({
|
||||
...state,
|
||||
phase: "waiting_for_approval",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
AgentAwarenessRelay.isAgentAwarenessResumableAfterDesktopFocus({
|
||||
...state,
|
||||
phase: "completed",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.isAgentAwarenessResumableAfterDesktopFocus({
|
||||
...state,
|
||||
phase: "failed",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(AgentAwarenessRelay.isAgentAwarenessResumableAfterDesktopFocus(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("resolves a null publish state when a thread or project snapshot disappeared", () => {
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
@@ -443,214 +411,6 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it.effect("does not inspect or publish thread activity while a desktop client is focused", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let fetchCount = 0;
|
||||
let snapshotReadCount = 0;
|
||||
const secrets = makeMemorySecretStore();
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const descriptor = {
|
||||
environmentId,
|
||||
label: "Test Desktop",
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
} satisfies ExecutionEnvironmentDescriptor;
|
||||
|
||||
globalThis.fetch = (() => {
|
||||
fetchCount += 1;
|
||||
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
|
||||
}) as unknown as typeof fetch;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}),
|
||||
);
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
|
||||
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
|
||||
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
|
||||
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
|
||||
Layer.succeed(ServerEnvironment.ServerEnvironment, {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
}),
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getThreadShellById: () =>
|
||||
Effect.sync(() => {
|
||||
snapshotReadCount += 1;
|
||||
return Option.none();
|
||||
}),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
Layer.succeed(
|
||||
FocusedDesktopClients.FocusedDesktopClients,
|
||||
FocusedDesktopClients.FocusedDesktopClients.of({
|
||||
anyFocused: Effect.succeed(true),
|
||||
changes: Stream.empty,
|
||||
acquire: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
yield* relay.publishThread(threadId);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
Layer.provide(dependencies),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(snapshotReadCount).toBe(0);
|
||||
expect(fetchCount).toBe(0);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rechecks desktop focus immediately before publishing agent activity", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let fetchCount = 0;
|
||||
let focusReadCount = 0;
|
||||
let snapshotReadCount = 0;
|
||||
const secrets = makeMemorySecretStore();
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
const projectId = "project-1" as ProjectId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/workspace",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationProjectShell;
|
||||
const thread = {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Run remote agent",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: "turn-1" as TurnId,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
latestUserMessageAt: now,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} satisfies OrchestrationThreadShell;
|
||||
const descriptor = {
|
||||
environmentId,
|
||||
label: "Test Desktop",
|
||||
platform: { os: "darwin", arch: "arm64" },
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: { repositoryIdentity: true },
|
||||
} satisfies ExecutionEnvironmentDescriptor;
|
||||
|
||||
globalThis.fetch = (() => {
|
||||
fetchCount += 1;
|
||||
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
|
||||
}) as unknown as typeof fetch;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}),
|
||||
);
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
|
||||
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
|
||||
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
|
||||
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
|
||||
Layer.succeed(ServerEnvironment.ServerEnvironment, {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
}),
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getThreadShellById: () =>
|
||||
Effect.sync(() => {
|
||||
snapshotReadCount += 1;
|
||||
return Option.some(thread);
|
||||
}),
|
||||
getProjectShellById: () => Effect.succeed(Option.some(project)),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
Layer.succeed(
|
||||
FocusedDesktopClients.FocusedDesktopClients,
|
||||
FocusedDesktopClients.FocusedDesktopClients.of({
|
||||
anyFocused: Effect.sync(() => {
|
||||
focusReadCount += 1;
|
||||
return focusReadCount > 1;
|
||||
}),
|
||||
changes: Stream.empty,
|
||||
acquire: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
yield* relay.publishThread(threadId);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
Layer.provide(dependencies),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(focusReadCount).toBe(2);
|
||||
expect(snapshotReadCount).toBe(1);
|
||||
expect(fetchCount).toBe(0);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps the orchestration listener armed until relay config is installed", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -792,18 +552,14 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("publishes to the relay transport and clears activity when desktop focus arrives", () =>
|
||||
it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const context = yield* Effect.context<never>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const events = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
const missingRelayCredentialRead = yield* Deferred.make<void>();
|
||||
const fetches = yield* Queue.unbounded<{
|
||||
readonly url: URL;
|
||||
readonly state: RelayAgentActivityState | null;
|
||||
}>();
|
||||
const fetchSeen = yield* Deferred.make<URL>();
|
||||
const userSpans: Array<string> = [];
|
||||
const productSpans: Array<string> = [];
|
||||
const collectingTracer = (spans: Array<string>) =>
|
||||
@@ -884,48 +640,16 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
} satisfies ExecutionEnvironmentDescriptor;
|
||||
let snapshotThreads: Array<OrchestrationThreadShell> = [thread];
|
||||
const focusedDesktopClients = yield* FocusedDesktopClients.make;
|
||||
const observedSecretStore = ServerSecretStore.ServerSecretStore.of({
|
||||
...secrets.store,
|
||||
get: (name) =>
|
||||
secrets.store
|
||||
.get(name)
|
||||
.pipe(
|
||||
Effect.tap((value) =>
|
||||
name === RELAY_ENVIRONMENT_CREDENTIAL_SECRET && Option.isNone(value)
|
||||
? Deferred.succeed(missingRelayCredentialRead, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
let tombstoneAttempts = 0;
|
||||
globalThis.fetch = (async (
|
||||
input: Parameters<typeof fetch>[0],
|
||||
init?: Parameters<typeof fetch>[1],
|
||||
) => {
|
||||
globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
|
||||
const url = new URL(
|
||||
typeof input === "string" || input instanceof URL
|
||||
? input
|
||||
: (input as unknown as { readonly url: string }).url,
|
||||
);
|
||||
const request =
|
||||
input instanceof Request
|
||||
? input
|
||||
: new Request(typeof input === "string" ? input : input.toString(), init);
|
||||
const payload = (await request.json()) as {
|
||||
readonly state: RelayAgentActivityState | null;
|
||||
};
|
||||
if (payload.state === null) {
|
||||
tombstoneAttempts += 1;
|
||||
if (tombstoneAttempts === 1) {
|
||||
throw new Error("transient tombstone publish failure");
|
||||
}
|
||||
}
|
||||
runFork(Queue.offer(fetches, { url, state: payload.state }));
|
||||
return Response.json({ ok: true, deliveries: [] });
|
||||
}) as typeof fetch;
|
||||
runFork(Deferred.succeed(fetchSeen, url));
|
||||
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
|
||||
}) as unknown as typeof fetch;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
@@ -933,7 +657,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
);
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, observedSecretStore),
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
|
||||
Layer.succeed(ServerEnvironment.ServerEnvironment, {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
@@ -949,13 +673,12 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
Effect.succeed({
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: snapshotThreads,
|
||||
threads: [thread],
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationShellSnapshot),
|
||||
getThreadShellById: () => Effect.succeed(Option.some(thread)),
|
||||
getProjectShellById: () => Effect.succeed(Option.some(project)),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
Layer.succeed(FocusedDesktopClients.FocusedDesktopClients, focusedDesktopClients),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -982,35 +705,10 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent);
|
||||
|
||||
const firstPublish = yield* Queue.take(fetches).pipe(Effect.timeout("2 seconds"));
|
||||
expect(firstPublish.url.origin).toBe("https://transport.example.test");
|
||||
expect(firstPublish.state?.phase).toBe("running");
|
||||
const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds"));
|
||||
expect(url.origin).toBe("https://transport.example.test");
|
||||
expect(productSpans).toContain("makePublishProof");
|
||||
expect(userSpans).not.toContain("makePublishProof");
|
||||
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* secrets.store.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
|
||||
const desktopFocusScope = yield* Scope.make();
|
||||
yield* focusedDesktopClients.acquire.pipe(Scope.provide(desktopFocusScope));
|
||||
yield* Deferred.await(missingRelayCredentialRead).pipe(Effect.timeout("2 seconds"));
|
||||
yield* secrets.setString(
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
"relay-credential-restored",
|
||||
);
|
||||
for (let iteration = 0; iteration < 10; iteration++) {
|
||||
if (tombstoneAttempts >= 2) {
|
||||
break;
|
||||
}
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const focusedPublish = yield* Queue.take(fetches).pipe(Effect.timeout("2 seconds"));
|
||||
expect(focusedPublish.url.origin).toBe("https://transport.example.test");
|
||||
expect(focusedPublish.state).toBeNull();
|
||||
expect(tombstoneAttempts).toBe(2);
|
||||
|
||||
snapshotThreads = [];
|
||||
yield* Scope.close(desktopFocusScope, Exit.void);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
|
||||
@@ -26,7 +26,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
|
||||
@@ -45,7 +44,6 @@ import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environme
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as FocusedDesktopClients from "../presence/FocusedDesktopClients.ts";
|
||||
|
||||
export class AgentAwarenessRelay extends Context.Service<
|
||||
AgentAwarenessRelay,
|
||||
@@ -291,23 +289,15 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: {
|
||||
.map((thread) => thread.id);
|
||||
}
|
||||
|
||||
export function isAgentAwarenessResumableAfterDesktopFocus(
|
||||
state: RelayAgentActivityState | null,
|
||||
): boolean {
|
||||
return state !== null && state.phase !== "completed" && state.phase !== "failed";
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const focusedDesktopClients = yield* FocusedDesktopClients.FocusedDesktopClients;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
|
||||
const activeSnapshotPublishedRef = yield* Ref.make(false);
|
||||
const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
|
||||
const publishSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const readSecretString = (name: string) =>
|
||||
secrets
|
||||
@@ -350,20 +340,7 @@ export const make = Effect.gen(function* () {
|
||||
const publishConfirmDeadlines = new Map<ThreadId, number>();
|
||||
let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
|
||||
|
||||
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (
|
||||
threadId: ThreadId,
|
||||
options?: { readonly desktopFocusTombstone?: boolean },
|
||||
) {
|
||||
const desktopFocusTombstone = options?.desktopFocusTombstone === true;
|
||||
if ((yield* focusedDesktopClients.anyFocused) !== desktopFocusTombstone) {
|
||||
yield* Effect.logDebug(
|
||||
desktopFocusTombstone
|
||||
? "desktop focus tombstone skipped; desktop is no longer focused"
|
||||
: "agent activity publish skipped; desktop client focused",
|
||||
{ threadId },
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
|
||||
const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
@@ -371,14 +348,14 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.logDebug("agent activity publish skipped; publication disabled", {
|
||||
threadId,
|
||||
});
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!relayConfig) {
|
||||
yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {
|
||||
threadId,
|
||||
});
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
const relayClient = yield* makeRelayClient(relayConfig);
|
||||
const environmentId = yield* serverEnvironment.getEnvironmentId;
|
||||
@@ -389,15 +366,6 @@ export const make = Effect.gen(function* () {
|
||||
readonly reason: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* focusedDesktopClients.anyFocused) !== desktopFocusTombstone) {
|
||||
yield* Effect.logDebug(
|
||||
desktopFocusTombstone
|
||||
? "desktop focus tombstone skipped; focus ended during publish preparation"
|
||||
: "agent activity publish skipped; desktop client focused during publish",
|
||||
{ threadId },
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const proof = yield* makePublishProof({
|
||||
privateKey: cloudLinkKeyPair.privateKey,
|
||||
relayIssuer: relayConfig.issuer,
|
||||
@@ -433,28 +401,8 @@ export const make = Effect.gen(function* () {
|
||||
ok: response.ok,
|
||||
deliveries: deliveryStats(response.deliveries),
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
if (desktopFocusTombstone) {
|
||||
const publishIdentity = agentAwarenessPublishIdentity(null);
|
||||
publishConfirmDeadlines.delete(threadId);
|
||||
const published = yield* publishState({
|
||||
projectId: null,
|
||||
state: null,
|
||||
reason: "desktop-focused",
|
||||
});
|
||||
if (!published) {
|
||||
return false;
|
||||
}
|
||||
yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
|
||||
const nextPublishedStates = new Map(publishedStates);
|
||||
nextPublishedStates.set(threadId, publishIdentity);
|
||||
return nextPublishedStates;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const thread = yield* snapshotQuery.getThreadShellById(threadId);
|
||||
const project = Option.isSome(thread)
|
||||
? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
|
||||
@@ -478,7 +426,7 @@ export const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
reason: snapshot.reason,
|
||||
});
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Two projections need confirmation before publishing, because both can
|
||||
@@ -508,10 +456,10 @@ export const make = Effect.gen(function* () {
|
||||
shell: describeThreadShellForAwareness(thread),
|
||||
});
|
||||
yield* schedulePublishConfirm(threadId);
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
if (nowMs < deadline) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
publishConfirmDeadlines.delete(threadId);
|
||||
yield* Effect.logInfo("agent activity deferred publish confirmed", {
|
||||
@@ -538,137 +486,30 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const published = yield* publishState({
|
||||
yield* publishState({
|
||||
projectId: snapshot.projectId,
|
||||
state: snapshot.state,
|
||||
reason: snapshot.reason,
|
||||
});
|
||||
if (!published) {
|
||||
return false;
|
||||
}
|
||||
yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
|
||||
const nextPublishedStates = new Map(publishedStates);
|
||||
nextPublishedStates.set(threadId, publishIdentity);
|
||||
return nextPublishedStates;
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
|
||||
publishSemaphore
|
||||
.withPermits(1)(publishThreadUnsafe(threadId))
|
||||
.pipe(
|
||||
Effect.asVoid,
|
||||
Effect.catchCause((cause) => {
|
||||
return Effect.logWarning("agent activity publish failed", {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
Effect.withSpan("AgentAwarenessRelay.publishThread"),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
|
||||
const resolveSnapshotThreadIds = Effect.fn("resolveSnapshotThreadIds")(function* (input: {
|
||||
readonly resumableOnly: boolean;
|
||||
}) {
|
||||
const environmentId = yield* serverEnvironment.getEnvironmentId;
|
||||
const snapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
if (!input.resumableOnly) {
|
||||
return resolveAgentAwarenessRelayActiveThreadIds({
|
||||
environmentId,
|
||||
projects: snapshot.projects,
|
||||
threads: snapshot.threads,
|
||||
});
|
||||
}
|
||||
const projectById = new Map(snapshot.projects.map((project) => [project.id, project]));
|
||||
return snapshot.threads.flatMap((thread) => {
|
||||
const project = projectById.get(thread.projectId);
|
||||
if (!project) {
|
||||
return [];
|
||||
}
|
||||
const state = sanitizeRelayAgentActivityState(
|
||||
projectThreadAwareness({
|
||||
environmentId,
|
||||
project,
|
||||
thread,
|
||||
}),
|
||||
);
|
||||
return isAgentAwarenessResumableAfterDesktopFocus(state) ? [thread.id] : [];
|
||||
});
|
||||
});
|
||||
|
||||
let scheduleDesktopFocusTombstoneRetry: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<void, never, Scope.Scope> = () => Effect.void;
|
||||
|
||||
const publishDesktopFocusTombstone = Effect.fn("publishDesktopFocusTombstone")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const published = yield* publishSemaphore
|
||||
.withPermits(1)(
|
||||
publishThreadUnsafe(threadId, {
|
||||
desktopFocusTombstone: true,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("desktop focus agent activity tombstone failed; retrying", {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(false)),
|
||||
),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
if (!published && (yield* focusedDesktopClients.anyFocused)) {
|
||||
yield* scheduleDesktopFocusTombstoneRetry(threadId);
|
||||
}
|
||||
});
|
||||
|
||||
scheduleDesktopFocusTombstoneRetry = (threadId) =>
|
||||
Effect.sleep("1 second").pipe(
|
||||
Effect.andThen(publishDesktopFocusTombstone(threadId)),
|
||||
Effect.forkScoped,
|
||||
Effect.asVoid,
|
||||
publishThreadUnsafe(threadId).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
return Effect.logWarning("agent activity publish failed", {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
Effect.withSpan("AgentAwarenessRelay.publishThread"),
|
||||
withRelayClientTracing,
|
||||
);
|
||||
|
||||
const suppressMobileAgentAwareness = Effect.fn("suppressMobileAgentAwareness")(function* (
|
||||
snapshotThreadIds?: ReadonlyArray<ThreadId>,
|
||||
) {
|
||||
const projectedThreadIds =
|
||||
snapshotThreadIds ?? (yield* resolveSnapshotThreadIds({ resumableOnly: false }));
|
||||
const publishedStates = yield* Ref.get(publishedStateByThreadRef);
|
||||
const threadIds = new Set(projectedThreadIds);
|
||||
for (const [threadId, identity] of publishedStates) {
|
||||
if (identity !== agentAwarenessPublishIdentity(null)) {
|
||||
threadIds.add(threadId);
|
||||
}
|
||||
}
|
||||
if (threadIds.size === 0) {
|
||||
yield* Effect.logDebug("desktop focus suppression has no mobile agent activity to clear");
|
||||
return;
|
||||
}
|
||||
yield* Effect.logInfo("desktop client focused; clearing mobile agent awareness", {
|
||||
count: threadIds.size,
|
||||
});
|
||||
yield* Effect.forEach(threadIds, publishDesktopFocusTombstone, {
|
||||
concurrency: 4,
|
||||
discard: true,
|
||||
});
|
||||
});
|
||||
|
||||
const resumeMobileAgentAwareness = Effect.fn("resumeMobileAgentAwareness")(function* () {
|
||||
const threadIds = yield* resolveSnapshotThreadIds({ resumableOnly: true });
|
||||
if (threadIds.length === 0) {
|
||||
yield* Effect.logDebug("desktop focus ended; no active mobile agent awareness to restore");
|
||||
return;
|
||||
}
|
||||
yield* Effect.logInfo("desktop focus ended; restoring active mobile agent awareness", {
|
||||
count: threadIds.length,
|
||||
});
|
||||
yield* Effect.forEach(threadIds, publishThread, { discard: true });
|
||||
});
|
||||
|
||||
const publishActiveThreadsUnsafe = Effect.gen(function* () {
|
||||
const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
@@ -689,10 +530,6 @@ export const make = Effect.gen(function* () {
|
||||
projects: snapshot.projects,
|
||||
threads: snapshot.threads,
|
||||
});
|
||||
if (yield* focusedDesktopClients.anyFocused) {
|
||||
yield* suppressMobileAgentAwareness(activeThreadIds);
|
||||
return true;
|
||||
}
|
||||
if (activeThreadIds.length === 0) {
|
||||
yield* Effect.logDebug("agent activity snapshot has no publishable threads");
|
||||
return true;
|
||||
@@ -790,14 +627,6 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.andThen(worker.enqueue(threadId)));
|
||||
}),
|
||||
);
|
||||
yield* Effect.forkScoped(
|
||||
focusedDesktopClients.changes.pipe(
|
||||
Stream.drop(1),
|
||||
Stream.runForEach((focused) =>
|
||||
focused ? suppressMobileAgentAwareness() : resumeMobileAgentAwareness(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -99,7 +99,6 @@ import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClien
|
||||
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
|
||||
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as FocusedDesktopClients from "./presence/FocusedDesktopClients.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
@@ -342,7 +341,7 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(ServerSettingsLayerLive),
|
||||
Layer.provideMerge(Layer.mergeAll(FocusedDesktopClients.layer, CheckpointingLayerLive)),
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(VcsLayerLive),
|
||||
|
||||
@@ -118,7 +118,6 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
|
||||
import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import * as FocusedDesktopClients from "./presence/FocusedDesktopClients.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
@@ -402,7 +401,6 @@ const makeWsRpcLayer = (
|
||||
yield* SourceControlRepositoryService.SourceControlRepositoryService;
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const focusedDesktopClients = yield* FocusedDesktopClients.FocusedDesktopClients;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
|
||||
const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
@@ -1013,14 +1011,6 @@ const makeWsRpcLayer = (
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
|
||||
|
||||
return WsRpcGroup.of({
|
||||
[WS_METHODS.clientReportDesktopFocus]: (_input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.clientReportDesktopFocus,
|
||||
currentSession.client.deviceType === "desktop"
|
||||
? FocusedDesktopClients.holdFocusLease(focusedDesktopClients)
|
||||
: Stream.empty,
|
||||
{ "rpc.aggregate": "client-presence" },
|
||||
),
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isDesktopClientFocused } from "./desktopFocus";
|
||||
|
||||
describe("isDesktopClientFocused", () => {
|
||||
it("requires the T3 Code document to be both visible and focused", () => {
|
||||
expect(isDesktopClientFocused({ visibilityState: "visible", hasFocus: true })).toBe(true);
|
||||
expect(isDesktopClientFocused({ visibilityState: "visible", hasFocus: false })).toBe(false);
|
||||
expect(isDesktopClientFocused({ visibilityState: "hidden", hasFocus: true })).toBe(false);
|
||||
expect(isDesktopClientFocused({ visibilityState: "hidden", hasFocus: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
export interface DesktopFocusSnapshot {
|
||||
readonly visibilityState: DocumentVisibilityState;
|
||||
readonly hasFocus: boolean;
|
||||
}
|
||||
|
||||
export function isDesktopClientFocused(snapshot: DesktopFocusSnapshot): boolean {
|
||||
return snapshot.visibilityState === "visible" && snapshot.hasFocus;
|
||||
}
|
||||
|
||||
function readDesktopFocus(documentTarget: Document): boolean {
|
||||
return isDesktopClientFocused({
|
||||
visibilityState: documentTarget.visibilityState,
|
||||
hasFocus: documentTarget.hasFocus(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports an initial value and every browser focus/visibility transition.
|
||||
* Stream.changes collapses focus+visibility events that describe the same
|
||||
* effective state.
|
||||
*/
|
||||
export function desktopFocusChanges(
|
||||
windowTarget: Window,
|
||||
documentTarget: Document,
|
||||
): Stream.Stream<boolean> {
|
||||
return Stream.callback<boolean>((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const report = () => Queue.offerUnsafe(queue, readDesktopFocus(documentTarget));
|
||||
windowTarget.addEventListener("focus", report);
|
||||
windowTarget.addEventListener("blur", report);
|
||||
documentTarget.addEventListener("visibilitychange", report);
|
||||
report();
|
||||
return report;
|
||||
}),
|
||||
(report) =>
|
||||
Effect.sync(() => {
|
||||
windowTarget.removeEventListener("focus", report);
|
||||
windowTarget.removeEventListener("blur", report);
|
||||
documentTarget.removeEventListener("visibilitychange", report);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
).pipe(Stream.changes);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
ClientPresentation,
|
||||
CloudSession,
|
||||
DesktopFocus,
|
||||
EnvironmentOwnedDataCleanup,
|
||||
PlatformConnectionSource,
|
||||
PrimaryEnvironmentAuth,
|
||||
@@ -58,7 +57,6 @@ import {
|
||||
readDesktopSecondaryBootstrapsResult,
|
||||
type DesktopSecondaryBootstrapsRead,
|
||||
} from "./desktopLocal";
|
||||
import { desktopFocusChanges } from "./desktopFocus";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
let nextObservedRpcRequestId = 0;
|
||||
@@ -280,10 +278,6 @@ const capabilitiesLayer = Layer.effectContext(
|
||||
Context.add(PrimaryEnvironmentAuth, primaryAuth),
|
||||
Context.add(RelayDeviceIdentity, identity),
|
||||
Context.add(ClientPresentation, presentation),
|
||||
Context.add(
|
||||
DesktopFocus,
|
||||
DesktopFocus.of({ changes: desktopFocusChanges(window, document) }),
|
||||
),
|
||||
Context.add(SshEnvironmentGateway, ssh),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId, WS_METHODS } from "@t3tools/contracts";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
@@ -12,7 +12,6 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import { DesktopFocus } from "../platform/capabilities.ts";
|
||||
import type { ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import * as Connectivity from "./connectivity.ts";
|
||||
import * as ConnectionDriver from "./driver.ts";
|
||||
@@ -116,7 +115,6 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
|
||||
readonly ready?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
|
||||
readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
|
||||
readonly rpcClient?: WsRpcProtocolClient;
|
||||
}) {
|
||||
const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(
|
||||
options?.networkStatus ?? "online",
|
||||
@@ -163,7 +161,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
|
||||
|
||||
const session = yield* Effect.acquireRelease(
|
||||
Effect.succeed({
|
||||
client: options?.rpcClient ?? TEST_RPC_CLIENT,
|
||||
client: TEST_RPC_CLIENT,
|
||||
initialConfig: Effect.die(new Error("Initial config is not used by supervisor tests.")),
|
||||
ready: options?.ready?.(attempt) ?? Effect.void,
|
||||
probe: options?.probe?.(attempt) ?? Effect.void,
|
||||
@@ -288,85 +286,6 @@ describe("EnvironmentSupervisor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the desktop focus RPC stream scoped to focus and the live connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const focused = yield* SubscriptionRef.make(true);
|
||||
const activeReports = yield* Ref.make(0);
|
||||
const reportAttempts = yield* Ref.make(0);
|
||||
const focusRpc = () =>
|
||||
Stream.fromEffect(Ref.updateAndGet(reportAttempts, (count) => count + 1)).pipe(
|
||||
Stream.flatMap((attempt) =>
|
||||
attempt === 1
|
||||
? Stream.fail(new Error("Transient focus report failure."))
|
||||
: Stream.fromEffect(Ref.update(activeReports, (count) => count + 1)).pipe(
|
||||
Stream.drain,
|
||||
Stream.concat(Stream.never),
|
||||
Stream.ensuring(Ref.update(activeReports, (count) => count - 1)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rpcClient = {
|
||||
[WS_METHODS.clientReportDesktopFocus]: focusRpc,
|
||||
} as unknown as WsRpcProtocolClient;
|
||||
const harness = yield* makeHarness({ rpcClient });
|
||||
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(
|
||||
Effect.provide(harness.dependencies),
|
||||
Effect.provideService(
|
||||
DesktopFocus,
|
||||
DesktopFocus.of({
|
||||
changes: SubscriptionRef.changes(focused).pipe(Stream.changes),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
for (
|
||||
let iteration = 0;
|
||||
iteration < 100 && (yield* Ref.get(reportAttempts)) !== 1;
|
||||
iteration++
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* Ref.get(reportAttempts)).toBe(1);
|
||||
yield* TestClock.adjust("1 second");
|
||||
for (
|
||||
let iteration = 0;
|
||||
iteration < 100 && (yield* Ref.get(activeReports)) !== 1;
|
||||
iteration++
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* Ref.get(activeReports)).toBe(1);
|
||||
expect(yield* Ref.get(reportAttempts)).toBe(2);
|
||||
|
||||
yield* SubscriptionRef.set(focused, false);
|
||||
for (
|
||||
let iteration = 0;
|
||||
iteration < 100 && (yield* Ref.get(activeReports)) !== 0;
|
||||
iteration++
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* Ref.get(activeReports)).toBe(0);
|
||||
|
||||
yield* SubscriptionRef.set(focused, true);
|
||||
for (
|
||||
let iteration = 0;
|
||||
iteration < 100 && (yield* Ref.get(activeReports)) !== 1;
|
||||
iteration++
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* Ref.get(activeReports)).toBe(1);
|
||||
|
||||
yield* supervisor.disconnect;
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "available");
|
||||
expect(yield* Ref.get(activeReports)).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("waits while offline and connects immediately when the network returns", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({ networkStatus: "offline" });
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -10,7 +9,6 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
@@ -29,7 +27,6 @@ import {
|
||||
} from "./model.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
|
||||
import * as ClientCapabilities from "../platform/capabilities.ts";
|
||||
import * as ConnectionWakeups from "./wakeups.ts";
|
||||
|
||||
const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000] as const;
|
||||
@@ -228,7 +225,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
const connectivity = yield* Connectivity.Connectivity;
|
||||
const driver = yield* ConnectionDriver.ConnectionDriver;
|
||||
const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
|
||||
const desktopFocus = yield* ClientCapabilities.DesktopFocus;
|
||||
const initialIntent: SupervisorIntent = {
|
||||
desired: options?.initiallyDesired ?? false,
|
||||
network: yield* connectivity.status,
|
||||
@@ -484,31 +480,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
}
|
||||
});
|
||||
|
||||
const reportDesktopFocus = (rpcSession: RpcSession.RpcSession) =>
|
||||
desktopFocus.changes.pipe(
|
||||
Stream.changes,
|
||||
Stream.switchMap((focused) =>
|
||||
focused
|
||||
? rpcSession.client[WS_METHODS.clientReportDesktopFocus]({}).pipe(
|
||||
Stream.tapError((error) =>
|
||||
Effect.logDebug("Desktop focus reporting failed; retrying.", {
|
||||
environmentId: target.environmentId,
|
||||
...safeErrorLogAttributes(error),
|
||||
}),
|
||||
),
|
||||
Stream.retry(Schedule.spaced("1 second")),
|
||||
)
|
||||
: Stream.empty,
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logDebug("Desktop focus reporting stopped for this connection.", {
|
||||
cause: Cause.pretty(cause),
|
||||
environmentId: target.environmentId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runAttempt = Effect.fnUntraced(function* (
|
||||
attempt: number,
|
||||
generation: number,
|
||||
@@ -605,7 +576,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
lastFailure: null,
|
||||
retryAt: null,
|
||||
});
|
||||
yield* reportDesktopFocus(active.lease.session).pipe(Effect.forkScoped);
|
||||
|
||||
const connectedExit = yield* Effect.raceFirst(
|
||||
active.lease.session.closed.pipe(
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { ConnectionAttemptError } from "../connection/model.ts";
|
||||
|
||||
@@ -44,16 +43,6 @@ export class ClientPresentation extends Context.Service<
|
||||
}
|
||||
>()("@t3tools/client-runtime/platform/capabilities/ClientPresentation") {}
|
||||
|
||||
/**
|
||||
* Emits the current and subsequent focus state for a desktop T3 Code surface.
|
||||
* Non-desktop clients use the empty default and never report desktop focus.
|
||||
*/
|
||||
export class DesktopFocus extends Context.Reference<{
|
||||
readonly changes: Stream.Stream<boolean>;
|
||||
}>("@t3tools/client-runtime/platform/capabilities/DesktopFocus", {
|
||||
defaultValue: () => ({ changes: Stream.empty }),
|
||||
}) {}
|
||||
|
||||
export class PrimaryEnvironmentAuth extends Context.Service<
|
||||
PrimaryEnvironmentAuth,
|
||||
{
|
||||
|
||||
@@ -43,7 +43,6 @@ export type EnvironmentSubscriptionRpcTag =
|
||||
| typeof ORCHESTRATION_WS_METHODS.subscribeShell
|
||||
| typeof ORCHESTRATION_WS_METHODS.subscribeThread
|
||||
| typeof WS_METHODS.subscribeAuthAccess
|
||||
| typeof WS_METHODS.clientReportDesktopFocus
|
||||
| typeof WS_METHODS.subscribeServerConfig
|
||||
| typeof WS_METHODS.subscribeServerLifecycle
|
||||
| typeof WS_METHODS.subscribeTerminalEvents
|
||||
|
||||
@@ -245,9 +245,6 @@ export const WS_METHODS = {
|
||||
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
|
||||
cloudInstallRelayClient: "cloud.installRelayClient",
|
||||
|
||||
// Client presence
|
||||
clientReportDesktopFocus: "client.reportDesktopFocus",
|
||||
|
||||
// Source control methods
|
||||
sourceControlLookupRepository: "sourceControl.lookupRepository",
|
||||
sourceControlCloneRepository: "sourceControl.cloneRepository",
|
||||
@@ -786,18 +783,6 @@ export const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeReso
|
||||
stream: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* The desktop keeps this stream open only while its T3 Code window/tab is
|
||||
* visible and focused. The server binds the focus lease to the stream scope,
|
||||
* so blur, navigation, transport loss, and process exit all release it.
|
||||
*/
|
||||
export const WsClientReportDesktopFocusRpc = Rpc.make(WS_METHODS.clientReportDesktopFocus, {
|
||||
payload: Schema.Struct({}),
|
||||
success: Schema.Void,
|
||||
error: EnvironmentAuthorizationError,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerProbeRpc,
|
||||
WsServerGetConfigRpc,
|
||||
@@ -871,7 +856,6 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsSubscribeAuthAccessRpc,
|
||||
WsSubscribeBackgroundPolicyRpc,
|
||||
WsSubscribeResourceTelemetryRpc,
|
||||
WsClientReportDesktopFocusRpc,
|
||||
WsOrchestrationDispatchCommandRpc,
|
||||
WsOrchestrationGetTurnDiffRpc,
|
||||
WsOrchestrationGetFullThreadDiffRpc,
|
||||
|
||||
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 9.5 KiB |