Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

Create SOPs through workflow chat and share the document editor (#7246)

Louis Beaumonta2e05178e9e1
diff --git a/apps/screenpipe-app-tauri/lib/workflows/guide.test.tsx b/apps/screenpipe-app-tauri/lib/workflows/guide.test.tsx
index 03e56d52c..dc2859d77 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/guide.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/workflows/guide.test.tsx
@@ -1,6 +1,6 @@
// screenpipe — AI that knows everything you've seen, said, or heard
// https://screenpipe.com
-import React, { useState } from "react";
+import React, { useMemo, useState } from "react";
import { describe, it, expect, vi, afterEach } from "vitest";
import {
render,
@@ -32,6 +32,14 @@ function GuideChat({ edit, save = vi.fn(), previousFeedback = false }: { edit: N
{page && <WorkflowAssistant context={page.context} onDockChange={() => {}} platform={{ load: async () => previousFeedback ? previous : null, save: async () => {}, ask: page.ask }} />}
</PageAssistantContext.Provider>;
}
+function GenerationChat({ platform }: { platform: NonNullable<WorkflowsPlatform["guides"]> }) {
+ const [page, setPage] = useState<PageAssistant | null>(null);
+ const assistant = useMemo(() => page ? { load: async () => null, save: async () => {}, ask: page.ask } : null, [page]);
+ return <PageAssistantContext.Provider value={setPage}>
+ <WorkflowGuide workflow={workflow} platform={platform} close={() => {}} />
+ {page && assistant && <WorkflowAssistant context={page.context} promptRequest={page.promptRequest} onDockChange={() => {}} platform={assistant} />}
+ </PageAssistantContext.Provider>;
+}
const workflow = structuredClone(fixtureWorkflowAnalysis.analysis.workflows[0]);
workflow.id = "research";
workflow.revision = 3;
@@ -192,7 +200,7 @@ describe("guide editor", () => {
await screen.findByRole("heading", { name: "Research guide" });
expect(platform.generate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Edit SOP" }));
- fireEvent.change(screen.getByLabelText("Guide title"), {
+ fireEvent.change(screen.getByLabelText("SOP title"), {
target: { value: "Team research handbook" },
});
await waitFor(() =>
@@ -318,11 +326,7 @@ describe("guide editor", () => {
}),
};
const view = render(
- <WorkflowGuide
- workflow={workflow}
- platform={platform}
- close={() => {}}
- />,
+ <GenerationChat platform={platform} />,
);
await waitFor(() => expect(signal).toBeDefined());
view.unmount();
@@ -342,16 +346,17 @@ describe("guide editor", () => {
save: vi.fn().mockRejectedValue(new Error("disk full")),
};
render(
- <WorkflowGuide
- workflow={workflow}
- platform={platform}
- close={() => {}}
- />,
+ <GenerationChat platform={platform} />,
);
await screen.findByText("Account unavailable");
- fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ fireEvent.click(screen.getByRole("button", { name: /Try again|Retry/ }));
+ await screen.findByText("disk full");
+ expect(screen.queryByText("Saved your SOP on this device. Review its steps on the page.")).toBeNull();
+ platform.save.mockResolvedValue(undefined);
+ fireEvent.click(screen.getByRole("button", { name: /Try again|Retry/ }));
+ await screen.findByText("Saved your SOP on this device. Review its steps on the page.");
+ expect(platform.generate).toHaveBeenCalledTimes(2);
await screen.findByRole("heading", { name: "Research guide" });
- await screen.findByRole("button", { name: "Retry save" });
});
});
diff --git a/apps/screenpipe-app-tauri/vitest.config.ts b/apps/screenpipe-app-tauri/vitest.config.ts
index 1cf673f27..3271cd943 100644
--- a/apps/screenpipe-app-tauri/vitest.config.ts
+++ b/apps/screenpipe-app-tauri/vitest.config.ts
@@ -47,6 +47,8 @@ export default defineConfig({
"@/lib/i18n/generated.json": path.resolve(__dirname, "lib/i18n/empty.json"),
// Resolve the shared workflow package peer from the desktop test host.
"lucide-react": path.resolve(__dirname, "node_modules/lucide-react"),
+ // Shared SOP/rich-text sources resolve editor dependencies from this test host.
+ ...Object.fromEntries(["prosemirror-model", "prosemirror-state", "prosemirror-view", "prosemirror-markdown", "prosemirror-commands", "prosemirror-history", "prosemirror-keymap", "prosemirror-inputrules", "prosemirror-schema-list"].map(name => [name, path.resolve(__dirname, "node_modules", name)])),
"gt-react": path.resolve(__dirname, "node_modules/gt-react/dist/index.client.mjs"),
"@": path.resolve(__dirname, "./"),
"@screenpipe-ext": path.resolve(__dirname, "../../crates/screenpipe-core/assets/extensions"),
diff --git a/apps/screenpipe-workflows-web/scripts/eval-sop-chat.cjs b/apps/screenpipe-workflows-web/scripts/eval-sop-chat.cjs
new file mode 100644
index 000000000..fe7842f64
--- /dev/null
+++ b/apps/screenpipe-workflows-web/scripts/eval-sop-chat.cjs
@@ -0,0 +1,55 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+const { chromium } = require("playwright");
+const assert = require("node:assert/strict"),
+ fs = require("fs");
+(async () => {
+ const b = await chromium.launch({ headless: true, channel: "chrome" });
+ const p = await b.newPage({ viewport: { width: 1440, height: 1000 } });
+ p.setDefaultTimeout(12000);
+ const errors = [];
+ p.on("pageerror", (e) => errors.push(e.message));
+ const dir = process.env.SOP_SCREENSHOTS || "/tmp/sop-chat-eval";
+ fs.mkdirSync(dir, { recursive: true });
+ await p.goto(
+ process.env.WORKFLOWS_PREVIEW_URL || "http://localhost:1431/preview",
+ );
+ await p.getByRole("button", { name: "Open map" }).first().click();
+ await p.screenshot({ path: dir + "/desktop-workflow.png" });
+ await p.getByRole("button", { name: "Create SOP", exact: true }).click();
+ await p.getByRole("button", { name: "Stop answer", exact: true }).waitFor();
+ await p.screenshot({ path: dir + "/desktop-creating.png" });
+ await p
+ .getByText("Saved your SOP on this device. Review its steps on the page.", {
+ exact: true,
+ })
+ .waitFor({ timeout: 15000 });
+ await p.screenshot({ path: dir + "/desktop-saved.png" });
+ await p.getByRole("button", { name: "Minimize chat", exact: true }).click();
+ await p.screenshot({ path: dir + "/desktop-document.png" });
+ assert.equal(
+ await p.locator('article[aria-label="SOP document"] h1').innerText(),
+ "Research synthesis",
+ );
+ await p.reload();
+ await p.getByRole("button", { name: "Open map" }).first().click();
+ await p.getByRole("button", { name: "Create SOP", exact: true }).click();
+ await p.getByText("Before you start", { exact: true }).last().waitFor();
+ assert.equal(
+ await p.getByRole("button", { name: "Stop answer", exact: true }).count(),
+ 0,
+ );
+ await p.setViewportSize({ width: 390, height: 844 });
+ await p.screenshot({ path: dir + "/desktop-mobile.png" });
+ assert(
+ await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
+ );
+ assert.deepEqual(errors, []);
+ console.log(
+ "PASS create in chat, real adapter persistence receipt, reopen without generation, mobile overflow; fixture adapter only",
+ );
+ await b.close();
+})().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/docs/pr-assets/sop-chat/after/desktop-creating.png b/docs/pr-assets/sop-chat/after/desktop-creating.png
new file mode 100644
index 000000000..6f855998d
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/desktop-creating.png differ
diff --git a/docs/pr-assets/sop-chat/after/desktop-document.png b/docs/pr-assets/sop-chat/after/desktop-document.png
new file mode 100644
index 000000000..73dae6d8e
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/desktop-document.png differ
diff --git a/docs/pr-assets/sop-chat/after/desktop-mobile.png b/docs/pr-assets/sop-chat/after/desktop-mobile.png
new file mode 100644
index 000000000..95e47c370
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/desktop-mobile.png differ
diff --git a/docs/pr-assets/sop-chat/after/desktop-saved.png b/docs/pr-assets/sop-chat/after/desktop-saved.png
new file mode 100644
index 000000000..1ba493707
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/desktop-saved.png differ
diff --git a/docs/pr-assets/sop-chat/after/desktop-workflow.png b/docs/pr-assets/sop-chat/after/desktop-workflow.png
new file mode 100644
index 000000000..8ba783889
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/desktop-workflow.png differ
diff --git a/docs/pr-assets/sop-chat/after/main-app-saved.png b/docs/pr-assets/sop-chat/after/main-app-saved.png
new file mode 100644
index 000000000..f20d21848
Binary files /dev/null and b/docs/pr-assets/sop-chat/after/main-app-saved.png differ
diff --git a/docs/pr-assets/sop-chat/before/desktop-creating.png b/docs/pr-assets/sop-chat/before/desktop-creating.png
new file mode 100644
index 000000000..e3f9404f9
Binary files /dev/null and b/docs/pr-assets/sop-chat/before/desktop-creating.png differ
diff --git a/docs/pr-assets/sop-chat/before/desktop-document.png b/docs/pr-assets/sop-chat/before/desktop-document.png
new file mode 100644
index 000000000..4941be673
Binary files /dev/null and b/docs/pr-assets/sop-chat/before/desktop-document.png differ
diff --git a/docs/pr-assets/sop-chat/before/desktop-workflow.png b/docs/pr-assets/sop-chat/before/desktop-workflow.png
new file mode 100644
index 000000000..5d91e604d
Binary files /dev/null and b/docs/pr-assets/sop-chat/before/desktop-workflow.png differ
diff --git a/package.json b/package.json
index 598984d1d..0ba4784db 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,8 @@
"./context": "./packages/workflows-ui/src/context-tool.ts",
"./context-import": "./packages/workflows-ui/src/context-import.ts",
"./rich-text": "./packages/workflows-ui/src/rich-text.tsx",
- "./procedure-markdown": "./packages/workflows-ui/src/procedure-markdown.ts"
+ "./procedure-markdown": "./packages/workflows-ui/src/procedure-markdown.ts",
+ "./sop-document": "./packages/workflows-ui/src/sop-document.tsx"
},
"dependencies": {
"react-markdown": "^9.1.0",
diff --git a/packages/workflows-ui/package.json b/packages/workflows-ui/package.json
index 59672d25d..7e77d2a91 100644
--- a/packages/workflows-ui/package.json
+++ b/packages/workflows-ui/package.json
@@ -17,7 +17,8 @@
"./context": "./src/context-tool.ts",
"./context-import": "./src/context-import.ts",
"./rich-text": "./src/rich-text.tsx",
- "./procedure-markdown": "./src/procedure-markdown.ts"
+ "./procedure-markdown": "./src/procedure-markdown.ts",
+ "./sop-document": "./src/sop-document.tsx"
},
"dependencies": {
"react-markdown": "^9.1.0",
diff --git a/packages/workflows-ui/src/guide-assistant.tsx b/packages/workflows-ui/src/guide-assistant.tsx
index d3a94a6b9..d79cab653 100644
--- a/packages/workflows-ui/src/guide-assistant.tsx
+++ b/packages/workflows-ui/src/guide-assistant.tsx
@@ -8,26 +8,35 @@ import type { WorkflowsPlatform } from "./platform";
import { PageAssistantContext } from "./page-assistant";
import { useGT } from "gt-react";
-
/** Routes SOP edits through the shell's chat, including history, dictation and stop. */
export function GuideAssistant(props: {
- guide: WorkflowGuide;
+ guide: WorkflowGuide | null;
+ promptRequest?: { id: string; text: string };
workflow: WorkflowMap;
platform: NonNullable<WorkflowsPlatform["guides"]>;
- update: (guide: WorkflowGuide) => void;
+ update: (guide: WorkflowGuide) => Promise<void>;
}) {
const ui = useGT();
const register = useContext(PageAssistantContext);
const current = useRef(props);
+ const unsaved = useRef<WorkflowGuide | null>(null);
current.current = props;
useEffect(() => {
if (!register) return;
const lifetime = new AbortController();
register({
- context: { key: `sop:${props.workflow.id || props.workflow.title}`, title: ui("SOP: {value1}", { value1: props.guide.title }), purpose: "sop" },
+ context: {
+ key: `sop:${props.workflow.id || props.workflow.title}`,
+ title: ui("SOP: {value1}", {
+ value1: props.guide?.title ?? props.workflow.title,
+ }),
+ purpose: "sop",
+ },
+ promptRequest: props.promptRequest,
ask: async ({ question, signal, onProgress }) => {
const { guide, workflow, platform, update } = current.current;
- if (!platform.edit) throw new Error("SOP editing is unavailable.");
+ if (guide && !platform.edit)
+ throw new Error("SOP editing is unavailable.");
const run = new AbortController();
const abort = () => run.abort();
signal.addEventListener("abort", abort, { once: true });
@@ -36,21 +45,41 @@ export function GuideAssistant(props: {
const runSignal = run.signal;
try {
runSignal.throwIfAborted();
- const next = await platform.edit(guide, workflow, question, runSignal, text => {
+ const progress = (text: string) => {
if (!runSignal.aborted) onProgress({ text, activity: "writing" });
- });
+ };
+ const next = guide
+ ? await platform.edit!(
+ guide,
+ workflow,
+ question,
+ runSignal,
+ progress,
+ )
+ : (unsaved.current ??
+ (await platform.load(workflow)) ??
+ (await platform.generate(workflow, runSignal, progress)));
runSignal.throwIfAborted();
if (current.current.guide !== guide)
- throw new Error("The SOP changed while the assistant was editing. Your edits were kept. Try again.");
- update(next);
- return "Updated the SOP. You can review the changes on the page.";
+ throw new Error(
+ "The SOP changed while the assistant was editing. Your edits were kept. Try again.",
+ );
+ unsaved.current = next;
+ await update(next);
+ unsaved.current = null;
+ return guide
+ ? "Saved the updated SOP. Review the changes on the page."
+ : "Saved your SOP on this device. Review its steps on the page.";
} finally {
signal.removeEventListener("abort", abort);
lifetime.signal.removeEventListener("abort", abort);
}
},
});
- return () => { lifetime.abort(); register(null); };
+ return () => {
+ lifetime.abort();
+ register(null);
+ };
}, [register, props.workflow.id, props.workflow.title]);
return null;
}
diff --git a/packages/workflows-ui/src/page-assistant.ts b/packages/workflows-ui/src/page-assistant.ts
index 0db49a999..fe59fe929 100644
--- a/packages/workflows-ui/src/page-assistant.ts
+++ b/packages/workflows-ui/src/page-assistant.ts
@@ -7,6 +7,7 @@ import type { AssistantContext, WorkflowsAssistantPlatform } from "./assistant";
/** A mounted page can supply an action to the existing chat without another composer. */
export type PageAssistant = {
context: AssistantContext;
+ promptRequest?: { id: string; text: string };
ask: WorkflowsAssistantPlatform["ask"];
};
export const PageAssistantContext = createContext<Dispatch<SetStateAction<PageAssistant | null>> | null>(null);
diff --git a/packages/workflows-ui/src/rich-text.tsx b/packages/workflows-ui/src/rich-text.tsx
index 51449b141..396152cdb 100644
--- a/packages/workflows-ui/src/rich-text.tsx
+++ b/packages/workflows-ui/src/rich-text.tsx
@@ -24,6 +24,7 @@ export function WorkflowRichText({
placeholder = "Add details…",
maxLength = 4000,
className = "",
+ fullDocument = false,
}: {
value: string;
onChange?: (value: string) => void;
@@ -31,6 +32,7 @@ export function WorkflowRichText({
placeholder?: string;
maxLength?: number;
className?: string;
+ fullDocument?: boolean;
}) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView>();
@@ -150,7 +152,7 @@ export function WorkflowRichText({
<div className={`${styles.root} ${className}`} data-testid="procedure-markdown">
<div
id={id}
- className={long && !expanded ? styles.collapsed : undefined}
+ className={!fullDocument && long && !expanded ? styles.collapsed : undefined}
onFocusCapture={() => setExpanded(true)}
>
<div
@@ -158,7 +160,7 @@ export function WorkflowRichText({
className={`${styles.document} ${editable ? styles.editable : ""}`}
/>
</div>
- {long && (
+ {!fullDocument && long && (
<button
type="button"
aria-expanded={expanded}
diff --git a/packages/workflows-ui/src/sop-document.module.css b/packages/workflows-ui/src/sop-document.module.css
new file mode 100644
index 000000000..89b1b245d
--- /dev/null
+++ b/packages/workflows-ui/src/sop-document.module.css
@@ -0,0 +1,52 @@
+/* screenpipe — AI that knows everything you've seen, said, or heard */
+/* https://screenpipe.com */
+.document {
+ width: 100%;
+ max-width: 900px;
+ min-width: 0;
+ margin: 0 auto;
+ color: inherit;
+ font-size: 16px;
+ line-height: 1.7;
+ overflow-wrap: anywhere;
+}
+.heading {
+ padding: 28px 0 32px;
+ margin-bottom: 24px;
+ border-bottom: 1px solid var(--line, #dfe1d9);
+}
+.kind {
+ font-size: 11px;
+ letter-spacing: 0.06em;
+ color: inherit;
+ opacity: 0.55;
+ margin: 0 0 14px;
+}
+.document .title {
+ font-family: inherit;
+ font-size: clamp(26px, 3vw, 38px);
+ font-weight: 600;
+ line-height: 1.2;
+ letter-spacing: -0.025em;
+ margin: 0;
+ width: 100%;
+ background: transparent;
+ color: inherit;
+ border: 0;
+ border-radius: 4px;
+ padding: 0;
+}
+.title:focus-visible {
+ outline: 2px solid currentColor;
+ outline-offset: 6px;
+}
+.subtitle {
+ margin-top: 18px;
+ font-size: 14px;
+ opacity: 0.65;
+}
+@media (max-width: 600px) {
+ .heading {
+ padding: 16px 0 24px;
+ }
+}
diff --git a/packages/workflows-ui/src/sop-document.tsx b/packages/workflows-ui/src/sop-document.tsx
new file mode 100644
index 000000000..afa68e32f
--- /dev/null
+++ b/packages/workflows-ui/src/sop-document.tsx
@@ -0,0 +1,53 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+"use client";
+import type { ReactNode } from "react";
+import { WorkflowRichText } from "./rich-text";
+import styles from "./sop-document.module.css";
+
+/** Shared document surface; storage, evidence access and publication stay in adapters. */
+export function SopDocument({
+ title,
+ subtitle,
+ content,
+ onTitleChange,
+ onContentChange,
+ children,
+}: {
+ title: string;
+ subtitle?: ReactNode;
+ content?: string;
+ onTitleChange?: (title: string) => void;
+ onContentChange?: (content: string) => void;
+ children?: ReactNode;
+}) {
+ return (
+ <article className={styles.document} aria-label="SOP document">
+ <header className={styles.heading}>
+ <p className={styles.kind}>Standard operating procedure</p>
+ {onTitleChange ? (
+ <input
+ className={styles.title}
+ aria-label="SOP title"
+ maxLength={300}
+ value={title}
+ onChange={(event) => onTitleChange(event.target.value)}
+ />
+ ) : (
+ <h1 className={styles.title}>{title}</h1>
+ )}
+ {subtitle && <div className={styles.subtitle}>{subtitle}</div>}
+ </header>
+ {content !== undefined && (
+ <WorkflowRichText
+ value={content}
+ onChange={onContentChange}
+ label="SOP text"
+ maxLength={60000}
+ fullDocument
+ />
+ )}
+ {children}
+ </article>
+ );
+}
diff --git a/packages/workflows-ui/src/workflow-assistant.tsx b/packages/workflows-ui/src/workflow-assistant.tsx
index fbae44c90..8f5130759 100644
--- a/packages/workflows-ui/src/workflow-assistant.tsx
+++ b/packages/workflows-ui/src/workflow-assistant.tsx
@@ -14,8 +14,9 @@ import { useGT } from "gt-react";
const FEEDBACK_PROMPT = "Review this workflow and ask me 3 specific questions to help refine it. Also invite any general feedback I have.";
-export function WorkflowAssistant({ platform, context, onDockChange, onWidthChange, onOpenChange, onModeChange, headerToggle = false, active = true, composerAccessory }: {
+export function WorkflowAssistant({ platform, context, onDockChange, onWidthChange, onOpenChange, onModeChange, headerToggle = false, active = true, composerAccessory, promptRequest }: {
platform: WorkflowsAssistantPlatform;
+ promptRequest?: { id: string; text: string };
context: AssistantContext;
onDockChange: (docked: boolean) => void;
onWidthChange?: (width: number) => void;
@@ -66,6 +67,7 @@ export function WorkflowAssistant({ platform, context, onDockChange, onWidthChan
const conversation = state.conversations.find((c) => c.id === state.activeId)!;
const feedbackContext = conversation.feedbackContext;
const selectedSop = useRef<string | null>(null);
+ const consumedPrompt = useRef<string | null>(null);
const width = Number.isFinite(state.sidebarWidth) ? Math.max(340, Math.min(560, state.sidebarWidth!)) : 420;
const persist = useCallback(async (snapshot: AssistantState) => {
@@ -203,16 +205,24 @@ export function WorkflowAssistant({ platform, context, onDockChange, onWidthChan
requestAnimationFrame(() => input.current?.focus());
}, [pendingFeedback, loaded, busy, update]);
+ useEffect(() => {
+ if (!promptRequest || !loaded || busy || controller.current || consumedPrompt.current === promptRequest.id) return;
+ consumedPrompt.current = promptRequest.id;
+ setOpen(true);
+ setIncludeContext(true);
+ void send(promptRequest.text, false, context);
+ }, [promptRequest, loaded, busy, context]);
+
const patchMessage = (conversationId: string, messageId: string, patch: Partial<AssistantMessage>) => update((current) => ({
...current, conversations: current.conversations.map((c) => c.id !== conversationId ? c : { ...c, messages: c.messages.map((m) => m.id === messageId ? { ...m, ...patch } : m) }),
}), 1000);
- async function send(question: string, retry = false) {
+ async function send(question: string, retry = false, requestedContext?: AssistantContext) {
if (!question.trim() || controller.current || !loadedRef.current) return;
const current = stateRef.current.conversations.find((c) => c.id === stateRef.current.activeId)!;
const previousUserIndex = current.messages.findLastIndex((m) => m.role === "user");
const history = retry ? current.messages.slice(0, previousUserIndex) : current.messages;
- const turnContext = retry ? current.messages[previousUserIndex]?.context ?? null : current.feedbackContext ? assistantContextSnapshot(current.feedbackContext) : includeContext ? assistantContextSnapshot(context) : null;
+ const turnContext = requestedContext ? assistantContextSnapshot(requestedContext) : retry ? current.messages[previousUserIndex]?.context ?? null : current.feedbackContext ? assistantContextSnapshot(current.feedbackContext) : includeContext ? assistantContextSnapshot(context) : null;
const userId = crypto.randomUUID();
const alreadySavedFeedback = retry && current.messages[previousUserIndex]?.feedbackSaved;
const answerId = crypto.randomUUID();
diff --git a/packages/workflows-ui/src/workflow-guide.tsx b/packages/workflows-ui/src/workflow-guide.tsx
index 851742a12..f36500267 100644
--- a/packages/workflows-ui/src/workflow-guide.tsx
+++ b/packages/workflows-ui/src/workflow-guide.tsx
@@ -25,11 +25,12 @@ import {
guideSourceImage,
type WorkflowGuide as Guide,
} from "./guide";
+import { WorkflowRichText } from "./rich-text";
+import { SopDocument } from "./sop-document";
import { GuideAssistant } from "./guide-assistant";
import styles from "./workflow-guide.module.css";
import { useGT } from "gt-react";
-
export function WorkflowGuide({
workflow,
platform,
@@ -40,9 +41,12 @@ export function WorkflowGuide({
close: () => void;
}) {
const ui = useGT();
+ const [promptRequest, setPromptRequest] = useState<{
+ id: string;
+ text: string;
+ }>();
const [draft, setDraft] = useState<Guide | null>(null);
const [busy, setBusy] = useState(true);
- const [progress, setProgress] = useState("Opening your SOP");
const [error, setError] = useState("");
const [saved, setSaved] = useState("");
const [editing, setEditing] = useState(false);
@@ -53,7 +57,6 @@ export function WorkflowGuide({
const [webError, setWebError] = useState("");
const [exportError, setExportError] = useState("");
const dialog = useRef<HTMLDialogElement>(null);
- const controller = useRef<AbortController>();
const latest = useRef<Guide | null>(null);
const saveVersion = useRef(0);
const loadVersion = useRef(0);
@@ -65,45 +68,21 @@ export function WorkflowGuide({
await platform.save(next);
if (mounted.current && version === saveVersion.current)
setSaved("Saved on this device");
- } catch {
+ } catch (cause) {
if (mounted.current && version === saveVersion.current)
setSaved("Could not save. Retry before leaving.");
+ throw cause;
}
}
function update(next: Guide) {
latest.current = next;
setDraft(next);
- void persist(next);
- }
- async function generate() {
- controller.current?.abort();
- const run = new AbortController();
- controller.current = run;
- setBusy(true);
- setError("");
- setProgress("Reading your workflow");
- try {
- const next = await platform.generate(workflow, run.signal, (message) => {
- if (!run.signal.aborted) setProgress(message);
- });
- if (run.signal.aborted) return;
- update(next);
- } catch (e) {
- if (!run.signal.aborted)
- setError(
- e instanceof Error
- ? e.message
- : ui("Could not create the SOP. Try again."),
- );
- } finally {
- if (!run.signal.aborted) setBusy(false);
- }
+ void persist(next).catch(() => {});
}
async function openGuide() {
const version = ++loadVersion.current;
setBusy(true);
setError("");
- setProgress("Opening your SOP");
try {
const existing = await platform.load(workflow);
if (version !== loadVersion.current) return;
@@ -112,7 +91,13 @@ export function WorkflowGuide({
setDraft(existing);
setSaved("Saved on this device");
setBusy(false);
- } else void generate();
+ } else {
+ setBusy(false);
+ setPromptRequest({
+ id: crypto.randomUUID(),
+ text: `Create an SOP for ${workflow.title} from its available evidence. Keep missing details as questions and save the draft for review.`,
+ });
+ }
} catch {
if (version === loadVersion.current) {
setError(
@@ -128,7 +113,6 @@ export function WorkflowGuide({
return () => {
loadVersion.current++;
mounted.current = false;
- controller.current?.abort();
};
}, []);
function jump(event: MouseEvent<HTMLAnchorElement>) {
@@ -174,7 +158,6 @@ export function WorkflowGuide({
<header className={styles.toolbar}>
<button
onClick={() => {
- controller.current?.abort();
close();
}}
>
@@ -200,9 +183,11 @@ export function WorkflowGuide({
</>
)}
</span>
- {saved.startsWith("Could not") && (
+ {draft && saved.startsWith("Could not") && (
<button
- onClick={() => latest.current && void persist(latest.current)}
+ onClick={() =>
+ latest.current && void persist(latest.current).catch(() => {})
+ }
>
Retry save
</button>
@@ -251,8 +236,25 @@ export function WorkflowGuide({
)}
</div>
</header>
+ {!busy && !error && (
+ <GuideAssistant
+ guide={draft}
+ workflow={workflow}
+ platform={platform}
+ promptRequest={promptRequest}
+ update={async (next) => {
+ await persist(next);
+ if (!mounted.current) return;
+ latest.current = next;
+ setDraft(next);
+ }}
+ />
+ )}
{draft && webReview && (
- <section className={styles.section} aria-label={ui("Open SOP on the web")}>
+ <section
+ className={styles.section}
+ aria-label={ui("Open SOP on the web")}
+ >
<h2>Open your SOP on the web</h2>
<p>
Save the reviewed SOP text to your Screenpipe account to edit and
@@ -285,55 +287,15 @@ export function WorkflowGuide({
</section>
)}
{!draft ? (
- <div className={styles.empty}>
- <div className={styles.mark}>
- {busy ? (
- <Loader2 className={styles.spin} size={25} />
- ) : (
- <BookOpen size={25} />
- )}
- </div>
- <p className={styles.eyebrow}>STANDARD OPERATING PROCEDURE</p>
- <h1>
+ <SopDocument title={workflow.title} subtitle="Draft for review">
+ <p role="status">
{busy
- ? ui("Turning your work into an SOP")
- : ui("Your SOP needs another try")}
- </h1>
- <p>{workflow.title}</p>
- {busy ? (
- <>
- <p role="status">{progress}</p>
- <div className={styles.phases}>
- <span>Source material</span>
- <span>Clear steps</span>
- <span>Ready to review</span>
- </div>
- <button
- onClick={() => {
- loadVersion.current++;
- controller.current?.abort();
- setBusy(false);
- setError(
- ui("Generation stopped. You can try again when you’re ready."),
- );
- }}
- >
- Stop
- </button>
- </>
- ) : (
- <>
- <p role="alert">{error}</p>
- <button
- className={styles.primary}
- onClick={() => void openGuide()}
- >
- Try again
- </button>
- </>
- )}
- <small>Your workflow stays unchanged.</small>
- </div>
+ ? "Opening SOP…"
+ : "Your SOP will appear here as you work with the assistant."}
+ </p>
+ {error && <p role="alert">{error}</p>}
+ {error && <button onClick={() => void openGuide()}>Try again</button>}
+ </SopDocument>
) : (
<div className={styles.layout}>
<aside className={styles.outline}>
@@ -359,46 +321,23 @@ export function WorkflowGuide({
</small>
</div>
</aside>
- <article className={styles.document}>
- <div className={styles.intro}>
- <p className={styles.eyebrow}>
- STANDARD OPERATING PROCEDURE <span>Draft for review</span>
- </p>
- {editing ? (
- <>
- <input
- aria-label={ui("Guide title")}
- value={draft.title}
- onChange={(e) =>
- update({ ...draft, title: e.target.value })
- }
- />
- <textarea
- aria-label={ui("Guide summary")}
- value={draft.summary}
- onChange={(e) =>
- update({ ...draft, summary: e.target.value })
- }
- />
- </>
- ) : (
- <>
- <h1>{draft.title}</h1>
- <p>{draft.summary}</p>
- </>
- )}
- <small>
- {draft.steps.length} steps · Based on workflow revision{" "}
- {draft.sourceRevision}
- </small>
- </div>
- {platform.edit && (
- <GuideAssistant
- guide={draft}
- workflow={workflow}
- platform={platform}
- update={update}
+ <SopDocument
+ title={draft.title}
+ onTitleChange={
+ editing ? (title) => update({ ...draft, title }) : undefined
+ }
+ subtitle={<>{draft.steps.length} steps · Draft for review</>}
+ >
+ {editing ? (
+ <textarea
+ aria-label="Guide summary"
+ value={draft.summary}
+ onChange={(event) =>
+ update({ ...draft, summary: event.target.value })
+ }
/>
+ ) : (
+ <p>{draft.summary}</p>
)}
{stale && (
<p className={styles.notice}>
@@ -431,7 +370,9 @@ export function WorkflowGuide({
<span className={styles.number}>{i + 1}</span>
{editing ? (
<input
- aria-label={ui("Step {value1} title", { value1: i + 1 })}
+ aria-label={ui("Step {value1} title", {
+ value1: i + 1,
+ })}
value={step.title}
onChange={(e) =>
update({
@@ -448,7 +389,9 @@ export function WorkflowGuide({
{editing && (
<div className={styles.stepTools}>
<button
- aria-label={ui("Move step {value1} up", { value1: i + 1 })}
+ aria-label={ui("Move step {value1} up", {
+ value1: i + 1,
+ })}
disabled={i === 0}
onClick={() => {
const steps = [...draft.steps];
@@ -462,7 +405,9 @@ export function WorkflowGuide({
<ArrowUp size={14} />
</button>
<button
- aria-label={ui("Move step {value1} down", { value1: i + 1 })}
+ aria-label={ui("Move step {value1} down", {
+ value1: i + 1,
+ })}
disabled={i === draft.steps.length - 1}
onClick={() => {
const steps = [...draft.steps];
@@ -476,7 +421,9 @@ export function WorkflowGuide({
<ArrowDown size={14} />
</button>
<button
- aria-label={ui("Remove step {value1}", { value1: i + 1 })}
+ aria-label={ui("Remove step {value1}", {
+ value1: i + 1,
+ })}
disabled={draft.steps.length === 1}
onClick={() =>
update({
@@ -490,29 +437,31 @@ export function WorkflowGuide({
</div>
)}
</div>
- {editing ? (
- <textarea
- aria-label={ui("Step {value1} instructions", { value1: i + 1 })}
- value={step.instruction}
- onChange={(e) =>
- update({
- ...draft,
- steps: draft.steps.map((s, j) =>
- j === i
- ? { ...s, instruction: e.target.value }
- : s,
- ),
- })
- }
- />
- ) : (
- <p>{step.instruction}</p>
- )}
+ <WorkflowRichText
+ value={step.instruction}
+ label={ui("Step {value1} instructions", {
+ value1: i + 1,
+ })}
+ fullDocument
+ onChange={
+ editing
+ ? (instruction) =>
+ update({
+ ...draft,
+ steps: draft.steps.map((step, index) =>
+ index === i ? { ...step, instruction } : step,
+ ),
+ })
+ : undefined
+ }
+ />
{image ? (
<figure>
<img
src={image}
- alt={ui("Source for {value1}", { value1: step.title })}
+ alt={ui("Source for {value1}", {
+ value1: step.title,
+ })}
draggable={false}
/>
{editing && (
@@ -557,7 +506,9 @@ export function WorkflowGuide({
) : (
<p className={styles.muted}>
{stale
- ? ui("Source changed. Regenerate this SOP to review its screenshots.")
+ ? ui(
+ "Source changed. Regenerate this SOP to review its screenshots.",
+ )
: ui("No captured screenshot for this step.")}
</p>
)}
@@ -565,7 +516,9 @@ export function WorkflowGuide({
<label className={styles.result}>
Expected result
<input
- aria-label={ui("Step {value1} expected result", { value1: i + 1 })}
+ aria-label={ui("Step {value1} expected result", {
+ value1: i + 1,
+ })}
value={step.expectedResult}
onChange={(e) =>
update({
@@ -624,7 +577,7 @@ export function WorkflowGuide({
"questions",
"No open questions in this draft.",
)}
- </article>
+ </SopDocument>
</div>
)}
<dialog ref={dialog} className={styles.exportDialog}>
diff --git a/packages/workflows-ui/src/workflows-app.tsx b/packages/workflows-ui/src/workflows-app.tsx
index 7d365e6b5..5aa25f6c4 100644
--- a/packages/workflows-ui/src/workflows-app.tsx
+++ b/packages/workflows-ui/src/workflows-app.tsx
@@ -526,7 +526,7 @@ function AppShell({
</nav>}
<main className={styles.main}>{children}</main>
</section>
- {assistant && <WorkflowAssistant composerAccessory={composerAccessory} active={active} platform={assistantPlatform!} context={pageAssistant?.context ?? assistant.context} onDockChange={setAssistantDocked} onWidthChange={setAssistantWidth} onOpenChange={setAssistantOpen} onModeChange={setAssistantMode} headerToggle />}
+ {assistant && <WorkflowAssistant composerAccessory={composerAccessory} active={active} platform={assistantPlatform!} context={pageAssistant?.context ?? assistant.context} promptRequest={pageAssistant?.promptRequest} onDockChange={setAssistantDocked} onWidthChange={setAssistantWidth} onOpenChange={setAssistantOpen} onModeChange={setAssistantMode} headerToggle />}
</div></PageAssistantContext.Provider>
);
}
@@ -991,7 +991,7 @@ function WorkflowDetail({ workflow, navigate, platform, workProfile, saveCorrect
return next;
});
const agentActions = workflowAgentActions?.(workflow);
- const workflowActions = <div className={styles.workflowActions}>{agentActions}{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 ? ui("Creating skill…") : skillSaved ? platform.skillInstallMode === "preview" ? ui("Skill preview") : ui("Skill installed") : skillDraft ? ui("Review skill") : ui("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>;
+ const workflowActions = <div className={styles.workflowActions}>{agentActions}{platform.guides && <button className={styles.skillButton} type="button" aria-label="Create SOP" title="Create SOP" onClick={() => setGuideOpen(true)}><BookOpen size={16} aria-hidden="true"/></button>}{platform.generateWorkflowSkill && platform.saveWorkflowSkill && <button className={styles.skillButton} type="button" onClick={openSkill}><Sparkles size={14} />{skillGenerating ? ui("Creating skill…") : skillSaved ? platform.skillInstallMode === "preview" ? ui("Skill preview") : ui("Skill installed") : skillDraft ? ui("Review skill") : ui("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>