mirror of
https://github.com/multica-ai/multica.git
synced 2026-08-13 03:15:34 +02:00
* feat(chat): add agent-generated quick actions
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): preserve mid-response quick-action fences
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): drop quick actions on empty reply to keep no_response fallback
An actions-only completion — a quick-actions footer with no visible text —
wrote an empty-content assistant message (message_kind=message). Older
Desktop/mobile clients ignore the quick_actions field and render that as an
empty bubble, breaking the MUL-4351 contract that an empty turn always gives
old clients a visible no_response fallback.
Drop the quick actions when the visible body is empty so an actions-only turn
falls through to the visible no_response outcome, and revert the completion
switch to gate the message row on visible text only. Update the completion
test to pin the corrected behavior.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
* feat(chat): generate quick actions via daemon suggestion pass
Replace the in-band runtime-brief instruction with a dedicated post-completion
provider turn: after a direct chat reply finishes, the daemon resumes the same
session with a JSON-only suggest prompt and forwards the raw output on the
complete callback. The server parses it leniently and reuses the existing
sanitize/redact/store/broadcast pipeline; the stripped in-band footer stays as
a fallback for older daemons and pre-upgrade sessions. The footer strip now
covers every chat completion, fixing the intro-turn protocol leak. Adds a
Settings → Chat toggle (client-persisted, default on) that hides the chips.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(chat): deliver quick actions async with skeleton placeholders
Decouple suggestion generation from the turn: the daemon reports completion
immediately (chat:done carries quick_actions_pending as a per-turn capability
signal) and runs the suggestion pass in the background, delivering results
through a new supplement endpoint + chat:quick_actions broadcast. A new turn
on the same session cancels the stale pass. Clients render pill skeletons
under the finished reply until the supplement resolves them (entrance
animation on arrival, 30s safety timeout); older daemons never raise the flag
so no skeleton dangles. Suggest usage re-reports merged totals because
task_usage upserts replace per (task, provider, model). Prompt now asks for
exactly 3 actions.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(chat): make the quick-actions toggle stop generation, not hide pills
The Settings → Chat toggle previously only hid rendered pills while the
daemon kept burning a suggestion call every turn. It now travels with each
send (quick_actions_enabled, absent = enabled for older clients), is stamped
on the chat task (migration 213), forwarded on the claim, and gates the
daemon's suggestion pass at the source — no call, no pending flag, no
skeleton. Existing suggestions stay visible; settings copy now says
'generate' instead of 'show'.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(migrations): renumber quick-action migrations onto current main
Merging current origin/main brought the vcs migrations to their canonical
216-221 prefixes, which collided with the quick-action migrations that were
sitting at 219/220 (backend CI red in
TestMigrationNumericPrefixesStayUniqueAfterLegacySet). Renumber them to the
next unused prefixes:
- 219_chat_message_quick_actions -> 222_chat_message_quick_actions
- 220_agent_task_quick_actions_disabled -> 223_agent_task_quick_actions_disabled
Contents are unchanged; sqlc regeneration produces no drift since the added
columns are independent of the vcs tables.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
* fix(mobile): render async chat quick actions via chat:quick_actions
The daemon generates quick actions in a background pass after the turn
finishes, delivering them on a separate chat:quick_actions event. Mobile
only handled chat:done (which invalidates + refetches an actions-less
message list) and keeps the messages query at staleTime: Infinity, so an
active mobile session never rendered async-generated quick actions until a
manual pull-to-refresh or refocus.
Add applyChatQuickActionsToCache — mirroring web's patcher — which patches
the supplement onto the targeted assistant message in the flat messages
cache, and subscribe to chat:quick_actions in use-chat-session-realtime.
Patch-only (no invalidate), matching web and mobile's cellular
patch-over-invalidate rule; an empty supplement is a terminal no-op. Covered
by chat-ws-updaters.test.ts.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): cancel in-flight messages refetch before quick-actions patch
The chat:done invalidate can leave a messages refetch in flight that read the
assistant row before the daemon persisted the quick actions. If that refetch
resolves after the chat:quick_actions setQueryData patch, it overwrites the
freshly-patched actions with an actions-less row. Both message caches are
staleTime: Infinity, so the overwrite never self-heals and the actions vanish
permanently (MUL-5149, Howard review).
applyChatQuickActionsToCache now awaits cancelQueries for the affected caches
(web: flat messages + messagesPage, mobile: flat messages) before patching, so
a stale in-flight refetch is cancelled and cannot land after the patch. Cancel
must precede setQueryData because cancelQueries reverts to the pre-fetch state.
WS handlers call it via `void` (fire-and-forget).
Adds an active-query race regression test on both web and mobile that holds a
refetch open across the supplement and asserts the patched actions survive;
verified to fail without the cancel.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
* feat(chat): quick-actions refresh/regenerate + review hardening (MUL-5149)
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): address quick-actions re-review (MUL-5149)
- Ack alignment: refresh request carries the target message_id; server
atomically confirms it is still the session's latest turn (409 stale
otherwise), so the client marker always matches the resolving
chat:quick_actions — no response reconciliation. Adds a regression test.
- Converge the pending marker on every terminal path: HandleFailedTasks
(sweeper/orphan) now resolves it, and the daemon reports a failed supplement
so FailTask resolves it instead of leaving a completed-but-unresolved task.
- Timeout fallback now clears the real query state (useQuickActionsPendingTimeout)
instead of a component-local flag that only masked the UI; drop the skeleton's
and pill row's local timers.
- frontend-test type-scale: text-xs -> text-caption. Strip EOF blank line.
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): close quick-actions refresh races and failure feedback (MUL-5149)
Third-round review of the refresh button surfaced three issues; all three
are addressed here.
§1/§2 Session-busy race + concurrent-refresh double-spend: a newer reply
that is queued/running but whose assistant row hasn't landed leaves the old
turn as latest-persisted, so the stale check passes and the regen resumes
the newer provider state — attaching suggestions to the wrong turn. And two
concurrent refreshes each enqueue a quota-spending pass. Add
HasActiveChatTaskForSession and refuse a refresh (ErrChatQuickActionsBusy →
409) whenever the session has any task in flight, checked under the same
session lock as the enqueue so no sibling insert slips past.
§3a Timeout re-arm on surface switch: the pending marker now carries an
absolute expires_at deadline instead of a per-mount timer, so switching
between the floating window and the chat tab resumes the same deadline
rather than restarting a fresh 30s window each remount.
§3b Generation failure masked as success: runChatSuggestPass now returns ok
so an explicit refresh distinguishes a failed pass (didn't start / didn't
complete / timed out) from a completed-but-empty one. On failure the regen
task reports failure, resolveFailedRegenerateQuickActions broadcasts a
FAILED chat:quick_actions, and the client resolves the spinner AND toasts
"couldn't refresh" instead of silently stopping on unchanged pills.
Co-authored-by: multica-agent <github@multica.ai>
* fix(chat): count deferred tasks in refresh busy check; solid refresh icon tone (MUL-5149)
Two re-review blockers on 2dc9404d.
§1 (deferred window): HasActiveChatTaskForSession only treated
queued/dispatched/running/waiting_local_directory as in-flight, so a chat
auto-retry armed with a backoff fire_at — inserted 'deferred' by
CreateRetryTask, as provider_network's ~5s final attempt is — slipped past
the busy check. In that window the failed turn has no assistant row yet, so
the old turn is still latest-persisted and refreshable; the regen would then
resume a session the retry is about to advance and pin the new turn's
suggestions onto the old one. Add 'deferred' so the set matches the
canonical in-flight status list the rest of the queries already use
(agent.sql has-active-task checks). New regression test covers a deferred
active turn.
CI (text-contrast gate): the refresh icon button used
text-muted-foreground/70 (transparency standing in for a text tone), which
the frontend-test contrast gate rejects. Switch to the solid
text-faint-foreground token — the tone the gate recommends for icons/glyphs,
already used repo-wide and clearing WCAG 1.4.11.
Co-authored-by: multica-agent <github@multica.ai>
* test(chat): assert quick-actions pending marker carries expires_at (MUL-5149)
The chat:done supplement-flow test still expected the 2-field marker from
before the absolute-deadline change; applyChatDoneToCache now stamps
expires_at, so the deep-equal failed on frontend-test. Assert the deadline is
present (expect.any(Number)) rather than a wall-clock-dependent value — its
timing semantics are covered by the pending-timeout hook.
Co-authored-by: multica-agent <github@multica.ai>
* fix(db): renumber regenerate-quick-actions migration 237 -> 240 (MUL-5149)
main merged Issue Quick Actions (MUL-5465) taking migrations 237/238/239
(quick_action, quick_action_workspace_index, comment_quick_action). This
branch independently took 237 for agent_task_queue.regenerate_quick_actions_for.
The two 237s do not textually conflict (different filenames) so the PR reads
mergeable, but the merged tree would carry two migration 237s. Renumber this
one to 240 so it applies after main's chain. The migration is a standalone
`ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS` — order-independent,
touches a column none of main's migrations reference.
Co-authored-by: multica-agent <github@multica.ai>
---------
Co-authored-by: Lambda <lambda@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
Co-authored-by: Walt <walt@multica.ai>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Naiyuan Qing <145280634+NevilleQingNY@users.noreply.github.com>
Co-authored-by: NevilleQingNY <nevilleqing@gmail.com>
420 lines
16 KiB
TypeScript
420 lines
16 KiB
TypeScript
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { api } from "../api";
|
|
import { useWorkspaceId } from "../hooks";
|
|
import { chatKeys, sortChatSessions, QUICK_ACTIONS_PENDING_TIMEOUT_MS } from "./queries";
|
|
import { createLogger } from "../logger";
|
|
import type {
|
|
ChatSession,
|
|
ChatPinnedAgent,
|
|
ChatDraftRestoresResponse,
|
|
ChatQuickActionsPendingState,
|
|
} from "../types";
|
|
|
|
const logger = createLogger("chat.mut");
|
|
|
|
/**
|
|
* Consume a deferred-cancellation draft restore (#5219) after the composer has
|
|
* applied it. The endpoint is idempotent, so consuming twice — or consuming a
|
|
* row a previous attempt already deleted — is safe, which is what lets this
|
|
* retry at all (mutations are `retry: false` app-wide).
|
|
*
|
|
* A lost consume must never re-restore a prompt the user has since sent, so the
|
|
* "applied" decision is not carried by this request: the caller records it in
|
|
* the persisted ledger (`markDraftRestoreApplied`) before firing, and reconciles
|
|
* any row that outlives its ledger entry by consuming it again. This mutation
|
|
* only has to make that reconciliation converge quickly.
|
|
*/
|
|
export function useConsumeChatDraftRestore() {
|
|
const qc = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: ({ sessionId, restoreId }: { sessionId: string; restoreId: string }) =>
|
|
api.consumeChatDraftRestore(sessionId, restoreId),
|
|
retry: 3,
|
|
retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 8000),
|
|
onMutate: ({ sessionId, restoreId }) => {
|
|
qc.setQueryData<ChatDraftRestoresResponse>(
|
|
chatKeys.draftRestores(sessionId),
|
|
(old) =>
|
|
old
|
|
? { ...old, restores: old.restores.filter((r) => r.id !== restoreId) }
|
|
: old,
|
|
);
|
|
},
|
|
onError: (err, { sessionId, restoreId }) => {
|
|
// Exhausted the retries. The draft is safe (it is in the composer) and the
|
|
// ledger keeps the row from being re-offered; the next mount reconciles it.
|
|
logger.warn("consumeChatDraftRestore.error", { sessionId, restoreId, err });
|
|
},
|
|
});
|
|
}
|
|
|
|
/** Pin an agent to the quick-agent bar (optimistic append). */
|
|
export function usePinChatAgent() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (agentId: string) => api.pinChatAgent(agentId),
|
|
onMutate: async (agentId) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
|
|
const prev = qc.getQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId));
|
|
qc.setQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId), (old) => {
|
|
if (old?.some((p) => p.agent_id === agentId)) return old;
|
|
const maxPos = old?.reduce((m, p) => Math.max(m, p.position), 0) ?? 0;
|
|
return [...(old ?? []), { agent_id: agentId, position: maxPos + 1 }];
|
|
});
|
|
return { prev };
|
|
},
|
|
onError: (err, agentId, ctx) => {
|
|
logger.error("pinChatAgent.error.rollback", { agentId, err });
|
|
if (ctx?.prev) qc.setQueryData(chatKeys.pinnedAgents(wsId), ctx.prev);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/** Unpin an agent from the quick-agent bar (optimistic removal). */
|
|
export function useUnpinChatAgent() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (agentId: string) => api.unpinChatAgent(agentId),
|
|
onMutate: async (agentId) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
|
|
const prev = qc.getQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId));
|
|
qc.setQueryData<ChatPinnedAgent[]>(chatKeys.pinnedAgents(wsId), (old) =>
|
|
old?.filter((p) => p.agent_id !== agentId),
|
|
);
|
|
return { prev };
|
|
},
|
|
onError: (err, agentId, ctx) => {
|
|
logger.error("unpinChatAgent.error.rollback", { agentId, err });
|
|
if (ctx?.prev) qc.setQueryData(chatKeys.pinnedAgents(wsId), ctx.prev);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.pinnedAgents(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
export function useCreateChatSession() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (data: { agent_id: string; title?: string; project_id?: string | null }) => {
|
|
logger.info("createChatSession.start", {
|
|
agent_id: data.agent_id,
|
|
project_id: data.project_id,
|
|
titleLength: data.title?.length ?? 0,
|
|
});
|
|
return api.createChatSession(data);
|
|
},
|
|
onSuccess: (session) => {
|
|
logger.info("createChatSession.success", { sessionId: session.id, agentId: session.agent_id });
|
|
},
|
|
onError: (err) => {
|
|
logger.error("createChatSession.error", err);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Clears the session's unread state server-side. Optimistically flips
|
|
* has_unread to false in the cached list so the FAB badge drops
|
|
* immediately. The server broadcasts chat:session_read so other devices
|
|
* also sync.
|
|
*/
|
|
export function useMarkChatSessionRead() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (sessionId: string) => {
|
|
logger.info("markChatSessionRead.start", { sessionId });
|
|
return api.markChatSessionRead(sessionId);
|
|
},
|
|
onMutate: async (sessionId) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
|
|
const clear = (old?: ChatSession[]) =>
|
|
old?.map((s) => (s.id === sessionId ? { ...s, has_unread: false, unread_count: 0 } : s));
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), clear);
|
|
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, sessionId, ctx) => {
|
|
logger.error("markChatSessionRead.error.rollback", { sessionId, err });
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Renames a chat session. Optimistically swaps the title in the cached
|
|
* list so the dropdown reflects the new label immediately; rolls back on
|
|
* error. The matching `chat:session_updated` WS event keeps other
|
|
* tabs/devices in sync — see use-realtime-sync.ts.
|
|
*/
|
|
export function useUpdateChatSession() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (data: { sessionId: string; title: string }) => {
|
|
logger.info("updateChatSession.start", {
|
|
sessionId: data.sessionId,
|
|
titleLength: data.title.length,
|
|
});
|
|
return api.updateChatSession(data.sessionId, { title: data.title });
|
|
},
|
|
onMutate: async ({ sessionId, title }) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
|
|
const patch = (old?: ChatSession[]) =>
|
|
old?.map((s) => (s.id === sessionId ? { ...s, title } : s));
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
|
|
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, vars, ctx) => {
|
|
logger.error("updateChatSession.error.rollback", { sessionId: vars.sessionId, err });
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Changes the project context of an existing chat without replacing the
|
|
* session. The optimistic patch keeps the context chip in place while the
|
|
* server validates the soft project reference; failures restore the old row.
|
|
*/
|
|
export function useSetChatSessionProject() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (data: { sessionId: string; projectId: string | null }) => {
|
|
logger.info("setChatSessionProject.start", data);
|
|
return api.updateChatSession(data.sessionId, { project_id: data.projectId });
|
|
},
|
|
onMutate: async ({ sessionId, projectId }) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
const patch = (old?: ChatSession[]) =>
|
|
old?.map((session) =>
|
|
session.id === sessionId ? { ...session, project_id: projectId } : session,
|
|
);
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
|
|
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, vars, ctx) => {
|
|
logger.error("setChatSessionProject.error.rollback", {
|
|
sessionId: vars.sessionId,
|
|
err,
|
|
});
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Pins or unpins a chat. Optimistically flips `pinned` and re-sorts the cached
|
|
* list (pinned first, then by activity) so the row jumps to / from the top
|
|
* instantly; rolls back on error. The matching `chat:session_updated` WS event
|
|
* carries the new pin state to other tabs/devices — see use-realtime-sync.ts.
|
|
*/
|
|
export function useSetChatSessionPinned() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (data: { sessionId: string; pinned: boolean }) => {
|
|
logger.info("setChatSessionPinned.start", data);
|
|
return api.setChatSessionPinned(data.sessionId, data.pinned);
|
|
},
|
|
onMutate: async ({ sessionId, pinned }) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
|
|
const patch = (old?: ChatSession[]) =>
|
|
old &&
|
|
sortChatSessions(old.map((s) => (s.id === sessionId ? { ...s, pinned } : s)));
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
|
|
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, vars, ctx) => {
|
|
logger.error("setChatSessionPinned.error.rollback", { sessionId: vars.sessionId, err });
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Archives or unarchives a chat session. Optimistically flips `status` in the
|
|
* cached list so the row moves between the active list and the "Archived" view
|
|
* instantly (both filter on status locally); rolls back on error. Bumps
|
|
* `updated_at` so the row re-sorts by activity in whichever view it lands.
|
|
* The matching `chat:session_updated` WS event carries the new status to other
|
|
* tabs/devices — see use-realtime-sync.ts.
|
|
*
|
|
* Archiving also zeroes the row's unread locally so every badge (FAB, sidebar
|
|
* Chat tab, chat-window header) drops it in the same frame the row moves to the
|
|
* Archived view. The backend already forces unread to 0 for archived rows (see
|
|
* ListAllChatSessionsByCreator / MUL-4360); this is the optimistic half so there
|
|
* is no window where the header/sidebar still count a just-archived session
|
|
* before the refetch lands. Unarchive does NOT restore a count here — the true
|
|
* unread state comes back from the server refetch (last_read_at is untouched).
|
|
*/
|
|
export function useSetChatSessionArchived() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (data: { sessionId: string; archived: boolean }) => {
|
|
logger.info("setChatSessionArchived.start", data);
|
|
return api.setChatSessionArchived(data.sessionId, data.archived);
|
|
},
|
|
onMutate: async ({ sessionId, archived }) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
|
|
const nowIso = new Date().toISOString();
|
|
const patch = (old?: ChatSession[]) =>
|
|
old &&
|
|
sortChatSessions(
|
|
old.map((s) =>
|
|
s.id === sessionId
|
|
? {
|
|
...s,
|
|
status: archived ? "archived" : "active",
|
|
updated_at: nowIso,
|
|
...(archived ? { unread_count: 0, has_unread: false } : {}),
|
|
}
|
|
: s,
|
|
),
|
|
);
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), patch);
|
|
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, vars, ctx) => {
|
|
logger.error("setChatSessionArchived.error.rollback", { sessionId: vars.sessionId, err });
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: () => {
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hard-deletes a chat session. Optimistically removes the row from the
|
|
* sessions list so the dropdown updates instantly; rolls back on error.
|
|
* The matching `chat:session_deleted` WS event keeps other tabs/devices
|
|
* in sync — see use-realtime-sync.ts.
|
|
*/
|
|
export function useDeleteChatSession() {
|
|
const qc = useQueryClient();
|
|
const wsId = useWorkspaceId();
|
|
|
|
return useMutation({
|
|
mutationFn: (sessionId: string) => {
|
|
logger.info("deleteChatSession.start", { sessionId });
|
|
return api.deleteChatSession(sessionId);
|
|
},
|
|
onMutate: async (sessionId) => {
|
|
await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
|
|
const prevSessions = qc.getQueryData<ChatSession[]>(chatKeys.sessions(wsId));
|
|
|
|
const drop = (old?: ChatSession[]) => old?.filter((s) => s.id !== sessionId);
|
|
qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), drop);
|
|
|
|
logger.debug("deleteChatSession.optimistic", { sessionId });
|
|
return { prevSessions };
|
|
},
|
|
onError: (err, sessionId, ctx) => {
|
|
logger.error("deleteChatSession.error.rollback", { sessionId, err });
|
|
if (ctx?.prevSessions) qc.setQueryData(chatKeys.sessions(wsId), ctx.prevSessions);
|
|
},
|
|
onSettled: (_data, _err, sessionId) => {
|
|
logger.debug("deleteChatSession.settled", { sessionId });
|
|
qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Refresh the quick-action suggestions for a session's latest assistant turn
|
|
* (MUL-5149). Optimistically raises the pending marker for that turn — its pills
|
|
* go inert and the refresh icon spins — and rolls it back on failure. The
|
|
* refreshed pills arrive over the chat:quick_actions realtime event, which
|
|
* clears the marker (applyChatQuickActionsToCache). Never retried: a refresh is
|
|
* an explicit, quota-spending user action.
|
|
*/
|
|
export function useRegenerateChatQuickActions() {
|
|
const qc = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: ({ sessionId, messageId }: { sessionId: string; messageId: string }) =>
|
|
api.regenerateChatQuickActions(sessionId, messageId),
|
|
onMutate: ({ sessionId, messageId }) => {
|
|
const previous = qc.getQueryData<ChatQuickActionsPendingState | null>(
|
|
chatKeys.quickActionsPending(sessionId),
|
|
);
|
|
// The server confirms messageId IS the latest turn (else 409 → onError
|
|
// rollback), so the marker's message_id is guaranteed to match the
|
|
// chat:quick_actions that resolves it — no ack reconciliation needed.
|
|
// task_id is unknown here and unused for resolution (applyChatQuickActionsToCache
|
|
// matches on message_id).
|
|
qc.setQueryData<ChatQuickActionsPendingState | null>(
|
|
chatKeys.quickActionsPending(sessionId),
|
|
{
|
|
message_id: messageId,
|
|
task_id: "",
|
|
expires_at: Date.now() + QUICK_ACTIONS_PENDING_TIMEOUT_MS,
|
|
},
|
|
);
|
|
return { previous, sessionId };
|
|
},
|
|
onError: (error, _vars, ctx) => {
|
|
logger.error("regenerateChatQuickActions.error", { error });
|
|
if (ctx) {
|
|
qc.setQueryData<ChatQuickActionsPendingState | null>(
|
|
chatKeys.quickActionsPending(ctx.sessionId),
|
|
ctx.previous ?? null,
|
|
);
|
|
}
|
|
},
|
|
});
|
|
}
|