fix: avoid stale Live Activities when publishing is disabled (#6325)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-08-14 10:00:25 +02:00
1 parent 7e01d33f0e
commit baaeda305c
10 files changed
+236 -7

No files matched your search

@@ -20,12 +20,15 @@ import {
clearAgentAwarenessRegistrationRecord,
loadAgentAwarenessRegistrationRecord,
loadOrCreateAgentAwarenessDeviceId,
loadPreferences,
saveAgentAwarenessRegistrationRecord,
} from "../../persistence/imperative";
import type { Preferences } from "../../persistence/mobile-preferences";
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
armAgentAwarenessLiveActivityForLocalWork,
getAgentAwarenessRegistrationStatus,
mergeAgentAwarenessRegistrationPreferences,
refreshActiveLiveActivityRemoteRegistration,
@@ -43,6 +46,13 @@ import * as Notifications from "expo-notifications";
const secureStore = vi.hoisted(() => new Map<string, string>());
const widgetMocks = vi.hoisted(() => ({
getInstances: vi.fn(() => []),
start: vi.fn(() => ({})),
}));
const environmentConfigsMock = vi.hoisted(() => ({
configs: new Map<
string,
{ environment: { capabilities: { agentActivityPublishing?: boolean } } }
>(),
}));
const backgroundRuntime = vi.hoisted(() => ({
pending: [] as Array<{
@@ -77,9 +87,22 @@ vi.mock("expo-widgets", () => ({
vi.mock("../../widgets/AgentActivity", () => ({
default: {
getInstances: widgetMocks.getInstances,
start: widgetMocks.start,
},
}));
// The state modules pull the whole connection stack (and native expo modules)
// into the import graph; the arming gate only needs the configs map.
vi.mock("../../state/atom-registry", () => ({
appAtomRegistry: {
get: () => environmentConfigsMock.configs,
},
}));
vi.mock("../../state/server", () => ({
environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
}));
vi.mock("expo-notifications", () => ({
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
@@ -227,6 +250,8 @@ describe("makeRelayDeviceRegistrationRequest", () => {
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
widgetMocks.getInstances.mockReset();
widgetMocks.getInstances.mockReturnValue([]);
widgetMocks.start.mockClear();
environmentConfigsMock.configs.clear();
});
it("preserves disabled Live Activity preferences in relay registrations", () => {
@@ -856,4 +881,55 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
},
);
it("skips the Live Activity seed when the environment reports publishing disabled", async () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
environmentConfigsMock.configs.set("env-1", {
environment: { capabilities: { agentActivityPublishing: false } },
});
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-1" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).not.toHaveBeenCalled();
});
it("seeds the Live Activity for publishing and pre-capability environments", async () => {
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
environmentConfigsMock.configs.set("env-publishing", {
environment: { capabilities: { agentActivityPublishing: true } },
});
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-publishing" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
// An environment without the capability may run an older server that
// still publishes; only an explicit false skips the seed.
widgetMocks.start.mockClear();
vi.mocked(loadPreferences).mockResolvedValueOnce({
liveActivitiesEnabled: true,
} as Preferences);
armAgentAwarenessLiveActivityForLocalWork({
environmentId: "env-pre-capability" as EnvironmentId,
threadTitle: "Fix the flaky test",
projectTitle: "t3code",
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
});
});
@@ -20,6 +20,8 @@ import {
import type { SavedRemoteConnection } from "../../lib/connection";
import { runtime } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import type { Preferences } from "../../persistence/mobile-preferences";
import {
clearAgentAwarenessRegistrationRecord,
@@ -448,18 +450,38 @@ function unregisterDeviceWithRelay(input: {
});
}
// The environment descriptor advertises whether agent-activity publishes
// currently leave that server (`capabilities.agentActivityPublishing`). Only
// an explicit false skips the seed card: older servers omit the capability
// but may still publish.
function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.agentActivityPublishing !== false
);
}
// Arms the lock-screen card the moment the user starts agent work from this
// phone, while the app is still foregrounded and the fresh activity's token
// can be registered immediately. The seeded row is a best-effort placeholder;
// the relay's registration replay repaints it with the authoritative
// aggregate within seconds. No-ops when a card is already armed.
// aggregate within seconds. No-ops when a card is already armed, and skips
// environments that report publishing disabled — the seed would sit on
// "Connecting" forever with no update ever arriving to repaint or end it.
export function armAgentAwarenessLiveActivityForLocalWork(input: {
readonly environmentId: EnvironmentId;
readonly threadTitle: string;
readonly projectTitle: string;
}): void {
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
return;
}
if (!environmentPublishesAgentActivity(input.environmentId)) {
logRegistrationDebug("live activity arming skipped; environment does not publish", {
environmentId: input.environmentId,
});
return;
}
void loadPreferences()
.catch(() => null)
.then((preferences) => {
@@ -709,6 +709,7 @@ export function NewTaskDraftScreen(props: {
// -only Activity start. If creation fails, the token registration's replay
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: selectedProject.environmentId,
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
projectTitle: selectedProject.title,
});
@@ -541,6 +541,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
// after the send so its preference read and native Activity start don't
// contend with the queued-message feedback on the tap frame.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: props.environmentId,
threadTitle: props.selectedThread.title,
projectTitle: props.environmentLabel ?? "T3 Code",
});
+3 -2
View File
@@ -36,6 +36,7 @@ import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import {
CLOUD_LINKED_USER_ID,
isAgentActivityPublishingEnabledValue,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
@@ -142,7 +143,7 @@ function stringToBytes(value: string): Uint8Array {
}
export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
return value === "true";
return isAgentActivityPublishingEnabledValue(value);
}
interface CloudCliStatus {
@@ -447,7 +448,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
),
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironment.layer,
ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
bootServiceLayer(config),
headlessRelayClientTracingLayer,
).pipe(
+40
View File
@@ -1,6 +1,10 @@
import { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as ServerSecretStore from "../auth/ServerSecretStore.ts";
export const CLOUD_MINT_PUBLIC_KEY = "cloud-mint-ed25519-public-key";
export const CLOUD_ENDPOINT_RUNTIME_CONFIG = "cloud-endpoint-runtime-config";
export const CLOUD_LINKED_USER_ID = "cloud-linked-user-id";
@@ -16,3 +20,39 @@ export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect(
export const decodeRuntimeConfig = Schema.decodeUnknownOption(
Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),
);
export function isAgentActivityPublishingEnabledValue(value: string | null): boolean {
return value === "true";
}
/** Whether agent-activity publishes currently leave this environment: the
publish opt-in secret is enabled and the relay link credentials exist.
Mirrors the per-publish gate in AgentAwarenessRelay, so the descriptor
capability never advertises publishing that the publisher would skip. */
export const readAgentActivityPublishingActive = (
secrets: ServerSecretStore.ServerSecretStore["Service"],
): Effect.Effect<boolean> =>
Effect.gen(function* () {
const readSecretString = (name: string) =>
secrets
.get(name)
.pipe(
Effect.map((bytes) =>
Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,
),
);
const [enabled, url, environmentCredential] = yield* Effect.all([
readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET),
readSecretString(RELAY_URL_SECRET),
readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
]);
// Empty strings are as unconfigured as missing files: the publisher's
// truthiness gate skips them, so the capability must too.
return (
isAgentActivityPublishingEnabledValue(enabled) &&
url !== null &&
url !== "" &&
environmentCredential !== null &&
environmentCredential !== ""
);
}).pipe(Effect.orElseSucceed(() => false));
@@ -3,9 +3,16 @@ import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
@@ -14,7 +21,21 @@ const isServerEnvironmentIdPersistenceError = Schema.is(
);
const makeServerEnvironmentLayer = (baseDir: string) =>
ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
ServerEnvironment.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
);
const emptySecretStoreLayer = Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
get: () => Effect.succeed(Option.none()),
set: () => Effect.void,
create: () => Effect.void,
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
remove: () => Effect.void,
}),
);
const makeServerConfig = Effect.fn(function* (baseDir: string) {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
@@ -71,6 +92,53 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.pullRequests).toBe(true);
expect(second.capabilities.threadTitleRegeneration).toBe(true);
expect(second.capabilities.agentActivityPublishing).toBe(false);
}),
);
it.effect("reports agent activity publishing from the current secret state", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-environment-publish-test-",
});
const testLayer = Layer.mergeAll(
ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),
ServerSecretStore.layer,
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
yield* Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const encode = (value: string) => new TextEncoder().encode(value);
const unlinked = yield* serverEnvironment.getDescriptor;
expect(unlinked.capabilities.agentActivityPublishing).toBe(false);
// The opt-in alone is not enough: without relay link credentials no
// publish would leave this environment.
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));
const withoutLink = yield* serverEnvironment.getDescriptor;
expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);
// Empty credentials are as unconfigured as missing ones: the
// publisher's truthiness gate skips them, so the capability must not
// advertise publishing.
yield* secrets.set(RELAY_URL_SECRET, encode(""));
yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));
const emptyUrl = yield* serverEnvironment.getDescriptor;
expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);
yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));
const linked = yield* serverEnvironment.getDescriptor;
expect(linked.capabilities.agentActivityPublishing).toBe(true);
// The toggle changes at runtime, so the same service instance must
// reflect a flip without a restart.
yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));
const disabled = yield* serverEnvironment.getDescriptor;
expect(disabled.capabilities.agentActivityPublishing).toBe(false);
}).pipe(Effect.provide(testLayer));
}),
);
@@ -113,6 +181,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
}).pipe(
Effect.provide(
ServerEnvironment.layer.pipe(
Layer.provide(emptySecretStoreLayer),
Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),
),
),
@@ -9,6 +9,8 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { readAgentActivityPublishingActive } from "../cloud/config.ts";
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
@@ -66,6 +68,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig.ServerConfig;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
@@ -156,13 +159,22 @@ export const make = Effect.gen(function* () {
return ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.succeed(descriptor),
// The publish opt-in and relay link change at runtime (`t3 connect
// publish`, the client settings toggle), so the capability is read per
// descriptor request rather than baked in at startup.
getDescriptor: readAgentActivityPublishingActive(secrets).pipe(
Effect.map((agentActivityPublishing) => ({
...descriptor,
capabilities: { ...descriptor.capabilities, agentActivityPublishing },
})),
),
});
});
/**
* ServerEnvironment is acquired from persisted filesystem and host-process
* state. It intentionally has no fallback Layer.succeed value: callers must
* provide the external platform services and a ServerConfig.
* provide the external platform services, a ServerConfig, and the
* ServerSecretStore backing the descriptor's publishing capability.
*/
export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));
+2 -1
View File
@@ -35,6 +35,7 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
isAgentActivityPublishingEnabledValue,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_ISSUER_SECRET,
@@ -102,7 +103,7 @@ export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | n
}
export function isAgentActivityPublishingEnabled(value: string | null): boolean {
return value === "true";
return isAgentActivityPublishingEnabledValue(value);
}
export function resolveAgentActivityPublishingStartupState(input: {
+6
View File
@@ -74,6 +74,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server can stream self-update progress before acknowledging the
restart. Clients fall back to server.updateServer when absent. */
serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),
/** Agent-activity publishes (push notifications and Live Activities)
currently leave this environment: the publish opt-in is enabled and the
relay link credentials exist. Clients skip seeding a Live Activity when
this is false — no update would ever repaint it. Absent on older
servers, which may still publish, so only an explicit false skips. */
agentActivityPublishing: Schema.optionalKey(Schema.Boolean),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;