Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

browser-extension: apply policy locks at delivery time

shukieshah0c428878cf49
diff --git a/CLAUDE.md b/CLAUDE.md
index 77a3eb74..e4fb4c5a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,7 +64,7 @@ Supported runtime surfaces today:
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
- GitHub Copilot CLI uses MDM/customer-managed OTLP HTTP for live spans and approval-like activity, plus `beacon endpoint copilot sync` to backfill local session records from `~/.copilot/session-state`. Poll events carry assistant text, complete tool results, command/file details, and token usage with `harness.collection_method=poll`, plus the shutdown's session-wide `totalNanoAiu` differenced into `gen_ai.usage.cost_usd` once per shutdown (10^9 nano-AIU = one AI credit = US$0.01), only for sessions started on or after the 2026-06-01 AI-credit cutover (`cli/beacon/internal/copilotsession/cost.go`); approvals still come only from the live OTLP path and are not synthesized from persisted records.
- Runtimes that ride shared hook/OTLP paths without a special contract worth expanding here include Antigravity CLI, Devin CLI, Devin Desktop, Factory Droid, Gemini CLI, Grok Build, Hermes Agent, Qwen Code, and VS Code. Installed hook/endpoint support is governed by `cli/beacon/cmd/endpoint_targets.go` plus the install/status switches in `cli/beacon/cmd/endpoint_hooks.go`; discovery rows live in `cli/beacon/internal/endpoint/harness`.
-- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change. Managed fleets install a signed, self-hosted Chrome build instead of the unpacked zip: Chrome policy (`ExtensionSettings` `force_installed`) installs the CRX from the `update_url` feed (`CHROME_UPDATE_URL` in `tools/targets.mjs`, also the manifest's `update_url`, dropped from the Firefox manifest), and the pinned `CHROME_EXTENSION_ID` there, derived from the CRX signing key, must never change either, because every fleet's policy names it. `tools/pack-crx.mjs` signs CRX3 files and writes the feed with `node:crypto` only, so the signing job runs it without `npm ci`. Admins lock settings through Chrome managed storage (`src/managed_schema.json`): `getSettingsState` in `src/background/settings.ts` lays those values over the stored ones on every read, each held to `parseSettingsPatch`, never writes them to `storage.local`, and reports them as `locked`, which the popup and options page show disabled and `SET_SETTINGS` refuses to change.
+- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change. Managed fleets install a signed, self-hosted Chrome build instead of the unpacked zip: Chrome policy (`ExtensionSettings` `force_installed`) installs the CRX from the `update_url` feed (`CHROME_UPDATE_URL` in `tools/targets.mjs`, also the manifest's `update_url`, dropped from the Firefox manifest), and the pinned `CHROME_EXTENSION_ID` there, derived from the CRX signing key, must never change either, because every fleet's policy names it. `tools/pack-crx.mjs` signs CRX3 files and writes the feed with `node:crypto` only, so the signing job runs it without `npm ci`. Admins lock settings through Chrome managed storage (`src/managed_schema.json`): `getSettingsState` in `src/background/settings.ts` lays those values over the stored ones on every read, each held to `parseSettingsPatch`, never writes them to `storage.local`, and reports them as `locked`, which the popup and options page show disabled and `SET_SETTINGS` refuses to change. A managed-storage read that fails (anything but a missing area or Firefox's no-manifest refusal) sets `managedError`: nothing is captured, changed or delivered until it reads. Delivery (`src/background/delivery.ts`) applies the locks in force at send time (`underPolicy`): a locked endpoint retargets queued batches, and a locked-off site or capture, or a locked retention stricter than the batch was built with, drops them. A copy installed by policy (`management.getSelf().installType === 'admin'`) holds delivery for `POLICY_GRACE_MS` after an install or update until Chrome delivers any managed value, because turns captured before then were shaped without the locks.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
- OTLP forward (`beacon endpoint install|repair --otlp-forward-endpoint`, `--otlp-forward-protocol grpc|http/protobuf`, `--otlp-forward-harness`, repeatable `--otlp-forward-header`, `--no-otlp-forward`; `config.json` `destinations.otlp_forward`): for machines whose runtimes already exported OTLP to another backend before Beacon pointed them at its collector. The collector renders an `otlp/forward` or `otlphttp/forward` exporter (both in `collector-builder/builder.yaml`) on `logs/forward`, `traces/forward` and `metrics/forward` pipelines fed by the same receiver: `memory_limiter`, `beacon_forward_filter` (`forwardfilterprocessor`; keeps only resources whose harness, resolved like beaconjson resolves it, is listed, default Claude Code and Codex, so browser-extension chats and other runtimes never leave), `claude_api_body` on logs, `beacon_privacy`, `batch`. The exporter's queue and retries are bounded so a down backend sheds data instead of pushing `memory_limiter` into refusing Beacon's own pipelines. It is a customer-chosen destination like the HEC exporters, not a Beacon network channel, and carries no hook or session-store data. Install and repair carry it over (`buildConfig`) until `--no-otlp-forward` removes it. Header values never go in `config.json` (ordinary accounts read the system one to find the system log): they live in `OTLPForwardSecretsPath` (`otlp-forward-headers.json`, 0600) and the 0600 collector config, `config.json` keeps `header_names`, and status, doctor and `config show` show names only. Guide: `docs/guides/kandji-otlp-forward-mdm.mdx`.
- Managed Microsoft Sentinel forwarder (`beacon endpoint sentinel forwarder install|status|remove --system`, hidden `reconcile`; `cli/beacon/internal/endpoint/sentinel/forwarder.go`, `cli/beacon/cmd/endpoint_sentinel_forwarder.go`; docs in `docs/log-forwarding/microsoft-sentinel.mdx#vector-and-the-logs-ingestion-api` and `docs/cli/sentinel.mdx`): the bundled Vector (the MSI ships `vector.exe` beside `beacon.exe`, checked against the pinned `packaging/vector/` checksums by `packaging/windows/fetch-vector.ps1`) run as a system service (`BeaconSentinelForwarder`, `beacon-sentinel-forwarder.service`, `com.beacon.endpoint.sentinel-forwarder`) through `service.ForwarderManager` with a `ForwarderSpec`; the Asymptote forwarder's spec is the zero value, byte-identical units, and has no Windows service, so `connect` stays refused there. System mode only. Its state is `<SystemBaseDir>/forwarders/sentinel/` (`forwarder.json` non-secret settings, `secrets.json` read by Vector's `file` secret backend, optional `client.pfx`, `vector.toml` with literal values, `data/` checkpoints, `logs/vector-<date>.log` warnings), `sysacl.SecureSecretDir`/`WriteSecretFile` (root-only 0700/0600 on POSIX), apart from `config.json` so repair never touches it. The credential is never a flag value (env or stdin). Install validates a scratch copy with Vector before writing anything, so a rejected install leaves the old forwarder. The config (`pack/vector.toml.tmpl`, shared with the manual env-var pack via `manualVectorConfig`) reads `runtime.jsonl` and `.1` with the default checksum fingerprint, acknowledgements on, a custom `retry_strategy` (401/403/408/429/5xx, unlimited), 512 KB batches. Vector recognizes a file by its first line, so after the log is replaced with a copy (the log-access switch) it keeps reading the old file until restarted: `lifecycle.Install` therefore reconciles with `Restart` on every install, repair and package upgrade (the macOS postinstall runs the hidden `reconcile`), which is also how the MSI upgrade re-registers the service its uninstall step removed. `lifecycle.Uninstall` always removes the service (so `vector.exe` can be replaced) and keeps the state under `KeepConfig`; repair keeps it running (`KeepForwarders`). `AZURE_AUTHORITY_HOST` (`--authority-host`) goes into the service environment. `sentinelmock` (and `cmd/sentinel-mock`) stands in for Entra ID and the Logs Ingestion API; `TestForwarderConfigDeliversThroughRealVector` runs real Vector against it in `linux-test` and `windows-test` (`BEACON_TEST_VECTOR_BIN`, `BEACON_TEST_SENTINEL_TRUST_STORE=1` on Windows), and `packaging/windows/smoke-sentinel-forwarder.ps1` drives the installed MSI through setup, upgrade, log-access switches and uninstall in `windows-package-smoke`.
diff --git a/browser-extension/src/background/delivery.ts b/browser-extension/src/background/delivery.ts
index a8b1ce81..d460839d 100644
--- a/browser-extension/src/background/delivery.ts
+++ b/browser-extension/src/background/delivery.ts
@@ -10,9 +10,16 @@
// for minutes (restarting during an install or upgrade, not yet started after
// boot, crash-looping) loses nothing it comes back from within the age limit.
// A batch the collector rejects (a non-retryable status) is dropped at once.
+//
+// Policy: a batch goes out under the locks in force when it is sent, not when it
+// was queued, so a lock an admin pushes later also covers what is still queued.
+// A copy installed by policy also holds delivery for a short while after an
+// install or update, until Chrome delivers its managed settings, because
+// turns captured in that window were shaped before any lock was known.
import { ext } from '../shared/browser.js';
-import type { ChatTurn, Settings } from '../shared/types.js';
+import type { ChatTurn, LockedSetting, Retention, Settings, SiteName } from '../shared/types.js';
+import { getSettingsState, type SettingsState } from './settings.js';
import { turnToEnvelope } from '../shared/normalize.js';
import type { LogsEnvelope } from '../shared/otlp.js';
import type { BrowserIdentity } from '../shared/browser-identity.js';
@@ -36,6 +43,15 @@ export const MAX_QUEUE_ITEMS = 2_000;
export const MAX_QUEUE_BYTES = 6 * 1024 * 1024;
/** Longest wait between retries, and so the longest delay after the collector recovers. */
export const MAX_RETRY_DELAY_MS = 60_000;
+/**
+ * How long a copy installed by policy holds delivery after an install or update while Chrome has
+ * delivered none of its managed settings. Chrome delivers them a moment after the install; an
+ * admin who pushes none gets delivery once this passes.
+ */
+export const POLICY_GRACE_MS = 30_000;
+/** How long the queue waits before trying again when Chrome cannot read the policy at all. */
+const UNREADABLE_POLICY_RETRY_MS = 60_000;
+const INSTALLED_KEY = 'installed_at';
interface QueueItem {
id: string;
@@ -49,6 +65,9 @@ interface QueueItem {
queuedAt?: number;
/** UTF-8 size of the serialized envelope, counted against MAX_QUEUE_BYTES. */
bytes?: number;
+ /** The site and retention the envelope was built for, checked against policy at send time. */
+ site?: SiteName;
+ retention?: Retention;
}
async function readQueue(): Promise<QueueItem[]> {
@@ -77,6 +96,8 @@ export async function enqueueTurn(
envelope,
attempts: 0,
queuedAt: Date.now(),
+ site: turn.site,
+ retention: settings.retention,
};
await withQueueLock(async () => {
const queue = await readQueue();
@@ -100,10 +121,21 @@ export async function flush(): Promise<void> {
if (stored.length === 0) return;
const queue = pruneQueue(stored, Date.now());
+ // Nothing goes out while the locks in force are unknown.
+ const policy = await getSettingsState();
+ const hold = policy.managedError != null ? UNREADABLE_POLICY_RETRY_MS : await policyPendingMs(policy);
+ if (hold > 0) {
+ await writeQueue(queue);
+ ext.alarms.create(ALARM, { when: Date.now() + hold });
+ return;
+ }
+
const remaining: QueueItem[] = [];
const waiting = new Set<string>();
- for (const item of queue) {
+ for (const queued of queue) {
+ const item = underPolicy(queued, policy);
+ if (!item) continue;
// Checked again at send time, not only when settings are saved: an item
// queued by an older build, or a tampered queue, must not reach anything
// but the local collector. Such an item is dropped, not retried.
@@ -128,6 +160,43 @@ export async function flush(): Promise<void> {
});
}
+const STRICTNESS: Record<Retention, number> = { full: 0, redacted: 1, metadata: 2 };
+
+/**
+ * A queued batch under the locks in force: the batch, sent to a locked endpoint if one is set, or
+ * undefined when a lock forbids sending it at all. A locked retention stricter than the one the
+ * batch was built with drops it, because its content cannot be taken back out.
+ */
+export function underPolicy(item: QueueItem, policy: SettingsState): QueueItem | undefined {
+ const { settings, locked } = policy;
+ const isLocked = (key: LockedSetting) => locked.includes(key);
+ if (isLocked('enabled') && !settings.enabled) return undefined;
+ if (item.site && isLocked(`sites.${item.site}`) && settings.sites[item.site] === false) return undefined;
+ if (isLocked('retention') && STRICTNESS[item.retention ?? 'full'] < STRICTNESS[settings.retention]) return undefined;
+ if (isLocked('endpoint')) item.endpoint = settings.endpoint;
+ return item;
+}
+
+/** Record an install or update, which starts a policy-installed copy's grace period. */
+export async function markInstalled(): Promise<void> {
+ await ext.storage.local.set({ [INSTALLED_KEY]: Date.now() });
+}
+
+/**
+ * Milliseconds to keep holding the queue for a policy that has not arrived: only a copy installed
+ * by policy, only within POLICY_GRACE_MS of its install or update, and only while no managed value
+ * is in force. Zero otherwise.
+ */
+async function policyPendingMs(policy: SettingsState): Promise<number> {
+ if (policy.locked.length > 0) return 0;
+ const installedAt = (await ext.storage.local.get(INSTALLED_KEY))[INSTALLED_KEY];
+ if (typeof installedAt !== 'number') return 0;
+ const left = installedAt + POLICY_GRACE_MS - Date.now();
+ if (left <= 0) return 0;
+ const self = await ext.management?.getSelf?.().catch(() => undefined);
+ return self?.installType === 'admin' ? left : 0;
+}
+
/**
* Drop batches past the age limit, then the oldest batches until the queue fits
* its caps. The newest batch is always kept. A batch from an older build has no
@@ -211,4 +280,8 @@ export function installFlushAlarm(): void {
// update, so a queue left from before would otherwise wait for the next turn.
// Flushing on worker start sends what is due and re-arms the retry for the rest.
void flush();
+ // A held queue goes out as soon as Chrome delivers or changes the policy.
+ ext.storage.onChanged?.addListener((_changes, area) => {
+ if (area === 'managed') void flush();
+ });
}
diff --git a/browser-extension/src/background/sw.ts b/browser-extension/src/background/sw.ts
index f366f123..b3206120 100644
--- a/browser-extension/src/background/sw.ts
+++ b/browser-extension/src/background/sw.ts
@@ -7,7 +7,7 @@ import { ext } from '../shared/browser.js';
import type { ChatTurn } from '../shared/types.js';
import { getSettingsState, lockedIn, saveSettings, siteEnabled } from './settings.js';
import { Assembler } from './assembler.js';
-import { enqueueTurn, flush, installFlushAlarm } from './delivery.js';
+import { enqueueTurn, flush, installFlushAlarm, markInstalled } from './delivery.js';
import { detectBrowser } from '../shared/browser-identity.js';
import { parseHost, parseInterceptEvent, parseSettingsPatch } from '../shared/validate.js';
import { isExtensionPage, isOwnContentScript, senderHost, type SenderLike } from './sender.js';
@@ -41,8 +41,9 @@ function finalizeAll(turns: ChatTurn[]): void {
for (const turn of turns) void finalizeTurn(turn);
}
-ext.runtime.onInstalled.addListener(() => {
+ext.runtime.onInstalled.addListener((details) => {
void saveSettings({}); // materialize defaults
+ if (details.reason === 'install' || details.reason === 'update') void markInstalled();
});
installFlushAlarm();
diff --git a/browser-extension/src/shared/browser.ts b/browser-extension/src/shared/browser.ts
index 98a3544b..07a51ef9 100644
--- a/browser-extension/src/shared/browser.ts
+++ b/browser-extension/src/shared/browser.ts
@@ -11,7 +11,8 @@
//
// Scope is deliberately small: only the APIs this extension uses (storage,
// including the policy-fed storage.managed, runtime, alarms, permissions,
-// tabs.onRemoved), which have the same shape on all three engines.
+// tabs.onRemoved, management.getSelf), which have the same shape on all three
+// engines.
// The type is Chrome's, because @types/chrome describes the promise overloads we
// call and Firefox/Safari match them for this subset.
diff --git a/browser-extension/test/unit/delivery-policy.test.ts b/browser-extension/test/unit/delivery-policy.test.ts
new file mode 100644
index 00000000..c83e7018
--- /dev/null
+++ b/browser-extension/test/unit/delivery-policy.test.ts
@@ -0,0 +1,158 @@
+// Queued batches go out under the policy in force when they are sent, and a copy installed by
+// policy holds delivery right after an install until Chrome delivers its managed settings.
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ChatTurn, Settings } from '../../src/shared/types.js';
+import { DEFAULT_SETTINGS } from '../../src/shared/types.js';
+
+const env = vi.hoisted(() => ({
+ storage: new Map<string, unknown>(),
+ managed: {} as Record<string, unknown> | Error,
+ installType: 'normal',
+ alarms: new Map<string, number>(),
+ posted: [] as { url: string; body: string }[],
+}));
+
+vi.mock('../../src/shared/browser.js', () => ({
+ ext: {
+ storage: {
+ local: {
+ get: async (key: string) => (env.storage.has(key) ? { [key]: structuredClone(env.storage.get(key)) } : {}),
+ set: async (items: Record<string, unknown>) => {
+ for (const [k, v] of Object.entries(items)) env.storage.set(k, structuredClone(v));
+ },
+ },
+ managed: {
+ get: async () => {
+ if (env.managed instanceof Error) throw env.managed;
+ return structuredClone(env.managed);
+ },
+ },
+ },
+ management: { getSelf: async () => ({ installType: env.installType }) },
+ alarms: { create: (name: string, info: { when: number }) => env.alarms.set(name, info.when) },
+ },
+}));
+
+vi.stubGlobal('fetch', async (url: string, init: { body: string }) => {
+ env.posted.push({ url, body: init.body });
+ return { ok: true, status: 200 };
+});
+
+const { enqueueTurn, flush, markInstalled, POLICY_GRACE_MS } = await import('../../src/background/delivery.js');
+
+function turn(id: string, site: ChatTurn['site'] = 'claude_web'): ChatTurn {
+ return {
+ site,
+ sessionId: 'conv-1',
+ turnId: id,
+ promptText: `secret prompt ${id}`,
+ inputMessages: [{ role: 'user', text: `secret prompt ${id}` }],
+ outputMessages: [{ role: 'assistant', text: `answer ${id}` }],
+ responseText: `answer ${id}`,
+ toolCalls: [],
+ startedAt: Date.now(),
+ completedAt: Date.now(),
+ captureMode: 'sse',
+ };
+}
+
+const full: Settings = { ...DEFAULT_SETTINGS, retention: 'full' };
+const queued = () => (env.storage.get('delivery_queue') as unknown[] | undefined) ?? [];
+
+/** Queue a turn while delivery is held by an unreadable policy, so it waits in the queue. */
+async function queueWhileHeld(t: ChatTurn, settings: Settings = full): Promise<void> {
+ env.managed = new Error('IO error: LOCK');
+ await enqueueTurn(t, settings);
+ env.managed = {};
+}
+
+beforeEach(() => {
+ env.storage.clear();
+ env.managed = {};
+ env.installType = 'normal';
+ env.alarms.clear();
+ env.posted.length = 0;
+});
+
+describe('policy at send time', () => {
+ it('holds every batch while the policy cannot be read', async () => {
+ await queueWhileHeld(turn('a'));
+ expect(env.posted).toHaveLength(0);
+ expect(queued()).toHaveLength(1);
+ expect(env.alarms.has('beacon_flush')).toBe(true);
+ });
+
+ it('drops a queued batch whose content a stricter locked retention forbids', async () => {
+ await queueWhileHeld(turn('a'));
+ env.managed = { retention: 'metadata' };
+ await flush();
+ expect(env.posted).toHaveLength(0);
+ expect(queued()).toHaveLength(0);
+ });
+
+ it('sends a queued batch that already meets the locked retention', async () => {
+ await queueWhileHeld(turn('a'), { ...full, retention: 'metadata' });
+ env.managed = { retention: 'redacted' };
+ await flush();
+ expect(env.posted).toHaveLength(1);
+ expect(env.posted[0].body).not.toContain('secret prompt');
+ });
+
+ it('sends a queued batch to the locked endpoint instead of the one it was queued for', async () => {
+ await queueWhileHeld(turn('a'));
+ env.managed = { endpoint: 'http://127.0.0.1:4400/v1/logs' };
+ await flush();
+ expect(env.posted.map((p) => p.url)).toEqual(['http://127.0.0.1:4400/v1/logs']);
+ });
+
+ it('drops queued batches for a site or capture switched off by policy, and keeps the rest', async () => {
+ await queueWhileHeld(turn('a', 'claude_web'));
+ await queueWhileHeld(turn('b', 'chatgpt_web'));
+ env.managed = { sites: { claude_web: false } };
+ await flush();
+ expect(env.posted).toHaveLength(1);
+ expect(env.posted[0].body).toContain('chatgpt_web');
+
+ await queueWhileHeld(turn('c'));
+ env.managed = { enabled: false };
+ await flush();
+ expect(env.posted).toHaveLength(1);
+ expect(queued()).toHaveLength(0);
+ });
+});
+
+describe('policy-installed copy right after install', () => {
+ it('holds delivery until the policy arrives, then applies it', async () => {
+ env.installType = 'admin';
+ await markInstalled();
+ await enqueueTurn(turn('a'), full);
+ expect(env.posted).toHaveLength(0);
+ expect(queued()).toHaveLength(1);
+
+ env.managed = { retention: 'metadata' };
+ await flush();
+ expect(env.posted).toHaveLength(0); // the full-text batch can no longer be sent
+ expect(queued()).toHaveLength(0);
+ });
+
+ it('delivers once the grace period passes with no policy pushed', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ env.installType = 'admin';
+ await markInstalled();
+ await enqueueTurn(turn('a'), full);
+ expect(env.posted).toHaveLength(0);
+ vi.setSystemTime(Date.now() + POLICY_GRACE_MS + 1);
+ await flush();
+ expect(env.posted).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not hold a copy the user installed', async () => {
+ await markInstalled();
+ await enqueueTurn(turn('a'), full);
+ expect(env.posted).toHaveLength(1);
+ });
+});