Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 182 additions & 0 deletions src/lib/file-watcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/**
* JSON file watcher shared by runner and UI machinery.
*
* `fs.watch` alone is unreliable for atomic-rename writes, so the watcher
* pairs it with a continuous mtime-polled re-read. The poll catches missed
* events; the watch keeps latency low when it does fire.
*/

import * as fs from 'fs';
import { basename, dirname } from 'node:path';
import { logToFile } from '@utils/debug';

const DEFAULT_POLL_INTERVAL_MS = 5000;
const DEFAULT_ATTACH_RETRY_INTERVAL_MS = 1000;
const DEFAULT_WATCH_DEBOUNCE_MS = 25;

export interface FileWatcherHandle {
refresh(): void;
stop(): void;
}

export interface FileWatcherOptions {
/** ms between mtime checks once the file exists. */
pollIntervalMs?: number;
/** ms between attach attempts while waiting for the file to appear. */
attachRetryIntervalMs?: number;
/** ms to coalesce duplicate filesystem events. */
watchDebounceMs?: number;
/** Ignore the file that exists when the watcher starts until it changes. */
ignoreInitialFile?: boolean;
/** Refuse to read files larger than this many bytes. */
maxFileSizeBytes?: number;
}

/** Watch `path` for JSON updates and call `onUpdate(parsed)` whenever the
* file's mtime changes and the contents are valid JSON. Caller must invoke
* `handle.stop()` to release the watcher. */
export function startFileWatcher(
path: string,
onUpdate: (parsed: unknown) => void,
options: FileWatcherOptions = {},
): FileWatcherHandle {
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const attachRetryIntervalMs =
options.attachRetryIntervalMs ?? DEFAULT_ATTACH_RETRY_INTERVAL_MS;
const watchDebounceMs = options.watchDebounceMs ?? DEFAULT_WATCH_DEBOUNCE_MS;

const watchers: fs.FSWatcher[] = [];
const intervals: Array<ReturnType<typeof setInterval>> = [];
const targetDir = dirname(path);
const targetName = basename(path);
let lastMtimeMs = 0;
let ignoredInitialSignature: string | null = null;
let watchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
let lastReadErrorSignature: string | null = null;
let stopped = false;

const signature = (stat: fs.Stats): string =>
`${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;

if (options.ignoreInitialFile) {
try {
const stat = fs.lstatSync(path);
if (stat.isFile() && !stat.isSymbolicLink()) {
ignoredInitialSignature = signature(stat);
}
} catch {
// No initial file to ignore.
}
}

const logReadError = (errorSignature: string, message: string) => {
if (lastReadErrorSignature === errorSignature) return;
lastReadErrorSignature = errorSignature;
logToFile(`[file-watcher] ${message}: ${path}`);
};

const read = (force = false) => {
let stat: fs.Stats;
try {
stat = fs.lstatSync(path);
} catch {
return;
}

if (!stat.isFile() || stat.isSymbolicLink()) return;
const fileSignature = signature(stat);

try {
if (ignoredInitialSignature) {
if (fileSignature === ignoredInitialSignature) return;
ignoredInitialSignature = null;
}
if (
options.maxFileSizeBytes !== undefined &&
stat.size > options.maxFileSizeBytes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we silently eat oversized files here (+ bad json in the catch below) → empty event plan tab, zero explanation why. can we logToFile both branches so it's actually debuggable?

) {
logReadError(
`oversized:${fileSignature}`,
`refusing oversized JSON file (${stat.size} bytes, limit ${options.maxFileSizeBytes} bytes)`,
);
return;
}
if (!force && stat.mtimeMs === lastMtimeMs) return;
lastMtimeMs = stat.mtimeMs;
const parsed: unknown = JSON.parse(fs.readFileSync(path, 'utf-8'));
lastReadErrorSignature = null;
onUpdate(parsed);
} catch (error) {
logReadError(
`invalid:${fileSignature}:${String(error)}`,
`could not read valid JSON (${String(error)})`,
);
}
};

const scheduleRead = () => {
if (stopped) return;
if (watchDebounceTimer) clearTimeout(watchDebounceTimer);
watchDebounceTimer = setTimeout(() => {
watchDebounceTimer = null;
read(true);
}, watchDebounceMs);
};

const attachWatch = () => {
watchers.push(
fs.watch(targetDir, (_eventType, filename) => {
if (filename == null || filename.toString() === targetName) {
scheduleRead();
}
}),
);
};

intervals.push(setInterval(() => read(), pollIntervalMs));

try {
attachWatch();
// Defer the initial callback until the caller has received the handle, so
// callbacks that stop their watcher cannot race handle assignment.
queueMicrotask(() => {
if (!stopped) read(true);
});
} catch {
// Parent directory does not exist yet. Polling still covers a later file;
// retry attaching the low-latency directory watcher until it appears.
const attachInterval = setInterval(() => {
try {
fs.accessSync(targetDir);
clearInterval(attachInterval);
const idx = intervals.indexOf(attachInterval);
if (idx >= 0) intervals.splice(idx, 1);
attachWatch();
read(true);
} catch {
// Still waiting.
}
}, attachRetryIntervalMs);
intervals.push(attachInterval);
}

return {
refresh() {
if (stopped) return;
if (watchDebounceTimer) {
clearTimeout(watchDebounceTimer);
watchDebounceTimer = null;
}
read(true);
},
stop() {
stopped = true;
if (watchDebounceTimer) {
clearTimeout(watchDebounceTimer);
watchDebounceTimer = null;
}
for (const watcher of watchers) watcher.close();
for (const interval of intervals) clearInterval(interval);
},
};
}
2 changes: 2 additions & 0 deletions src/lib/programs/posthog-integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { HostResolution } from '@lib/host-resolution';
import { POSTHOG_INTEGRATION_PROGRAM } from './steps.js';
import { getContentBlocks } from './content/index.js';
import { buildCodingAgentPrompt } from './handoff.js';
import { EVENT_PLAN_FILE } from './constants.js';

const DASHBOARD_DEEP_LINK_KEY = 'dashboardDeepLink';

Expand All @@ -42,6 +43,7 @@ export const posthogIntegrationConfig: ProgramConfig = {
description: 'Set up PostHog SDK integration',
id: 'posthog-integration',
agentFlow: 'integration-v2',
eventPlanFile: EVENT_PLAN_FILE,
steps: POSTHOG_INTEGRATION_PROGRAM,
getContentBlocks,
// Basic integration runs without structured user input; drop wizard_ask
Expand Down
7 changes: 7 additions & 0 deletions src/lib/programs/program-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,13 @@ export interface ProgramConfig {
* read it synchronously without resolving a deferred `run` function.
*/
reportFile?: string;
/**
* Agent-authored event-plan artifact to mirror into the wizard session.
* Relative to `session.installDir`. Programs that do not produce an event
* plan leave this unset, so generic runner machinery does not inspect a
* stale or unrelated `.posthog-events.json` file.
*/
eventPlanFile?: string;
/**
* LearnCard deck rendered in the shared `RunScreen` while the agent
* runs. Lives at `<program>/content/index.tsx` by convention.
Expand Down
4 changes: 4 additions & 0 deletions src/lib/runners/run-non-interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { analytics } from '@utils/analytics';
import { resolveNoTelemetry } from './resolve-no-telemetry';
import type { WizardStore } from '@ui/tui/store';
import type { TaskStreamPush } from '@lib/task-stream/task-stream-push';
import { join } from 'node:path';
import type { OutroData, RunPhase as RunPhaseT } from '@lib/wizard-session';

/**
Expand Down Expand Up @@ -153,6 +154,9 @@ export function runNonInteractive(
onError: (e) => logToFile('[headless task-stream]', e.message),
}),
],
eventPlanPath: config.eventPlanFile
? join(session.installDir, config.eventPlanFile)
: undefined,
enabled: !session.noTelemetry,
});
taskStream.attach();
Expand Down
4 changes: 4 additions & 0 deletions src/lib/runners/run-wizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { WizardSession } from '@lib/wizard-session';
import type { TaskStreamPush as TaskStreamPushClass } from '@lib/task-stream/task-stream-push';
import { resolveNoTelemetry } from './resolve-no-telemetry';
import { runCleanups } from '@utils/wizard-abort';
import { join } from 'node:path';

const WIZARD_VERSION = VERSION;

Expand Down Expand Up @@ -121,6 +122,9 @@ export function runWizard(
onError: (err) => logToFile('[task-stream-push]', err.message),
}),
],
eventPlanPath: config.eventPlanFile
? join(session.installDir, config.eventPlanFile)
: undefined,
enabled: taskStreamEnabled,
});
const activeStream = taskStream;
Expand Down
Loading
Loading