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: prevent stale preset closure on chat summary card click (#4892)

Akarsh Kushwaha56fd2105c583
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/pi-types.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/pi-types.ts
index 8e84fa6ed..0f17be8f9 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/pi-types.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/pi-types.ts
@@ -156,6 +156,7 @@ export type PiSendTransportOptions = {
abortControllerRef: PiTransportRefs["abortControllerRef"];
activePipeExecution: { name: string } | null;
activePreset: AIPreset | undefined;
+ activePresetRef?: React.MutableRefObject<AIPreset | undefined>;
attachedDocsRef: React.MutableRefObject<ExtractedDoc[]>;
autoSendBypassRef: PiTransportRefs["autoSendBypassRef"];
buildProviderConfig: PiProviderConfigBuilder;
@@ -222,6 +223,7 @@ export type PiSendTransportOptions = {
export type PiForegroundEventsOptions = {
activePreset: AIPreset | undefined;
+ activePresetRef?: React.MutableRefObject<AIPreset | undefined>;
buildProviderConfig: PiProviderConfigBuilder;
cancelStreamingMessageRender: StreamingActions["cancelStreamingMessageRender"];
clearPipeExecution: () => void;
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
index 39fc1e66a..5a4ff585c 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
@@ -33,6 +33,7 @@ const POST_STREAM_SIDE_EFFECT_DELAY_MS = 1_500;
export function usePiForegroundEvents({
activePreset,
+ activePresetRef,
buildProviderConfig,
cancelStreamingMessageRender,
clearPipeExecution,
@@ -80,6 +81,7 @@ export function usePiForegroundEvents({
syncThinkingLevelAfterStart,
turnIntentTextValuesMatch,
}: PiForegroundEventsOptions) {
+ const getActivePreset = () => activePresetRef?.current ?? activePreset;
// Listen for Pi / pipe events.
//
// Stage 3 of the events refactor: the panel registers with the
@@ -140,8 +142,8 @@ export function usePiForegroundEvents({
role: "assistant",
content: "Processing...",
timestamp: Date.now(),
- model: activePreset?.model,
- provider: activePreset?.provider,
+ model: getActivePreset()?.model,
+ provider: getActivePreset()?.provider,
});
return base;
});
@@ -159,8 +161,8 @@ export function usePiForegroundEvents({
role: "assistant",
content: "Processing...",
timestamp: Date.now(),
- model: activePreset?.model,
- provider: activePreset?.provider,
+ model: getActivePreset()?.model,
+ provider: getActivePreset()?.provider,
} as any);
storeState.actions.setStreaming(sidNow, {
streamingMessageId: newAssistantId,
@@ -400,7 +402,7 @@ export function usePiForegroundEvents({
);
}
} else {
- const providerError = buildProviderErrorMessage(errorStr, activePreset);
+ const providerError = buildProviderErrorMessage(errorStr, getActivePreset());
if (providerError && piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
setMessages((prev) =>
@@ -439,7 +441,7 @@ export function usePiForegroundEvents({
prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade to Screenpipe Business. Switch to a free model (auto, glm-5, gemini flash) to keep going." } : m)
);
} else {
- const providerError = buildProviderErrorMessage(fullError, activePreset);
+ const providerError = buildProviderErrorMessage(fullError, getActivePreset());
if (providerError) {
setMessages((prev) =>
prev.map((m) => m.id === msgId
@@ -557,8 +559,8 @@ export function usePiForegroundEvents({
...(matchedTurnIntent ? { turnIntentId: matchedTurnIntent.id } : {}),
...(nextUserIntent === "steer" ? { steeredResponse: true } : {}),
timestamp: Date.now(),
- model: activePreset?.model,
- provider: activePreset?.provider,
+ model: getActivePreset()?.model,
+ provider: getActivePreset()?.provider,
};
let nextRows: Message[] | null = null;
@@ -616,7 +618,7 @@ export function usePiForegroundEvents({
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
- const providerError = buildProviderErrorMessage(errMsg, activePreset);
+ const providerError = buildProviderErrorMessage(errMsg, getActivePreset());
if (authTokenInvalidated) {
setMessages((prev) =>
prev.map((m) => m.id === msgId ? { ...m, content: buildInvalidatedAuthTokenMessage() } : m)
@@ -690,7 +692,7 @@ export function usePiForegroundEvents({
} else if (errStr.includes("model_not_allowed")) {
content = "This model requires an upgrade to Screenpipe Business. Switch to a free model (auto, glm-5, gemini flash) to keep going.";
} else {
- content = buildProviderErrorMessage(errStr, activePreset) || errStr;
+ content = buildProviderErrorMessage(errStr, getActivePreset()) || errStr;
}
}
@@ -742,10 +744,10 @@ export function usePiForegroundEvents({
} else if (lastErr && lastErrKind === "rate") {
content = buildRateLimitMessage(lastErr);
} else if (lastErr) {
- content = buildProviderErrorMessage(lastErr, activePreset) || `Error: ${lastErr}`;
+ content = buildProviderErrorMessage(lastErr, getActivePreset()) || `Error: ${lastErr}`;
emptyResponseRetryPrompt = lastUserMessageRef.current || undefined;
} else {
- content = buildNoResponseMessage(activePreset);
+ content = buildNoResponseMessage(getActivePreset());
emptyResponseRetryPrompt = lastUserMessageRef.current || undefined;
}
}
@@ -771,8 +773,8 @@ export function usePiForegroundEvents({
});
if (!isPipeWatch) {
const analyticsPayload = {
- provider: activePreset?.provider,
- model: activePreset?.model,
+ provider: getActivePreset()?.provider,
+ model: getActivePreset()?.model,
has_tool_use: blocksSnapshot.some((b) => b.type === "tool"),
response_length: streamedText?.length ?? 0,
};
@@ -874,7 +876,7 @@ export function usePiForegroundEvents({
prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade to Screenpipe Business. Switch to a free model (auto, glm-5, gemini flash) to keep going." } : m)
);
} else {
- const providerError = buildProviderErrorMessage(errorStr, activePreset);
+ const providerError = buildProviderErrorMessage(errorStr, getActivePreset());
if (providerError) {
setMessages((prev) =>
prev.map((m) => m.id === msgId
@@ -912,8 +914,8 @@ export function usePiForegroundEvents({
: errorStr.includes("model_not_allowed") ? "model_not_allowed"
: "other";
posthog.capture("chat_response_error", {
- provider: activePreset?.provider,
- model: activePreset?.model,
+ provider: getActivePreset()?.provider,
+ model: getActivePreset()?.model,
error_type: errorCategory,
});
piStreamingTextRef.current = "";
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
index cc5b1e126..d92adb8e9 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-send-transport.ts
@@ -28,6 +28,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
abortControllerRef,
activePipeExecution,
activePreset,
+ activePresetRef,
attachedDocsRef,
autoSendBypassRef,
buildProviderConfig,
@@ -74,6 +75,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
stagePendingAttachments,
syncThinkingLevelAfterStart,
} = options;
+ const getActivePreset = () => activePresetRef?.current ?? activePreset;
const { enqueuePiMessage } = createPiMessageQueueTransport(
options,
(message, displayLabel, imageDataUrls) => sendPiMessage(message, displayLabel, imageDataUrls),
@@ -274,8 +276,8 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
role: "assistant",
content: "Processing...",
timestamp: Date.now(),
- model: activePreset?.model,
- provider: activePreset?.provider,
+ model: getActivePreset()?.model,
+ provider: getActivePreset()?.provider,
} as any);
storeState.actions.setStreaming(sidNow, {
streamingMessageId: assistantMessageId,
@@ -296,8 +298,8 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
}
posthog.capture("chat_message_sent", {
- provider: activePreset?.provider,
- model: activePreset?.model,
+ provider: getActivePreset()?.provider,
+ model: getActivePreset()?.model,
has_images: outgoingImages.length > 0 || !!prefillFrameId,
has_context: !!prefillContext,
message_index: messages.filter((m) => m.role === "user").length,
@@ -338,7 +340,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
setMessages((prev) => [
...prev,
- { id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now(), model: activePreset?.model, provider: activePreset?.provider },
+ { id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now(), model: getActivePreset()?.model, provider: getActivePreset()?.provider },
]);
// Always re-inject the recent conversation history into every prompt
@@ -390,7 +392,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
}
}
- const providerPreflight = await preflightChatProvider(activePreset);
+ const providerPreflight = await preflightChatProvider(getActivePreset());
if (!providerPreflight.ok) {
piStreamingTextRef.current = "";
piMessageIdRef.current = null;
@@ -470,13 +472,14 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
const rawError = result.error;
let errorMsg: string;
let retryPrompt: string | undefined;
- const providerError = buildProviderErrorMessage(rawError, activePreset);
+ const currentPreset = getActivePreset();
+ const providerError = buildProviderErrorMessage(rawError, currentPreset);
if (rawError.includes("already processing")) {
errorMsg = "The AI was mid-response when your message arrived.";
retryPrompt = userMessage;
} else if (rawError.includes("Broken pipe") || rawError.includes("not running") || rawError.includes("has died") || rawError.includes("Pi not initialized")) {
- const provider = activePreset?.provider;
+ const provider = currentPreset?.provider;
errorMsg = provider === "native-ollama"
? "Ollama isn't running. Start it with: `ollama serve`"
: "AI agent crashed — restarting automatically...";
@@ -485,7 +488,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
errorMsg = providerError;
retryPrompt = userMessage;
} else if (rawError.includes("not found")) {
- errorMsg = `Model "${activePreset?.model}" not found. Check your AI preset in settings.`;
+ errorMsg = `Model "${currentPreset?.model}" not found. Check your AI preset in settings.`;
} else {
errorMsg = rawError;
retryPrompt = userMessage;
@@ -505,7 +508,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
if (timeoutId) clearTimeout(timeoutId);
piMessageIdRef.current = null;
const rawError = error instanceof Error ? error.message : "Unknown error";
- const providerError = buildProviderErrorMessage(rawError, activePreset);
+ const providerError = buildProviderErrorMessage(rawError, getActivePreset());
setMessages((prev) =>
prev.map((m) =>
m.id === assistantMessageId
@@ -520,7 +523,7 @@ export function usePiSendTransport(options: PiSendTransportOptions) {
}
async function sendMessage(userMessage: string, displayLabel?: string, imageDataUrls?: string[]) {
- if ((!canChat && !autoSendBypassRef.current) || (!activePreset && !autoSendBypassRef.current)) return;
+ if ((!canChat && !autoSendBypassRef.current) || (!getActivePreset() && !autoSendBypassRef.current)) return;
const trimmed = userMessage.trim();
const outgoingImages = imageDataUrls ?? pastedImages;
const queuedDocs = attachedDocsRef.current;
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
index 3961e418e..d114ea5d8 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -85,6 +85,7 @@ interface UseChatConversationsOpts {
pendingDocsRef?: MutableRefObject<any[]>;
settings: any;
selectedPreset?: AIPreset | null;
+ selectedPresetRef?: MutableRefObject<AIPreset | undefined | null>;
inlineHistoryEnabled?: boolean;
}
@@ -136,6 +137,10 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
selectedPreset,
inlineHistoryEnabled = true,
} = opts;
+ const getSelectedPreset = () =>
+ opts.selectedPresetRef && opts.selectedPresetRef.current !== undefined
+ ? (opts.selectedPresetRef.current ?? null)
+ : opts.selectedPreset;
const componentUnmountedRef = useRef(false);
const [showHistory, setShowHistoryRaw] = useState(() => {
@@ -501,10 +506,11 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
const existingTitle = existing?.title?.trim() || null;
const computedLastUserMessageAt = newestUserMessageTimestamp(msgs);
+ const currentPreset = getSelectedPreset();
const hasValidPreset =
- selectedPreset &&
- selectedPreset.provider &&
- selectedPreset.model?.trim();
+ currentPreset &&
+ currentPreset.provider &&
+ currentPreset.model?.trim();
const existingSource = existing?.titleSource;
const existingLooksFallback = isFallbackLikeTitle(
@@ -560,7 +566,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
try {
const aiTitle = await titleCreatedByAI(
rawContent,
- selectedPreset,
+ currentPreset,
settings?.user?.token ?? null,
async (partial) => {
try {
@@ -746,7 +752,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
})()),
// Persist the preset ID so the model selection survives app restart
// and is restored when switching between chats.
- ...(selectedPreset?.id ? { presetId: selectedPreset.id } : existing?.presetId ? { presetId: existing.presetId } : {}),
+ ...(currentPreset?.id ? { presetId: currentPreset.id } : existing?.presetId ? { presetId: existing.presetId } : {}),
};
// Mirror the final messages into the in-memory chat-store BEFORE
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 4d2195eec..9aceed20a 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -195,6 +195,21 @@ export function StandaloneChat({
const [isStreaming, setIsStreaming] = useState(false);
const [highlightedMessageId, setHighlightedMessageId] = useState<string | null>(null);
const [activePreset, setActivePreset] = useState<AIPreset | undefined>();
+ const activePresetRef = useRef<AIPreset | undefined>(activePreset);
+ activePresetRef.current = activePreset;
+
+ const handleSetActivePreset = useCallback((preset: AIPreset | undefined | ((prev: AIPreset | undefined) => AIPreset | undefined)) => {
+ if (typeof preset === "function") {
+ setActivePreset((prev) => {
+ const next = preset(prev);
+ activePresetRef.current = next;
+ return next;
+ });
+ } else {
+ activePresetRef.current = preset;
+ setActivePreset(preset);
+ }
+ }, []);
const isStreamingRef = useRef(false);
// Mirrors of streaming-relevant state so the unmount-snapshot effect (which
// runs with `[]` deps) can read the latest values instead of stale closures.
@@ -690,6 +705,7 @@ export function StandaloneChat({
pendingDocsRef,
settings,
selectedPreset: activePreset ?? null,
+ selectedPresetRef: activePresetRef,
inlineHistoryEnabled: !hideInlineHistory,
});
const loadConversationRef = useRef(loadConversation);
@@ -741,7 +757,7 @@ export function StandaloneChat({
});
useChatWindowSyncEvents({
aiPresets: settings?.aiPresets,
- setActivePreset,
+ setActivePreset: handleSetActivePreset,
});
const {
@@ -783,7 +799,7 @@ export function StandaloneChat({
syncThinkingLevelAfterStart,
} = usePiSessionLifecycle({
activePreset,
- setActivePreset,
+ setActivePreset: handleSetActivePreset,
aiPresets: settings.aiPresets,
isSettingsLoaded,
shouldFreezePresetSelection: Boolean(activePipeExecution),
@@ -824,7 +840,7 @@ export function StandaloneChat({
usePipeWatchSession({
aiPresets: settings.aiPresets,
- setActivePreset,
+ setActivePreset: handleSetActivePreset,
startPipeExecution,
loadConversationRef,
setIsStreaming,
@@ -843,6 +859,7 @@ export function StandaloneChat({
abortControllerRef,
activePipeExecution,
activePreset,
+ activePresetRef,
attachedDocsRef,
autoSendBypassRef,
buildProviderConfig,
@@ -1092,6 +1109,7 @@ export function StandaloneChat({
usePiForegroundEvents({
activePreset,
+ activePresetRef,
buildProviderConfig,
cancelStreamingMessageRender,
clearPipeExecution,
@@ -1471,7 +1489,7 @@ export function StandaloneChat({
activePipeExecution,
currentQueueSessionId,
onPresetSaved: handlePiRestart,
- onSelectPreset: setActivePreset,
+ onSelectPreset: handleSetActivePreset,
}}
connectBanner={{
show: showConnectBanner,
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx b/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
index 4c26d0f02..4184be012 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx
@@ -56,6 +56,7 @@ const saveCalls: Array<{
browserState?: any;
lastUserMessageAt?: number;
lastViewedAt?: number;
+ presetId?: string;
}> = [];
vi.mock("@/lib/chat-storage", () => ({
@@ -66,6 +67,7 @@ vi.mock("@/lib/chat-storage", () => ({
browserState: conv.browserState,
lastUserMessageAt: conv.lastUserMessageAt,
lastViewedAt: conv.lastViewedAt,
+ presetId: conv.presetId,
});
}),
loadConversationFile: vi.fn(async () => null),
@@ -108,6 +110,8 @@ function useHarness(args: {
initialMessages: any[];
initialConversationId: string | null;
initialPiSessionId: string;
+ selectedPreset?: any;
+ selectedPresetRef?: any;
}) {
const messagesRef = useRef(args.initialMessages);
const conversationIdRef = useRef<string | null>(args.initialConversationId);
@@ -141,6 +145,8 @@ function useHarness(args: {
setPastedImages: vi.fn() as any,
settings: { chatHistory: { historyEnabled: true } },
inlineHistoryEnabled: false,
+ selectedPreset: args.selectedPreset ?? null,
+ selectedPresetRef: args.selectedPresetRef,
});
return { hook, messagesRef, conversationIdRef, piSessionIdRef };
@@ -316,4 +322,28 @@ describe("saveConversation race (PR #3600 / issue #3636 candidate)", () => {
expect(saveCalls).toHaveLength(1);
expect(saveCalls[0].lastViewedAt).toBe(8_500);
});
+
+ it("resolves selectedPreset via ref when available to prevent stale closure on summary card click (#4820)", async () => {
+ const selectedPresetRef = { current: { id: "argus", model: "argus-model", provider: "ollama" } as any };
+ const messages = [
+ { id: "u1", role: "user" as const, content: "hello", timestamp: 1_000 },
+ ];
+
+ const { result } = renderHook(() =>
+ useHarness({
+ initialMessages: messages,
+ initialConversationId: "chat-card",
+ initialPiSessionId: "chat-card",
+ selectedPreset: { id: "gpt-4o", model: "gpt-4o", provider: "openai" } as any, // Stale closure value
+ selectedPresetRef, // Latest ref value
+ }),
+ );
+
+ await act(async () => {
+ await result.current.hook.saveConversation(messages);
+ });
+
+ expect(saveCalls).toHaveLength(1);
+ expect(saveCalls[0].presetId).toBe("argus");
+ });
});