Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(vault): anchor provision cards to agent replies (#1117)

Call Whitefbc4189c4da0
diff --git a/ui/src/components/ui/vault-request-card.tsx b/ui/src/components/ui/vault-request-card.tsx
index d33ce4400..ad6860caf 100644
--- a/ui/src/components/ui/vault-request-card.tsx
+++ b/ui/src/components/ui/vault-request-card.tsx
@@ -1,4 +1,5 @@
-import { useMemo, useState } from 'react';
+import { createContext, useCallback, useContext, useMemo, useState } from 'react';
+import type { ReactNode } from 'react';
import { ArrowRight, KeyRound, LockKeyhole, PenTool, Wallet } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -16,6 +17,45 @@ function requestType(request: VaultRequest): RequestType {
return t === 'sign' || t === 'provision' ? t : 'access';
}
+type OpenProvisionDialog = (request: VaultRequest) => void;
+
+const VaultProvisionDialogContext = createContext<OpenProvisionDialog | null>(null);
+
+export const VaultProvisionDialogProvider: React.FC<{
+ requests: VaultRequest[];
+ onResolved: () => void;
+ disabled?: boolean;
+ children: ReactNode;
+}> = ({ requests, onResolved, disabled = false, children }) => {
+ const [activeRequestId, setActiveRequestId] = useState<string | null>(null);
+ const openProvisionDialog = useCallback((request: VaultRequest) => {
+ setActiveRequestId(request.id);
+ }, []);
+ const activeRequest = useMemo(
+ () => requests.find((request) => request.id === activeRequestId && requestType(request) === 'provision'),
+ [activeRequestId, requests],
+ );
+
+ return (
+ <VaultProvisionDialogContext.Provider value={disabled ? null : openProvisionDialog}>
+ {children}
+ {activeRequest ? (
+ <VaultSecretDialog
+ open={!disabled}
+ onOpenChange={(open) => {
+ if (!open) setActiveRequestId(null);
+ }}
+ request={activeRequest}
+ onCreated={() => {
+ setActiveRequestId(null);
+ onResolved();
+ }}
+ />
+ ) : null}
+ </VaultProvisionDialogContext.Provider>
+ );
+};
+
/**
* One pending vault request rendered as an inline chat card (design: Form A). Provision opens
* the shared {@link VaultSecretDialog}; access / sign open the shared {@link VaultApprovalDialog}
@@ -25,6 +65,8 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const type = useMemo(() => requestType(request), [request]);
+ const openProvisionDialog = useContext(VaultProvisionDialogContext);
+ const externallyOwnedProvision = type === 'provision' && openProvisionDialog !== null;
const card = (request.card ?? {}) as {
kind?: string;
protection?: string;
@@ -70,13 +112,20 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
) : null}
</div>
</div>
- <Button size="sm" className="shrink-0" onClick={() => setOpen(true)}>
+ <Button
+ size="sm"
+ className="shrink-0"
+ onClick={() => {
+ if (externallyOwnedProvision) openProvisionDialog(request);
+ else setOpen(true);
+ }}
+ >
{meta.action}
<ArrowRight className="size-3.5" />
</Button>
</div>
- {type === 'provision' ? (
+ {type === 'provision' && !externallyOwnedProvision ? (
<VaultSecretDialog
open={open}
onOpenChange={setOpen}
@@ -86,7 +135,7 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
onResolved();
}}
/>
- ) : (
+ ) : type !== 'provision' ? (
<VaultApprovalDialog
request={open ? request : null}
onResolved={() => {
@@ -95,7 +144,7 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
}}
onClose={() => setOpen(false)}
/>
- )}
+ ) : null}
</>
);
};
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index db03c61f5..f4d65e8c1 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -6,7 +6,7 @@ import { MemoryRouter } from 'react-router-dom';
import { describe, expect, it } from 'vitest';
import en from '../../i18n/en.json';
-import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import type { VaultRequest, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { ToastProvider } from '../../context/ToastContext';
import { isVoiceControlDisabled } from '../../lib/voiceRecording';
import { ChatHeaderBar, MessageRow } from './ChatPage';
@@ -436,6 +436,35 @@ describe('archived conflicts converge whatever the verb', () => {
// request, not the write. Locked (not hidden) for the same reason the quick-reply
// group is: the card is the transcript record of what was asked.
describe('read-only transcript locks the secret-request cards', () => {
+ it('withdraws a stale pending provision card attached to an Agent reply', () => {
+ const pending = {
+ id: 'vrq_stale',
+ request_type: 'provision',
+ secret_name: 'STALE_API_KEY',
+ requester: { session_id: 'ses_01J8XK5M8T' },
+ delivery: {},
+ status: 'pending',
+ message_id: null,
+ created_at: '2026-07-27T04:04:00.500Z',
+ decided_at: null,
+ expires_at: null,
+ } satisfies VaultRequest;
+
+ const archived = render(
+ <MessageRow
+ message={agentWithQuickReplies()}
+ session={session({ status: 'archived' })}
+ messageFontSize={13}
+ onQuickReply={() => undefined}
+ vaultRequests={[pending]}
+ onVaultRequestResolved={() => undefined}
+ readOnly
+ />,
+ );
+
+ expect(archived).not.toContain('STALE_API_KEY');
+ });
+
it('renders the recorded ask, disabled, with the reason', () => {
const locked = render(<SecretRequestCard name="OPENAI_API_KEY" readOnly />);
// Still legible as a transcript entry...
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index ebd24fc23..f3e382e53 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -19,6 +19,7 @@ import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessa
import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
+import { isVaultApprovalRequest, placeVaultProvisionRequests } from '../../lib/vaultRequestPlacement';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
import { showPageEmbeddedPath } from '../../apps/showPageAvatar';
import { downloadFile, fileMeta } from '../../lib/filesApi';
@@ -67,6 +68,7 @@ import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { VaultApprovalFloat, VaultChatRequests } from '../ui/vault-chat-requests';
+import { VaultProvisionDialogProvider, VaultRequestCard } from '../ui/vault-request-card';
import { StatusPill } from '../visual';
import { usePendingVaultRequests } from '../../lib/usePendingVaultRequests';
import { hasInAppBackEntry } from '../../lib/navigationHistory';
@@ -316,18 +318,13 @@ export const ChatPage: React.FC = () => {
);
useRegisterComposerTarget(composerTarget);
- // Pending vault requests for this session → inline cards at the transcript end (Transcript
- // footer) + a floating approval bar when those cards scroll off-viewport (approvals only).
+ // Pending vault requests for this session. Provision requests are attached to
+ // the Agent reply that announced them; access/sign retain the approval flow.
const { requests: vaultRequests, refresh: refreshVaultRequests } = usePendingVaultRequests(sessionId ?? '');
- // All pending approval (access/sign) requests for this session — governs the float's mount and
- // its open dialog's lifetime; the off-screen subset (reported per-card by VaultChatRequests)
- // only drives whether the bar itself is shown.
+ // All pending approval (access/sign) requests for this session govern the
+ // float's mount and dialog lifetime. Provision requests never enter it.
const pendingApprovals = useMemo(
- () =>
- vaultRequests.filter((request) => {
- const type = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;
- return type === 'access' || type === 'sign';
- }),
+ () => vaultRequests.filter(isVaultApprovalRequest),
[vaultRequests],
);
const [offscreenApprovals, setOffscreenApprovals] = useState<VaultRequest[]>([]);
@@ -343,6 +340,14 @@ export const ChatPage: React.FC = () => {
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);
const [messages, setMessages] = useState<WorkbenchMessage[]>([]);
+ const provisionPlacement = useMemo(
+ () => placeVaultProvisionRequests(messages, vaultRequests),
+ [messages, vaultRequests],
+ );
+ const transcriptTailVaultRequests = useMemo(
+ () => [...pendingApprovals, ...provisionPlacement.unanchored],
+ [pendingApprovals, provisionPlacement],
+ );
// Mirror the latest messages into a ref (updated every render) so effects that
// must NOT re-run on every message change — chiefly the deep-link jump effect,
// whose around-fetch would otherwise be cancelled by an SSE/reconcile update —
@@ -1968,6 +1973,12 @@ export const ChatPage: React.FC = () => {
// ``h-16`` header occupies 4rem at the top, so subtract that instead.
<ImageViewerProvider images={sessionImages}>
<FileViewerProvider>
+ <VaultProvisionDialogProvider
+ key={sessionId ?? 'no-session'}
+ requests={vaultRequests}
+ onResolved={refreshVaultRequests}
+ disabled={readOnly}
+ >
{/* Mobile: a FIXED full-screen flex column (the AppShell brand header is
hidden on chat) so the composer has NO scrollable ancestor — that is what
let iOS fling it off the top. useIosKeyboardInset then sizes this surface
@@ -2061,6 +2072,8 @@ export const ChatPage: React.FC = () => {
highlightedId={highlightedId}
messageFontSize={messageFontSize}
onQuickReply={handleQuickReply}
+ provisionRequestsByMessage={provisionPlacement.byMessageId}
+ onVaultRequestResolved={refreshVaultRequests}
onQuoteSelection={quoteSelectionToComposer}
onAskInNewSession={askInNewSession}
readOnly={readOnly}
@@ -2091,7 +2104,7 @@ export const ChatPage: React.FC = () => {
// approve/deny buttons would write to a session that can't accept it.
sessionId && !readOnly ? (
<VaultChatRequests
- requests={vaultRequests}
+ requests={transcriptTailVaultRequests}
onResolved={refreshVaultRequests}
onOffscreenApprovalsChange={setOffscreenApprovals}
/>
@@ -2130,6 +2143,7 @@ export const ChatPage: React.FC = () => {
/>
</div>
</div>
+ </VaultProvisionDialogProvider>
</FileViewerProvider>
</ImageViewerProvider>
);
@@ -2790,6 +2804,8 @@ interface TranscriptProps {
highlightedId: string | null;
messageFontSize: number;
onQuickReply: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
+ provisionRequestsByMessage: Map<string, VaultRequest[]>;
+ onVaultRequestResolved: () => void;
// Chat-selection toolbar: quote the selection into the composer, or fork +
// ask in a new session seeded with the quote.
onQuoteSelection: (text: string) => void;
@@ -2822,8 +2838,8 @@ interface TranscriptProps {
showToolCalls: boolean;
onToggleTools: () => void;
};
- // Rendered at the end of the scroll content, after the last message (e.g. the in-scroll
- // vault request cards). Part of the timeline, so it scrolls with the conversation.
+ // Rendered at the end of the scroll content for approval cards and the brief
+ // pre-reply window where a provision request has no Agent message to own yet.
footer?: React.ReactNode;
}
@@ -2841,6 +2857,8 @@ const Transcript: React.FC<TranscriptProps> = ({
highlightedId,
messageFontSize,
onQuickReply,
+ provisionRequestsByMessage,
+ onVaultRequestResolved,
onQuoteSelection,
onAskInNewSession,
readOnly,
@@ -3263,6 +3281,8 @@ const Transcript: React.FC<TranscriptProps> = ({
session={session}
messageFontSize={messageFontSize}
onQuickReply={onQuickReply}
+ vaultRequests={provisionRequestsByMessage.get(message.id)}
+ onVaultRequestResolved={onVaultRequestResolved}
onOpenLocalFile={openLocalFile}
readOnly={readOnly}
highlighted={message.id === highlightedId}
@@ -3362,6 +3382,8 @@ type MessageRowProps = {
session: WorkbenchSession;
messageFontSize: number;
onQuickReply?: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
+ vaultRequests?: VaultRequest[];
+ onVaultRequestResolved?: () => void;
onOpenLocalFile?: (target: LocalFileLinkTarget) => void | Promise<void>;
// Archived session: the row still renders in full — including the quick-reply
// group and which option was chosen, which is part of the transcript — but the
@@ -3384,7 +3406,17 @@ type MessageRowProps = {
// useCallback), so the default shallow compare is correct here.
// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
// which renders a single row rather than mounting the whole page.
-export const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, onOpenLocalFile, readOnly, highlighted }: MessageRowProps) {
+export const MessageRow = memo(function MessageRow({
+ message,
+ session,
+ messageFontSize,
+ onQuickReply,
+ vaultRequests,
+ onVaultRequestResolved,
+ onOpenLocalFile,
+ readOnly,
+ highlighted,
+}: MessageRowProps) {
const { t } = useTranslation();
const navigate = useNavigate();
// Harness rows are collapsed by default; this tracks the per-row expand state.
@@ -3464,6 +3496,16 @@ export const MessageRow = memo(function MessageRow({ message, session, messageFo
onChoose={(choice) => onQuickReply(message.id, choice)}
/>
) : null;
+ // Unlike a `$<NAME>` marker in the reply text, attached requests are live
+ // pending state, not authored transcript content. Archive expires that state,
+ // so a stale tab must withdraw the card instead of preserving a false action.
+ const vaultRequestsNode = !readOnly && vaultRequests?.length && onVaultRequestResolved ? (
+ <div className="flex w-full flex-col gap-2 pt-1">
+ {vaultRequests.map((request) => (
+ <VaultRequestCard key={request.id} request={request} onResolved={onVaultRequestResolved} />
+ ))}
+ </div>
+ ) : null;
// Agent / system replies AND the user's own messages render as markdown (users
// routinely type lists / code / **emphasis** and expect it formatted). Only
@@ -3637,6 +3679,7 @@ export const MessageRow = memo(function MessageRow({ message, session, messageFo
{attachmentsNode}
</div>
{quickRepliesNode}
+ {vaultRequestsNode}
{time}
</div>
</div>
diff --git a/ui/src/lib/transcriptOrder.test.ts b/ui/src/lib/transcriptOrder.test.ts
index e813976f5..5cd5c6e46 100644
--- a/ui/src/lib/transcriptOrder.test.ts
+++ b/ui/src/lib/transcriptOrder.test.ts
@@ -1,7 +1,13 @@
import { describe, expect, it } from 'vitest';
import type { WorkbenchMessage } from '../context/ApiContext';
-import { byCreatedThenId, mergeById, insertMessageOrdered } from './transcriptOrder';
+import {
+ byCreatedThenId,
+ mergeById,
+ insertMessageOrdered,
+ messageOrderTimeMs,
+ timestampOrderTimeMs,
+} from './transcriptOrder';
// The transcript keeps its rows in durable (created_at, id) order at all times.
// Only id + created_at drive ordering, so fixtures fill just those; the rest is
@@ -15,6 +21,30 @@ const mk = (id: string, created_at: string): WorkbenchMessage =>
({ id, created_at }) as unknown as WorkbenchMessage;
const ids = (list: WorkbenchMessage[]): string[] => list.map((m) => m.id);
+describe('messageOrderTimeMs', () => {
+ it('recovers subsecond positions from canonical message ids', () => {
+ const createdAt = '2026-07-30T10:00:00Z';
+ const preciseTime = Date.parse('2026-07-30T10:00:00.800Z');
+ const preciseId = `msg_${Math.floor(preciseTime * 1_000).toString(16).padStart(15, '0')}deadbeef`;
+
+ expect(messageOrderTimeMs(mk(preciseId, createdAt))).toBe(preciseTime);
+ expect(messageOrderTimeMs(mk('imported-id', createdAt))).toBe(Date.parse(createdAt));
+ });
+});
+
+describe('timestampOrderTimeMs', () => {
+ it('retains microseconds from UTC and offset ISO timestamps', () => {
+ const base = Date.parse('2026-07-30T10:00:00.500Z');
+
+ expect(timestampOrderTimeMs('2026-07-30T10:00:00.500100Z')).toBeCloseTo(base + 0.1, 6);
+ expect(timestampOrderTimeMs('2026-07-30T18:00:00.500900+08:00')).toBeCloseTo(base + 0.9, 6);
+ });
+
+ it('preserves Date.parse invalid timestamp behavior', () => {
+ expect(timestampOrderTimeMs('not-a-timestamp')).toBeNaN();
+ });
+});
+
describe('byCreatedThenId', () => {
it('orders by created_at first', () => {
expect(byCreatedThenId(mk('b', t(1)), mk('a', t(2)))).toBe(-1);
diff --git a/ui/src/lib/transcriptOrder.ts b/ui/src/lib/transcriptOrder.ts
index 903e08737..c736fc6b2 100644
--- a/ui/src/lib/transcriptOrder.ts
+++ b/ui/src/lib/transcriptOrder.ts
@@ -1,5 +1,38 @@
import type { WorkbenchMessage } from '../context/ApiContext';
+const TIME_SORTABLE_MESSAGE_ID_RE = /^msg_([0-9a-f]{15})/i;
+const ISO_FRACTION_RE = /\.(\d+)(?=Z$|[+-]\d{2}:?\d{2}$)/;
+
+/** Parse an ISO timestamp without dropping precision beyond milliseconds. */
+export const timestampOrderTimeMs = (timestamp: string): number => {
+ const fraction = ISO_FRACTION_RE.exec(timestamp);
+ if (!fraction) return Date.parse(timestamp);
+
+ const millisecondDigits = fraction[1].padEnd(3, '0').slice(0, 3);
+ const normalized = `${timestamp.slice(0, fraction.index)}.${millisecondDigits}${timestamp.slice(fraction.index + fraction[0].length)}`;
+ const milliseconds = Date.parse(normalized);
+ if (Number.isNaN(milliseconds)) return milliseconds;
+
+ const microseconds = Number.parseInt(fraction[1].padEnd(6, '0').slice(0, 6), 10);
+ return milliseconds + (microseconds % 1_000) / 1_000;
+};
+
+/** Best available wall-clock position for a durable transcript row.
+ *
+ * Persisted message timestamps are second-resolution. Canonical `msg_` ids add
+ * a microsecond clock prefix specifically to preserve ordering inside that
+ * second, so prefer it whenever present and retain `created_at` for imported or
+ * historical ids.
+ */
+export const messageOrderTimeMs = (message: Pick<WorkbenchMessage, 'id' | 'created_at'>): number => {
+ const idTime = TIME_SORTABLE_MESSAGE_ID_RE.exec(message.id)?.[1];
+ if (idTime) {
+ const microseconds = Number.parseInt(idTime, 16);
+ if (Number.isSafeInteger(microseconds)) return microseconds / 1_000;
+ }
+ return timestampOrderTimeMs(message.created_at);
+};
+
// Pure ordering/merge helpers for the chat transcript, kept transport-agnostic
// (they only read ``created_at`` / ``id``) so the ordering contract can be unit
// tested independently of the ChatPage component. The chat keeps its ``messages``
diff --git a/ui/src/lib/vaultRequestPlacement.test.ts b/ui/src/lib/vaultRequestPlacement.test.ts
new file mode 100644
index 000000000..8c78af2f2
--- /dev/null
+++ b/ui/src/lib/vaultRequestPlacement.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it } from 'vitest';
+
+import type { VaultRequest, WorkbenchMessage } from '@/context/ApiContext';
+import {
+ isVaultApprovalRequest,
+ placeVaultProvisionRequests,
+ vaultRequestType,
+} from './vaultRequestPlacement';
+
+const message = (id: string, createdAt: string, author = 'agent'): WorkbenchMessage => ({
+ id,
+ scope_id: null,
+ session_id: 'ses_test',
+ platform: 'avibe',
+ author,
+ type: author === 'agent' ? 'result' : 'user',
+ source: author,
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ text: id,
+ content: {},
+ metadata: {},
+ created_at: createdAt,
+ updated_at: createdAt,
+ delivered_at: null,
+ read_at: null,
+});
+
+const request = (
+ id: string,
+ type: string,
+ createdAt: string,
+ messageId: string | null = null,
+ requester: unknown = {},
+): VaultRequest => ({
+ id,
+ request_type: type,
+ secret_name: 'API_KEY',
+ requester,
+ delivery: {},
+ status: 'pending',
+ message_id: messageId,
+ created_at: createdAt,
+ decided_at: null,
+ expires_at: null,
+});
+
+const orderedMessage = (
+ idSuffix: string,
+ orderAt: string,
+ createdAt: string,
+ author = 'agent',
+): WorkbenchMessage => {
+ const microseconds = Math.floor(Date.parse(orderAt) * 1_000);
+ return message(`msg_${microseconds.toString(16).padStart(15, '0')}${idSuffix}`, createdAt, author);
+};
+
+const microsecondMessage = (
+ idSuffix: string,
+ microsecondsAfterSecond: number,
+ author = 'agent',
+): WorkbenchMessage => {
+ const secondStart = Date.parse('2026-07-30T10:00:00Z') * 1_000;
+ return message(
+ `msg_${(secondStart + microsecondsAfterSecond).toString(16).padStart(15, '0')}${idSuffix}`,
+ '2026-07-30T10:00:00Z',
+ author,
+ );
+};
+
+describe('vaultRequestType', () => {
+ it('keeps provision separate from access and sign approvals', () => {
+ expect(vaultRequestType(request('p', 'provision', '2026-07-30T10:00:00Z'))).toBe('provision');
+ expect(isVaultApprovalRequest(request('a', 'access', '2026-07-30T10:00:00Z'))).toBe(true);
+ expect(isVaultApprovalRequest(request('s', 'sign', '2026-07-30T10:00:00Z'))).toBe(true);
+ expect(isVaultApprovalRequest(request('p', 'provision', '2026-07-30T10:00:00Z'))).toBe(false);
+ });
+});
+
+describe('placeVaultProvisionRequests', () => {
+ const messages = [
+ message('user-before', '2026-07-30T09:59:00Z', 'user'),
+ message('agent-owner', '2026-07-30T10:00:10Z'),
+ message('agent-later', '2026-07-30T10:01:00Z'),
+ ];
+
+ it('uses an explicit Agent message anchor when one is present', () => {
+ const placed = placeVaultProvisionRequests(
+ messages,
+ [request('p', 'provision', '2026-07-30T10:00:00Z', 'agent-later')],
+ );
+
+ expect(placed.byMessageId.get('agent-later')?.map((item) => item.id)).toEqual(['p']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('anchors legacy requests to the first Agent reply after creation', () => {
+ const placed = placeVaultProvisionRequests(
+ messages,
+ [request('p', 'provision', '2026-07-30T10:00:00Z')],
+ );
+
+ expect(placed.byMessageId.get('agent-owner')?.map((item) => item.id)).toEqual(['p']);
+ expect(placed.byMessageId.has('agent-later')).toBe(false);
+ });
+
+ it('uses the message id clock when the reply shares the request second', () => {
+ const sameSecondMessages = [
+ orderedMessage('11111111', '2026-07-30T10:00:00.100Z', '2026-07-30T10:00:00Z', 'user'),
+ orderedMessage('22222222', '2026-07-30T10:00:00.800Z', '2026-07-30T10:00:00Z'),
+ ];
+ const placed = placeVaultProvisionRequests(sameSecondMessages, [
+ request('p', 'provision', '2026-07-30T10:00:00.500Z'),
+ ]);
+
+ expect(placed.byMessageId.get(sameSecondMessages[1].id)?.map((item) => item.id)).toEqual(['p']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('does not round a request back onto an earlier reply in the same millisecond', () => {
+ const earlierInput = microsecondMessage('11111111', 100_000, 'user');
+ const earlierReply = microsecondMessage('22222222', 500_100);
+ const ownerReply = microsecondMessage('33333333', 500_950);
+ const placed = placeVaultProvisionRequests([earlierInput, earlierReply, ownerReply], [
+ request('p', 'provision', '2026-07-30T10:00:00.500900Z'),
+ ]);
+
+ expect(placed.byMessageId.has(earlierReply.id)).toBe(false);
+ expect(placed.byMessageId.get(ownerReply.id)?.map((item) => item.id)).toEqual(['p']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('does not cross a later user or harness input-turn boundary', () => {
+ for (const boundaryKind of ['user', 'harness'] as const) {
+ const origin = orderedMessage('11111111', '2026-07-30T10:00:00.100Z', '2026-07-30T10:00:00Z', 'user');
+ const boundary = orderedMessage('22222222', '2026-07-30T10:00:00.700Z', '2026-07-30T10:00:00Z', boundaryKind);
+ if (boundaryKind === 'harness') boundary.type = 'harness';
+ const unrelated = orderedMessage('33333333', '2026-07-30T10:00:00.900Z', '2026-07-30T10:00:00Z');
+ const placed = placeVaultProvisionRequests([origin, boundary, unrelated], [
+ request(`p-${boundaryKind}`, 'provision', '2026-07-30T10:00:00.500Z'),
+ ]);
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual([`p-${boundaryKind}`]);
+ }
+ });
+
+ it('uses an available turn identity before the timestamp fallback', () => {
+ const identifiedMessages = messages.map((item) => item.id === 'agent-later'
+ ? { ...item, metadata: { turn_id: 'turn-owner' } }
+ : item);
+ const placed = placeVaultProvisionRequests(identifiedMessages, [
+ request('p', 'provision', '2026-07-30T10:00:00Z', null, { turn_id: 'turn-owner' }),
+ ]);
+
+ expect(placed.byMessageId.get('agent-later')?.map((item) => item.id)).toEqual(['p']);
+ expect(placed.byMessageId.has('agent-owner')).toBe(false);
+ });
+
+ it('keeps approvals out of message placement and leaves unmatched provisions visible', () => {
+ const placed = placeVaultProvisionRequests(messages, [
+ request('approval', 'access', '2026-07-30T10:00:00Z'),
+ request('future', 'provision', '2026-07-30T11:00:00Z'),
+ ]);
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['future']);
+ });
+
+ it('does not attach a request whose owning reply may be outside the retained window', () => {
+ const placed = placeVaultProvisionRequests(
+ [message('agent-visible', '2026-07-30T10:00:10Z')],
+ [request('older', 'provision', '2026-07-30T09:00:00Z')],
+ );
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['older']);
+ });
+});
diff --git a/ui/src/lib/vaultRequestPlacement.ts b/ui/src/lib/vaultRequestPlacement.ts
new file mode 100644
index 000000000..3c626fe39
--- /dev/null
+++ b/ui/src/lib/vaultRequestPlacement.ts
@@ -0,0 +1,109 @@
+import type { VaultRequest, WorkbenchMessage } from '@/context/ApiContext';
+import { chatRowKind } from '@/lib/chatRowKind';
+import { specFor } from '@/lib/messageTypes';
+import { messageOrderTimeMs, timestampOrderTimeMs } from '@/lib/transcriptOrder';
+
+export type VaultRequestType = 'access' | 'sign' | 'provision' | 'other';
+
+export function vaultRequestType(request: VaultRequest): VaultRequestType {
+ const cardType = (request.card as { request_type?: unknown } | null)?.request_type;
+ const type = typeof cardType === 'string' ? cardType : request.request_type;
+ return type === 'access' || type === 'sign' || type === 'provision' ? type : 'other';
+}
+
+export function isVaultApprovalRequest(request: VaultRequest): boolean {
+ const type = vaultRequestType(request);
+ return type === 'access' || type === 'sign';
+}
+
+export type VaultProvisionPlacement = {
+ byMessageId: Map<string, VaultRequest[]>;
+ unanchored: VaultRequest[];
+};
+
+function isAgentReply(message: WorkbenchMessage): boolean {
+ return chatRowKind(message).kind === 'agent';
+}
+
+function isInputTurn(message: WorkbenchMessage): boolean {
+ return specFor(message.type).inputAuthors.includes(message.author);
+}
+
+function appendRequest(map: Map<string, VaultRequest[]>, messageId: string, request: VaultRequest): void {
+ const current = map.get(messageId);
+ if (current) current.push(request);
+ else map.set(messageId, [request]);
+}
+
+function record(value: unknown): Record<string, unknown> {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : {};
+}
+
+function sameRequestTurn(request: VaultRequest, message: WorkbenchMessage): boolean {
+ const requester = record(request.requester);
+ const metadata = record(message.metadata);
+ for (const key of ['turn_id', 'run_id'] as const) {
+ const requestId = typeof requester[key] === 'string' ? requester[key] : '';
+ if (requestId && requestId === metadata[key]) return true;
+ }
+ return false;
+}
+
+function inferReplyWithinTurn(
+ messages: WorkbenchMessage[],
+ requestTime: number,
+): WorkbenchMessage | undefined {
+ for (const message of messages) {
+ const messageTime = messageOrderTimeMs(message);
+ if (Number.isNaN(messageTime) || messageTime < requestTime) continue;
+ // An anchorless request belongs only to the turn that created it. Once a
+ // later user/harness input starts another turn, no later Agent row can own it.
+ if (isInputTurn(message)) return undefined;
+ if (isAgentReply(message)) return message;
+ }
+ return undefined;
+}
+
+/** Attach provision requests to the Agent reply that announced them.
+ *
+ * Newer producers can set `message_id` explicitly. Historical CLI-created rows
+ * do not, so use the session's serialized turn order: the first Agent-authored
+ * message created after the request is the reply that owns it. Requests without
+ * either anchor remain visible at the transcript tail until a reply arrives.
+ */
+export function placeVaultProvisionRequests(
+ messages: WorkbenchMessage[],
+ requests: VaultRequest[],
+): VaultProvisionPlacement {
+ const byMessageId = new Map<string, VaultRequest[]>();
+ const unanchored: VaultRequest[] = [];
+ const messagesById = new Map(messages.map((message) => [message.id, message]));
+ const agentMessages = messages.filter(isAgentReply);
+ const firstLoadedTime = messages.length > 0 ? messageOrderTimeMs(messages[0]) : Number.NaN;
+
+ for (const request of requests) {
+ if (vaultRequestType(request) !== 'provision') continue;
+
+ const explicit = request.message_id ? messagesById.get(request.message_id) : undefined;
+ if (explicit && isAgentReply(explicit)) {
+ appendRequest(byMessageId, explicit.id, request);
+ continue;
+ }
+
+ const requestTime = timestampOrderTimeMs(request.created_at);
+ const sameTurn = agentMessages.find((message) => sameRequestTurn(request, message));
+ // Do not guess when the request predates the retained message window: its
+ // real owner may have been trimmed, and attaching it to the first visible
+ // later reply would move the card to an unrelated turn.
+ const windowCoversRequest = Number.isNaN(firstLoadedTime) || firstLoadedTime <= requestTime;
+ const inferred = sameTurn ?? (Number.isNaN(requestTime) || !windowCoversRequest
+ ? undefined
+ : inferReplyWithinTurn(messages, requestTime));
+ if (inferred) appendRequest(byMessageId, inferred.id, request);
+ else unanchored.push(request);
+ }
+
+ return { byMessageId, unanchored };
+}