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
feat(workflows): edit and reorder inline with automatic saving
louis0a9b86f20cab
diff --git a/apps/screenpipe-workflows-web/scripts/eval-workflow-editor.cjs b/apps/screenpipe-workflows-web/scripts/eval-workflow-editor.cjsindex 8a6bc86e1..007c569ad 100644--- a/apps/screenpipe-workflows-web/scripts/eval-workflow-editor.cjs+++ b/apps/screenpipe-workflows-web/scripts/eval-workflow-editor.cjs@@ -2,192 +2,147 @@// https://screenpipe.comconst { chromium } = require("playwright");const assert = require("node:assert/strict");-const out =- process.env.WORKFLOW_EDITOR_ARTIFACTS ||- require("node:path").join(- require("node:os").tmpdir(),- "screenpipe-workflow-editor-eval",- );+const out = process.env.WORKFLOW_EDITOR_ARTIFACTS || require("node:path").join(require("node:os").tmpdir(), "screenpipe-workflow-editor-eval");require("node:fs").mkdirSync(out, { recursive: true });(async () => {- const b = await chromium.launch({ headless: true, channel: "chrome" });- const p = await b.newPage({ viewport: { width: 1440, height: 1100 } });+ const browser = await chromium.launch({ headless: true, channel: "chrome" });+ const page = await browser.newPage({ viewport: { width: 1440, height: 1100 } });const errors = [];- p.on("pageerror", (e) => errors.push(e.message));- const check = async (label, f) => {- await f();- console.log("PASS", label);- };- const field = (n) => p.getByRole("textbox", { name: n, exact: true });- const button = (n) => p.getByRole("button", { name: n, exact: true });+ page.on("pageerror", e => errors.push(e.message));+ const field = name => page.getByRole("textbox", { name, exact: true });+ const button = name => page.getByRole("button", { name, exact: true });+ const saved = () => page.getByRole("status", { name: "Save status" }).filter({ hasText: /^Saved$/ }).waitFor();+ const stored = () => page.evaluate(() => JSON.parse(localStorage.getItem("screenpipe:fictional-workflow-editor-preview"))?.analysis.workflows.find(w => w.id === "Research synthesis"));+ const check = async (label, f) => { await f(); console.log("PASS", label); };try {- await p.goto(- process.env.WORKFLOWS_PREVIEW_URL || "http://127.0.0.1:1431/preview",- );- await p.getByRole("button", { name: "Edit steps", exact: true }).first().click();- await p.getByText("Drag handles to reorder · click text to edit", { exact: true }).waitFor();- console.log("PASS catalog opens editor directly with drag hint");- await check("save disabled for unchanged draft", async () =>- assert(await button("Save").isDisabled()),- );- await check("inline edit + undo", async () => {- await field("Workflow title").fill("Research brief");- await button("Undo last edit").click();- assert.equal(- await field("Workflow title").inputValue(),- "Research synthesis",- );- await field("Workflow title").fill("Research brief");+ await page.goto(process.env.WORKFLOWS_PREVIEW_URL || "http://127.0.0.1:1431/preview");+ await button("Open map").first().click();+ await check("workflow is editable immediately, without edit/save controls", async () => {+ await field("Workflow title").waitFor();+ assert.equal(await button("Edit workflow").count(), 0);+ assert.equal(await button("Edit steps").count(), 0);+ assert.equal(await button("Save").count(), 0);+ assert.equal(await button("Move step 1").getAttribute("draggable"), "true");});- await check("keyboard stage reorder", async () => {- await button("Move step 1").focus();- await p.keyboard.press("Alt+ArrowDown");+ await check("drag step, auto-save and retain its screenshot", async () => {+ await button("Move step 1").dragTo(page.getByRole("article", { name: "Step 2", exact: true }));assert.equal(await field("Step 2 title").inputValue(), "Collect sources");+ await saved();+ const workflow = await stored();+ assert.equal(workflow.stages[1].name, "Collect sources");+ assert(workflow.stages[1].screenshot.dataUrl);});- await check("drag step reorder", async () => {- await button("Move step 2").dragTo(- p.getByRole("article", { name: "Step 1", exact: true }),- );+ await check("undo works after automatic save", async () => {+ await button("Undo last edit").click();assert.equal(await field("Step 1 title").inputValue(), "Collect sources");+ await saved();+ assert.equal((await stored()).stages[0].name, "Collect sources");});- await check("new block validation + keyboard reorder", async () => {+ await check("successive saved reorders preserve source identity", async () => {+ const before = await stored();+ await button("Move step 1").focus();+ await page.keyboard.press("Alt+ArrowDown");+ await saved();+ await button("Move step 2").focus();+ await page.keyboard.press("Alt+ArrowDown");+ await saved();+ const after = await stored();+ assert.equal(after.stages[2].name, "Collect sources");+ assert.deepEqual(after.stages[2].screenshot, before.stages[0].screenshot);+ await button("Move step 3").dragTo(page.getByRole("article", { name: "Step 1", exact: true }));+ await saved();+ });+ await check("typing auto-saves without losing focus", async () => {+ await field("Workflow title").fill("Research brief");+ await saved();+ assert(await field("Workflow title").evaluate(e => e === document.activeElement));+ assert.equal((await stored()).title, "Research brief");+ });+ await check("empty blocks remain drafts until filled", async () => {+ const before = await stored();await button("Add block").first().click();- assert(await button("Save").isDisabled());- await field("Block 1 in step 1").fill(- "Gather source links in the research note.",- );+ await page.getByText("Finish the empty block to save", { exact: true }).waitFor();+ await page.waitForTimeout(850);+ assert.equal((await stored()).revision, before.revision);+ await field("Block 1 in step 1").fill("Gather the dated source links.");+ await saved();await button("Add block").first().click();- await field("Block 2 in step 1").fill(- "Check that every source is dated.",- );- await button("Move block 2 in step 1").focus();- await p.keyboard.press("Alt+ArrowUp");- assert.equal(- await field("Block 1 in step 1").inputValue(),- "Check that every source is dated.",- );+ await field("Block 2 in step 1").fill("Check the source author.");+ await saved();});- await check("drag block reorder", async () => {+ await check("drag blocks auto-saves their new order", async () => {await button("Move block 1 in step 1").dragTo(field("Block 2 in step 1"));- assert.equal(- await field("Block 1 in step 1").inputValue(),- "Gather source links in the research note.",- );+ await saved();+ assert.deepEqual((await stored()).stages[0].procedure.map(p => p.text), ["Check the source author.", "Gather the dated source links."]);});- await check("add step + delete + undo", async () => {- await button("Add step").click();- await field("Step 4 title").fill("Send for review");- await field("Step 4 description").fill(- "Ask the project owner to review the brief.",- );- await button("Delete step 4").click();- assert.equal(await field("Step 4 title").count(), 0);- await button("Undo last edit").click();- assert.equal(await field("Step 4 title").inputValue(), "Send for review");- });- await p- .locator("[data-workflows-scroll-region]")- .evaluate((e) => (e.scrollTop = 0));- await p.screenshot({ path: out + "/edited-blocks.png" });- await check("failed save keeps draft", async () => {- await p.evaluate(() => {+ await check("failed auto-save keeps text, exposes retry, does not loop", async () => {+ await page.evaluate(() => {window.__setItem = Storage.prototype.setItem;- Storage.prototype.setItem = function (k, v) {- if (k === "screenpipe:fictional-workflow-editor-preview")- throw new Error("Simulated disk full");+ window.__failedSaves = 0;+ Storage.prototype.setItem = function(k, v) {+ if (k === "screenpipe:fictional-workflow-editor-preview") { window.__failedSaves++; throw new Error("Simulated disk full"); }return window.__setItem.call(this, k, v);};});- await button("Save").click();- await p- .getByRole("alert")- .filter({ hasText: "Simulated disk full" })- .waitFor();- assert.equal(- await field("Workflow title").inputValue(),- "Research brief",- );- await p.evaluate(() => (Storage.prototype.setItem = window.__setItem));+ await field("Workflow description").fill("A traceable research brief for the team.");+ await page.getByRole("alert").filter({ hasText: "Simulated disk full" }).waitFor();+ await page.waitForTimeout(850);+ assert.equal(await page.evaluate(() => window.__failedSaves), 1);+ assert.equal(await field("Workflow description").inputValue(), "A traceable research brief for the team.");+ await page.evaluate(() => Storage.prototype.setItem = window.__setItem);+ await button("Retry save").click();+ await saved();});-- await check("save + reload persistence", async () => {- await button("Save").click();- await button("Edit workflow").waitFor();- await p.reload();- await p.getByRole("button", { name: "Open map" }).first().click();- await button("Edit workflow").click();- assert.equal(- await field("Workflow title").inputValue(),- "Research brief",- );- assert.equal(await field("Step 4 title").inputValue(), "Send for review");- assert.equal(- await field("Block 2 in step 1").inputValue(),- "Check that every source is dated.",- );+ await check("leaving before debounce flushes valid changes", async () => {+ await field("Workflow outcome").fill("A reviewed brief is ready to share.");+ await button("All workflows").click();+ await page.waitForFunction(() => JSON.parse(localStorage.getItem("screenpipe:fictional-workflow-editor-preview")).analysis.workflows.some(w => w.outcome === "A reviewed brief is ready to share."));+ await button("Open map").first().click();+ assert.equal(await field("Workflow outcome").inputValue(), "A reviewed brief is ready to share.");+ });+ await check("reload restores saved title, steps and blocks", async () => {+ await page.reload();+ await button("Open map").first().click();+ assert.equal(await field("Workflow title").inputValue(), "Research brief");+ assert.equal(await field("Step 1 title").inputValue(), "Collect sources");+ assert.equal(await field("Block 1 in step 1").inputValue(), "Check the source author.");});- await check("concurrent write is rejected with draft kept", async () => {- await field("Workflow title").fill("My concurrent draft");- await p.evaluate(() => {+ await check("concurrent change rejected with local draft retained", async () => {+ await page.evaluate(() => {const k = "screenpipe:fictional-workflow-editor-preview";const v = JSON.parse(localStorage.getItem(k));- v.analysis.workflows.find(- (w) => w.id === "Research synthesis",- ).revision += 1;+ const workflow = v.analysis.workflows.find(w => w.id === "Research synthesis");+ workflow.revision++;+ workflow.title = "Another editor's title";localStorage.setItem(k, JSON.stringify(v));});- await button("Save").click();- await p- .getByRole("alert")- .filter({ hasText: "Workflow changed" })- .waitFor();- assert.equal(- await field("Workflow title").inputValue(),- "My concurrent draft",- );- });- await check("cancel leaves saved content unchanged", async () => {- await button("Cancel edits").click();- await button("Edit workflow").click();- assert.equal(- await field("Workflow title").inputValue(),- "Research brief",- );+ await field("Workflow title").fill("My local draft");+ await page.getByRole("alert").filter({ hasText: "Workflow changed" }).waitFor();+ assert.equal(await field("Workflow title").inputValue(), "My local draft");+ assert.equal((await stored()).title, "Another editor's title");+ await button("Discard draft and view latest").click();+ assert.equal(await field("Workflow title").inputValue(), "Another editor's title");});await check("incomplete draft survives navigation", async () => {await button("Add step").click();- await p- .getByRole("button", { name: "Home", exact: false })- .first()- .click();- await p.getByRole("button", { name: "Open map" }).first().click();- await button("Edit workflow").click();- assert.equal(await field("Step 5 title").count(), 1);- assert(await button("Save").isDisabled());- await button("Cancel edits").click();- });- await button("Edit workflow").click();- await p.setViewportSize({ width: 720, height: 1000 });- await p.waitForTimeout(250);- await check("narrow fields fit their contents", async () => {- const clipped = await p- .locator("textarea")- .evaluateAll((es) =>- es- .filter((e) => e.scrollHeight > e.clientHeight + 3)- .map((e) => e.getAttribute("aria-label")),- );- assert.deepEqual(clipped, []);+ await button("All workflows").click();+ await button("Open map").first().click();+ assert.equal(await field("Step 4 title").inputValue(), "");+ await field("Step 4 title").fill("Send for review");+ await saved();});- await p.screenshot({ path: out + "/editor-narrow-tested.png" });- await p.emulateMedia({ colorScheme: "dark" });- await p.screenshot({ path: out + "/editor-dark-preference.png" });+ await page.locator("[data-workflows-scroll-region]").evaluate(e => e.scrollTop = 0);+ await page.screenshot({ path: out + "/inline-workflow.png" });+ for (const width of [1050, 720, 390]) {+ await page.setViewportSize({ width, height: 1000 });+ await check(`fields and controls fit at ${width}px`, async () => {+ await page.waitForTimeout(100);+ const bad = await page.locator("main textarea, main button").evaluateAll(es => es.filter(e => e.getBoundingClientRect().width && (e.getBoundingClientRect().right > innerWidth + 1 || (e.tagName === "TEXTAREA" && e.scrollHeight > e.clientHeight + 3))).map(e => e.getAttribute("aria-label") || e.textContent));+ assert.deepEqual(bad, []);+ });+ await page.screenshot({ path: `${out}/inline-${width}.png` });+ }assert.deepEqual(errors, []);console.log("PASS no browser exceptions");- } finally {- await b.close();- }-})().catch((e) => {- console.error(e);- process.exitCode = 1;-});+ } finally { await browser.close(); }+})().catch(e => { console.error(e); process.exitCode = 1; });diff --git a/packages/workflows-ui/src/workflow-editor.module.css b/packages/workflows-ui/src/workflow-editor.module.cssindex 6ea209845..93a540fd9 100644--- a/packages/workflows-ui/src/workflow-editor.module.css+++ b/packages/workflows-ui/src/workflow-editor.module.css@@ -70,8 +70,7 @@color: var(--muted);}.toolbar {- position: sticky;- top: -28px;+ position: relative;z-index: 3;display: flex;align-items: center;@@ -87,7 +86,9 @@align-items: center;gap: 8px;}-.toolbar > div:last-child { flex-shrink: 0; }+.toolbar > div:last-child { flex: 1; min-width: 0; justify-content: flex-end; flex-wrap: wrap; }+.toolbar > div:last-child > div { margin: 0; gap: 6px; }+.toolbar > div:first-child { flex: 0 1 auto; }.toolbar strong {white-space: nowrap;font-size: 13px;diff --git a/packages/workflows-ui/src/workflow-editor.tsx b/packages/workflows-ui/src/workflow-editor.tsxindex ef7dba23f..863bf2968 100644--- a/packages/workflows-ui/src/workflow-editor.tsx+++ b/packages/workflows-ui/src/workflow-editor.tsx@@ -1,18 +1,17 @@// screenpipe — AI that knows everything you've seen, said, or heard// https://screenpipe.com"use client";-import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";import {ArrowDown,ArrowUp,- Check,GripVertical,Plus,Trash2,Undo2,X,} from "lucide-react";-import type { WorkflowMap } from "./model";+import type { WorkflowMap, WorkflowStage } from "./model";import {moveBlock,validWorkflowEdit,@@ -66,61 +65,80 @@ function Text({);}-export function WorkflowEditor({- workflow,- save,- close,-}: {+type EditorStage = Omit<StageEdit, "procedure"> & { key: string; procedure: (StageEdit["procedure"][number] & { key: string })[] };+type EditorDraft = Omit<WorkflowEdit, "stages"> & { stages: EditorStage[] };+function keyedDraft(draft: WorkflowEdit): EditorDraft {+ return { ...draft, stages: draft.stages.map(stage => ({ ...stage, key: (stage as EditorStage).key || crypto.randomUUID(), procedure: stage.procedure.map(block => ({ ...block, key: (block as EditorStage["procedure"][number]).key || crypto.randomUUID() })) })) };+}+function payload(draft: EditorDraft): WorkflowEdit {+ return { ...draft, stages: draft.stages.map(({ key, procedure, ...stage }) => ({ ...stage, procedure: procedure.map(({ key, ...block }) => block) })) };+}+// Keep local identities while source positions change after each saved reorder.+function rebase(draft: EditorDraft, sent: EditorDraft, saved: WorkflowMap): EditorDraft {+ return { ...draft, id: saved.id ?? sent.id, expected_revision: saved.revision ?? 0, stages: draft.stages.map(stage => {+ const index = sent.stages.findIndex(s => s.key === stage.key);+ return { ...stage, sourceIndex: index < 0 ? null : index, procedure: stage.procedure.map(block => {+ const blockIndex = index < 0 ? -1 : sent.stages[index].procedure.findIndex(p => p.key === block.key);+ return { ...block, sourceIndex: blockIndex < 0 ? null : blockIndex };+ }) };+ }) };+}++export function WorkflowEditor({ workflow, save, actions, renderSource }: {workflow: WorkflowMap;- save: (draft: WorkflowEdit) => Promise<void>;- close: () => void;+ save: (draft: WorkflowEdit) => Promise<WorkflowMap>;+ actions?: ReactNode;+ renderSource?: (stage: WorkflowStage) => ReactNode;}) {const key = `screenpipe:workflow-edit:${workflow.id ?? workflow.title}`;- const [initial] = useState(() => workflowEdit(workflow));- const [draft, setDraft] = useState<WorkflowEdit>(() => {+ const [initial, setInitial] = useState(() => keyedDraft(workflowEdit(workflow)));+ const [draft, setDraft] = useState<EditorDraft>(() => {try {const saved = JSON.parse(sessionStorage.getItem(key) || "null");- if (saved?.id === initial.id && validWorkflowEdit(saved, true))- return saved;- } catch {- /* Optional tab-local recovery. */- }+ if (saved?.id === initial.id && validWorkflowEdit(saved, true)) return keyedDraft(saved);+ } catch { /* Optional tab-local recovery. */ }return initial;});- const [history, setHistory] = useState<WorkflowEdit[]>([]);+ const [history, setHistory] = useState<EditorDraft[]>([]);const [saving, setSaving] = useState(false);+ const [savedOnce, setSavedOnce] = useState(false);const [error, setError] = useState("");const [announcement, setAnnouncement] = useState("");const [dragOver, setDragOver] = useState<number | null>(null);const [blockDragOver, setBlockDragOver] = useState<string | null>(null);const dragging = useRef<{ stage: number; detail?: number } | null>(null);const busy = useRef(false);- const dirty = JSON.stringify(draft) !== JSON.stringify(initial);+ const mounted = useRef(true);+ const current = useRef(draft);+ const baseline = useRef(initial);+ const dirty = JSON.stringify(payload(draft)) !== JSON.stringify(payload(initial));const valid = validWorkflowEdit(draft);- useEffect(() => {+ function remember(next: EditorDraft, base = baseline.current) {try {- if (dirty) sessionStorage.setItem(key, JSON.stringify(draft));+ if (JSON.stringify(payload(next)) !== JSON.stringify(payload(base))) sessionStorage.setItem(key, JSON.stringify(next));else sessionStorage.removeItem(key);- } catch {- /* Editing still works when storage is full/disabled. */- }- }, [draft, dirty, key]);+ } catch { /* Editing works when storage is unavailable. */ }+ }+ useEffect(() => { remember(draft); }, [draft, initial, key]);useEffect(() => {const warn = (e: BeforeUnloadEvent) => {- if (dirty) {- e.preventDefault();- e.returnValue = "";- }+ if (dirty) { e.preventDefault(); e.returnValue = ""; }};window.addEventListener("beforeunload", warn);return () => window.removeEventListener("beforeunload", warn);}, [dirty]);- function change(next: WorkflowEdit) {- setHistory((h) => [...h.slice(-49), draft]);+ function update(next: EditorDraft) {+ current.current = next;setDraft(next);+ remember(next);+ }+ function change(next: EditorDraft) {+ const previous = current.current;+ setHistory(h => [...h.slice(-49), previous]);+ update(next);setError("");}- function stageChange(index: number, next: StageEdit) {+ function stageChange(index: number, next: EditorStage) {change({...draft,stages: draft.stages.map((s, i) => (i === index ? next : s)),@@ -148,35 +166,58 @@ export function WorkflowEditor({?.focus(),);}- function clearDraft() {- try {- sessionStorage.removeItem(key);- } catch {}+ function useLatest() {+ const next = keyedDraft(workflowEdit(workflow));+ baseline.current = next;+ setInitial(next);+ update(next);+ setHistory([]);+ setError("");}async function submit() {- if (!dirty || !valid || busy.current) return;+ const sent = current.current;+ if (!validWorkflowEdit(sent) || busy.current || JSON.stringify(payload(sent)) === JSON.stringify(payload(baseline.current))) return;busy.current = true;setSaving(true);setError("");+ let succeeded = false;try {- await save(draft);- clearDraft();- close();+ const saved = await save(payload(sent));+ const base = rebase(sent, sent, saved);+ baseline.current = base;+ setInitial(base);+ const next = rebase(current.current, sent, saved);+ update(next);+ setHistory(h => h.map(entry => rebase(entry, sent, saved)));+ setSavedOnce(true);+ succeeded = true;} catch (e) {- setError(- e instanceof Error- ? e.message- : "Could not save. Your draft is still here.",- );+ setError(e instanceof Error ? e.message : "Could not save. Your changes are kept here.");} finally {busy.current = false;setSaving(false);+ // Finish edits made during a save even if the user has left this page.+ if (succeeded && !mounted.current) void submit();}}+ useEffect(() => {+ if (!dirty && !saving && draft.expected_revision !== (workflow.revision ?? 0)) useLatest();+ }, [workflow.revision, dirty, saving]);+ const flush = useRef(submit);+ flush.current = submit;+ useEffect(() => {+ mounted.current = true;+ return () => { mounted.current = false; void flush.current(); };+ }, []);+ useEffect(() => {+ if (!dirty || !valid || saving || error || draft.expected_revision !== (workflow.revision ?? 0)) return;+ const timer = setTimeout(() => void flush.current(), 700);+ return () => clearTimeout(timer);+ }, [draft, dirty, valid, saving, error, workflow.revision]);return (<sectionclassName={styles.editor}- aria-label="Edit workflow"+ aria-label="Workflow document"onKeyDown={(e) => {if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {e.preventDefault();@@ -187,74 +228,34 @@ export function WorkflowEditor({}}><header className={styles.toolbar}>+ <div><span role="status" aria-label="Save status">{error ? "Not saved" : saving ? "Saving…" : dirty ? valid ? "Saving…" : "Finish the empty block to save" : savedOnce ? "Saved" : ""}</span></div><div>- <strong>Edit workflow</strong>- <span role="status">- {saving- ? "Saving…"- : dirty- ? "Unsaved changes"- : "Your edits stay through AI updates"}- </span>- </div>- <div>- <button- type="button"- title="Undo last edit"- aria-label="Undo last edit"- disabled={!history.length || saving}- onClick={() => {- setDraft(history[history.length - 1]);- setHistory((h) => h.slice(0, -1));- setError("");- }}- >- <Undo2 size={17} />- </button>- <button- type="button"- title="Cancel edits"- aria-label="Cancel edits"- disabled={saving}- onClick={() => {- clearDraft();- close();- }}- >- <X size={17} />- </button>- <button- type="button"- className={styles.save}- disabled={!dirty || !valid || saving}- onClick={() => void submit()}- >- <Check size={16} />- Save- </button>+ {actions}+ <button type="button" title="Undo last edit" aria-label="Undo last edit" disabled={!history.length} onClick={() => {+ update(history[history.length - 1]);+ setHistory(h => h.slice(0, -1));+ setError("");+ }}><Undo2 size={17} /></button></div></header>{error && (<p role="alert" className={styles.error}>- {error}+ {error} <button type="button" onClick={() => void submit()} disabled={saving}>Retry save</button></p>)}- {draft.expected_revision !== (workflow.revision ?? 0) && (+ {!saving && draft.expected_revision !== (workflow.revision ?? 0) && (<p role="alert" className={styles.error}>A newer version is available. Your draft is kept.{" "}<buttontype="button"disabled={saving}- onClick={() => {- clearDraft();- close();- }}+ onClick={useLatest}>Discard draft and view latest</button></p>)}- <fieldset disabled={saving}>+ <fieldset><div className={styles.intro}><Texttitle@@ -281,11 +282,7 @@ export function WorkflowEditor({{draft.stages.map((stage, index) => (<articleclassName={`${styles.step} ${dragOver === index ? styles.drop : ""}`}- key={- stage.sourceIndex === null- ? `new-${index}`- : `source-${stage.sourceIndex}`- }+ key={stage.key}aria-label={`Step ${index + 1}`}onDragOver={(e) => {if (@@ -384,15 +381,12 @@ export function WorkflowEditor({stageChange(index, { ...stage, description })}/>+ {stage.sourceIndex !== null && workflow.stages[stage.sourceIndex] && renderSource?.(workflow.stages[stage.sourceIndex])}<div className={styles.blocks}>{stage.procedure.map((detail, detailIndex) => (<divclassName={`${styles.block} ${blockDragOver === `${index}:${detailIndex}` ? styles.blockDrop : ""}`}- key={- detail.sourceIndex === null- ? `new-${detailIndex}`- : `source-${detail.sourceIndex}`- }+ key={detail.key}onDragOver={(e) => {if (dragging.current?.stage === index &&@@ -510,7 +504,7 @@ export function WorkflowEditor({...stage,procedure: [...stage.procedure,- { sourceIndex: null, kind: "action", text: "" },+ { key: crypto.randomUUID(), sourceIndex: null, kind: "action", text: "" },],});focusField(@@ -533,7 +527,7 @@ export function WorkflowEditor({...draft,stages: [...draft.stages,- { sourceIndex: null, name: "", description: "", procedure: [] },+ { key: crypto.randomUUID(), sourceIndex: null, name: "", description: "", procedure: [] },],});focusField(`Step ${draft.stages.length + 1} title`);diff --git a/packages/workflows-ui/src/workflows-app.module.css b/packages/workflows-ui/src/workflows-app.module.cssindex 1f1acecea..1bfff85d8 100644--- a/packages/workflows-ui/src/workflows-app.module.css+++ b/packages/workflows-ui/src/workflows-app.module.css@@ -465,7 +465,6 @@.cardFooter span { color: #83867e; font-size: 8px; }.cardActions { display: flex; align-items: center; gap: 8px; margin-left: auto; }.cardActions button { display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-height: 32px; padding: 6px 8px; border: 0; border-radius: 5px; background: transparent; color: var(--ink); font: inherit; font-size: 11px; font-weight: 550; white-space: nowrap; cursor: pointer; }-.cardActions .cardEdit { position: relative; z-index: 1; border: 1px solid var(--line); background: var(--panel); }.cardActions button:hover { background: var(--soft); }.cardActions button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }.cardOpen::after { content: ""; position: absolute; inset: 0; border-radius: 10px; }diff --git a/packages/workflows-ui/src/workflows-app.tsx b/packages/workflows-ui/src/workflows-app.tsxindex 0f949a376..3c306d497 100644--- a/packages/workflows-ui/src/workflows-app.tsx+++ b/packages/workflows-ui/src/workflows-app.tsx@@ -6,7 +6,6 @@import { useNavigationWidth } from "./use-navigation-width";import { WorkflowEditor } from "./workflow-editor";import { retainNewerWorkflowEdits, type WorkflowEdit } from "./workflow-edits";-import { Pencil } from "lucide-react";import { WorkflowModelControl } from "./model-choice";import { matchesSidebarShortcut, useSidebarShortcuts } from "./sidebar-shortcuts";import { WorkflowGuide } from "./workflow-guide";@@ -701,7 +700,7 @@ function OverviewView({);}-function WorkflowsView({ workflows, knownWorkflowCount, activityPeriod, filters, setFilters, openWorkflow, editWorkflow, analyze, analyzing, error, stop, updatedAt, checkedThrough, changes, job, subscribe, analysisUnavailableReason }: { analysisUnavailableReason?: string; workflows: WorkflowMap[]; knownWorkflowCount: number; activityPeriod: WorkflowActivityPeriod; filters: WorkflowFilters; setFilters: (filters: WorkflowFilters) => void; openWorkflow: (index: number) => void; editWorkflow?: (index: number) => void; analyze: () => void; analyzing: boolean; error: string; stop?: () => void; updatedAt?: string; checkedThrough?: string; changes?: { created: number; updated: number }; job?: WorkflowAnalysisJob | null; subscribe?: WorkflowsPlatform["subscribeAnalysisActivity"] }) {+function WorkflowsView({ workflows, knownWorkflowCount, activityPeriod, filters, setFilters, openWorkflow, analyze, analyzing, error, stop, updatedAt, checkedThrough, changes, job, subscribe, analysisUnavailableReason }: { analysisUnavailableReason?: string; workflows: WorkflowMap[]; knownWorkflowCount: number; activityPeriod: WorkflowActivityPeriod; filters: WorkflowFilters; setFilters: (filters: WorkflowFilters) => void; openWorkflow: (index: number) => void; analyze: () => void; analyzing: boolean; error: string; stop?: () => void; updatedAt?: string; checkedThrough?: string; changes?: { created: number; updated: number }; job?: WorkflowAnalysisJob | null; subscribe?: WorkflowsPlatform["subscribeAnalysisActivity"] }) {const [filtersOpen, setFiltersOpen] = useState(false);const visible = useMemo(() => filterWorkflows(workflows, filters), [filters, workflows]);const availableApps = useMemo(() => [...new Set(workflows.flatMap((workflow) => workflow.apps))].sort((a, b) => a.localeCompare(b)), [workflows]);@@ -742,7 +741,6 @@ function WorkflowsView({ workflows, knownWorkflowCount, activityPeriod, filters,<div className={styles.cardPath}><span>{workflow.trigger}</span><ArrowRight size={12} /><span>{workflow.outcome}</span></div><div className={styles.cardMetrics}><div title={timing ? "Estimated elapsed time from source-backed start and finish moments. Includes pauses; not active work time. Open the map to inspect the runs." : "Not enough evidence of complete workflow runs to estimate an average."}><span>{timing?.sampleCount === 1 ? "Time for one run" : !timing && hasMeasuredDuration(workflow) ? "Meeting duration" : "Avg. time / run"}</span><strong>{timing ? formatEstimatedMinutes(timing.averageMinutes) : hasMeasuredDuration(workflow) ? formatMinutes(workflow.totalMinutes) : "—"}</strong>{timing && <small>{timing.sampleCount} run{timing.sampleCount === 1 ? "" : "s"} · estimated</small>}</div><div><span>Stages</span><strong>{workflow.stages.length}</strong></div><div><span>Evidence</span><strong>{workflow.quality.evidenceCount}</strong></div><div><span>Screenshots</span><strong>{workflow.quality.screenshotCount}/{workflow.stages.length}</strong></div></div><div className={styles.cardFooter}><span>{workflow.frequency}</span><div className={styles.cardActions}>- {editWorkflow && <button type="button" className={styles.cardEdit} onClick={() => editWorkflow(originalIndex)}><Pencil size={13} />Edit steps</button>}<button type="button" className={styles.cardOpen} onClick={() => openWorkflow(originalIndex)}>Open map <ChevronRight size={14} /></button></div></div></article>@@ -884,8 +882,7 @@ function WorkflowCorrection({ workflow, save }: { workflow: WorkflowMap; save: (</details>;}-function WorkflowDetail({ workflow, initialEditing = false, navigate, platform, workProfile, saveCorrection, saveEdits, onShareWorkflow }: { workflow: WorkflowMap | null; initialEditing?: boolean; navigate: (view: AppView) => void; platform: WorkflowsPlatform; workProfile: WorkProfile | null; saveCorrection?: (note: string) => Promise<void>; saveEdits?: (draft: WorkflowEdit) => Promise<void>; onShareWorkflow?: WorkflowsAppProps["onShareWorkflow"] }) {- const [editing, setEditing] = useState(initialEditing);+function WorkflowDetail({ workflow, navigate, platform, workProfile, saveCorrection, saveEdits, onShareWorkflow }: { workflow: WorkflowMap | null; navigate: (view: AppView) => void; platform: WorkflowsPlatform; workProfile: WorkProfile | null; saveCorrection?: (note: string) => Promise<void>; saveEdits?: (draft: WorkflowEdit) => Promise<WorkflowMap>; onShareWorkflow?: WorkflowsAppProps["onShareWorkflow"] }) {const [expandedStages, setExpandedStages] = useState<Set<number>>(() => new Set());const [guideOpen, setGuideOpen] = useState(false);const [skillOpen, setSkillOpen] = useState(false);@@ -933,7 +930,6 @@ function WorkflowDetail({ workflow, initialEditing = false, navigate, platform,.catch((error) => setSkillError(error instanceof Error ? error.message : String(error || "Could not save the skill."))).finally(() => setSkillSaving(false));}, [platform, skillDraft]);- if (workflow && editing && saveEdits) return <WorkflowEditor key={workflow.id || workflow.title} workflow={workflow} save={saveEdits} close={() => setEditing(false)} />;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);@@ -947,17 +943,25 @@ function WorkflowDetail({ workflow, initialEditing = false, navigate, platform,else next.add(index);return next;});+ const workflowActions = <div className={styles.workflowActions}>{platform.guides && <button className={styles.skillButton} type="button" onClick={() => setGuideOpen(true)}><BookOpen size={14}/>Create SOP</button>}{platform.generateWorkflowSkill && platform.saveWorkflowSkill && <button className={styles.skillButton} type="button" onClick={openSkill}><Sparkles size={14} />{skillGenerating ? "Creating skill…" : skillSaved ? platform.skillInstallMode === "preview" ? "Skill preview" : "Skill installed" : skillDraft ? "Review skill" : "Create skill"}</button>}{onShareWorkflow && <button className={styles.skillButton} type="button" onClick={() => onShareWorkflow(workflow)}><Share2 size={14} />Share with team</button>}{platform.assistant?.saveFeedback && <button className={styles.skillButton} type="button" onClick={() => window.dispatchEvent(new CustomEvent("workflows:feedback", { detail: { key: `feedback:${workflow.id || workflow.title}`, title: workflow.title, workflow, purpose: "feedback" } }))}><MessageCircle size={14} />Feedback</button>}</div>;return (<><button className={styles.backButton} onClick={() => navigate("workflows")}><ArrowLeft size={14} />All workflows</button>- <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><div className={styles.workflowActions}>{saveEdits && <button className={styles.skillButton} type="button" title="Edit workflow" aria-label="Edit workflow" onClick={() => setEditing(true)}><Pencil size={15} />Edit workflow</button>}{platform.guides && <button className={styles.skillButton} type="button" onClick={() => setGuideOpen(true)}><BookOpen size={14}/>Create SOP</button>}{platform.generateWorkflowSkill && platform.saveWorkflowSkill && <button className={styles.skillButton} type="button" onClick={openSkill}><Sparkles size={14} />{skillGenerating ? "Creating skill…" : skillSaved ? platform.skillInstallMode === "preview" ? "Skill preview" : "Skill installed" : skillDraft ? "Review skill" : "Create skill"}</button>}{onShareWorkflow && <button className={styles.skillButton} type="button" onClick={() => onShareWorkflow(workflow)}><Share2 size={14} />Share with team</button>}{platform.assistant?.saveFeedback && <button className={styles.skillButton} type="button" onClick={() => window.dispatchEvent(new CustomEvent("workflows:feedback", { detail: { key: `feedback:${workflow.id || workflow.title}`, title: workflow.title, workflow, purpose: "feedback" } }))}><MessageCircle size={14} />Feedback</button>}</div></div>+ {saveEdits ? <WorkflowEditor key={workflow.id || workflow.title} workflow={workflow} save={saveEdits} actions={workflowActions} renderSource={stage => <details className={styles.workflowQuality}>+ <summary><div><strong>Sources and screenshots</strong></div><ChevronDown size={14} /></summary>+ <p>{stage.apps.join(" · ")} · {stage.observedOccurrences} observations across {stage.observedDays} days</p>+ {stage.screenshot?.visualVerified && <div className={styles.stageScreenshot}><div className={styles.screenshotFrame}><img src={stage.screenshot.dataUrl} alt={`Captured reference for ${stage.name}`} draggable={false} data-lm-disable="true" /></div><CapturedMomentButton frameId={stage.screenshot.frameId} timestamp={stage.screenshot.timestamp} open={platform.openCapturedMoment} /></div>}+ {stage.procedure?.filter(p => p.quote).map((p, i) => <blockquote key={i}>{p.quote}<small>{p.app} · {formatEvidenceTimestamp(p.timestamp)}</small></blockquote>)}+ {stage.openQuestions?.map((question, i) => <p key={i}>{question}</p>)}+ {!stage.screenshot?.visualVerified && !stage.procedure?.some(p => p.quote) && <p>No captured source attached.</p>}+ </details>} /> : <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 ? "Avg. time / run" : "Time for one run"}</span><strong>{formatEstimatedMinutes(timing.averageMinutes)}</strong><small>{timing.sampleCount} run{timing.sampleCount === 1 ? "" : "s"} · estimated elapsed time</small></div> : measuredDuration && <div className={styles.detailTotal}><span>Observed meeting duration</span><strong>{workflowDurationLabel(workflow)}</strong></div>}- </section>+ </section>}<p className={styles.workflowReviewState}>{workflow.userEditedAt ? "Edited by you · sources kept as references" : workflow.evidenceStatus === "supported-steps" ? "Source-backed steps · not execution-tested" : "Needs review"}</p>- <WorkflowReplay key={`replay:${workflow.title}`} workflow={workflow} loadRecording={platform.loadWorkflowRecording} releaseRecording={platform.releaseWorkflowRecording} openCapturedMoment={platform.openCapturedMoment} />+ <details className={styles.workflowQuality}><summary>Captured example</summary><WorkflowReplay key={`replay:${workflow.title}`} workflow={workflow} loadRecording={platform.loadWorkflowRecording} releaseRecording={platform.releaseWorkflowRecording} openCapturedMoment={platform.openCapturedMoment} /></details>{saveCorrection && !platform.assistant?.saveFeedback && <WorkflowCorrection key={`correction:${workflow.title}`} workflow={workflow} save={saveCorrection} />}- <section className={styles.flowMap}>+ {!saveEdits && <section className={styles.flowMap}><div className={styles.flowMapHeader}><div><strong>Steps</strong></div><button onClick={() => setExpandedStages(allStagesOpen ? new Set() : new Set(workflow.stages.map((_, index) => index)))}>{allStagesOpen ? "Collapse all" : "Expand all"}</button></div><div className={styles.flowEndpoint}><span>Starts when</span><strong>{workflow.trigger}</strong></div><div className={styles.stageList}>@@ -992,7 +996,7 @@ function WorkflowDetail({ workflow, initialEditing = false, navigate, platform,})}</div><div className={styles.flowEndpoint}><span>Ends with</span><strong>{workflow.outcome}</strong></div>- </section>+ </section>}{!!workflow.variations.length && <section className={styles.panel}><h2>Variations</h2><ul className={styles.plainList}>{workflow.variations.map(item => <li key={item}>{item}</li>)}</ul></section>}{!!actionableFriction.length && <><div className={styles.sectionHeading}><div><span>Within reach</span><h2>Friction you can affect</h2></div></div><BottleneckList items={actionableFriction.map((item) => ({ ...item, workflowTitle: workflow.title, repetitions: workflow.repetitions }))} /></>}{!!constraints.length && <><div className={styles.sectionHeading}><div><span>Plan around</span><h2>External and required constraints</h2></div></div><BottleneckList items={constraints.map((item) => ({ ...item, workflowTitle: workflow.title, repetitions: workflow.repetitions }))} numbered={false} /></>}@@ -1252,7 +1256,6 @@ export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "sconst [analysisJob, setAnalysisJob] = useState<WorkflowAnalysisJob | null>(null);const [analysisError, setAnalysisError] = useState("");const [selectedWorkflow, setSelectedWorkflow] = useState(0);- const [editOnOpen, setEditOnOpen] = useState(false);const [activityPeriod, setActivityPeriod] = useState<WorkflowActivityPeriod>(0);const [filters, setFilters] = useState<WorkflowFilters>(defaultWorkflowFilters);const [view, setView] = useState<AppView>("workflows");@@ -1280,9 +1283,8 @@ export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "s[activityPeriod, analysis?.analyzedAt, knownWorkflows],);const activeWorkflow = workflows[selectedWorkflow] ?? workflows[0] ?? null;- const openWorkflow = useCallback((index: number, edit = false) => {+ const openWorkflow = useCallback((index: number) => {if (index < 0) return;- setEditOnOpen(edit);setSelectedWorkflow(index);navigate("workflow");}, [navigate]);@@ -1578,8 +1580,8 @@ export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "sswitch (view) {case "overview": content = <OverviewView analysis={analysis ? { ...analysis, analysis: { workflows } } : null} analyzing={analyzing} error={analysisError} analyze={() => void analyze()} openWorkflow={openWorkflow} navigate={navigate} knownWorkflowCount={knownWorkflows.length} activityPeriod={activityPeriod} runtime={runtime} workProfile={workProfile} refreshRuntime={refreshRuntime} openAccount={platform.openAccount} />; break;case "time": content = <TimeView analysis={analysis} analyze={() => void analyze()} analyzing={analyzing} workProfile={workProfile} lens={timeLens} setLens={setTimeLens} />; break;- case "workflows": content = <WorkflowsView editWorkflow={catalogReady && platform.saveWorkflowEdits && (!activeScope || activeScope.kind === "personal") ? (index) => openWorkflow(index, true) : undefined} analysisUnavailableReason={onAnalysisUnavailable ? undefined : analysisUnavailableReason} workflows={workflows} knownWorkflowCount={knownWorkflows.length} activityPeriod={activityPeriod} filters={filters} setFilters={setFilters} openWorkflow={openWorkflow} analyze={() => void analyze()} analyzing={analyzing} error={analysisError} stop={platform.cancelAnalysisJob ? () => { void platform.cancelAnalysisJob!().catch(error => setAnalysisError(String(error))); } : undefined} updatedAt={analysis?.analyzedAt} checkedThrough={analysis?.checkedThrough} changes={analysis?.changes} job={analysisJob} subscribe={platform.subscribeAnalysisActivity} />; break;- case "workflow": content = <WorkflowDetail key={activeWorkflow?.id || activeWorkflow?.title} initialEditing={editOnOpen} onShareWorkflow={onShareWorkflow} workflow={activeWorkflow} navigate={navigate} platform={platform} workProfile={workProfile} saveEdits={catalogReady && platform.saveWorkflowEdits && (!activeScope || activeScope.kind === "personal") ? async (draft) => {+ case "workflows": content = <WorkflowsView analysisUnavailableReason={onAnalysisUnavailable ? undefined : analysisUnavailableReason} workflows={workflows} knownWorkflowCount={knownWorkflows.length} activityPeriod={activityPeriod} filters={filters} setFilters={setFilters} openWorkflow={openWorkflow} analyze={() => void analyze()} analyzing={analyzing} error={analysisError} stop={platform.cancelAnalysisJob ? () => { void platform.cancelAnalysisJob!().catch(error => setAnalysisError(String(error))); } : undefined} updatedAt={analysis?.analyzedAt} checkedThrough={analysis?.checkedThrough} changes={analysis?.changes} job={analysisJob} subscribe={platform.subscribeAnalysisActivity} />; break;+ case "workflow": content = <WorkflowDetail key={activeWorkflow?.id || activeWorkflow?.title} onShareWorkflow={onShareWorkflow} workflow={activeWorkflow} navigate={navigate} platform={platform} workProfile={workProfile} saveEdits={catalogReady && platform.saveWorkflowEdits && (!activeScope || activeScope.kind === "personal") ? async (draft) => {let saved: WorkflowMap;try { saved = await platform.saveWorkflowEdits!(draft); }catch (error) {@@ -1592,6 +1594,7 @@ export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "sthrow error;}setAnalysis(current => current ? { ...current, analysis: { ...current.analysis, workflows: current.analysis.workflows.map(w => (w.id ?? w.title) === draft.id && (saved.revision ?? 0) >= (w.revision ?? 0) ? saved : w) } } : current);+ return saved;} : undefined} saveCorrection={!analyzing && platform.saveCapturedWork && (!activeScope || activeScope.kind === "personal") ? async (note) => {if (!analysis || !activeWorkflow) return;const updated = { ...analysis, analysis: { workflows: analysis.analysis.workflows.map((workflow) => (workflow.id && activeWorkflow.id ? workflow.id === activeWorkflow.id : workflow.title === activeWorkflow.title) ? { ...workflow, userCorrection: note } : workflow) } };