"use client"; import { api } from "@/lib/client/api"; import { PENDING_ATTACHMENTS_KEY } from "@/components/prompts/insert"; import type { PendingAttachment } from "@/lib/client/types"; /** * Library files → new chat hand-off (consumed by the Chat workstream). * * `useFilesInNewChat(fileIds)` copies the files into pending `message_attachments` (POST /api/library/files/attach), * stashes the descriptors in `sessionStorage["polyllm:pending-attachments"]` and returns the href * `/app/chat?attachments=` to navigate to. A new chat view should, on mount, read `?attachments=` and * `consumePendingAttachments()` to seed the composer chips (the ids go straight into `message.attachmentIds`). */ export async function prepareFilesForNewChat(fileIds: string[]): Promise<{ href: string; attachments: PendingAttachment[] }> { const res = await api<{ attachments: PendingAttachment[] }>("/api/library/files/attach", { method: "POST", json: { fileIds } }); try { window.sessionStorage.setItem(PENDING_ATTACHMENTS_KEY, JSON.stringify({ at: Date.now(), attachments: res.attachments })); } catch { /* ignore */ } return { href: `/app/chat?attachments=${encodeURIComponent(res.attachments.map((a) => a.id).join(","))}`, attachments: res.attachments }; } /** Reads and clears stashed pending attachments (null when absent or older than 5 minutes). */ export function consumePendingAttachments(): PendingAttachment[] | null { try { const raw = window.sessionStorage.getItem(PENDING_ATTACHMENTS_KEY); if (!raw) return null; window.sessionStorage.removeItem(PENDING_ATTACHMENTS_KEY); const d = JSON.parse(raw) as { at: number; attachments: PendingAttachment[] }; if (!Array.isArray(d?.attachments) || Date.now() - (d.at ?? 0) > 5 * 60_000) return null; return d.attachments; } catch { return null; } }