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

fix(app): make Live View edits safe and reversible

Louis Beaumont98753a419b8f
diff --git a/apps/screenpipe-app-tauri/components/settings/__tests__/brain-overview.test.tsx b/apps/screenpipe-app-tauri/components/settings/__tests__/brain-overview.test.tsx
index 5b02215fd..6f8acc429 100644
--- a/apps/screenpipe-app-tauri/components/settings/__tests__/brain-overview.test.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/__tests__/brain-overview.test.tsx
@@ -1782,7 +1782,66 @@ describe("BrainOverview", () => {
],
}),
);
- expect(await screen.findByTestId("overview-undo-banner")).toBeTruthy();
+ expect(await screen.findByTestId("overview-undo")).toHaveAttribute(
+ "title",
+ "Undo last Live View change (⌘Z)",
+ );
+
+ fireEvent.keyDown(window, { key: "z", metaKey: true });
+ await waitFor(() => expect(mocks.saveBrainView).toHaveBeenCalledTimes(2));
+ expect(mocks.saveBrainView).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ id: "my-overview",
+ expectedRevision: 4,
+ slots: [expect.objectContaining({ title: "Focus time" })],
+ }),
+ );
+ });
+
+ it("accept all applies every proposal in one action", async () => {
+ mocks.listBrainViews.mockResolvedValue({
+ status: "ok",
+ data: [populatedView],
+ });
+ mocks.generateLiveViewWithPi.mockResolvedValue({
+ title: populatedView.title,
+ timeRange: populatedView.timeRange,
+ periodPolicy: populatedView.periodPolicy,
+ note: "Changed the breakdown.",
+ blocks: [
+ {
+ id: "focus-time",
+ title: "Time by project",
+ intent: "Group active time by project.",
+ component: "bar-chart.v1",
+ width: 12,
+ pipeName: "daily-summary",
+ },
+ ],
+ });
+ mocks.saveBrainView.mockImplementation(async (request) => ({
+ status: "ok",
+ data: {
+ ...populatedView,
+ revision: 4,
+ slots: request.slots,
+ },
+ }));
+ render(<BrainOverview />);
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "edit Focus time with AI" }),
+ );
+ fireEvent.change(
+ await screen.findByPlaceholderText("e.g. group by project instead"),
+ { target: { value: "group this by project" } },
+ );
+ fireEvent.click(screen.getByRole("button", { name: "update" }));
+ fireEvent.click(await screen.findByTestId("live-view-ai-accept-all"));
+
+ await waitFor(() => expect(mocks.saveBrainView).toHaveBeenCalledTimes(1));
+ expect(screen.queryByTestId("live-view-ai-review")).toBeNull();
+ expect(await screen.findByTestId("overview-undo")).toBeTruthy();
});
it("rejects a staged Block edit without writing the dashboard", async () => {
diff --git a/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx b/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
index 7915a5d61..8cbae2b4d 100644
--- a/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
@@ -1444,6 +1444,7 @@ export function BrainOverview({
? {
title: reference.title,
timeRange: reference.timeRange,
+ periodPolicy: reference.periodPolicy,
blocks: reference.slots.map((slot) => ({
id: slot.id,
title: slot.title,
@@ -1457,6 +1458,7 @@ export function BrainOverview({
currentViewRef: reference
? { id: reference.id, revision: reference.revision }
: null,
+ targetBlockId: target.scope === "block" ? target.block.id : null,
signal: controller.signal,
onPhase: (phase) =>
setBuilderFeedback({
@@ -1825,20 +1827,10 @@ export function BrainOverview({
proposal.id === slotId ? { ...proposal, status: decision } : proposal,
),
);
- const next = aiBlockProposals.findIndex(
- (proposal) => proposal.id === slotId,
- );
- const following = aiBlockProposals
- .slice(next + 1)
- .find((proposal) => proposal.status === "pending");
- setProposalFocusSlotId(following?.id ?? slotId);
- };
-
- const decideAllAiProposals = (decision: "accepted" | "rejected") => {
- setAiBlockProposals((current) =>
- current.map((proposal) => ({ ...proposal, status: decision })),
- );
- setProposalFocusSlotId(aiBlockProposals[0]?.id ?? null);
+ // A local accept/reject action must not pan the whole canvas to another
+ // Block. The initial proposal is focused once; review then stays spatially
+ // stable under the user's pointer.
+ setProposalFocusSlotId(null);
};
const discardAiProposals = () => {
@@ -1850,9 +1842,11 @@ export function BrainOverview({
setBuilderFeedback(null);
};
- const applyAcceptedAiProposals = async () => {
+ const applyAcceptedAiProposals = async (
+ reviewedProposals: AiBlockProposal[] = aiBlockProposals,
+ ) => {
if (!view) return;
- const accepted = aiBlockProposals.filter(
+ const accepted = reviewedProposals.filter(
(proposal) => proposal.status === "accepted",
);
if (accepted.length === 0) {
@@ -1893,7 +1887,7 @@ export function BrainOverview({
posthog.capture("live_view_ai_proposal_applied", {
analytics_schema_version: LIVE_VIEW_ANALYTICS_SCHEMA_VERSION,
accepted_block_count: accepted.length,
- rejected_block_count: aiBlockProposals.filter(
+ rejected_block_count: reviewedProposals.filter(
(proposal) => proposal.status === "rejected",
).length,
});
@@ -1917,6 +1911,16 @@ export function BrainOverview({
}
};
+ const acceptAllAiProposals = async () => {
+ const reviewed = aiBlockProposals.map((proposal) => ({
+ ...proposal,
+ status: "accepted" as const,
+ }));
+ setAiBlockProposals(reviewed);
+ setProposalFocusSlotId(null);
+ await applyAcceptedAiProposals(reviewed);
+ };
+
const save = async (
refreshData = false,
destination: PreviewDestination = draft?.revision === 0 ? "new" : "replace",
@@ -2241,6 +2245,11 @@ export function BrainOverview({
});
if (result.status === "error") throw new Error(result.error);
setView(result.data);
+ setViews((current) =>
+ current.map((candidate) =>
+ candidate.id === result.data.id ? result.data : candidate,
+ ),
+ );
setUndoView(null);
setUndoRevision(null);
posthog.capture("live_view_dashboard_saved", {
@@ -2271,6 +2280,31 @@ export function BrainOverview({
}
};
+ useEffect(() => {
+ const handleUndoShortcut = (event: KeyboardEvent) => {
+ if (
+ !(event.metaKey || event.ctrlKey) ||
+ event.shiftKey ||
+ event.key.toLowerCase() !== "z" ||
+ !undoView ||
+ saving
+ ) {
+ return;
+ }
+ const target = event.target;
+ if (
+ target instanceof Element &&
+ target.closest("input, textarea, [contenteditable='true']")
+ ) {
+ return;
+ }
+ event.preventDefault();
+ void restorePreviousView();
+ };
+ window.addEventListener("keydown", handleUndoShortcut);
+ return () => window.removeEventListener("keydown", handleUndoShortcut);
+ }, [saving, undoView]);
+
const changeTimeRange = async (timeRange: BrainViewTimeRange) => {
if (!view || timeRange === view.timeRange) return;
if (
@@ -2769,6 +2803,20 @@ export function BrainOverview({
data-testid="overview-header-controls"
className="flex w-full flex-wrap items-center gap-2 lg:w-auto lg:justify-end"
>
+ {undoView && (
+ <Button
+ data-testid="overview-undo"
+ variant="outline"
+ size="icon"
+ className="h-9 w-9 shrink-0 rounded-none"
+ aria-label="undo last Live View change"
+ title="Undo last Live View change (⌘Z)"
+ disabled={saving}
+ onClick={() => void restorePreviousView()}
+ >
+ <Undo2 className="h-3.5 w-3.5" />
+ </Button>
+ )}
{view.periodPolicy.type !== "fixed.v1" && (
<Select
value={view.timeRange}
@@ -2852,25 +2900,6 @@ export function BrainOverview({
/>
</div>
)}
- {undoView && (
- <div
- data-testid="overview-undo-banner"
- className="mb-4 flex items-center gap-3 border border-border bg-muted/30 px-3 py-2 text-xs"
- >
- <Undo2 className="h-3.5 w-3.5 shrink-0" />
- <span>Your previous dashboard layout is available.</span>
- <Button
- data-testid="overview-undo"
- variant="ghost"
- size="sm"
- className="ml-auto h-7 rounded-none px-2"
- disabled={saving}
- onClick={() => void restorePreviousView()}
- >
- undo
- </Button>
- </div>
- )}
{aiBlockProposals.length > 0 && (
<div
data-testid="live-view-ai-review"
@@ -2900,7 +2929,9 @@ export function BrainOverview({
size="sm"
variant="ghost"
className="h-7 rounded-none px-2"
- onClick={() => decideAllAiProposals("accepted")}
+ disabled={saving}
+ title="Accept and save every proposed change"
+ onClick={() => void acceptAllAiProposals()}
>
<Check className="mr-1 h-3 w-3" /> accept all
</Button>
@@ -2909,7 +2940,9 @@ export function BrainOverview({
size="sm"
variant="ghost"
className="h-7 rounded-none px-2"
- onClick={() => decideAllAiProposals("rejected")}
+ disabled={saving}
+ title="Reject and discard every proposed change"
+ onClick={discardAiProposals}
>
<X className="mr-1 h-3 w-3" /> reject all
</Button>
diff --git a/apps/screenpipe-app-tauri/lib/live-views/__tests__/generate-live-view-with-pi.test.ts b/apps/screenpipe-app-tauri/lib/live-views/__tests__/generate-live-view-with-pi.test.ts
index 63fa81e6b..45ac99f84 100644
--- a/apps/screenpipe-app-tauri/lib/live-views/__tests__/generate-live-view-with-pi.test.ts
+++ b/apps/screenpipe-app-tauri/lib/live-views/__tests__/generate-live-view-with-pi.test.ts
@@ -184,6 +184,127 @@ describe("parseGeneratedLiveView", () => {
expect(result.blocks[0].title).toBe("First");
});
+ it("applies targeted edit operations while preserving omitted fields and bindings", () => {
+ const currentView = {
+ title: "Daily",
+ timeRange: "7d" as const,
+ periodPolicy: {
+ type: "selectable.v1" as const,
+ values: ["today", "7d"] as const,
+ },
+ blocks: [
+ {
+ id: "focus",
+ title: "Focus",
+ intent: "Show focused time.",
+ component: "metric.v1" as const,
+ width: 6 as const,
+ pipeName: "time-tracker",
+ },
+ ],
+ };
+ const result = parseGeneratedLiveView(
+ JSON.stringify({
+ operations: [
+ {
+ op: "update",
+ blockId: "focus",
+ block: { title: "Deep focus" },
+ },
+ {
+ op: "add",
+ block: {
+ id: "meetings",
+ title: "Meetings",
+ intent: "List meetings in the selected period.",
+ component: "list.v1",
+ width: 6,
+ pipeName: "meeting-summary",
+ },
+ },
+ ],
+ note: "Updated two Blocks.",
+ }),
+ ["time-tracker", "meeting-summary"],
+ "dashboard",
+ currentView,
+ );
+
+ expect(result.title).toBe("Daily");
+ expect(result.timeRange).toBe("7d");
+ expect(result.periodPolicy).toEqual(currentView.periodPolicy);
+ expect(result.blocks).toEqual([
+ expect.objectContaining({
+ id: "focus",
+ title: "Deep focus",
+ intent: "Show focused time.",
+ pipeName: "time-tracker",
+ }),
+ expect.objectContaining({
+ id: "meetings",
+ pipeName: "meeting-summary",
+ }),
+ ]);
+ });
+
+ it("rejects a Block edit that targets a different Block", () => {
+ expect(() =>
+ parseGeneratedLiveView(
+ JSON.stringify({
+ operations: [
+ {
+ op: "update",
+ blockId: "other",
+ block: { title: "Changed" },
+ },
+ ],
+ }),
+ [],
+ "block",
+ {
+ title: "Daily",
+ timeRange: "today",
+ blocks: [
+ {
+ id: "focus",
+ title: "Focus",
+ intent: "Show focus.",
+ component: "metric.v1",
+ width: 6,
+ pipeName: null,
+ },
+ {
+ id: "other",
+ title: "Other",
+ intent: "Show other.",
+ component: "metric.v1",
+ width: 6,
+ pipeName: null,
+ },
+ ],
+ },
+ "focus",
+ ),
+ ).toThrow("outside the requested target focus");
+ });
+
+ it("rejects whole-dashboard output for an existing Live View", () => {
+ expect(() =>
+ parseGeneratedLiveView(
+ JSON.stringify({
+ blocks: [{ title: "Replacement", component: "metric.v1" }],
+ }),
+ [],
+ "dashboard",
+ {
+ title: "Existing",
+ timeRange: "today",
+ blocks: [],
+ },
+ ),
+ ).toThrow("targeted Live View changes");
+ });
+
it("rejects arbitrary or unusable output", () => {
expect(() =>
parseGeneratedLiveView(
@@ -223,7 +344,11 @@ describe("parseGeneratedLiveView", () => {
});
expect(prompt).toContain('"id":"daily","revision":7');
- expect(prompt).toContain("Preserve every existing section");
+ expect(prompt).toContain(
+ "Do not restate, remove, or update unrelated Blocks",
+ );
+ expect(prompt).toContain('"op":"add"');
+ expect(prompt).toContain("Never return a complete blocks array");
expect(prompt).not.toContain("Current Live View:\n{");
expect(prompt).not.toContain("Focus time");
});
diff --git a/apps/screenpipe-app-tauri/lib/live-views/generate-live-view-with-pi.ts b/apps/screenpipe-app-tauri/lib/live-views/generate-live-view-with-pi.ts
index 0861cb447..efec4e700 100644
--- a/apps/screenpipe-app-tauri/lib/live-views/generate-live-view-with-pi.ts
+++ b/apps/screenpipe-app-tauri/lib/live-views/generate-live-view-with-pi.ts
@@ -79,12 +79,14 @@ type GenerateLiveViewOptions = {
currentView?: {
title: string;
timeRange: BrainViewTimeRange;
+ periodPolicy?: BrainViewPeriodPolicy;
blocks: GeneratedLiveViewBlock[];
} | null;
currentViewRef?: {
id: string;
revision: number;
} | null;
+ targetBlockId?: string | null;
signal?: AbortSignal;
onPhase?: (phase: "starting" | "working" | "reviewing") => void;
};
@@ -166,6 +168,8 @@ export function parseGeneratedLiveView(
raw: string,
allowedPipeNames: string[],
scope: LiveViewGenerationScope,
+ currentView: GenerateLiveViewOptions["currentView"] = null,
+ targetBlockId: string | null = null,
): GeneratedLiveView {
const response = firstJsonObject(raw);
const wrappedView = asRecord(response.view);
@@ -177,42 +181,121 @@ export function parseGeneratedLiveView(
? [parsed.block]
: [];
const allowedPipes = new Set(allowedPipeNames);
- const maxBlocks = scope === "block" ? 1 : 8;
- const blocks = rawBlocks
- .slice(0, maxBlocks)
- .map(asRecord)
- .filter((block): block is Record<string, unknown> => Boolean(block))
- .map((block) => {
- const component = componentValue(
- block.component ?? block.kind ?? block.type,
- );
- const title = typeof block.title === "string" ? block.title.trim() : "";
- if (!component || !title) return null;
- const intent =
- typeof block.intent === "string" && block.intent.trim()
- ? block.intent.trim().slice(0, 800)
- : title;
- const requestedPipe =
- typeof block.pipeName === "string"
- ? block.pipeName
- : typeof block.pipe === "string"
- ? block.pipe
- : nestedPipeName(block);
- return {
- ...(typeof block.id === "string" && block.id.trim()
- ? { id: block.id.trim().slice(0, 120) }
- : {}),
- title: title.slice(0, 120),
- intent,
- component,
- width: widthValue(block.width),
- pipeName:
- requestedPipe && allowedPipes.has(requestedPipe)
- ? requestedPipe
- : null,
- } satisfies GeneratedLiveViewBlock;
- })
- .filter((block): block is GeneratedLiveViewBlock => Boolean(block));
+ const parseBlocks = (
+ values: unknown[],
+ maxBlocks: number,
+ ): GeneratedLiveViewBlock[] =>
+ values
+ .slice(0, maxBlocks)
+ .map(asRecord)
+ .filter((block): block is Record<string, unknown> => Boolean(block))
+ .map((block) => {
+ const component = componentValue(
+ block.component ?? block.kind ?? block.type,
+ );
+ const title = typeof block.title === "string" ? block.title.trim() : "";
+ if (!component || !title) return null;
+ const intent =
+ typeof block.intent === "string" && block.intent.trim()
+ ? block.intent.trim().slice(0, 800)
+ : title;
+ const requestedPipe =
+ typeof block.pipeName === "string"
+ ? block.pipeName
+ : typeof block.pipe === "string"
+ ? block.pipe
+ : nestedPipeName(block);
+ return {
+ ...(typeof block.id === "string" && block.id.trim()
+ ? { id: block.id.trim().slice(0, 120) }
+ : {}),
+ title: title.slice(0, 120),
+ intent,
+ component,
+ width: widthValue(block.width),
+ pipeName:
+ requestedPipe && allowedPipes.has(requestedPipe)
+ ? requestedPipe
+ : null,
+ } satisfies GeneratedLiveViewBlock;
+ })
+ .filter((block): block is GeneratedLiveViewBlock => Boolean(block));
+
+ let blocks: GeneratedLiveViewBlock[];
+ let operationCount = 0;
+ if (currentView) {
+ if (!Array.isArray(parsed.operations)) {
+ throw new Error("AI did not return targeted Live View changes");
+ }
+ if (parsed.operations.length > 12) {
+ throw new Error("AI proposed too many Live View changes");
+ }
+ blocks = currentView.blocks.map((block) => ({ ...block }));
+ for (const value of parsed.operations) {
+ const operation = asRecord(value);
+ if (!operation || typeof operation.op !== "string") {
+ throw new Error("AI returned an invalid Live View operation");
+ }
+ const op = operation.op.trim().toLowerCase();
+ const blockId =
+ typeof operation.blockId === "string"
+ ? operation.blockId.trim()
+ : typeof operation.id === "string"
+ ? operation.id.trim()
+ : "";
+ if (scope === "block" && targetBlockId) {
+ if (op !== "update" || blockId !== targetBlockId) {
+ throw new Error(
+ `AI tried to change a Block outside the requested target ${targetBlockId}`,
+ );
+ }
+ }
+ if (op === "remove") {
+ const index = blocks.findIndex((block) => block.id === blockId);
+ if (index < 0)
+ throw new Error(`AI tried to remove unknown Block ${blockId}`);
+ blocks.splice(index, 1);
+ operationCount += 1;
+ continue;
+ }
+ const rawBlock = asRecord(operation.block ?? operation.changes);
+ if (!rawBlock) {
+ throw new Error(`AI returned an invalid ${op} operation`);
+ }
+ if (op === "add") {
+ const [added] = parseBlocks([rawBlock], 1);
+ if (!added) throw new Error("AI returned an invalid Block to add");
+ if (added.id && blocks.some((block) => block.id === added.id)) {
+ throw new Error(`AI tried to add existing Block ${added.id}`);
+ }
+ blocks.push(added);
+ operationCount += 1;
+ continue;
+ }
+ if (op === "update") {
+ const index = blocks.findIndex((block) => block.id === blockId);
+ if (index < 0)
+ throw new Error(`AI tried to update unknown Block ${blockId}`);
+ const previous = blocks[index];
+ const [updated] = parseBlocks(
+ [{ ...previous, ...rawBlock, id: blockId }],
+ 1,
+ );
+ if (!updated)
+ throw new Error(`AI returned an invalid update for ${blockId}`);
+ blocks[index] = updated;
+ operationCount += 1;
+ continue;
+ }
+ throw new Error(`AI returned unsupported Live View operation ${op}`);
+ }
+ if (operationCount === 0) {
+ throw new Error("AI did not propose any targeted Live View changes");
+ }
+ } else {
+ const maxBlocks = scope === "block" ? 1 : 8;
+ blocks = parseBlocks(rawBlocks, maxBlocks);
+ }
if (blocks.length === 0) {
throw new Error("AI did not create any usable sections");
@@ -221,9 +304,11 @@ export function parseGeneratedLiveView(
const title =
typeof parsed.title === "string" && parsed.title.trim()
? parsed.title.trim().slice(0, 120)
- : scope === "block"
- ? blocks[0].title
- : "My Live View";
+ : currentView?.title
+ ? currentView.title
+ : scope === "block"
+ ? blocks[0].title
+ : "My Live View";
const note =
typeof parsed.note === "string" && parsed.note.trim()
? parsed.note.trim().slice(0, 240)
@@ -231,25 +316,38 @@ export function parseGeneratedLiveView(
? `Created ${blocks[0].title}.`
: `Created ${blocks.length} sections.`;
- const timeRange = timeRangeValue(parsed.timeRange ?? parsed.time_range);
+ const hasTimeRange =
+ typeof (parsed.timeRange ?? parsed.time_range) === "string";
+ const timeRange = hasTimeRange
+ ? timeRangeValue(parsed.timeRange ?? parsed.time_range)
+ : (currentView?.timeRange ?? "today");
return {
title,
timeRange,
- periodPolicy: periodPolicyValue(
- parsed.timeRangeBehavior ?? parsed.time_range_behavior,
- timeRange,
- ),
+ periodPolicy:
+ currentView && !hasTimeRange && parsed.timeRangeBehavior == null
+ ? currentView.periodPolicy
+ : periodPolicyValue(
+ parsed.timeRangeBehavior ?? parsed.time_range_behavior,
+ timeRange,
+ ),
blocks,
note,
};
}
-function generationSystemPrompt(): string {
+function generationSystemPrompt(editing: boolean): string {
+ const outputContract = editing
+ ? `Return only targeted operations. Never return a complete blocks array.
+Use {"op":"add","block":{...}} to append a new Block, {"op":"update","blockId":"existing-id","block":{...}} to update one existing Block, and {"op":"remove","blockId":"existing-id"} only when the user explicitly requested removal. An update may include only changed fields; omitted fields are preserved by the app.
+JSON shape: {"operations":[{"op":"add","block":{"id":"new-stable-id","title":"Block title","intent":"Precise source-backed calculation or summary.","component":"metric.v1","width":6,"pipeName":null}}],"note":"Short explanation"}`
+ : `For a new dashboard, return the complete blocks array.
+JSON shape: {"title":"View title","timeRange":"today","timeRangeBehavior":"selectable","blocks":[{"id":"stable-id","title":"Block title","intent":"Precise source-backed calculation or summary.","component":"metric.v1","width":6,"pipeName":null}],"note":"Short explanation"}`;
return `Design a safe Screenpipe Live View and return only one JSON object, with no markdown or prose.
If a current view id is supplied, you may only call screenpipe_live_view action "get" for that exact id. Never call "save" or any other tool. The app reviews changes before saving. Preserve every unchanged Block id and reuse the id of every edited Block.
Use only these components: metric.v1, list.v1, bar-chart.v1, line-chart.v1, table.v1, timeline.v1, markdown.v1. Width must be 3, 6, or 12. Use only supplied pipe names, otherwise null. Never invent a pipe.
-Each Block needs a precise, source-backed intent describing the calculation or summary for the selected period and how missing evidence is handled. Avoid duplicate Blocks. For new dashboards create 4 to 7 Blocks; edits may return 1 to 8. Use timeRange today, 24h, 7d, or 30d. Use timeRangeBehavior fixed only when the view is inherently tied to that period, otherwise selectable.
-JSON shape: {"title":"View title","timeRange":"today","timeRangeBehavior":"selectable","blocks":[{"id":"existing-id-when-editing","title":"Block title","intent":"Precise source-backed calculation or summary.","component":"metric.v1","width":6,"pipeName":null}],"note":"Short explanation"}`;
+Each Block needs a precise, source-backed intent describing the calculation or summary for the selected period and how missing evidence is handled. Avoid duplicate Blocks. For new dashboards create 4 to 7 Blocks; edits may propose 1 to 8 operations. Use timeRange today, 24h, 7d, or 30d. Use timeRangeBehavior fixed only when the view is inherently tied to that period, otherwise selectable.
+${outputContract}`;
}
export function buildLiveViewGenerationPrompt(
@@ -257,9 +355,11 @@ export function buildLiveViewGenerationPrompt(
): string {
const scopeInstruction =
options.scope === "block"
- ? "Create exactly one new section to add to the existing Live View."
+ ? options.currentViewRef
+ ? `Propose exactly one update operation for Block id ${JSON.stringify(options.targetBlockId)}. Do not add, remove, or change any other Block.`
+ : "Create exactly one new section to add to the existing Live View."
: options.currentViewRef
- ? "Edit the referenced current Live View. Preserve every existing section the user did not ask to change, apply the request, and return the complete revised dashboard. Do not create a separate dashboard."
+ ? "Edit the referenced current Live View with the smallest explicit operation set. Do not restate, remove, or update unrelated Blocks."
: "Create a complete Live View with 4 to 7 useful, visually varied sections. Return the full dashboard.";
const pipes = relevantPipes(options.prompt, options.pipes).map((pipe) => ({
name: pipe.name,
@@ -276,7 +376,7 @@ export function buildLiveViewGenerationPrompt(
? `These are reviewed Pipe Store candidates available for automatic installation. Bind every section to one of them. Use at most ${options.maxSelectedPipes ?? 2} distinct pipes across the dashboard. Prefer the smallest set that works from Screenpipe's local capture alone. Avoid a pipe that mentions syncing or saving to a named external app unless the user explicitly asked for that app.`
: "These pipes are already installed. Use null only when no installed pipe can produce the requested section.";
- return `${generationSystemPrompt()}
+ return `${generationSystemPrompt(Boolean(options.currentViewRef))}
${scopeInstruction}
@@ -293,7 +393,7 @@ Current Live View reference:
${options.currentViewRef ? JSON.stringify(options.currentViewRef) : "null"}
Focused section context:
-${options.currentView ? JSON.stringify(options.currentView) : "null"}
+${options.targetBlockId ? JSON.stringify({ blockId: options.targetBlockId }) : "null"}
Choose the simplest useful layout. Reply with only the required JSON object.`;
}
@@ -528,6 +628,8 @@ export async function generateLiveViewWithPi(
raw,
options.pipes.map((pipe) => pipe.name),
options.scope,
+ options.currentView,
+ options.targetBlockId ?? null,
);
const selectedPipes = new Set(
generated.blocks