Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 14 additions & 19 deletions packages/core/src/client/AssistantChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1057,18 +1057,17 @@ const AssistantChatInner = forwardRef<
const [reconnectFrozen, setReconnectFrozen] = useState(false);
const reconnectRunIdRef = useRef<string | null>(null);
const reconnectAbortRef = useRef<AbortController | null>(null);
// Nuclear stop: user clicked stop but runtime hasn't cleared yet.
// This ONLY affects UI display (button + thinking indicator). Submission
// and queue gating still use the real `isRunning` so we never overlap a
// new run on top of one that's still cancelling on the server.
// Nuclear stop: user clicked stop. Clears the stop button/indicator AND
// lets new submissions go through immediately — prevents the "stuck
// queueing forever" state where isReconnecting or isRuntimeRunning gets
// wedged (e.g. after a tab refresh + stop during reconnect).
const [forceStopped, setForceStopped] = useState(false);
// Real running state — drives submission/queue gating. Treat reconnecting
// to an active run the same as running.
const isRunning = isRuntimeRunning || isReconnecting;
// to an active run the same as running, UNLESS the user has explicitly
// clicked stop (forceStopped).
const isRunning = !forceStopped && (isRuntimeRunning || isReconnecting);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 forceStopped now gates submission state, risking race with server run persistence

The new isRunning = !forceStopped && (...) makes submissions possible immediately after Stop, but the previous run may still be aborting on the server. If the user submits quickly, the server could persist the old run's partial output before the new user message is saved to the database, causing loss or out-of-order history on reconnect.


React with 👍 or 👎 to help me improve.

// UI-only running state — drives the stop button and thinking indicator.
// forceStopped lets us flip the indicator off immediately even if the
// underlying runtime or reconnect state hasn't caught up yet.
const showRunningInUI = !forceStopped && isRunning;
const showRunningInUI = isRunning;
const wasRunningRef = useRef(false);
const tiptapRef = useRef<TiptapComposerHandle>(null);

Expand Down Expand Up @@ -1800,34 +1799,30 @@ const AssistantChatInner = forwardRef<
onSlashCommand={onSlashCommand}
execMode={execMode}
onExecModeChange={onExecModeChange}
actionButton={
extraActionButton={
showRunningInUI ? (
<button
type="button"
onClick={() => {
// Immediately force the indicator off — belt-and-suspenders
// so the UI is never stuck even if the runtime or reconnect
// state takes time (or fails) to clear on its own.
// Nuclear stop: flip forceStopped so isRunning is false
// immediately. This unblocks submission even if the
// runtime or reconnect state is stuck.
setForceStopped(true);

if (isReconnecting) {
// Abort the server-side run (fire-and-forget)
if (reconnectRunIdRef.current) {
fetch(
`${apiUrl}/runs/${encodeURIComponent(reconnectRunIdRef.current)}/abort`,
{ method: "POST" },
);
}
// Abort the client-side SSE stream
reconnectAbortRef.current?.abort();
reconnectAbortRef.current = null;
reconnectRunIdRef.current = null;
setIsReconnecting(false);
// Keep reconnectContent visible (frozen) — don't wipe it
setReconnectFrozen(reconnectContent.length > 0);
}

// Always try to cancel the runtime run too (handles the
// normal non-reconnect path and is a no-op if not running)
threadRuntime.cancelRun();

window.dispatchEvent(
Expand All @@ -1839,7 +1834,7 @@ const AssistantChatInner = forwardRef<
}),
);
}}
className="shrink-0 flex h-7 w-7 items-center justify-center rounded-md bg-primary text-primary-foreground hover:opacity-90"
className="shrink-0 flex h-7 w-7 items-center justify-center rounded-md bg-muted text-foreground hover:bg-muted/80"
title="Stop generating"
>
<IconPlayerStop className="h-3.5 w-3.5" />
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/client/composer/TiptapComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ interface TiptapComposerProps {
onSubmit?: (text: string, references: Reference[]) => void;
/** Custom action button (e.g. stop button) to render instead of the default send button. */
actionButton?: React.ReactNode;
/** Extra button to render alongside the default send button (e.g. stop while running). */
extraActionButton?: React.ReactNode;
/** Custom attachment button to render instead of ComposerPrimitive.AddAttachment. */
attachButton?: React.ReactNode;
/** Called when a slash command (e.g. /clear, /help) is executed */
Expand Down Expand Up @@ -152,6 +154,7 @@ export function TiptapComposer({
focusRef,
onSubmit,
actionButton,
extraActionButton,
attachButton,
onSlashCommand,
execMode,
Expand Down Expand Up @@ -764,6 +767,7 @@ export function TiptapComposer({
{execMode && onExecModeChange && (
<ModeSelector mode={execMode} onChange={onExecModeChange} />
)}
{extraActionButton}
<button
type="button"
onClick={submitComposer}
Expand Down
3 changes: 3 additions & 0 deletions templates/analytics/app/components/dashboard/SqlChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@ function BarRenderer({
}}
labelFormatter={formatXLabel}
formatter={(v: number) => formatYValue(v, yFormatter)}
itemSorter={(item) => -(Number(item.value) || 0)}
/>
{yKeys.map((key, i) => (
<Bar
Expand Down Expand Up @@ -568,6 +569,7 @@ function TimeSeriesRenderer({
}}
labelFormatter={formatXLabel}
formatter={(v: number) => formatYValue(v, yFormatter)}
itemSorter={(item) => -(Number(item.value) || 0)}
/>
{yKeys.map((key, i) => (
<Line
Expand Down Expand Up @@ -642,6 +644,7 @@ function TimeSeriesRenderer({
}}
labelFormatter={formatXLabel}
formatter={(v: number) => formatYValue(v, yFormatter)}
itemSorter={(item) => -(Number(item.value) || 0)}
/>
{yKeys.map((key, i) => (
<Area
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function SqlChartCard({
)}
<button
onClick={onRemove}
className="p-1 rounded text-muted-foreground hover:text-destructive"
className="p-1 rounded text-muted-foreground hover:text-foreground"
title="Remove panel"
>
<IconTrash className="h-3.5 w-3.5" />
Expand Down
39 changes: 37 additions & 2 deletions templates/calendar/app/hooks/use-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,26 @@ import {
import { useActionQuery } from "@agent-native/core/client";
import type { CalendarEvent } from "@shared/api";

export function useEvents(
function buildEventsParams(
from?: string,
to?: string,
overlayEmails?: string[],
) {
): Record<string, string> {
const params: Record<string, string> = {};
if (from) params.from = from;
if (to) params.to = to;
if (overlayEmails && overlayEmails.length > 0) {
params.overlayEmails = overlayEmails.join(",");
}
return params;
}

export function useEvents(
from?: string,
to?: string,
overlayEmails?: string[],
) {
const params = buildEventsParams(from, to, overlayEmails);

return useActionQuery<CalendarEvent[]>("list-events", params, {
retry: false,
Expand All @@ -27,6 +36,32 @@ export function useEvents(
});
}

/**
* Warm the events query cache for a given range without triggering a render.
* Use to pre-fetch adjacent weeks so j/k navigation is instant — the same
* stale/gc settings as `useEvents` apply, so the prefetched data is picked up
* by the real query when the user actually navigates.
*/
export function prefetchEvents(
queryClient: ReturnType<typeof useQueryClient>,
from: string,
to: string,
overlayEmails?: string[],
) {
const params = buildEventsParams(from, to, overlayEmails);
return queryClient.prefetchQuery({
queryKey: ["action", "list-events", params],
queryFn: async () => {
const qs = new URLSearchParams(params).toString();
const res = await fetch(`/_agent-native/actions/list-events?${qs}`);
if (!res.ok) throw new Error("prefetch list-events failed");
return res.json();
},
staleTime: 30_000,
gcTime: 30 * 60 * 1000,
});
}

export function useEvent(id: string) {
return useQuery<CalendarEvent>({
queryKey: ["events", id],
Expand Down
46 changes: 46 additions & 0 deletions templates/calendar/app/pages/CalendarView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
useCreateEvent,
useUpdateEvent,
useDeleteEvent,
prefetchEvents,
} from "@/hooks/use-events";
import { useOverlayPeople } from "@/hooks/use-overlay-people";
import { useGoogleAuthStatus } from "@/hooks/use-google-auth";
Expand Down Expand Up @@ -142,6 +143,51 @@ export default function CalendarView() {
} = useEvents(from, to, overlayEmails);
const rawEvents = Array.isArray(rawEventsData) ? rawEventsData : [];

// Warm the adjacent ranges so j/k (and the chevron buttons) feel instant.
// Borrowed from the mail template's background-warm pattern — fire-and-forget
// prefetch that lets React Query dedupe and reuse the response when the user
// actually navigates. Only runs once the current range has loaded so we
// don't fight the primary fetch for bandwidth.
useEffect(() => {
if (isLoading) return;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Prefetch concurrency: adjacent ranges fetch while primary range is loading

The guard if (isLoading) return doesn't account for placeholderData: keepPreviousData in useEvents(). Navigating keeps old data visible, so isLoading stays false while the new range is still fetching. This causes adjacent prefetches to run concurrently with the primary fetch on every navigation, multiplying requests against Google Calendar and external feeds.


React with 👍 or 👎 to help me improve.

const ranges = (() => {
switch (viewMode) {
case "month": {
const next = addMonths(selectedDate, 1);
const prev = subMonths(selectedDate, 1);
return [next, prev].map((d) => ({
from: startOfWeek(startOfMonth(d)).toISOString(),
to: endOfWeek(endOfMonth(d)).toISOString(),
}));
}
case "week": {
// Two weeks forward so rapid `j j` stays instant, plus one back.
const next = addWeeks(selectedDate, 1);
const next2 = addWeeks(selectedDate, 2);
const prev = subWeeks(selectedDate, 1);
return [next, next2, prev].map((d) => ({
from: startOfWeek(d).toISOString(),
to: endOfWeek(d).toISOString(),
}));
}
case "day": {
const next = addDays(selectedDate, 1);
const prev = subDays(selectedDate, 1);
return [next, prev].map((d) => {
const start = new Date(d);
start.setHours(0, 0, 0, 0);
const end = new Date(d);
end.setHours(23, 59, 59, 999);
return { from: start.toISOString(), to: end.toISOString() };
});
}
}
})();
for (const range of ranges) {
void prefetchEvents(queryClient, range.from, range.to, overlayEmails);
}
}, [isLoading, viewMode, selectedDate, overlayEmails, queryClient]);

// Show skeleton only when loading with no cached data (new date range).
// Tab refocus keeps cached data visible and refetches in background.
const eventsLoading = isLoading;
Expand Down
Loading