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

12.6 KB
Raw Blame
// screenpipe — AI that knows everything you've seen, said, or heard
// https://screenpipe.com

import React from "react";
import posthog from "posthog-js";
import { act, fireEvent, render, screen, within, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { RecordingStatus } from "@/components/recording-status";
import { SidebarFooter } from "@/components/sidebar-footer";
import { DeviceWorkflows as IntegratedWorkflows, workflowAgentTask } from "./integrated-workflows";

// DeviceWorkflows is normally mounted beneath the app shell's settings and policy providers.
vi.mock("@/lib/hooks/use-settings", () => ({
  useSettings: () => ({ settings: { aiPresets: [], user: {} }, updateSettings: vi.fn() }),
}));
vi.mock("@/lib/hooks/use-model-upsell-gating", () => ({
  useModelUpsellGating: () => false,
}));
vi.mock("@/lib/hooks/use-managed-policy", () => ({
  useManagedPolicy: () => ({ isManagedDeployment: false, policy: {} }),
}));
vi.mock("@/lib/hooks/use-pi-models", () => ({
  usePiModels: () => ({ piModels: [], isLoading: false, upgradeEligible: false }),
}));

vi.mock("@/lib/workflows/desktop-platform", async () => {
  const { createFixtureWorkflowsPlatform, fixtureWorkflowAnalysis } = await import("@screenpipe/workflows-ui/fixture");
  return { desktopWorkflowsPlatform: {
    ...createFixtureWorkflowsPlatform(),
    // jsdom cannot rasterize the browser fixture's SVG screenshots.
    loadCapturedWork: async () => {
      const catalog = structuredClone(fixtureWorkflowAnalysis);
      catalog.analysis.workflows.forEach((workflow, index) => {
        workflow.id = `wf-fixture-${index}`;
        // The persisted catalog represents unanswered corrections as null.
        workflow.userCorrection = null;
      });
      return catalog;
    },
  } };
});
vi.mock("@/components/connected-share-dialog", () => ({
  ConnectedShareDialog: ({ open, artifact, onOpenChange, onConnect, connectionsRevision }: any) => open ? <div role="dialog" aria-label="Sharing review"><h2>{artifact.title}</h2><p>{artifact.surface}</p><span>Connections revision {connectionsRevision}</span><button onClick={() => onConnect("slack")}>Connect Slack</button><button onClick={() => onOpenChange(false)}>Close sharing</button></div> : null,
}));
vi.mock("@/components/settings/connections-section", () => ({
  ConnectionsSection: ({ panelOnly, focusConnectionId, focusScopeVariant, focusRequestId, onConnectionClose }: any) => !focusRequestId ? null : <div role="dialog" aria-label="Connection setup"><p>{panelOnly ? "Panel only" : "All connections"} {focusConnectionId} {focusScopeVariant}</p><button onClick={onConnectionClose}>Close connection</button></div>,
}));
vi.mock("posthog-js", () => ({ default: { capture: vi.fn() } }));

it("renders the native recording dot and opens device controls in Workflows", async () => {
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={
    <RecordingStatus devices={[{ name: "Display 1", fullName: "Display 1", kind: "monitor", active: true, id: 1 }]}
      onDevicesChange={vi.fn()} meetingActive={false} onPauseRecording={vi.fn()} />
  } />);
  fireEvent.click(await screen.findByRole("button", { name: "Recording" }));
  expect(await screen.findByTestId("recording-status-popover")).toBeVisible();
  expect(screen.getByText("Display 1")).toBeVisible();
  expect(screen.getByRole("button", { name: "Pause all recording" })).toBeVisible();
  expect(screen.queryByText("Starting")).not.toBeInTheDocument();
});

it("keeps Settings and Help in the footer and opens workspace shortcuts from Help", async () => {
  const settings = vi.fn(), help = vi.fn();
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null}
    navigationFooter={({ openKeyboardShortcuts }) => <SidebarFooter onSettings={settings} onHelp={help} onKeyboardShortcuts={openKeyboardShortcuts} />} />);
  fireEvent.click(screen.getByRole("button", { name: "Settings" }));
  expect(settings).toHaveBeenCalledOnce();
  expect(screen.queryByRole("button", { name: /Keyboard shortcuts/ })).not.toBeInTheDocument();
  fireEvent.keyDown(screen.getByRole("button", { name: "Help" }), { key: "Enter" });
  fireEvent.click(await screen.findByRole("menuitem", { name: "Keyboard shortcuts" }));
  expect(await screen.findByRole("dialog", { name: /command/i })).toBeVisible();
});

it("opens the team invite popover and web management from the Workflows footer", async () => {
  const manageTeam = vi.fn();
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null}
    navigationFooter={({ openKeyboardShortcuts }) => <SidebarFooter
      onSettings={vi.fn()} onHelp={vi.fn()} onKeyboardShortcuts={openKeyboardShortcuts}
      teamEntry={{ kind: "team", label: "Example Studio", href: "https://screenpipe.com/team-dashboard?team_id=studio", teamId: "studio", canInvite: true }}
      teamToken="fixture-only" onTeam={manageTeam} />} />);
  fireEvent.click(screen.getByRole("button", { name: "Example Studio, team menu" }));
  expect(await screen.findByRole("textbox", { name: "Teammate email" })).toHaveFocus();
  expect(screen.getByRole("button", { name: "Send invitation" })).toBeDisabled();
  expect(manageTeam).not.toHaveBeenCalled();
  fireEvent.click(screen.getByRole("button", { name: "Manage team on the web" }));
  expect(manageTeam).toHaveBeenCalledOnce();
});

it("opens the existing sharing review from the selected workflow in the main app", async () => {
  window.history.replaceState(null, "", "/home?mode=workflows");
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null} />);
  // Wait for saved data instead of interacting with a transient empty screen.
  const card = (await screen.findByRole("heading", { name: "Research synthesis" })).closest("article")!;
  fireEvent.click(within(card).getByRole("button"));
  expect(screen.queryByRole("dialog", { name: "Sharing review" })).not.toBeInTheDocument();
  const agent = screen.getByRole("button", { name: "Open in agent" });
  expect(agent.parentElement).toContainElement(screen.getByRole("button", { name: "Share", exact: true }));
  expect(screen.queryByRole("button", { name: "Feedback", exact: true })).not.toBeInTheDocument();
  expect(screen.queryByRole("button", { name: "Create SOP" })).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "More workflow actions" }));
  for (const name of ["Create SOP", "Create skill", "Variables", "History", "Workflow details", "Undo last edit"]) {
    expect(screen.getByRole("menuitem", { name })).toBeVisible();
  }
  expect(screen.queryByRole("menuitem", { name: "Feedback" })).not.toBeInTheDocument();
  fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
  fireEvent.keyDown(agent, { key: "ArrowDown" });
  for (const name of ["Codex", "Claude", "Cursor", "Screenpipe"]) {
    expect(await screen.findByRole("menuitem", { name })).toBeVisible();
  }
  fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
  fireEvent.click(screen.getByRole("button", { name: "Share", exact: true }));
  expect(screen.getByRole("dialog", { name: "Sharing review" })).toHaveTextContent("Research synthesis");
  expect(screen.getByRole("dialog", { name: "Sharing review" })).toHaveTextContent("workflow");
  fireEvent.click(screen.getByRole("button", { name: "Connect Slack" }));
  expect(screen.getByRole("dialog", { name: "Connection setup" })).toHaveTextContent("Panel only slack send");
  fireEvent.click(screen.getByRole("button", { name: "Close connection" }));
  expect(screen.queryByRole("dialog", { name: "Connection setup" })).not.toBeInTheDocument();
  expect(screen.getByRole("dialog", { name: "Sharing review" })).toHaveTextContent("Connections revision 1");
  // Reopening must issue another focus request after the first panel unmounts.
  fireEvent.click(screen.getByRole("button", { name: "Connect Slack" }));
  expect(screen.getByRole("dialog", { name: "Connection setup" })).toHaveTextContent("Panel only slack send");
  fireEvent.click(screen.getByRole("button", { name: "Close connection" }));
  expect(screen.getByRole("dialog", { name: "Sharing review" })).toHaveTextContent("Connections revision 2");
  fireEvent.click(screen.getByRole("button", { name: "Close sharing" }));
  expect(screen.queryByRole("dialog", { name: "Sharing review" })).not.toBeInTheDocument();
  expect(screen.getByRole("textbox", { name: "Workflow title" })).toHaveValue("Research synthesis");
});

vi.mock("@/lib/workflows/rollout", () => ({ useWorkflowsRolloutEnabled: () => true, requireWorkflowsRollout: vi.fn() }));

it("hands off workflow identity without embedding captured content", async () => {
  const { fixtureWorkflowAnalysis } = await import("@screenpipe/workflows-ui/fixture");
  const workflow = fixtureWorkflowAnalysis.analysis.workflows[0];
  const task = workflowAgentTask({ ...workflow, id: "wf-example", title: 'Review "launch"' });
  expect(task.previewPrompt).toContain('wf-example');
  expect(task.previewPrompt).toContain(JSON.stringify('Review "launch"'));
  expect(task.previewPrompt).toContain("Retrieve its current steps and sources");
  expect(task.previewPrompt).toContain("confirm before sending");
  expect(task.previewPrompt).not.toContain(workflow.stages[0].evidence[0].detail);
});


it("keeps catalog search and refresh alongside local document filters", async () => {
  window.history.replaceState(null, "", "/home?mode=workflows");
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null} />);
  await screen.findByRole("heading", { name: "Research synthesis" });
  expect(screen.getByRole("button", { name: "Filter workflows" })).toBeVisible();
  expect(screen.getByRole("group", { name: "Workflow collection view" })).toBeVisible();
  expect(screen.getByRole("button", { name: "Update now" })).toHaveAttribute("title", "Update now");
  const search = screen.getByPlaceholderText("Search workflows…");
  fireEvent.change(search, { target: { value: "no-such-workflow-xyz" } });
  expect(screen.getByText("No workflows match these filters")).toBeVisible();
  fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));
  expect(screen.getByRole("heading", { name: "Research synthesis" })).toBeVisible();
  expect(search).toHaveValue("");
});


it("waits for the catalog then opens the exact workflow once across delivery retries", async () => {
  sessionStorage.clear();
  const posthog = (await import("posthog-js")).default;
  vi.mocked(posthog.capture).mockClear();
  const { rememberWorkflowReview } = await import("@/lib/workflows/notification");
  const request = { key: "cold-start", workflowId: "wf-fixture-4" };
  rememberWorkflowReview(request);
  window.history.replaceState(null, "", "/home?mode=workflows");
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null} />);
  expect(await screen.findByRole("button", { name: "More workflow actions" })).toBeVisible();
  expect(screen.getByRole("textbox", { name: "Workflow title" })).toHaveValue("Research synthesis");
  act(() => rememberWorkflowReview(request));
  await waitFor(() => expect(vi.mocked(posthog.capture).mock.calls.filter(c => c[0] === "workflow_notification_opened")).toHaveLength(1));
  expect(sessionStorage.getItem("screenpipe:workflow-review-request")).toBeNull();
});

it("recovers a removed workflow into the catalog without claiming it opened", async () => {
  sessionStorage.clear();
  const posthog = (await import("posthog-js")).default;
  vi.mocked(posthog.capture).mockClear();
  const { rememberWorkflowReview } = await import("@/lib/workflows/notification");
  rememberWorkflowReview({ key: "missing", workflowId: "wf-missing" });
  window.history.replaceState(null, "", "/home?mode=workflows");
  render(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null} />);
  expect(await screen.findByText("This workflow is no longer available. Your other workflows are shown below.")).toBeVisible();
  expect(screen.getByRole("heading", { name: "Workflows", level: 1 })).toBeVisible();
  expect(posthog.capture).toHaveBeenCalledWith("workflow_notification_open_failed", expect.objectContaining({ reason: "workflow_unavailable" }));
});

 it("wires visible device Workflows visits to explicit telemetry", async () => {
  vi.mocked(posthog.capture).mockClear();
  const app = render(<IntegratedWorkflows active={false} onModeChange={vi.fn()} recordingStatus={null} />);
  expect(posthog.capture).not.toHaveBeenCalledWith("workflow_opened", expect.anything());
  app.rerender(<IntegratedWorkflows active onModeChange={vi.fn()} recordingStatus={null} />);
  await screen.findByRole("heading", { name: "Research synthesis" });
  expect(posthog.capture).toHaveBeenCalledWith("workflow_opened", expect.objectContaining({ surface: "desktop_workflows", workflow_source: "device" }));
});