Skip to content

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

feat(pipes): one-off polish — stale-install guard + UI cancel button

Louis Beaumontf3839d985183
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index 3674e8485..4e075f107 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -35,6 +35,7 @@ import React, { useEffect, useMemo, useState } from "react";
import { Pin, X, AlertCircle, ChevronDown, ChevronRight, Activity } from "lucide-react";
import { useRunningPipes } from "@/lib/hooks/use-running-pipes";
import { useUpcomingPipes, type UpcomingPipe } from "@/lib/hooks/use-upcoming-pipes";
+import { localFetch } from "@/lib/api";
import { emit, listen } from "@tauri-apps/api/event";
import { cn } from "@/lib/utils";
import {
@@ -90,7 +91,29 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
}, [actions]);
const runningPipes = useRunningPipes();
- const upcomingPipes = useUpcomingPipes();
+ const {
+ pipes: upcomingPipes,
+ refetch: refetchUpcoming,
+ dismiss: dismissUpcoming,
+ } = useUpcomingPipes();
+
+ // Cancel a one-off pipe before it fires. Optimistically removes the row
+ // (so the click feels instant), then disables on the server, then refetches
+ // to reconcile — if the disable failed, the row reappears on the next
+ // poll/refetch and the user can try again.
+ const handleCancelUpcoming = async (pipeName: string) => {
+ dismissUpcoming(pipeName);
+ try {
+ await localFetch(`/pipes/${encodeURIComponent(pipeName)}/enable`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled: false }),
+ });
+ } catch {
+ // best-effort — refetch reconciles either way
+ }
+ void refetchUpcoming();
+ };
// Pipe-watch / pipe-run sessions also rendered in Scheduled get filtered
// out here — otherwise the same pipe shows up twice (live row in
@@ -225,7 +248,10 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
data-testid="chat-sidebar"
>
{upcomingPipes.length > 0 && (
- <CollapsibleUpcoming pipes={upcomingPipes} />
+ <CollapsibleUpcoming
+ pipes={upcomingPipes}
+ onCancel={handleCancelUpcoming}
+ />
)}
{runningPipes.length > 0 && (
@@ -514,7 +540,13 @@ function formatCountdown(runAt: string): string | null {
* fired yet. Mirrors `CollapsibleScheduled` visually but shows a
* countdown ("in 2d 4h") instead of an elapsed badge, and uses a steady
* (non-pulsing) clock-style dot to differentiate from running pipes. */
-function CollapsibleUpcoming({ pipes }: { pipes: UpcomingPipe[] }) {
+function CollapsibleUpcoming({
+ pipes,
+ onCancel,
+}: {
+ pipes: UpcomingPipe[];
+ onCancel: (pipeName: string) => void | Promise<void>;
+}) {
const [collapsed, setCollapsedRaw] = useState<boolean>(() => {
try {
return localStorage.getItem("screenpipe:upcoming-collapsed") === "true";
@@ -558,7 +590,7 @@ function CollapsibleUpcoming({ pipes }: { pipes: UpcomingPipe[] }) {
>
<div className="flex flex-col">
{pipes.map((p) => (
- <UpcomingRow key={p.pipeName} pipe={p} />
+ <UpcomingRow key={p.pipeName} pipe={p} onCancel={onCancel} />
))}
</div>
</div>
@@ -567,7 +599,13 @@ function CollapsibleUpcoming({ pipes }: { pipes: UpcomingPipe[] }) {
);
}
-function UpcomingRow({ pipe }: { pipe: UpcomingPipe }) {
+function UpcomingRow({
+ pipe,
+ onCancel,
+}: {
+ pipe: UpcomingPipe;
+ onCancel: (pipeName: string) => void | Promise<void>;
+}) {
// Re-tick once a minute so the countdown stays fresh while the row is
// mounted. Cheap: max one timer per upcoming pipe; users rarely have
// more than a handful queued.
@@ -585,7 +623,7 @@ function UpcomingRow({ pipe }: { pipe: UpcomingPipe }) {
const absLabel = `${fireDate.toLocaleDateString()} ${fireDate.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
return (
<div
- className="flex items-center gap-2 px-2.5 py-1 mx-0 rounded-md text-foreground select-none cursor-default"
+ className="group flex items-center gap-2 px-2.5 py-1 mx-0 rounded-md text-foreground select-none cursor-default hover:bg-muted/40"
title={`scheduled for ${absLabel} — pipe: ${pipe.pipeName}`}
data-testid={`upcoming-row-${pipe.pipeName}`}
>
@@ -600,9 +638,25 @@ function UpcomingRow({ pipe }: { pipe: UpcomingPipe }) {
<span className="truncate flex-1 text-xs">
{pipe.title || pipe.pipeName}
</span>
- <span className="text-[10px] text-muted-foreground/60 tabular-nums shrink-0">
+ {/* Countdown swaps out for the cancel button on hover — keeps the row
+ height stable (no layout shift) and avoids surfacing a destructive
+ action until the user clearly intends to interact. */}
+ <span className="text-[10px] text-muted-foreground/60 tabular-nums shrink-0 group-hover:hidden">
{countdown}
</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void onCancel(pipe.pipeName);
+ }}
+ className="hidden group-hover:inline-flex items-center justify-center p-0.5 rounded hover:bg-muted text-muted-foreground shrink-0"
+ title="cancel"
+ aria-label={`cancel ${pipe.title || pipe.pipeName}`}
+ data-testid={`upcoming-cancel-${pipe.pipeName}`}
+ >
+ <X className="h-3 w-3" />
+ </button>
</div>
);
}
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-upcoming-pipes.ts b/apps/screenpipe-app-tauri/lib/hooks/use-upcoming-pipes.ts
index 6f82019ee..f8af99430 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-upcoming-pipes.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-upcoming-pipes.ts
@@ -16,7 +16,7 @@
* bus.
*/
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { localFetch } from "@/lib/api";
import { useSettings } from "@/lib/hooks/use-settings";
@@ -51,23 +51,43 @@ function parseUpcoming(raw: any[]): UpcomingPipe[] {
return out;
}
-export function useUpcomingPipes(): UpcomingPipe[] {
+export interface UseUpcomingPipesResult {
+ pipes: UpcomingPipe[];
+ /** Force a refetch — call after a mutation (cancel/install) so the
+ * sidebar reflects the change without waiting up to 30s for the
+ * next poll. */
+ refetch: () => Promise<void>;
+ /** Optimistically remove a pipe from the list. Used by cancel-handlers
+ * to make the row disappear instantly while the disable API call is
+ * in flight; the next refetch reconciles either way. */
+ dismiss: (pipeName: string) => void;
+}
+
+export function useUpcomingPipes(): UseUpcomingPipesResult {
const [pipes, setPipes] = useState<UpcomingPipe[]>([]);
const { isSettingsLoaded } = useSettings();
+ const refetch = useCallback(async () => {
+ try {
+ const res = await localFetch("/pipes");
+ if (!res.ok) return;
+ const json = await res.json();
+ setPipes(parseUpcoming(json.data || []));
+ } catch {
+ // best-effort — silent failure, retry next tick
+ }
+ }, []);
+
+ const dismiss = useCallback((pipeName: string) => {
+ setPipes((prev) => prev.filter((p) => p.pipeName !== pipeName));
+ }, []);
+
useEffect(() => {
if (!isSettingsLoaded) return;
let cancelled = false;
const poll = async () => {
- try {
- const res = await localFetch("/pipes");
- if (!res.ok) return;
- const json = await res.json();
- if (cancelled) return;
- setPipes(parseUpcoming(json.data || []));
- } catch {
- // best-effort — silent failure, retry next tick
- }
+ if (cancelled) return;
+ await refetch();
};
void poll();
const id = setInterval(poll, 30_000);
@@ -75,7 +95,7 @@ export function useUpcomingPipes(): UpcomingPipe[] {
cancelled = true;
clearInterval(id);
};
- }, [isSettingsLoaded]);
+ }, [isSettingsLoaded, refetch]);
- return pipes;
+ return { pipes, refetch, dismiss };
}
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index ef1f7e1b2..a45e81d90 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -2616,6 +2616,12 @@ impl PipeManager {
let content = std::fs::read_to_string(&pipe_md)?;
let (mut config, body) = parse_frontmatter(&content)?;
+ // Block enabling a stale one-off — would either silently no-op
+ // (caught by the scheduler's stale guard) or fire a confusingly
+ // old reminder. User must set a new `at <iso>` first.
+ if enabled {
+ validate_one_off_freshness(&config.schedule)?;
+ }
config.enabled = enabled;
let new_content = serialize_pipe(&config, &body)?;
atomic_write(&pipe_md, &new_content)?;
@@ -4110,6 +4116,39 @@ Pipe name: {}
// Schedule parsing
// ---------------------------------------------------------------------------
+/// Maximum lateness before a one-off pipe is considered stale and refused.
+/// Tolerates clock skew, brief app downtime, and crash-then-restart. Any
+/// longer than this, the user almost certainly didn't expect the task to
+/// run "now" — they expected it then. Better to no-op than surprise them.
+const ONE_OFF_STALE_THRESHOLD: chrono::Duration = chrono::Duration::hours(1);
+
+/// Validate that a `schedule: at <iso>` timestamp isn't already stale.
+/// Returns `Ok(())` for any non-one-off schedule. Called from `install_pipe`
+/// and `enable_pipe` so a stale one-off never lands on disk in the active
+/// state — the user gets a clear error instead of a silent no-op pipe.
+fn validate_one_off_freshness(schedule: &str) -> Result<()> {
+ if let Some(ParsedSchedule::Once(run_at)) = parse_schedule(schedule) {
+ let lateness = Utc::now().signed_duration_since(run_at);
+ if lateness > ONE_OFF_STALE_THRESHOLD {
+ let mins = lateness.num_minutes();
+ let pretty = if mins < 60 {
+ format!("{}m", mins)
+ } else if mins < 1440 {
+ format!("{}h", mins / 60)
+ } else {
+ format!("{}d", mins / 1440)
+ };
+ return Err(anyhow!(
+ "one-off `at <iso>` schedule is {} in the past — set a future RFC3339 \
+ timestamp (e.g. `at {}`) or use `schedule: manual` for a non-firing template",
+ pretty,
+ (Utc::now() + chrono::Duration::hours(1)).to_rfc3339()
+ ));
+ }
+ }
+ Ok(())
+}
+
/// Parsed schedule — fixed interval, cron, or a single fire-once timestamp.
pub enum ParsedSchedule {
Interval(std::time::Duration),
@@ -4338,7 +4377,20 @@ fn should_run(schedule: &str, last_run: DateTime<Utc>) -> bool {
// Fire if we've reached the timestamp AND haven't run since
// (cheap re-fire guard against in-memory last_run resets).
// The auto-disable happens in the scheduler tick after queueing.
- Utc::now() >= run_at && last_run < run_at
+ //
+ // Defense in depth against stale timestamps: if the run-at is
+ // more than ONE_OFF_STALE_THRESHOLD in the past (e.g. AI
+ // hallucinated a past time, or app was off for days and is
+ // catching up), refuse to fire — surprising the user with a
+ // "weeks-old reminder running now" is worse than missing it.
+ // Install / enable validation also rejects stale timestamps so
+ // a stale pipe never reaches the scheduler in the first place;
+ // this is the runtime backstop.
+ let now = Utc::now();
+ if now.signed_duration_since(run_at) > ONE_OFF_STALE_THRESHOLD {
+ return false;
+ }
+ now >= run_at && last_run < run_at
}
}
}
@@ -4983,9 +5035,10 @@ mod tests {
#[test]
fn test_should_run_once_in_past_unfired() {
- // Past timestamp, never fired (last_run = epoch) → fire now.
- let an_hour_ago = Utc::now() - chrono::Duration::hours(1);
- let schedule = format!("at {}", an_hour_ago.to_rfc3339());
+ // Past timestamp within the freshness window (30m < ONE_OFF_STALE_THRESHOLD),
+ // never fired (last_run = epoch) → fire now.
+ let thirty_min_ago = Utc::now() - chrono::Duration::minutes(30);
+ let schedule = format!("at {}", thirty_min_ago.to_rfc3339());
assert!(should_run(&schedule, DateTime::UNIX_EPOCH));
}
@@ -5006,6 +5059,56 @@ mod tests {
assert!(!should_run(&schedule, DateTime::UNIX_EPOCH));
}
+ #[test]
+ fn test_should_run_once_stale_refused() {
+ // Stale past timestamp (>1h) → runtime guard refuses to fire even
+ // if the pipe somehow got past install/enable validation.
+ let two_hours_ago = Utc::now() - chrono::Duration::hours(2);
+ let schedule = format!("at {}", two_hours_ago.to_rfc3339());
+ assert!(!should_run(&schedule, DateTime::UNIX_EPOCH));
+ }
+
+ #[test]
+ fn test_should_run_once_recent_past_fires() {
+ // Past timestamp within freshness window (e.g. 5 min ago — clock
+ // skew, brief downtime) still fires. Prevents needless misses.
+ let five_min_ago = Utc::now() - chrono::Duration::minutes(5);
+ let schedule = format!("at {}", five_min_ago.to_rfc3339());
+ assert!(should_run(&schedule, DateTime::UNIX_EPOCH));
+ }
+
+ #[test]
+ fn test_validate_one_off_freshness_future_ok() {
+ let in_an_hour = Utc::now() + chrono::Duration::hours(1);
+ let schedule = format!("at {}", in_an_hour.to_rfc3339());
+ assert!(validate_one_off_freshness(&schedule).is_ok());
+ }
+
+ #[test]
+ fn test_validate_one_off_freshness_recent_past_ok() {
+ let twenty_min_ago = Utc::now() - chrono::Duration::minutes(20);
+ let schedule = format!("at {}", twenty_min_ago.to_rfc3339());
+ assert!(validate_one_off_freshness(&schedule).is_ok());
+ }
+
+ #[test]
+ fn test_validate_one_off_freshness_stale_err() {
+ let three_days_ago = Utc::now() - chrono::Duration::days(3);
+ let schedule = format!("at {}", three_days_ago.to_rfc3339());
+ let err = validate_one_off_freshness(&schedule).unwrap_err();
+ let msg = err.to_string();
+ assert!(msg.contains("in the past"), "msg = {}", msg);
+ }
+
+ #[test]
+ fn test_validate_one_off_freshness_non_one_off_passes_through() {
+ // Recurring / cron / manual schedules are out-of-scope for this
+ // validator — must always return Ok.
+ assert!(validate_one_off_freshness("every 1h").is_ok());
+ assert!(validate_one_off_freshness("manual").is_ok());
+ assert!(validate_one_off_freshness("0 */2 * * *").is_ok());
+ }
+
// -- should_run ---------------------------------------------------------
#[test]