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): remount Live View canvas after accepted edits

Louis Beaumont77528dcb4059
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 64d962dc7..d27c1dd66 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
@@ -1811,36 +1811,63 @@ describe("BrainOverview", () => {
blocks: [
{
id: "focus-time",
- title: "Time by project",
- intent: "Group active time by project.",
- component: "bar-chart.v1",
- width: 12,
+ title: "Focus time",
+ intent: "Calculate focused work time",
+ component: "metric.v1",
+ width: 6,
+ pipeName: "daily-summary",
+ },
+ {
+ id: "habit-signals",
+ title: "Habit signals",
+ intent: "Show recurring work habits.",
+ component: "list.v1",
+ width: 6,
pipeName: "daily-summary",
},
],
});
- mocks.saveBrainView.mockImplementation(async (request) => ({
- status: "ok",
- data: {
- ...populatedView,
- revision: 4,
- slots: request.slots,
- },
- }));
+ let finishSave: (() => void) | undefined;
+ const saveGate = new Promise<void>((resolve) => {
+ finishSave = resolve;
+ });
+ mocks.saveBrainView.mockImplementation(async (request) => {
+ await saveGate;
+ return {
+ 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" }));
+ const canvasBeforeAccept = await screen.findByTestId("live-view-canvas");
+ fireEvent.change(await screen.findByTestId("live-view-ai-prompt"), {
+ target: { value: "add habit signals" },
+ });
+ fireEvent.click(screen.getByTestId("live-view-ai-generate"));
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("live-view-canvas-applying")).toBeTruthy();
+ expect(screen.queryByTestId("live-view-canvas")).toBeNull();
+ finishSave?.();
+ await waitFor(() =>
+ expect(screen.queryByTestId("live-view-ai-review")).toBeNull(),
+ );
+ expect(mocks.saveBrainView).toHaveBeenCalledWith(
+ expect.objectContaining({
+ slots: expect.arrayContaining([
+ expect.objectContaining({ id: "habit-signals" }),
+ ]),
+ }),
+ );
+ expect(await screen.findByTestId("live-view-canvas")).not.toBe(
+ canvasBeforeAccept,
+ );
expect(await screen.findByTestId("overview-undo")).toBeTruthy();
});
diff --git a/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx b/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
index 44bf575f2..dda603e70 100644
--- a/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/brain-overview.tsx
@@ -521,6 +521,7 @@ export function BrainOverview({
const [draft, setDraft] = useState<ViewDefinition | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ const [applyingAiProposals, setApplyingAiProposals] = useState(false);
const [editing, setEditing] = useState(false);
const [aiPreview, setAiPreview] = useState(false);
const [previewSource, setPreviewSource] = useState<PreviewSource | null>(
@@ -618,6 +619,65 @@ export function BrainOverview({
writeActiveAiPresetId(presetId);
}, []);
const activeViewId = view?.id;
+ const slots = useMemo(
+ () => normalizedSlots(view?.slots ?? []),
+ [view?.slots],
+ );
+ const proposalById = useMemo(
+ () => new Map(aiBlockProposals.map((proposal) => [proposal.id, proposal])),
+ [aiBlockProposals],
+ );
+ const proposalSlots = useMemo(
+ () =>
+ normalizedSlots([
+ ...slots.map((slot) => {
+ const proposal = proposalById.get(slot.id);
+ if (!proposal || proposal.status === "rejected" || !proposal.after) {
+ return slot;
+ }
+ return proposal.kind === "remove" ? slot : proposal.after;
+ }),
+ ...aiBlockProposals.flatMap((proposal) =>
+ proposal.kind === "add" && proposal.after ? [proposal.after] : [],
+ ),
+ ]),
+ [aiBlockProposals, proposalById, slots],
+ );
+ const proposalView = useMemo(
+ () =>
+ view && aiBlockProposals.length > 0
+ ? { ...view, slots: proposalSlots }
+ : view,
+ [aiBlockProposals.length, proposalSlots, view],
+ );
+ const visibleCanvasDocument = useMemo(
+ () =>
+ proposalView && aiBlockProposals.length > 0
+ ? reconcileCanvasDocument(proposalView, canvasDocument)
+ : canvasDocument,
+ [aiBlockProposals.length, canvasDocument, proposalView],
+ );
+ const canvasProposals = useMemo(
+ () =>
+ new Map(
+ aiBlockProposals.map((proposal) => [
+ proposal.id,
+ { kind: proposal.kind, status: proposal.status },
+ ]),
+ ),
+ [aiBlockProposals],
+ );
+ const refreshingSlotIds = useMemo(
+ () =>
+ new Set(
+ dataRefresh?.viewId === view?.id &&
+ (dataRefresh?.status === "starting" ||
+ dataRefresh?.status === "running")
+ ? (dataRefresh?.slotIds ?? [])
+ : [],
+ ),
+ [dataRefresh, view?.id],
+ );
const onboardingActivation = useMemo(() => {
// The activation record lives in localStorage. This counter invalidates
// the memo after background setup updates that external store.
@@ -1886,6 +1946,11 @@ export function BrainOverview({
}
const normalized = normalizedSlots(nextSlots);
const previous = copyViewDefinition(view);
+ // React Flow cannot safely reconcile the proposal graph with the newly
+ // persisted graph inside the same controlled store. Unmount it for the
+ // duration of the transaction, then mount a fresh store at the new
+ // revision after the save completes.
+ setApplyingAiProposals(true);
setSaving(true);
try {
const result = await commands.saveBrainView({
@@ -1929,6 +1994,7 @@ export function BrainOverview({
});
} finally {
setSaving(false);
+ setApplyingAiProposals(false);
}
};
@@ -2732,28 +2798,6 @@ export function BrainOverview({
}
if (!view) return null;
- const slots = normalizedSlots(view.slots);
- const proposalById = new Map(
- aiBlockProposals.map((proposal) => [proposal.id, proposal]),
- );
- const proposalSlots = normalizedSlots([
- ...slots.map((slot) => {
- const proposal = proposalById.get(slot.id);
- if (!proposal || proposal.status === "rejected" || !proposal.after) {
- return slot;
- }
- return proposal.kind === "remove" ? slot : proposal.after;
- }),
- ...aiBlockProposals.flatMap((proposal) =>
- proposal.kind === "add" && proposal.after ? [proposal.after] : [],
- ),
- ]);
- const proposalView =
- aiBlockProposals.length > 0 ? { ...view, slots: proposalSlots } : view;
- const visibleCanvasDocument =
- aiBlockProposals.length > 0
- ? reconcileCanvasDocument(proposalView, canvasDocument)
- : canvasDocument;
const boundSlotCount = slots.filter((slot) => slot.binding).length;
const periodRanges = allowedLiveViewTimeRanges(view.periodPolicy);
const latestUpdate = liveViewLatestUpdate(slots);
@@ -2763,9 +2807,6 @@ export function BrainOverview({
const dashboardBusy = saving || refreshIsActive;
const canvasReady =
!canvasLoading && visibleCanvasDocument?.viewId === view.id && !canvasError;
- const refreshingSlotIds = new Set(
- refreshIsActive ? (dataRefresh?.slotIds ?? []) : [],
- );
const dashboardSelectionDisabled = saving;
const showOnboardingActivation = Boolean(
onboardingActivation && !onboardingActivation.completedAt,
@@ -3044,8 +3085,16 @@ export function BrainOverview({
>
add your first Block
</button>
+ ) : applyingAiProposals ? (
+ <div
+ data-testid="live-view-canvas-applying"
+ className="flex min-h-0 flex-1 items-center justify-center border border-border font-mono text-[10px] uppercase tracking-wide text-muted-foreground"
+ >
+ applying changes
+ </div>
) : canvasReady && canvasDocument ? (
<LiveViewCanvas
+ key={`${view.id}:${view.revision}`}
document={visibleCanvasDocument!}
slots={proposalSlots}
timeRange={view.timeRange}
@@ -3059,14 +3108,7 @@ export function BrainOverview({
onAiEdit={editSlotWithAi}
onItemAction={recordItemAction}
onItemHandoff={handoffItem}
- proposals={
- new Map(
- aiBlockProposals.map((proposal) => [
- proposal.id,
- { kind: proposal.kind, status: proposal.status },
- ]),
- )
- }
+ proposals={canvasProposals}
focusSlotId={proposalFocusSlotId}
onProposalDecision={decideAiProposal}
/>
diff --git a/apps/screenpipe-app-tauri/components/settings/live-view-canvas.tsx b/apps/screenpipe-app-tauri/components/settings/live-view-canvas.tsx
index dd34b8803..d7d3e9498 100644
--- a/apps/screenpipe-app-tauri/components/settings/live-view-canvas.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/live-view-canvas.tsx
@@ -456,6 +456,22 @@ export function LiveViewCanvas({
const drawSessionRef = useRef<DrawSession | null>(null);
const latestDocumentRef = useRef(document);
const isMountedRef = useRef(true);
+ const callbacksRef = useRef({
+ onFeedback,
+ onRegenerate,
+ onAiEdit,
+ onItemAction,
+ onItemHandoff,
+ onProposalDecision,
+ });
+ callbacksRef.current = {
+ onFeedback,
+ onRegenerate,
+ onAiEdit,
+ onItemAction,
+ onItemHandoff,
+ onProposalDecision,
+ };
const slotsById = useMemo(
() => new Map(slots.map((slot) => [slot.id, slot])),
[slots],
@@ -697,7 +713,7 @@ export function LiveViewCanvas({
aiEditing: aiEditingSlotId === slot.id,
proposal: proposals.get(slot.id) ?? null,
onProposalDecision: (decision) =>
- onProposalDecision(slot.id, decision),
+ callbacksRef.current.onProposalDecision(slot.id, decision),
tool,
selected: selection.includes(id),
connectPending: arrowSource === id,
@@ -705,11 +721,13 @@ export function LiveViewCanvas({
onConnectIntent: connectNode,
onResize: updateNodeGeometry,
onFeedback: (rating, correction) =>
- onFeedback(slot, rating, correction),
- onRegenerate: () => onRegenerate(slot),
- onAiEdit: (prompt) => onAiEdit(slot, prompt),
- onItemAction: (request) => onItemAction(slot, request),
- onItemHandoff: (item) => onItemHandoff(slot, item),
+ callbacksRef.current.onFeedback(slot, rating, correction),
+ onRegenerate: () => callbacksRef.current.onRegenerate(slot),
+ onAiEdit: (prompt) => callbacksRef.current.onAiEdit(slot, prompt),
+ onItemAction: (request) =>
+ callbacksRef.current.onItemAction(slot, request),
+ onItemHandoff: (item) =>
+ callbacksRef.current.onItemHandoff(slot, item),
},
},
];
@@ -765,12 +783,6 @@ export function LiveViewCanvas({
connectNode,
document.blocks,
document.notes,
- onAiEdit,
- onFeedback,
- onItemAction,
- onItemHandoff,
- onRegenerate,
- onProposalDecision,
proposals,
refreshingSlotIds,
selection,