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
Show workflow and step timing in compact hover details
Louis Beaumonta6e9470c3f3d
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-timing.test.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-timing.test.tsxindex 69911e1fb..0064a0795 100644--- a/apps/screenpipe-app-tauri/components/workflows/workflow-timing.test.tsx+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-timing.test.tsx@@ -1,6 +1,8 @@// screenpipe — AI that knows everything you've seen, said, or heard// https://screenpipe.comimport React from "react";+import { TimingDisclosure } from "../../../../packages/workflows-ui/src/timing-disclosure";+import { WorkflowEditor } from "../../../../packages/workflows-ui/src/workflow-editor";import { act, fireEvent, render, screen, within } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { WorkflowsApp, workflowTiming, sanitizeWorkflowAnalysis, filterWorkflows, defaultWorkflowFilters } from "@screenpipe/workflows-ui";@@ -14,6 +16,7 @@ describe("workflow elapsed timing", () => {const catalog = sanitizeWorkflowAnalysis(fixtureWorkflowAnalysis);expect(catalog.analysis.workflows.find(w => w.title === workflow.title)?.timing?.averageMinutes).toBe(24);expect(workflowTiming(null)).toBeNull();+ expect(catalog.analysis.workflows.find(w => w.title === workflow.title)?.stages[0].timing).toMatchObject({ averageMinutes: 5, sampleCount: 2 });});it("rejects invalid dates, duplicate and overlapping runs", () => {const value = workflow.timing!;@@ -21,11 +24,32 @@ describe("workflow elapsed timing", () => {expect(workflowTiming({ ...value, runs: [{ ...value.runs[0], end: { ...value.runs[0].end, timestamp: "invalid" } }] })).toBeNull();expect(workflowTiming({ ...value, basis: "model-guess" })).toBeNull();});+ it("labels legacy meeting medians accurately", () => {+ render(<TimingDisclosure value={null} label="Meeting timing" measured={{ minutes: 30, samples: 4 }} />);+ fireEvent.click(screen.getByRole("button", { name: "Meeting timing" }));+ expect(screen.getByRole("tooltip")).toHaveTextContent("30m median duration");+ expect(screen.getByRole("tooltip")).not.toHaveTextContent("on average");+ });it("filters by average time, without classifying unknowns as short runs", () => {const unknown = { ...workflow, timing: null, durationSource: "unknown" as const };expect(filterWorkflows([workflow, unknown], { ...defaultWorkflowFilters, duration: "medium" })).toEqual([workflow]);expect(filterWorkflows([unknown], { ...defaultWorkflowFilters, duration: "short" })).toEqual([]);});+ it("keeps step timing tied to its source on reorder and hides stale timing while editing", async () => {+ sessionStorage.clear();+ render(<WorkflowEditor workflow={workflow} save={() => new Promise(() => {})} />);+ fireEvent.keyDown(screen.getByRole("button", { name: "Move step 1" }), { key: "ArrowDown", altKey: true });+ const moved = screen.getByRole("button", { name: "Timing for step 2" });+ fireEvent.mouseEnter(moved);+ expect(screen.getByRole("tooltip")).toHaveTextContent("5m on average");+ fireEvent.mouseLeave(moved);+ fireEvent.change(screen.getByRole("textbox", { name: "Step 2 title" }), { target: { value: "Different scope" } });+ fireEvent.mouseEnter(moved);+ expect(screen.getByRole("tooltip")).toHaveTextContent("Time not measured yet");+ fireEvent.mouseLeave(moved);+ fireEvent.mouseEnter(screen.getByRole("button", { name: "Workflow timing" }));+ expect(screen.getByRole("tooltip")).toHaveTextContent("Time not measured yet");+ });it("shows average, single and unknown cards without the removed evidence diagnostics", async () => {window.history.replaceState(null, "", "/home?mode=workflows");const openLink = vi.fn().mockResolvedValue(undefined);@@ -33,18 +57,40 @@ describe("workflow elapsed timing", () => {platform.assistant!.openLink = openLink;await act(async () => { render(<WorkflowsApp platform={platform} initialAnalysis={fixtureWorkflowAnalysis} storageKey={null} />); });const card = screen.getByRole("heading", { name: "Research synthesis" }).closest("article")!;- expect(within(card).getByText(/~24m \/ run · estimated/)).toBeVisible();+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();+ const clock = within(card).getByRole("button", { name: "Timing for Research synthesis" });+ fireEvent.mouseEnter(clock);+ expect(screen.getByRole("tooltip")).toHaveTextContent("24m on average");+ expect(screen.getByRole("tooltip")).toHaveTextContent("3 observed runs · 18m to 30m");+ fireEvent.keyDown(clock, { key: "Escape" });+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();expect(within(card).getByText(workflow.description)).toBeVisible();expect(card.querySelector("details")).toBeNull();- expect(within(card).getAllByRole("button")).toHaveLength(1);+ expect(within(card).getAllByRole("button")).toHaveLength(2);const single = screen.getByRole("heading", { name: "Partner meeting preparation" }).closest("article")!;- expect(within(single).getByText(/~12m \/ run · estimated/)).toBeVisible();+ const singleClock = within(single).getByRole("button", { name: "Timing for Partner meeting preparation" });+ fireEvent.focus(singleClock);+ expect(screen.getByRole("tooltip")).toHaveTextContent("12m for one run");+ expect(screen.getByRole("tooltip")).not.toHaveTextContent("on average");+ fireEvent.blur(singleClock);const unknown = screen.getByRole("heading", { name: "Website release check" }).closest("article")!;expect(within(unknown).queryByText(/\/ run/)).not.toBeInTheDocument();fireEvent.click(within(card).getByRole("button", { name: "Open map" }));expect(screen.queryByText("Correct this workflow")).not.toBeInTheDocument();expect(screen.queryByText("Evidence and limitations")).not.toBeInTheDocument();expect(screen.getByRole("region", { name: "Questions and feedback" })).toBeVisible();+ const global = screen.getByRole("button", { name: "Workflow timing" });+ fireEvent.click(global);+ expect(screen.getByRole("tooltip")).toHaveTextContent("24m on average");+ fireEvent.pointerDown(document.body);+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();+ const step = screen.getByRole("button", { name: "Timing for step 1" });+ fireEvent.mouseEnter(step);+ expect(screen.getByRole("tooltip")).toHaveTextContent("5m on average");+ expect(screen.getByRole("tooltip")).toHaveTextContent("2 observed runs · 4m to 6m");+ fireEvent.mouseLeave(step);+ fireEvent.focus(screen.getByRole("button", { name: "Timing for step 2" }));+ expect(screen.getByRole("tooltip")).toHaveTextContent("Time not measured yet");// Removing diagnostic chrome must not discard the persisted run boundaries.expect(workflowTiming(workflow.timing)).toMatchObject({ averageMinutes: 24, sampleCount: 3 });});diff --git a/apps/screenpipe-workflows-web/scripts/check-workflow-timing-browser.cjs b/apps/screenpipe-workflows-web/scripts/check-workflow-timing-browser.cjsindex 445615d1c..42c04cc1b 100644--- a/apps/screenpipe-workflows-web/scripts/check-workflow-timing-browser.cjs+++ b/apps/screenpipe-workflows-web/scripts/check-workflow-timing-browser.cjs@@ -1,46 +1,90 @@// screenpipe — AI that knows everything you've seen, said, or heard// https://screenpipe.com-// Consume the catalog saved by workflow_timing_e2e. No user data or live app writes.+// Test the real desktop browser preview. Optionally use the native test's saved catalog.const { chromium } = require('playwright');const assert = require('node:assert/strict');const fs = require('node:fs');+const path = require('node:path');const catalogPath = process.env.WORKFLOW_TIMING_CATALOG_OUTPUT;-if (!catalogPath) throw new Error('Set WORKFLOW_TIMING_CATALOG_OUTPUT to the native test catalog');-const catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf8'));-const workflow = catalog.analysis.workflows[0];+const catalog = catalogPath ? JSON.parse(fs.readFileSync(catalogPath, 'utf8')) : null;+const title = catalog?.analysis.workflows[0].title || 'Research synthesis';+const average = catalog ? '7m' : '24m';+const stepTime = catalog ? '4m for one run' : '5m on average';+const output = process.env.WORKFLOW_TIMING_ARTIFACTS || '/tmp/workflow-timing-hover';+fs.mkdirSync(output, { recursive: true });(async () => {- const browser = await chromium.launch({ headless: true, channel: 'chrome' });+ const browser = await chromium.launch({ headless: true, channel: "chrome" });+ let page;try {- const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });+ page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });const errors = [];page.on('pageerror', error => errors.push(error.message));- const base = process.env.WORKFLOW_TIMING_PREVIEW_URL || 'http://127.0.0.1:1437/preview.html';- await page.goto(base + '?catalog=empty');- await page.evaluate(value => localStorage.setItem('screenpipe:fictional-workflow-editor-preview', JSON.stringify(value)), catalog);- await page.goto(base + '?catalog=native-timing');- await page.getByRole('heading', { name: workflow.title, exact: true }).waitFor();- await page.getByText(/~7m \/ run · estimated/).waitFor();- await page.getByText('Workflow details', { exact: true }).click();- await page.getByText('~7m', { exact: true }).waitFor();- assert.equal(await page.getByText('2 runs · estimated', { exact: true }).count(), 1);- await page.locator('article').first().screenshot({ path: process.env.WORKFLOW_TIMING_CARD_SCREENSHOT || '/tmp/workflow-timing-native-card.png' });- await page.getByRole('button', { name: 'Open map' }).click();- await page.getByText('Evidence and limitations', { exact: true }).click();- const region = page.getByRole('region', { name: 'Time per run' });- await region.waitFor();- assert.match(await region.innerText(), /6m–8m across 2 runs/);- assert.equal(await region.locator('summary').count(), 2);- await region.locator('summary').first().click();- await region.getByText(workflow.timing.runs[0].start.quote, { exact: true }).waitFor();- await region.getByText(workflow.timing.runs[0].end.quote, { exact: true }).waitFor();- await page.screenshot({ path: process.env.WORKFLOW_TIMING_SCREENSHOT || '/tmp/workflow-timing-native-ui.png', fullPage: true });+ const base = process.env.WORKFLOW_TIMING_PREVIEW_URL || 'http://127.0.0.1:1420/home?mode=workflows';+ if (catalog) await page.addInitScript(value => { const key = 'screenpipe:fictional-workflow-editor-preview'; if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(value)); }, catalog);+ await page.goto(base);+ await page.getByRole('heading', { name: title, exact: true, includeHidden: true }).waitFor({ state: 'attached' });+ // The mock desktop can show the unrelated storage migration prompt on first launch.+ const later = page.getByRole('button', { name: 'Do later', exact: true });+ try { await later.waitFor({ timeout: 5000 }); await later.click(); }+ catch (error) { if (error.name !== 'TimeoutError') throw error; }+ const card = page.getByRole('heading', { name: title, exact: true }).locator('..');+ await card.waitFor();+ assert.equal(await page.getByRole('tooltip').count(), 0);+ await page.screenshot({ path: path.join(output, 'catalog.png') });+ const cardClock = card.getByRole('button', { name: `Timing for ${title}`, exact: true });+ await cardClock.hover();+ await page.getByRole('tooltip').getByText(`${average} on average`, { exact: true }).waitFor();+ await card.screenshot({ path: path.join(output, 'card-hover.png') });+ await cardClock.focus();+ await page.keyboard.press('Escape');+ assert.equal(await page.getByRole('tooltip').count(), 0);+ await card.getByRole('button', { name: 'Open map' }).click();+ const titleInput = page.getByRole('textbox', { name: 'Workflow title', exact: true });+ await titleInput.waitFor();+ const global = page.getByRole('button', { name: 'Workflow timing', exact: true });+ await global.hover();+ await page.getByRole('tooltip').getByText(`${average} on average`, { exact: true }).waitFor();+ await page.screenshot({ path: path.join(output, 'workflow-hover.png') });+ await titleInput.hover();+ const first = page.getByRole('button', { name: 'Timing for step 1', exact: true });+ await first.hover();+ await page.getByRole('tooltip').getByText(stepTime, { exact: true }).waitFor();+ await page.screenshot({ path: path.join(output, 'step-hover.png') });+ await first.focus();+ await page.keyboard.press('Escape');+ assert.equal(await page.getByRole('tooltip').count(), 0);+ const unknown = page.getByRole('button', { name: 'Timing for step 2', exact: true });+ await unknown.click();+ await page.getByRole('tooltip').getByText('Time not measured yet', { exact: true }).waitFor();+ await titleInput.click();+ assert.equal(await page.getByRole('tooltip').count(), 0);+ // Keyboard reorder must keep the sampled timing with the step's source.+ await page.getByRole('button', { name: 'Move step 1', exact: true }).focus();+ await page.keyboard.press('Alt+ArrowDown');+ await page.getByRole('button', { name: 'Timing for step 2', exact: true }).hover();+ await page.getByRole('tooltip').getByText(stepTime, { exact: true }).waitFor();+ // Wait for the real fixture adapter's autosave, then reload and reopen.+ await page.getByText('Saved', { exact: true }).waitFor();+ await page.reload();+ await page.getByRole('heading', { name: title, exact: true, includeHidden: true }).waitFor({ state: 'attached' });+ try { await later.waitFor({ timeout: 5000 }); await later.click(); }+ catch (error) { if (error.name !== 'TimeoutError') throw error; }+ const reopenedCard = page.getByRole('heading', { name: title, exact: true }).locator('..');+ await reopenedCard.getByRole('button', { name: 'Open map' }).click();+ await page.getByRole('textbox', { name: 'Workflow title', exact: true }).waitFor();+ await page.getByRole('button', { name: 'Timing for step 2', exact: true }).hover();+ await page.getByRole('tooltip').getByText(stepTime, { exact: true }).waitFor();await page.setViewportSize({ width: 700, height: 900 });+ const clock = page.getByRole('button', { name: 'Timing for step 2', exact: true });+ await clock.click();+ const bounds = await page.getByRole('tooltip').boundingBox();+ assert(bounds && bounds.x >= 0 && bounds.x + bounds.width <= 700, 'timing disclosure fits narrow window');assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));- await page.goto(base + '?catalog=native-timing');- await page.getByText(/~7m \/ run · estimated/).waitFor();- await page.reload();- await page.getByText(/~7m \/ run · estimated/).waitFor();+ await page.screenshot({ path: path.join(output, 'narrow.png') });assert.deepEqual(errors, []);- console.log('PASS native saved catalog: 7m average, two distinct runs, evidence disclosure, narrow layout, reload, no browser errors');+ console.log('PASS averages, single/unknown timing, hover, keyboard/Escape, tap/dismiss, reorder, saved reload, narrow layout, no browser errors');+ } catch (error) {+ if (page) { console.error('Browser state:', page.url(), (await page.locator('body').innerText()).slice(0,5000)); await page.screenshot({ path: path.join(output, 'failure.png') }); }+ throw error;} finally { await browser.close(); }})().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/crates/screenpipe-core/assets/pipes/workflow-discovery/output.md b/crates/screenpipe-core/assets/pipes/workflow-discovery/output.mdindex 0e40261c4..534827e60 100644--- a/crates/screenpipe-core/assets/pipes/workflow-discovery/output.md+++ b/crates/screenpipe-core/assets/pipes/workflow-discovery/output.md@@ -1 +1 @@-{"evidenceVersion":2,"workflows":[{"id":string|null,"title":string,"description":string,"trigger":string,"outcome":string,"confidence":integer,"apps":[string],"people":[string],"teams":[string],"handoffs":[string],"variations":[string],"openQuestions":[string],"limitations":[string],"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"captureSequence":[{"timestamp":string,"app":string}],"stages":[{"name":string,"description":string,"screenshotFrameIds":[integer],"confidence":integer,"apps":[string],"procedure":[{"kind":"action"|"input"|"output"|"decision"|"check","text":string,"timestamp":string,"app":string,"quote":string}],"openQuestions":[string],"evidence":[{"timestamp":string,"app":string}]}],"bottlenecks":[{"label":string,"stage":string,"type":"waiting"|"switching"|"rework"|"handoff"|"unclear","control":"direct"|"influence"|"external"|"required","controlReason":string,"detail":string,"confidence":integer}],"evidence":[{"timestamp":string,"app":string}]}],"timeCategories":[{"label":string,"description":string,"rowIds":[string]}]}.+{"evidenceVersion":2,"workflows":[{"id":string|null,"title":string,"description":string,"trigger":string,"outcome":string,"confidence":integer,"apps":[string],"people":[string],"teams":[string],"handoffs":[string],"variations":[string],"openQuestions":[string],"limitations":[string],"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"captureSequence":[{"timestamp":string,"app":string}],"stages":[{"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"name":string,"description":string,"screenshotFrameIds":[integer],"confidence":integer,"apps":[string],"procedure":[{"kind":"action"|"input"|"output"|"decision"|"check","text":string,"timestamp":string,"app":string,"quote":string}],"openQuestions":[string],"evidence":[{"timestamp":string,"app":string}]}],"bottlenecks":[{"label":string,"stage":string,"type":"waiting"|"switching"|"rework"|"handoff"|"unclear","control":"direct"|"influence"|"external"|"required","controlReason":string,"detail":string,"confidence":integer}],"evidence":[{"timestamp":string,"app":string}]}],"timeCategories":[{"label":string,"description":string,"rowIds":[string]}]}.diff --git a/crates/screenpipe-core/assets/pipes/workflow-review/output.md b/crates/screenpipe-core/assets/pipes/workflow-review/output.mdindex 9e2fa8328..70ff32e68 100644--- a/crates/screenpipe-core/assets/pipes/workflow-review/output.md+++ b/crates/screenpipe-core/assets/pipes/workflow-review/output.md@@ -1 +1 @@-{"id":string|null,"title":string,"description":string,"trigger":string,"outcome":string,"confidence":integer,"apps":[string],"people":[string],"teams":[string],"handoffs":[string],"variations":[string],"openQuestions":[string],"limitations":[string],"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"captureSequence":[{"timestamp":string,"app":string}],"stages":[{"name":string,"description":string,"screenshotFrameIds":[integer],"confidence":integer,"apps":[string],"procedure":[{"kind":"action"|"input"|"output"|"decision"|"check","text":string,"timestamp":string,"app":string,"quote":string}],"openQuestions":[string],"evidence":[{"timestamp":string,"app":string}]}],"bottlenecks":[{"label":string,"stage":string,"type":"waiting"|"switching"|"rework"|"handoff"|"unclear","control":"direct"|"influence"|"external"|"required","controlReason":string,"detail":string,"confidence":integer}],"evidence":[{"timestamp":string,"app":string}]}+{"id":string|null,"title":string,"description":string,"trigger":string,"outcome":string,"confidence":integer,"apps":[string],"people":[string],"teams":[string],"handoffs":[string],"variations":[string],"openQuestions":[string],"limitations":[string],"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"captureSequence":[{"timestamp":string,"app":string}],"stages":[{"timingRuns":[{"start":{"timestamp":string,"app":string,"quote":string},"end":{"timestamp":string,"app":string,"quote":string},"summary":string}],"name":string,"description":string,"screenshotFrameIds":[integer],"confidence":integer,"apps":[string],"procedure":[{"kind":"action"|"input"|"output"|"decision"|"check","text":string,"timestamp":string,"app":string,"quote":string}],"openQuestions":[string],"evidence":[{"timestamp":string,"app":string}]}],"bottlenecks":[{"label":string,"stage":string,"type":"waiting"|"switching"|"rework"|"handoff"|"unclear","control":"direct"|"influence"|"external"|"required","controlReason":string,"detail":string,"confidence":integer}],"evidence":[{"timestamp":string,"app":string}]}diff --git a/crates/screenpipe-core/assets/skills/screenpipe-workflow-maintenance/SKILL.md b/crates/screenpipe-core/assets/skills/screenpipe-workflow-maintenance/SKILL.mdindex 40490f4a9..dd6fe8e5c 100644--- a/crates/screenpipe-core/assets/skills/screenpipe-workflow-maintenance/SKILL.md+++ b/crates/screenpipe-core/assets/skills/screenpipe-workflow-maintenance/SKILL.md@@ -75,6 +75,13 @@ replace measurements with [] because this interval has no new occurrence. If timstays unknown, preserve the procedure and explain the missing boundary, interruptionor failed lookup in limitations. Investigate first; never invent a UI number.+For individual steps, save optional stages[].timingRuns using the same boundary+format and continuity checks. Investigate the start and completion of that step,+not just the whole job. Keep valid prior step runs and leave [] when boundaries+are missing. Never divide a workflow total among steps or sum step averages into+a workflow average: samples and gaps can differ. The app computes each average+independently. A single run is labeled as one observation, not a typical average.+## Older installed pipeline tasksOnly without workflow_workspace and when explicitly assigned the legacy pipeline:diff --git a/crates/screenpipe-core/src/workflows/evidence.rs b/crates/screenpipe-core/src/workflows/evidence.rsindex 033e8bcd7..729a83e14 100644--- a/crates/screenpipe-core/src/workflows/evidence.rs+++ b/crates/screenpipe-core/src/workflows/evidence.rs@@ -31,6 +31,16 @@ fn references(.and_then(Value::as_array).into_iter().flatten()+ .chain(+ stage+ .get("timingRuns")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .flat_map(|run| {+ [run.get("start"), run.get("end")].into_iter().flatten()+ }),+ )}).chain(workflow@@ -431,10 +441,18 @@ mod tests {.unwrap().with_timezone(&Utc);let end = start + ChronoDuration::minutes(20);- let value = json!({"workflows":[{"timingRuns":[{"start":{"timestamp":start,"app":"Editor"},"end":{"timestamp":end,"app":"Browser"}}]}]});+ let run = json!({"start":{"timestamp":start,"app":"Editor"},"end":{"timestamp":end,"app":"Browser"}});+ let value =+ json!({"workflows":[{"stages":[{"timingRuns":[run.clone()]}],"timingRuns":[run]}]});assert_eq!(references(&value, start, start + ChronoDuration::days(1)).unwrap(),vec![(start, "Editor".into()), (end, "Browser".into())]);+ let mut step_only = value;+ step_only["workflows"][0]["timingRuns"] = json!([]);+ assert_eq!(+ references(&step_only, start, start + ChronoDuration::days(1)).unwrap(),+ vec![(start, "Editor".into()), (end, "Browser".into())]+ );}}diff --git a/crates/screenpipe-core/src/workflows/mod.rs b/crates/screenpipe-core/src/workflows/mod.rsindex 2eea80a2d..550eda5e8 100644--- a/crates/screenpipe-core/src/workflows/mod.rs+++ b/crates/screenpipe-core/src/workflows/mod.rs@@ -691,6 +691,7 @@ pub fn normalize_analysis(stages.push(json!({"name": name,"description": stage_description,+ "timing": timing::normalize_timing(stage, catalog)?,"procedure": procedure,"openQuestions": open_questions,"activeMinutes": 0,diff --git a/crates/screenpipe-core/src/workflows/timing.rs b/crates/screenpipe-core/src/workflows/timing.rsindex 632c75052..2186f6698 100644--- a/crates/screenpipe-core/src/workflows/timing.rs+++ b/crates/screenpipe-core/src/workflows/timing.rs@@ -14,7 +14,7 @@ pub fn normalize_timing(value: &Value, catalog: &EvidenceCatalog) -> Result<Valureturn Ok(Value::Null);}if proposed.len() > 30 {- return Err("Keep at most 30 representative timing runs per workflow".into());+ return Err("Keep at most 30 representative timing runs per workflow or step".into());}let boundary = |value: &Value| -> Result<(DateTime<Utc>, Value), String> {let at = value["timestamp"]@@ -51,7 +51,7 @@ pub fn normalize_timing(value: &Value, catalog: &EvidenceCatalog) -> Result<Valureturn Err("A timing run must finish after it starts".into());}let summary = non_empty_string(run, "summary")- .ok_or("Explain why the timing boundaries belong to one complete workflow run")?;+ .ok_or("Explain why the timing boundaries belong to one complete occurrence")?;runs.push((start,end,@@ -128,6 +128,8 @@ mod tests {json!({"name":key,"description":"A source-backed review step","evidence":[boundary],"procedure":[{"kind":"action","text":"Review research","timestamp":boundary["timestamp"],"app":boundary["app"],"quote":boundary["quote"]}]})}).collect::<Vec<_>>());+ // Each step has independent samples; unknown steps must stay unknown.+ workflow["stages"][0]["timingRuns"] = json!([workflow["timingRuns"][0]]);let result = normalize_analysis(json!({"evidenceVersion":2,"workflows":[workflow.clone()]}),90,@@ -135,6 +137,24 @@ mod tests {).unwrap();assert_eq!(result["workflows"][0]["timing"]["averageMinutes"], 30.0);+ assert_eq!(+ result["workflows"][0]["stages"][0]["timing"]["averageMinutes"],+ 10.0+ );+ assert_eq!(+ result["workflows"][0]["stages"][0]["timing"]["sampleCount"],+ 1+ );+ assert!(result["workflows"][0]["stages"][1]["timing"].is_null());+ let mut bad_step = workflow.clone();+ bad_step["stages"][0]["timingRuns"][0]["end"]["quote"] =+ json!("Fabricated step completion");+ assert!(normalize_analysis(+ json!({"evidenceVersion":2,"workflows":[bad_step]}),+ 90,+ &catalog+ )+ .is_err());// Timing does not promote elapsed time to active time or verified steps.assert_eq!(result["workflows"][0]["activeMinutes"], 0);workflow["timingRuns"][0]["start"]["timestamp"] = json!("2020-01-01T00:00:00Z");diff --git a/crates/screenpipe-engine/src/routes/workflow_catalog.rs b/crates/screenpipe-engine/src/routes/workflow_catalog.rsindex 9a3e31a6e..65a310276 100644--- a/crates/screenpipe-engine/src/routes/workflow_catalog.rs+++ b/crates/screenpipe-engine/src/routes/workflow_catalog.rs@@ -116,7 +116,7 @@ pub(crate) async fn context("confidence":w["confidence"], "people":w["people"], "teams":w["teams"], "handoffs":w["handoffs"], "variations":w["variations"], "bottlenecks":w["bottlenecks"], "captureSequence":w["captureSequence"],"timingRuns":w["timing"]["runs"], "limitations":w["limitations"], "openQuestions":w["openQuestions"], "quality":w["quality"], "apps":w["apps"],"evidence":context_source_refs(&w["evidence"]),- "stages":w["stages"].as_array().into_iter().flatten().map(|s| json!({"name":s["name"],"description":s["description"],"apps":s["apps"],"confidence":s["confidence"],"userEdited":s["userEdited"],"screenshot":s.get("screenshot").filter(|v| v.is_object()).map(|v| json!({"frameId":v["frameId"],"timestamp":v["timestamp"],"app":v["app"],"visualVerified":v["visualVerified"]})),"screenshots":stage_screenshots(s).iter().map(|v| json!({"frameId":v["frameId"],"timestamp":v["timestamp"],"app":v["app"],"visualVerified":v["visualVerified"]})).collect::<Vec<_>>(),"procedure":s["procedure"],"evidence":context_source_refs(&s["evidence"]),"openQuestions":s["openQuestions"]})).collect::<Vec<_>>()+ "stages":w["stages"].as_array().into_iter().flatten().map(|s| json!({"name":s["name"],"description":s["description"],"timingRuns":s["timing"]["runs"],"apps":s["apps"],"confidence":s["confidence"],"userEdited":s["userEdited"],"screenshot":s.get("screenshot").filter(|v| v.is_object()).map(|v| json!({"frameId":v["frameId"],"timestamp":v["timestamp"],"app":v["app"],"visualVerified":v["visualVerified"]})),"screenshots":stage_screenshots(s).iter().map(|v| json!({"frameId":v["frameId"],"timestamp":v["timestamp"],"app":v["app"],"visualVerified":v["visualVerified"]})).collect::<Vec<_>>(),"procedure":s["procedure"],"evidence":context_source_refs(&s["evidence"]),"openQuestions":s["openQuestions"]})).collect::<Vec<_>>()})).collect();Ok(Json(json!({"revision":value["revision"].as_u64().unwrap_or(0), "now":Utc::now().to_rfc3339(),diff --git a/crates/screenpipe-engine/src/routes/workflow_edits.rs b/crates/screenpipe-engine/src/routes/workflow_edits.rsindex 369ef64eb..c82ade86d 100644--- a/crates/screenpipe-engine/src/routes/workflow_edits.rs+++ b/crates/screenpipe-engine/src/routes/workflow_edits.rs@@ -160,6 +160,7 @@ fn apply_edit(previous: &Value, body: &EditRequest) -> Result<Value, ApiError> {next["procedure"] = json!(details);}if next != prior {+ next["timing"] = Value::Null;next["userEdited"] = json!(true);}stages.push(next);@@ -264,6 +265,28 @@ mod tests {assert_eq!(prior, original());}#[test]+ fn step_timing_follows_reorders_but_not_changed_instructions() {+ let mut prior = original();+ prior["stages"][0]["timing"] = json!({"averageMinutes":2});+ prior["stages"][1]["timing"] = json!({"averageMinutes":3});+ let mut body = request();+ body.stages.swap(0, 1);+ let reordered = apply_edit(&prior, &body).unwrap();+ assert_eq!(+ reordered["stages"][0]["timing"],+ prior["stages"][1]["timing"]+ );+ assert_eq!(+ reordered["stages"][1]["timing"],+ prior["stages"][0]["timing"]+ );+ assert!(reordered["timing"].is_null());+ body.stages[1].procedure[0].text = "Read a different set of sources".into();+ let edited = apply_edit(&prior, &body).unwrap();+ assert!(edited["stages"][1]["timing"].is_null());+ assert_eq!(edited["stages"][0]["timing"], prior["stages"][1]["timing"]);+ }+ #[test]fn rename_reorder_add_delete_preserve_references_not_verification() {let prior = original();let mut body = request();diff --git a/crates/screenpipe-engine/tests/workflow_timing_e2e.rs b/crates/screenpipe-engine/tests/workflow_timing_e2e.rsindex 0a8218b96..f708a8fa7 100644--- a/crates/screenpipe-engine/tests/workflow_timing_e2e.rs+++ b/crates/screenpipe-engine/tests/workflow_timing_e2e.rs@@ -23,7 +23,8 @@ fn fixture() -> Value {// Publication must validate this fifth reference before applying UI limits.stages[0]["evidence"] = json!(rows);stages[0]["procedure"].as_array_mut().unwrap().push(json!({"kind":"check","text":"Verify the receipt total.","timestamp":rows[4]["timestamp"],"app":"Receipts","quote":rows[4]["quote"]}));- json!({"rows":rows,"expectedAverageMinutes":7,"expectedSamples":2,"payload":{"id":"wf-receipts","title":"Record vendor invoice receipts","description":"Enter vendor invoices and confirm the receipts are saved.","trigger":"A vendor invoice arrives","outcome":"Receipt saved","apps":["Receipts"],"confidence":90,"timingRuns":runs,"stages":stages,"evidence":rows,"captureSequence":[rows[0],rows[1]],"limitations":[],"openQuestions":[],"variations":[],"bottlenecks":[]}})+ stages[0]["timingRuns"] = json!([{"start":rows[0],"end":rows[4],"summary":"Invoice entry ends when the total is verified."}]);+ json!({"rows":rows,"expectedStepAverageMinutes":4,"expectedAverageMinutes":7,"expectedSamples":2,"payload":{"id":"wf-receipts","title":"Record vendor invoice receipts","description":"Enter vendor invoices and confirm the receipts are saved.","trigger":"A vendor invoice arrives","outcome":"Receipt saved","apps":["Receipts"],"confidence":90,"timingRuns":runs,"stages":stages,"evidence":rows,"captureSequence":[rows[0],rows[1]],"limitations":[],"openQuestions":[],"variations":[],"bottlenecks":[]}})}async fn post(client: &reqwest::Client, base: &str, body: Value) -> (u16, Value) {@@ -225,6 +226,17 @@ async fn timing_survives_verified_publication_retries_and_disk_reload() {assert_eq!(timing["minMinutes"], 6.0);assert_eq!(timing["maxMinutes"], 8.0);assert_eq!(timing["basis"], "estimated-elapsed");+ if let Some(expected) = input.get("expectedStepAverageMinutes") {+ let stage = &saved["analysis"]["workflows"][0]["stages"][0];+ assert_eq!(stage["timing"]["averageMinutes"].as_f64(), expected.as_f64());+ assert_eq!(stage["timing"]["sampleCount"], 1);+ assert!(saved["analysis"]["workflows"][0]["stages"][1]["timing"].is_null());+ let context = get(&client, &base, "/workflows/context").await;+ assert_eq!(+ context["workflows"][0]["stages"][0]["timingRuns"],+ stage["timing"]["runs"]+ );+ }let disk: Value = serde_json::from_slice(&tokio::fs::read(&path).await.unwrap()).unwrap();// HTTP localizes timestamps; disk stores UTC. Compare instants, not offsets.let canonical = |mut value: Value| {@@ -256,6 +268,10 @@ async fn timing_survives_verified_publication_retries_and_disk_reload() {}let reloaded = get(&client, &base, "/workflows/catalog").await;assert_eq!(reloaded["analysis"]["workflows"][0]["timing"], *timing);+ assert_eq!(+ reloaded["analysis"]["workflows"][0]["stages"][0]["timing"],+ saved["analysis"]["workflows"][0]["stages"][0]["timing"]+ );assert_eq!(reloaded["agentWorkspace"]["cycle"]["status"], "complete");if let Ok(output) = std::env::var("WORKFLOW_TIMING_CATALOG_OUTPUT") {tokio::fs::write(output, reloaded.to_string())diff --git a/packages/workflows-ui/src/catalog.ts b/packages/workflows-ui/src/catalog.tsindex 7c533469c..f391fe2cb 100644--- a/packages/workflows-ui/src/catalog.ts+++ b/packages/workflows-ui/src/catalog.ts@@ -145,6 +145,7 @@ export function sanitizeWorkflowAnalysis(analysis: WorkflowAnalysis): WorkflowAnfrequency: `Observed on ${workflow.quality.distinctDays} captured day${workflow.quality.distinctDays === 1 ? "" : "s"} in a ${workflow.analysisDays}-day scan`,stages: workflow.stages.map((stage) => ({...stage,+ timing: workflowTiming(stage.timing),// Keep legacy image bytes for explicit SOP review. Evidence surfaces// and coverage counts still require visualVerified.activeMinutes: 0,diff --git a/packages/workflows-ui/src/fixture-platform.ts b/packages/workflows-ui/src/fixture-platform.tsindex 4584684c6..4db45f0d9 100644--- a/packages/workflows-ui/src/fixture-platform.ts+++ b/packages/workflows-ui/src/fixture-platform.ts@@ -18,6 +18,7 @@ import type {import type { WorkflowsPlatform } from "./platform";import { isAssistantState, type AssistantState, type WorkflowsAssistantPlatform } from "./assistant";import { guideKey, parseGuide, type WorkflowGuide } from "./guide";+import { isUnchangedStage } from "./workflow-edits";import { workflowTiming } from "./timing";function fixtureAssistant(): WorkflowsAssistantPlatform {@@ -124,6 +125,13 @@ function fixtureWorkflow(input: FixtureWorkflow, index: number): WorkflowMap {name,description: input.stageDetails?.[stageIndex]?.description ?? [`Gather the inputs needed to begin ${input.title.toLowerCase()}.`, "Work through the main decision and supporting context.", "Review the result and close the loop."][stageIndex],procedure: input.stageDetails?.[stageIndex]?.blocks.map(block => ({ ...block, quote: "", timestamp: "", app: "" })),+ // Explicit fictional step occurrences, independent of the workflow totals.+ timing: workflowTiming({ basis: "estimated-elapsed", runs: index === 4 && stageIndex === 0 ? [4, 6].map((minutes, i) => {+ const start = new Date(Date.UTC(2026, 8, i + 1, 16));+ return { start: { timestamp: start.toISOString(), app: input.apps[0], quote: "Started gathering fictional research inputs" },+ end: { timestamp: new Date(start.getTime() + minutes * 60_000).toISOString(), app: input.apps[0], quote: "Finished gathering fictional research inputs" },+ summary: "One uninterrupted fictional input gathering step" };+ }) : [] }),activeMinutes: stageActive,waitingMinutes: stageIndex === 1 ? input.waitingMinutes : 0,apps: [input.apps[Math.min(stageIndex, input.apps.length - 1)]],@@ -532,11 +540,13 @@ export function createFixtureWorkflowsPlatform(analysis: WorkflowAnalysis = fixtconst stages = draft.stages.map(s => {const prior = s.sourceIndex === null ? null : workflow.stages[s.sourceIndex];return { ...(prior ?? { activeMinutes: 0, waitingMinutes: 0, apps: [], confidence: 0, observedOccurrences: 0, observedDays: 0, evidence: [] }),+ timing: isUnchangedStage(s, prior ?? undefined) ? prior?.timing : null,name: s.name.trim(), description: s.description.trim(), userEdited: true,procedure: s.procedure.map(p => ({ ...(p.sourceIndex === null ? { quote: "", timestamp: "", app: "" } : prior?.procedure?.[p.sourceIndex] ?? { quote: "", timestamp: "", app: "" }), kind: p.kind, text: p.text.trim(), userEdited: true })),};});- const saved = { ...workflow, id: draft.id, revision: draft.expected_revision + 1, title: draft.title.trim(), description: draft.description.trim(), trigger: draft.trigger.trim(), outcome: draft.outcome.trim(), stages, userEditedAt: new Date().toISOString() };+ const unchangedStages = draft.stages.length === workflow.stages.length && draft.stages.every((s, i) => s.sourceIndex === i && isUnchangedStage(s, workflow.stages[i]));+ const saved = { ...workflow, ...(unchangedStages ? {} : { timing: null, durationSource: "unknown" as const, durationSampleCount: 0 }), id: draft.id, revision: draft.expected_revision + 1, title: draft.title.trim(), description: draft.description.trim(), trigger: draft.trigger.trim(), outcome: draft.outcome.trim(), stages, userEditedAt: new Date().toISOString() };const next = { ...current, analysis: { workflows: current.analysis.workflows.map(w => w === workflow ? saved : w) } };localStorage.setItem(storageKey, JSON.stringify(next));current = next;diff --git a/packages/workflows-ui/src/model.ts b/packages/workflows-ui/src/model.tsindex 0df1e6b08..b896c315a 100644--- a/packages/workflows-ui/src/model.ts+++ b/packages/workflows-ui/src/model.ts@@ -93,6 +93,7 @@ export type WorkflowScreenshot = {};export type WorkflowStage = {+ timing?: WorkflowTiming | null;userEdited?: boolean;name: string;description: string;diff --git a/packages/workflows-ui/src/timing-disclosure.module.css b/packages/workflows-ui/src/timing-disclosure.module.cssnew file mode 100644index 000000000..03f9f974a--- /dev/null+++ b/packages/workflows-ui/src/timing-disclosure.module.css@@ -0,0 +1,12 @@+/* screenpipe — AI that knows everything you've seen, said, or heard */+/* https://screenpipe.com */+.root { position: relative; display: inline-flex; flex: none; align-self: flex-start; font-size: 12px; }+.root .trigger { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 4px; border: 0; border-radius: 4px; background: transparent; color: var(--muted); cursor: pointer; }+.root .trigger:hover, .root .trigger[aria-expanded="true"] { color: var(--ink); background: var(--soft); }+.root .trigger:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }+.anchor { position: absolute; top: 100%; right: 0; z-index: 20; padding-top: 4px; width: min(250px, calc(100vw - 48px)); }+.content { box-sizing: border-box; display: flex; flex-direction: column; gap: 5px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); color: var(--ink); box-shadow: 0 4px 16px #00000012; text-align: left; font-size: 12px; line-height: 1.5; font-weight: 400; }+.content strong { font-size: 13px; font-weight: 600; }+.content small { color: var(--muted); font-size: 11px; }++.anchor[data-above] { top: auto; bottom: 100%; padding-top: 0; padding-bottom: 4px; }diff --git a/packages/workflows-ui/src/timing-disclosure.tsx b/packages/workflows-ui/src/timing-disclosure.tsxnew file mode 100644index 000000000..a4676b7cd--- /dev/null+++ b/packages/workflows-ui/src/timing-disclosure.tsx@@ -0,0 +1,60 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com+"use client";+import { useEffect, useId, useRef, useState } from "react";+import { Clock3 } from "lucide-react";+import { workflowTiming, formatTimingMinutes } from "./timing";+import styles from "./timing-disclosure.module.css";++/** Lightweight, local disclosure: no requests, timers or per-row document listeners. */+export function TimingDisclosure({ value, label, measured }: {+ value: unknown;+ label: string;+ measured?: { minutes: number; samples: number };+}) {+ const timing = workflowTiming(value);+ const recording = !timing && measured && Number.isFinite(measured.minutes) && measured.minutes > 0 && measured.samples >= 2 ? measured : null;+ const [open, setOpen] = useState(false);+ const [above, setAbove] = useState(false);+ const [pinned, setPinned] = useState(false);+ const root = useRef<HTMLSpanElement>(null);+ const id = useId();+ const show = () => {+ const bounds = root.current?.getBoundingClientRect();+ setAbove(Boolean(bounds && bounds.bottom + 150 > window.innerHeight && bounds.top > 150));+ setOpen(true);+ };+ const close = () => { setOpen(false); setPinned(false); };+ useEffect(() => {+ if (!pinned) return;+ const dismiss = (event: PointerEvent) => {+ if (!root.current?.contains(event.target as Node)) { setOpen(false); setPinned(false); }+ };+ document.addEventListener("pointerdown", dismiss);+ return () => document.removeEventListener("pointerdown", dismiss);+ }, [pinned]);+ return <span ref={root} className={styles.root}+ onMouseEnter={show} onMouseLeave={() => { if (!pinned && !root.current?.contains(document.activeElement)) setOpen(false); }}+ onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) close(); }}+ onKeyDown={event => { if (event.key === "Escape") { event.stopPropagation(); close(); } }}>+ <button type="button" className={styles.trigger} aria-label={label}+ aria-expanded={open} aria-controls={open ? id : undefined} aria-describedby={open ? id : undefined}+ onFocus={show} onClick={() => { if (pinned) close(); else { show(); setPinned(true); } }}>+ <Clock3 size={15} aria-hidden="true" />+ </button>+ {open && <span className={styles.anchor} data-above={above || undefined}><span id={id} role="tooltip" className={styles.content}>+ {timing ? <>+ <strong>{formatTimingMinutes(timing.averageMinutes)} {timing.sampleCount > 1 ? "on average" : "for one run"}</strong>+ <span>{timing.sampleCount === 1 ? "1 observed run" : `${timing.sampleCount} observed runs · ${formatTimingMinutes(timing.minMinutes)} to ${formatTimingMinutes(timing.maxMinutes)}`}</span>+ <small>Estimated elapsed time, including pauses. Not active work time.</small>+ </> : recording ? <>+ <strong>{formatTimingMinutes(recording.minutes)} median duration</strong>+ <span>{recording.samples} recorded meetings</span>+ <small>Meeting duration only.</small>+ </> : <>+ <strong>Time not measured yet</strong>+ <span>A complete start and finish are needed to estimate this duration.</span>+ </>}+ </span></span>}+ </span>;+}diff --git a/packages/workflows-ui/src/timing.ts b/packages/workflows-ui/src/timing.tsindex 2da37045f..47f46697e 100644--- a/packages/workflows-ui/src/timing.ts+++ b/packages/workflows-ui/src/timing.ts@@ -17,3 +17,12 @@ export function workflowTiming(value: unknown): WorkflowTiming | null {averageMinutes: minutes.reduce((sum, value) => sum + value, 0) / minutes.length,minMinutes: Math.min(...minutes), maxMinutes: Math.max(...minutes) };}++export function formatTimingMinutes(value: number): string {+ if (value > 0 && value < 1) return "<1m";+ const minutes = Math.max(0, Math.round(value || 0));+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ const remainder = minutes % 60;+ return remainder ? `${hours}h ${remainder}m` : `${hours}h`;+}diff --git a/packages/workflows-ui/src/workflow-editor.module.css b/packages/workflows-ui/src/workflow-editor.module.cssindex 1fa70df41..51a009242 100644--- a/packages/workflows-ui/src/workflow-editor.module.css+++ b/packages/workflows-ui/src/workflow-editor.module.css@@ -109,3 +109,9 @@.stepMenu, .blockMenu { animation: menuReveal 150ms ease-out; }}@keyframes menuReveal { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: translateY(0); } }++.titleRow { display: flex; align-items: flex-start; gap: 8px; }+.titleRow > textarea { flex: 1; min-width: 0; }+.titleRow > span { margin-top: 6px; }+.stepActions { display: flex; align-items: flex-start; }+.step:hover > .stepTop .controls, .step:focus-within > .stepTop .controls { opacity: 1; pointer-events: auto; }diff --git a/packages/workflows-ui/src/workflow-editor.tsx b/packages/workflows-ui/src/workflow-editor.tsxindex e8871c13d..9e49daa0e 100644--- a/packages/workflows-ui/src/workflow-editor.tsx+++ b/packages/workflows-ui/src/workflow-editor.tsx@@ -14,12 +14,14 @@ import {import type { WorkflowMap, WorkflowStage } from "./model";import {moveBlock,+ isUnchangedStage,validWorkflowEdit,workflowEdit,type WorkflowEdit,type StageEdit,} from "./workflow-edits";import { InlineText } from "./inline-text";+import { TimingDisclosure } from "./timing-disclosure";import styles from "./workflow-editor.module.css";function Text(props: Parameters<typeof InlineText>[0] & { title?: boolean }) {@@ -60,6 +62,7 @@ export function WorkflowEditor({ workflow, save, actions, renderSource }: {} catch { /* Optional tab-local recovery. */ }return initial;});+ const unchangedStages = draft.stages.length === workflow.stages.length && draft.stages.every((stage, index) => stage.sourceIndex === index && isUnchangedStage(stage, workflow.stages[index]));const [history, setHistory] = useState<EditorDraft[]>([]);const [saving, setSaving] = useState(false);const [savedOnce, setSavedOnce] = useState(false);@@ -253,12 +256,16 @@ export function WorkflowEditor({ workflow, save, actions, renderSource }: {)}<fieldset><div className={styles.intro}>+ <div className={styles.titleRow}><Texttitlelabel="Workflow title"value={draft.title}onChange={(title) => change({ ...draft, title })}/>+ <TimingDisclosure label="Workflow timing" value={unchangedStages ? workflow.timing : null}+ measured={unchangedStages && workflow.durationSource === "measured-meeting" ? { minutes: workflow.totalMinutes, samples: workflow.durationSampleCount ?? 0 } : undefined} />+ </div><Textlabel="Workflow description"value={draft.description}@@ -336,6 +343,10 @@ export function WorkflowEditor({ workflow, save, actions, renderSource }: {value={stage.name}onChange={(name) => stageChange(index, { ...stage, name })}/>+ <div className={styles.stepActions}>+ <TimingDisclosure label={`Timing for step ${index + 1}`} value={stage.sourceIndex !== null &&+ isUnchangedStage(stage, workflow.stages[stage.sourceIndex])+ ? workflow.stages[stage.sourceIndex]?.timing : null} /><details data-step-actions className={styles.controls} onKeyDown={event => {if (event.key === "Escape") {event.preventDefault(); event.stopPropagation();@@ -376,6 +387,7 @@ export function WorkflowEditor({ workflow, save, actions, renderSource }: {<Trash2 size={15} /></button></div></details>+ </div></div><Textrichdiff --git a/packages/workflows-ui/src/workflow-edits.ts b/packages/workflows-ui/src/workflow-edits.tsindex f09c21ba1..cf654616c 100644--- a/packages/workflows-ui/src/workflow-edits.ts+++ b/packages/workflows-ui/src/workflow-edits.ts@@ -22,6 +22,14 @@ export type WorkflowEdit = {outcome: string;stages: StageEdit[];};+/** Match authored content to the referenced step before reusing its timing. */+export function isUnchangedStage(edit: StageEdit, source: WorkflowStage | undefined): boolean {+ return Boolean(source && edit.name.trim() === source.name && edit.description.trim() === source.description+ && edit.procedure.length === (source.procedure?.length ?? 0)+ && edit.procedure.every((block, index) => block.sourceIndex === index+ && block.kind === source.procedure![index].kind && block.text.trim() === source.procedure![index].text));+}+export function workflowEdit(workflow: WorkflowMap): WorkflowEdit {return {id: workflow.id ?? workflow.title,diff --git a/packages/workflows-ui/src/workflows-app.module.css b/packages/workflows-ui/src/workflows-app.module.cssindex 71d8bd7d2..a2b380b4a 100644--- a/packages/workflows-ui/src/workflows-app.module.css+++ b/packages/workflows-ui/src/workflows-app.module.css@@ -456,6 +456,7 @@.cardSummary span { opacity: .5; }.cardSummary .readyToReview { opacity: 1; color: var(--ink); font-weight: 500; }.cardActions { display: flex; align-items: center; margin-left: auto; }+.cardActions > span { z-index: 2; }.cardOpen { display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-height: 28px; padding: 4px 0 4px 8px; border: 0; border-radius: 4px; background: transparent; color: var(--ink); font: inherit; font-size: 11px; font-weight: 550; white-space: nowrap; cursor: pointer; }.cardOpen::after { content: ""; position: absolute; inset: 0; border-radius: 8px; }.cardOpen:focus-visible { outline: none; }@@ -465,7 +466,7 @@@media (hover: none) { .cardOpenLabel { opacity: 1; } }@media (prefers-reduced-motion: reduce) { .cardOpenLabel { transition: none; } }-.detailHeader { display: grid; grid-template-columns: minmax(0,1fr) 245px; gap: 60px; align-items: end; margin-bottom: 29px; }+.detailHeader { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 16px; align-items: start; margin-bottom: 29px; }.detailHeader h1 { margin: 16px 0 9px; font-size: clamp(32px,4vw,49px); letter-spacing: -.052em; }.detailHeader > div > p { max-width: 760px; margin: 0; color: #70746a; font-size: 12px; line-height: 1.6; }.workflowActions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 17px; }@@ -520,7 +521,7 @@.flowEndpoint strong { font-size: 10px; }.stageList { position: relative; display: flex; flex-direction: column; padding: 14px 0 14px 35px; }.stageList::before { content: ""; position: absolute; top: 0; bottom: 0; left: 48px; width: 1px; background: #cfd1c8; }-.stageList article { position: relative; z-index: 1; overflow: hidden; border: 1px solid #dddeda; border-radius: 8px; background: #fff; }+.stageList article { position: relative; z-index: 1; overflow: visible; border: 1px solid #dddeda; border-radius: 8px; background: #fff; }.stageList article + article { margin-top: 8px; }.stageList .stageBottleneck { border-color: #dfca89; box-shadow: inset 3px 0 0 #efc64d; }.stageList .stageConstraint { border-color: #d6d9d1; box-shadow: inset 3px 0 0 #b8bdb2; }@@ -1075,3 +1076,11 @@.topbar:has(.toolbarAccessory) .search { flex: 1 1 calc(100% - 52px); min-width: 0; }.toolbarAccessory { margin-right: auto; }}++/* Keep timing outside the step expansion button for keyboard and touch use. */+.stageHeadingRow { display: flex; align-items: flex-start; gap: 4px; }+.stageHeadingRow > button { flex: 1; min-width: 0; }+.stageHeadingRow > span { margin: 12px 12px 0 0; }++.stageList article:hover, .stageList article:focus-within { z-index: 2; }+.detailHeader > span { justify-self: end; }diff --git a/packages/workflows-ui/src/workflows-app.tsx b/packages/workflows-ui/src/workflows-app.tsxindex 1bf9be4f3..534097f44 100644--- a/packages/workflows-ui/src/workflows-app.tsx+++ b/packages/workflows-ui/src/workflows-app.tsx@@ -19,7 +19,8 @@ import { WorkflowAssistant } from "./workflow-assistant";import { PageAssistantContext, type PageAssistant } from "./page-assistant";import { useWorkflowRunActivity, type WorkflowActivityState } from "./use-workflow-run-activity";import { WorkflowRunProgress } from "./workflow-run-progress";-import { workflowTiming } from "./timing";+import { workflowTiming, formatTimingMinutes as formatMinutes } from "./timing";+import { TimingDisclosure } from "./timing-disclosure";import { CapturedMomentButton } from "./workflow-replay";import type { AssistantContext, AssistantState } from "./assistant";@@ -150,19 +151,6 @@ async function completedJobResult(platform: WorkflowsPlatform, initialJob: Workfthrow new Error("The workflow report is still processing. You can leave this page and refresh later.");}-function formatMinutes(value: number) {- if (value > 0 && value < 1) return "<1m";- const minutes = Math.max(0, Math.round(value || 0));- if (minutes < 60) return `${minutes}m`;- const hours = Math.floor(minutes / 60);- const remainder = minutes % 60;- return remainder ? `${hours}h ${remainder}m` : `${hours}h`;-}--function formatEstimatedMinutes(value: number) {- return value < 1 ? "<1m" : `~${formatMinutes(value)}`;-}-function formatCurrency(value: number, currency: string) {try {return new Intl.NumberFormat(undefined, {@@ -217,7 +205,7 @@ function hasMeasuredDuration(workflow: WorkflowMap) {function workflowDurationLabel(workflow: WorkflowMap) {const timing = workflowTiming(workflow.timing);- if (timing) return `${formatEstimatedMinutes(timing.averageMinutes)} ${timing.sampleCount > 1 ? "avg. per run" : "for one run"}`;+ if (timing) return `${timing.averageMinutes < 1 ? "" : "~"}${formatMinutes(timing.averageMinutes)} ${timing.sampleCount > 1 ? "avg. per run" : "for one run"}`;return hasMeasuredDuration(workflow) ? formatMinutes(workflow.totalMinutes) : "Not measured";}@@ -731,9 +719,9 @@ function WorkflowsView({ reviewIds, workflows, knownWorkflowCount, query, setQue<div className={styles.cardSummary}>{workflow.id && reviewIds?.has(workflow.id) && <><span className={styles.readyToReview}>{ui("Ready to review")}</span><span aria-hidden="true">·</span></>}{workflow.stages.length} steps- {timing && <><span aria-hidden="true">·</span>{`${formatEstimatedMinutes(timing.averageMinutes)} / run · estimated`}</>}</div><div className={styles.cardActions}>+ {timing && <TimingDisclosure label={`Timing for ${workflow.title}`} value={timing} />}<button type="button" className={styles.cardOpen} onClick={() => openWorkflow(originalIndex)}><span className={styles.cardOpenLabel}>{ui("Open map")}</span><ChevronRight size={14} /></button></div></div>@@ -976,8 +964,7 @@ function WorkflowDetail({ canSaveAnswers, composerAccessory, active, onAnswersSa}, [platform, skillDraft]);if (workflow && guideOpen && platform.guides) return <WorkflowGuide key={workflow.id || workflow.title} workflow={workflow} platform={platform.guides} close={() => setGuideOpen(false)} />;if (!workflow) return <section className={styles.emptyState}><ListTree size={23} /><h2>No workflow selected</h2><button className={styles.primaryButton} onClick={() => navigate("workflows")}>View workflows</button></section>;- const measuredDuration = hasMeasuredDuration(workflow);- const timing = workflowTiming(workflow.timing);+const allStagesOpen = expandedStages.size === workflow.stages.length;const actionableFriction = workflow.bottlenecks.filter(isActionableBottleneck);const constraints = workflow.bottlenecks.filter((item) => !isActionableBottleneck(item));@@ -994,7 +981,7 @@ function WorkflowDetail({ canSaveAnswers, composerAccessory, active, onAnswersSa<button className={styles.backButton} onClick={() => navigate("workflows")}><ArrowLeft size={14} />All workflows</button>{saveEdits ? <WorkflowEditor key={workflow.id || workflow.title} workflow={workflow} save={saveEdits} actions={workflowActions} renderSource={stage => <WorkflowStepEvidence workflow={workflow} stage={stage} platform={platform} />} /> : <section className={styles.detailHeader}><div><Pill>Evidence on {workflow.repetitions} captured day{workflow.repetitions === 1 ? "" : "s"}</Pill><h1>{workflow.title}</h1><p>{workflow.description}</p>{workflowActions}</div>- {timing ? <div className={styles.detailTotal}><span>{timing.sampleCount > 1 ? ui("Avg. time / run") : ui("Time for one run")}</span><strong>{formatEstimatedMinutes(timing.averageMinutes)}</strong><small>{ui("{count, plural, one {# run} other {# runs}}", { count: timing.sampleCount })} · estimated elapsed time</small></div> : measuredDuration && <div className={styles.detailTotal}><span>Observed meeting duration</span><strong>{workflowDurationLabel(workflow)}</strong></div>}+ <TimingDisclosure label="Workflow timing" value={workflow.timing} measured={hasMeasuredDuration(workflow) ? { minutes: workflow.totalMinutes, samples: workflow.durationSampleCount ?? 0 } : undefined} /></section>}<div className={styles.workflowNotes}><p className={styles.workflowReviewState}>{workflow.userEditedAt ? ui("Edited by you · sources kept as references") : workflow.evidenceStatus === "supported-steps" ? ui("Source-backed steps · not execution-tested") : ui("Needs review")}</p>@@ -1009,11 +996,14 @@ function WorkflowDetail({ canSaveAnswers, composerAccessory, active, onAnswersSaconst constraint = stageFriction.find((item) => !isActionableBottleneck(item));const open = expandedStages.has(index);return <article key={`${stage.name}-${index}`} className={`${actionableStageFriction ? styles.stageBottleneck : ""} ${constraint ? styles.stageConstraint : ""} ${open ? styles.stageOpen : ""}`}>+ <div className={styles.stageHeadingRow}><button className={styles.stageSummary} onClick={() => toggleStage(index)} aria-expanded={open}><div className={styles.stageNumber}>{index + 1}</div><div className={styles.stageBody}><div><h3>{stage.name}</h3>{actionableStageFriction && <Pill tone="warm"><AlertTriangle size={11} />Actionable friction</Pill>}{!actionableStageFriction && constraint && <Pill><ShieldCheck size={11} />{controlLabel(constraint)}</Pill>}</div><p>{stage.description}</p><span>{stage.apps.join(" · ") || ui("App not clear")} · {ui("{count, plural, one {# observation} other {# observations}}", { count: stage.observedOccurrences })} across {ui("{count, plural, one {# day} other {# days}}", { count: stage.observedDays })}</span></div><ChevronDown className={styles.stageChevron} size={15} /></button>+ <TimingDisclosure label={`Timing for step ${index + 1}`} value={stage.timing} />+ </div>{open && <div className={styles.stageDisclosure}><section className={styles.procedureDetails} aria-label={ui("Procedure details for {value1}", { value1: stage.name })}>{stage.procedure?.length ? <ol>{stage.procedure.map((detail, detailIndex) => <li key={`${detail.kind}-${detailIndex}`}>