YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(onboarding): fail closed on the timeline choice and apply it on replay
Anshgrover237f894430ed78
diff --git a/apps/screenpipe-app-tauri/app/onboarding/page.test.tsx b/apps/screenpipe-app-tauri/app/onboarding/page.test.tsxindex 5b86d1bf0..1aa1a4d67 100644--- a/apps/screenpipe-app-tauri/app/onboarding/page.test.tsx+++ b/apps/screenpipe-app-tauri/app/onboarding/page.test.tsx@@ -306,6 +306,26 @@ describe("timeline slide sequencing", () => {expect(screen.queryByText("timeline choice")).not.toBeInTheDocument();});+ // The step writes disableTimeline AND disableScreenshots, so a policy owning+ // either one already decides the outcome and the choice must not be offered.+ it("skips straight to engine when policy manages disableScreenshots only", async () => {+ mocks.isSettingLocked.mockImplementation(+ (key: string) => key === "disableScreenshots"+ );++ render(<OnboardingPage />);++ fireEvent.click(+ await screen.findByRole("button", { name: /finish permissions/i })+ );++ await waitFor(() =>+ expect(mocks.setOnboardingStep).toHaveBeenCalledWith("engine")+ );+ expect(await screen.findByText("engine")).toBeInTheDocument();+ expect(screen.queryByText("timeline choice")).not.toBeInTheDocument();+ });+it("resumes a saved timeline step and advances to engine from it", async () => {onboardingData.currentStep = "timeline";@@ -313,4 +333,17 @@ describe("timeline slide sequencing", () => {expect(await screen.findByText("timeline choice")).toBeInTheDocument();});++ it.each(["disableTimeline", "disableScreenshots"])(+ "does not resume onto the timeline slide when policy manages %s",+ async (lockedKey) => {+ onboardingData.currentStep = "timeline";+ mocks.isSettingLocked.mockImplementation((key: string) => key === lockedKey);++ render(<OnboardingPage />);++ expect(await screen.findByText("engine")).toBeInTheDocument();+ expect(screen.queryByText("timeline choice")).not.toBeInTheDocument();+ }+ );});diff --git a/apps/screenpipe-app-tauri/app/onboarding/page.tsx b/apps/screenpipe-app-tauri/app/onboarding/page.tsxindex dcb11d5cd..ac46e2189 100644--- a/apps/screenpipe-app-tauri/app/onboarding/page.tsx+++ b/apps/screenpipe-app-tauri/app/onboarding/page.tsx@@ -137,15 +137,20 @@ export default function OnboardingPage() {policy: managedPolicy,isSettingLocked,} = useManagedPolicy();- // Nothing to choose when policy manages disableTimeline — drop the slide- // from the sequence (also keeps the progress bar count honest).+ // The timeline slide writes disableTimeline AND disableScreenshots, so a+ // policy owning either one already decides the outcome — showing the choice+ // would let it contradict what the user picked. Drop the slide from the+ // sequence in that case (which also keeps the progress bar count honest).+ const timelineChoiceLocked =+ isSettingLocked("disableTimeline") || isSettingLocked("disableScreenshots");const visibleOrder = useMemo(- () =>- SLIDE_ORDER.filter(- (s) => s !== "timeline" || !isSettingLocked("disableTimeline")- ),- [isSettingLocked]+ () => SLIDE_ORDER.filter((s) => s !== "timeline" || !timelineChoiceLocked),+ [timelineChoiceLocked]);+ // Read by the mount-only restore effect below, which must not re-run when the+ // policy resolves. Assigned during render, per the ref-mirror rule in CLAUDE.md.+ const lockedRef = React.useRef(timelineChoiceLocked);+ lockedRef.current = timelineChoiceLocked;// Restore saved step on mountuseEffect(() => {@@ -179,7 +184,11 @@ export default function OnboardingPage() {};const mapped = stepMap[step];if (mapped) {- setCurrentSlide(mapped);+ // A step saved before policy took ownership must not resume onto a+ // slide the policy now decides — skip to the next visible one.+ setCurrentSlide(+ mapped === "timeline" && lockedRef.current ? "engine" : mapped+ );}}};diff --git a/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.test.tsx b/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.test.tsxindex 621ccde33..935136047 100644--- a/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.test.tsx+++ b/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.test.tsx@@ -4,7 +4,13 @@import "@testing-library/jest-dom/vitest";import React from "react";-import { act, fireEvent, render, screen } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import TimelineChoice from "./timeline-choice";@@ -12,6 +18,9 @@ const mocks = vi.hoisted(() => ({updateSettings: vi.fn().mockResolvedValue(undefined),settings: { deviceTier: undefined as string | null | undefined },capture: vi.fn(),+ localFetch: vi.fn(),+ stopScreenpipe: vi.fn().mockResolvedValue(undefined),+ spawnScreenpipe: vi.fn().mockResolvedValue(undefined),}));vi.mock("@/lib/hooks/use-settings", () => ({@@ -21,6 +30,17 @@ vi.mock("@/lib/hooks/use-settings", () => ({}),}));+vi.mock("@/lib/api", () => ({+ localFetch: mocks.localFetch,+}));++vi.mock("@/lib/utils/tauri", () => ({+ commands: {+ stopScreenpipe: mocks.stopScreenpipe,+ spawnScreenpipe: mocks.spawnScreenpipe,+ },+}));+vi.mock("posthog-js", () => ({default: {capture: mocks.capture,@@ -32,6 +52,10 @@ describe("TimelineChoice", () => {vi.clearAllMocks();mocks.settings.deviceTier = undefined;mocks.updateSettings.mockResolvedValue(undefined);+ mocks.stopScreenpipe.mockResolvedValue(undefined);+ mocks.spawnScreenpipe.mockResolvedValue(undefined);+ // Default: nothing on the port — first-run onboarding, engine not spawned.+ mocks.localFetch.mockRejectedValue(new Error("connection refused"));});it("recommends on for high tier and keeps both capture flags on when chosen", async () => {@@ -123,19 +147,103 @@ describe("TimelineChoice", () => {expect(handleNextSlide).toHaveBeenCalledTimes(1);});- it("still advances when updateSettings fails", async () => {- mocks.settings.deviceTier = "high";+ // Fail closed: advancing on a failed write would spawn the engine with+ // capture still on — the opposite of what the user asked for.+ it("stays on the step and surfaces a retryable error when the write fails", async () => {+ mocks.settings.deviceTier = "low";mocks.updateSettings.mockRejectedValue(new Error("store write failed"));const handleNextSlide = vi.fn();render(<TimelineChoice handleNextSlide={handleNextSlide} />);+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /keep it off/i }));+ });++ expect(handleNextSlide).not.toHaveBeenCalled();+ expect(await screen.findByRole("alert")).toHaveTextContent(+ /couldn't save that choice/i,+ );+ expect(mocks.capture).toHaveBeenCalledWith(+ "onboarding_timeline_choice_failed",+ { stage: "persist" },+ );+ });++ it("advances on a retry that succeeds", async () => {+ mocks.settings.deviceTier = "low";+ mocks.updateSettings.mockRejectedValueOnce(new Error("store write failed"));+ const handleNextSlide = vi.fn();+ render(<TimelineChoice handleNextSlide={handleNextSlide} />);++ const offButton = screen.getByRole("button", { name: /keep it off/i });+ await act(async () => {+ fireEvent.click(offButton);+ });+ expect(handleNextSlide).not.toHaveBeenCalled();++ // second attempt uses the default resolved mock+ await act(async () => {+ fireEvent.click(offButton);+ });++ expect(mocks.updateSettings).toHaveBeenCalledTimes(2);+ expect(mocks.updateSettings).toHaveBeenLastCalledWith({+ disableTimeline: true,+ disableScreenshots: true,+ });+ await waitFor(() => expect(handleNextSlide).toHaveBeenCalledTimes(1));+ });++ it("does not restart screenpipe during first-run onboarding", async () => {+ mocks.settings.deviceTier = "high";+ const handleNextSlide = vi.fn();+ render(<TimelineChoice handleNextSlide={handleNextSlide} />);+await act(async () => {fireEvent.click(screen.getByRole("button", { name: /timeline on/i }));});+ expect(mocks.stopScreenpipe).not.toHaveBeenCalled();+ expect(mocks.spawnScreenpipe).not.toHaveBeenCalled();+ expect(handleNextSlide).toHaveBeenCalledTimes(1);+ });++ // Onboarding replay (tray -> "Reset Onboarding") can run while the recorder+ // is live; both flags are only read at spawn, so it has to be restarted.+ it("restarts a running engine so a replayed choice takes effect", async () => {+ mocks.settings.deviceTier = "low";+ mocks.localFetch.mockResolvedValue({ ok: true, status: 200 });+ const handleNextSlide = vi.fn();+ render(<TimelineChoice handleNextSlide={handleNextSlide} />);++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /keep it off/i }));+ });++ await waitFor(() => expect(mocks.spawnScreenpipe).toHaveBeenCalledTimes(1));+ expect(mocks.stopScreenpipe).toHaveBeenCalledTimes(1);expect(handleNextSlide).toHaveBeenCalledTimes(1);});+ it("keeps the user on the step when the restart fails", async () => {+ mocks.settings.deviceTier = "low";+ mocks.localFetch.mockResolvedValue({ ok: true, status: 200 });+ mocks.spawnScreenpipe.mockRejectedValue(new Error("spawn failed"));+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const handleNextSlide = vi.fn();+ render(<TimelineChoice handleNextSlide={handleNextSlide} />);++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: /keep it off/i }));+ });++ expect(await screen.findByRole("alert")).toHaveTextContent(+ /didn't restart/i,+ );+ expect(handleNextSlide).not.toHaveBeenCalled();+ consoleError.mockRestore();+ });+it("only persists the first choice when both buttons are clicked quickly", async () => {mocks.settings.deviceTier = "high";const handleNextSlide = vi.fn();diff --git a/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.tsx b/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.tsxindex 93c4571e9..3094fd295 100644--- a/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.tsx+++ b/apps/screenpipe-app-tauri/components/onboarding/timeline-choice.tsx@@ -6,9 +6,11 @@import React, { useRef, useState } from "react";import { motion } from "framer-motion";-import { Camera, Check, Cpu, HardDrive } from "lucide-react";+import { Camera, Check, Cpu, HardDrive, Loader } from "lucide-react";import posthog from "posthog-js";import { useSettings } from "@/lib/hooks/use-settings";+import { commands } from "@/lib/utils/tauri";+import { localFetch } from "@/lib/api";interface TimelineChoiceProps {handleNextSlide: () => void;@@ -139,27 +141,70 @@ const COSTS = [},];+/**+ * Restart screenpipe if it is already running, so a choice made on an+ * onboarding replay reaches the live recorder.+ *+ * Both flags are read at spawn, and engine-startup skips spawning when /health+ * already reports a live engine (tray → "Reset Onboarding" while recording).+ * Without this, a replayed choice would change storage and UI while the running+ * recorder kept its old behaviour until some later restart. Mirrors the+ * stop → wait → spawn sequence in components/settings/display-section.tsx.+ *+ * Returns false only when a restart was needed and failed.+ */+async function applyToRunningEngine(): Promise<boolean> {+ let engineRunning = false;+ try {+ const res = await localFetch("/health", {+ signal: AbortSignal.timeout(3000),+ });+ // /health answers 503 while a pipeline has no data yet, which still means+ // an engine is up — any response at all is enough here.+ engineRunning = !!res;+ } catch {+ // Nothing listening: first-run onboarding, engine not spawned yet.+ return true;+ }+ if (!engineRunning) return true;++ try {+ await commands.stopScreenpipe();+ await new Promise((r) => setTimeout(r, 500));+ await commands.spawnScreenpipe(null);+ return true;+ } catch (e) {+ console.error("failed to restart screenpipe after timeline choice:", e);+ return false;+ }+}+// ─── Main ────────────────────────────────────────────────────────────────────//-// Pure UI: no effects. When disableTimeline is enterprise-policy-managed the-// slide sequencer in app/onboarding/page.tsx leaves this slide out entirely.+// Pure UI apart from the persist/restart the buttons trigger. When either+// capture flag is enterprise-policy-managed the slide sequencer in+// app/onboarding/page.tsx leaves this slide out entirely.export default function TimelineChoice({ handleNextSlide }: TimelineChoiceProps) {const { settings, updateSettings } = useSettings();const mountTimeRef = useRef(Date.now());const hasAdvanced = useRef(false);+ const inFlight = useRef(false);const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);const lowTier = isLowTier(settings.deviceTier);// Recommendation: keep the timeline on unless the device is low tier.const recommendEnabled = !lowTier;const choose = async (enabled: boolean) => {- // hasAdvanced is a ref, not state: state updates don't land between two- // rapid clicks, so only a synchronous guard prevents a double persist.- if (hasAdvanced.current) return;- hasAdvanced.current = true;+ // Refs, not state: state updates don't land between two rapid clicks, so+ // only a synchronous guard prevents a double persist. inFlight is separate+ // from hasAdvanced so a failed attempt stays retryable.+ if (hasAdvanced.current || inFlight.current) return;+ inFlight.current = true;setSaving(true);+ setError(null);posthog.capture("onboarding_timeline_choice", {timeline_enabled: enabled,screenshots_enabled: enabled,@@ -167,25 +212,37 @@ export default function TimelineChoice({ handleNextSlide }: TimelineChoiceProps)followed_recommendation: enabled === recommendEnabled,time_spent_ms: Date.now() - mountTimeRef.current,});++ // Fail closed: advancing after a failed write would start the engine with+ // capture still on, i.e. the opposite of what the user just asked for —+ // worst on exactly the low-end machines this step exists to protect.try {// Both flags move together. On its own `disableTimeline` only skips the// in-memory hot frame cache — screen capture, JPEG writes, the OCR// fallback and the ffmpeg compaction worker all keep running, so "saves- // ram, cpu & disk" would not hold. `disableScreenshots` stops that work- // while accessibility-tree capture continues, which is why search, ask- // and pipes are unaffected either way.- //- // This slide runs before engine-startup spawns screenpipe, so both values- // are read at first spawn — no restart needed here (unlike the- // settings-page toggles).+ // ram, cpu & disk" would not hold.await updateSettings({disableTimeline: !enabled,disableScreenshots: !enabled,});- } catch {- // non-fatal: the defaults (both on) apply; the user can change them- // later in settings+ } catch (e) {+ console.error("failed to save timeline choice:", e);+ posthog.capture("onboarding_timeline_choice_failed", { stage: "persist" });+ setError("couldn't save that choice. check disk space and try again.");+ inFlight.current = false;+ setSaving(false);+ return;+ }++ if (!(await applyToRunningEngine())) {+ posthog.capture("onboarding_timeline_choice_failed", { stage: "restart" });+ setError("saved, but screenpipe didn't restart. try again to apply it.");+ inFlight.current = false;+ setSaving(false);+ return;}++ hasAdvanced.current = true;handleNextSlide();};@@ -267,12 +324,26 @@ export default function TimelineChoice({ handleNextSlide }: TimelineChoiceProps)</p><p className="font-mono text-[10px] text-muted-foreground/70 mt-1 leading-snug">the timeline can take a real toll on machines like this one.- keeping it off saves memory, cpu and disk — everything is still- recorded and searchable; only the visual rewind view is off.+ keeping it off saves memory, cpu and disk. the text screenpipe+ reads from your apps stays recorded and searchable — you lose the+ visual rewind, and apps that don't expose their text stop+ being captured.</p></motion.div>)}+ {/* Persist / restart failure — the step never advances past this */}+ {error && (+ <motion.p+ role="alert"+ className="w-full border border-destructive/50 bg-destructive/[0.06] p-3 mt-3 font-mono text-[10px] text-destructive leading-snug"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ >+ {error}+ </motion.p>+ )}+{/* Choice */}<motion.divclassName="w-full flex gap-2 mt-4"@@ -289,7 +360,10 @@ export default function TimelineChoice({ handleNextSlide }: TimelineChoiceProps): "border-border text-foreground hover:border-foreground"}`}>- <span>timeline on</span>+ <span className="flex items-center gap-1.5">+ {saving && <Loader className="w-3 h-3 animate-spin" />}+ timeline on+ </span>{recommendEnabled? recommendedTag: subtext("full visual rewind of your screen")}@@ -303,7 +377,10 @@ export default function TimelineChoice({ handleNextSlide }: TimelineChoiceProps): "border-border text-foreground hover:border-foreground"}`}>- <span>keep it off</span>+ <span className="flex items-center gap-1.5">+ {saving && <Loader className="w-3 h-3 animate-spin" />}+ keep it off+ </span>{!recommendEnabled? recommendedTag: subtext("saves ram, cpu & disk")}