Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add native credential approvals and precise conversation message links (#1502)

Regan Bellf94ad37ea2fd
diff --git a/docs/demos/credential-approvals.html b/docs/demos/credential-approvals.html
new file mode 100644
index 000000000..46efbc387
--- /dev/null
+++ b/docs/demos/credential-approvals.html
@@ -0,0 +1,199 @@
+<!doctype html>
+<html lang="en">
+ <meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>
+ Credential approval demo</title
+ ><style>
+ body {
+ font: 16px/1.5 system-ui;
+ margin: 60px auto;
+ padding: 24px;
+ max-width: 800px;
+ color: #222;
+ }
+ h1 {
+ font-size: 24px;
+ }
+ article {
+ padding: 24px;
+ border: 1px solid #ddd;
+ border-radius: 12px;
+ margin: 24px 0;
+ }
+ a {
+ color: #1264a3;
+ }
+ button {
+ background: white;
+ border: 1px solid #999;
+ border-radius: 5px;
+ padding: 8px 16px;
+ margin: 6px 8px 0 0;
+ font: 600 14px system-ui;
+ cursor: pointer;
+ }
+ button.primary {
+ background: #007a5a;
+ border-color: #007a5a;
+ color: white;
+ }
+ button.danger {
+ color: #b42332;
+ border-color: #b42332;
+ }
+ small {
+ display: block;
+ color: #666;
+ margin: 16px 0;
+ }
+ #conversation {
+ margin-top: 50px;
+ }
+ section {
+ padding: 20px;
+ border: 2px solid #635bff;
+ border-radius: 12px;
+ }
+ </style>
+ <h1>Credential approval</h1>
+ <p>
+ Interactive preview using the production Block Kit payload and synthetic data. Slack's surrounding interface is
+ represented by a minimal HTML renderer; button persistence is mocked here.
+ </p>
+ <article id="card"></article>
+ <button id="reset">Reset preview</button>
+ <div id="conversation">
+ <h2>Originating conversation</h2>
+ <section>Check the nightly build and capture a status screenshot.</section>
+ </div>
+ <script>
+ const cards = {
+ pending: {
+ text: "Approval needed: use your AWS credential in the Build group. Check the nightly build and capture a status screenshot.",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: ":lock: *Approval needed.*\nUse your *AWS* credential <https://qm.example/s/build?seq=120|in the Build group>.\n*Why:* Check the nightly build and capture a status screenshot.",
+ },
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "plain_text",
+ text: "Allow once permits one credential use. Allow always permits future use in this conversation until revoked.",
+ },
+ ],
+ },
+ {
+ type: "actions",
+ block_id: "keychain_ask:demo",
+ elements: [
+ {
+ type: "button",
+ text: { type: "plain_text", text: "Allow once" },
+ action_id: "keychain_allow_once",
+ value: "demo",
+ style: "primary",
+ },
+ {
+ type: "button",
+ text: { type: "plain_text", text: "Allow always" },
+ action_id: "keychain_allow_always",
+ value: "demo",
+ },
+ {
+ type: "button",
+ text: { type: "plain_text", text: "Deny" },
+ action_id: "keychain_deny",
+ value: "demo",
+ style: "danger",
+ },
+ ],
+ },
+ ],
+ },
+ once: {
+ text: "Approved — one-time access.",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*Approved — one-time access.*\nUse your *AWS* credential <https://qm.example/s/build?seq=120|in the Build group>.\n*Why:* Check the nightly build and capture a status screenshot.",
+ },
+ },
+ ],
+ },
+ standing: {
+ text: "Approved — ongoing access for this conversation.",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*Approved — ongoing access for this conversation.*\nUse your *AWS* credential <https://qm.example/s/build?seq=120|in the Build group>.\n*Why:* Check the nightly build and capture a status screenshot.",
+ },
+ },
+ ],
+ },
+ declined: {
+ text: "Denied.",
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*Denied.*\nUse your *AWS* credential <https://qm.example/s/build?seq=120|in the Build group>.\n*Why:* Check the nightly build and capture a status screenshot.",
+ },
+ },
+ ],
+ },
+ };
+ const card = document.querySelector("#card");
+ function mrkdwn(text) {
+ return text
+ .replace(/:lock:/g, "🔒")
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/&lt;([^|]+)\|([^&]+)&gt;/g, '<a href="#conversation">$2</a>')
+ .replace(/\*([^*]+)\*/g, "<strong>$1</strong>")
+ .replace(/\n/g, "<br>");
+ }
+ function show(state) {
+ card.replaceChildren();
+ for (const block of cards[state].blocks) {
+ if (block.type === "section") {
+ const p = document.createElement("div");
+ p.innerHTML = mrkdwn(block.text.text);
+ card.append(p);
+ }
+ if (block.type === "context") {
+ const p = document.createElement("small");
+ p.textContent = block.elements[0].text;
+ card.append(p);
+ }
+ if (block.type === "actions") {
+ for (const action of block.elements) {
+ const b = document.createElement("button");
+ b.textContent = action.text.text;
+ b.className = action.style || "";
+ b.onclick = () =>
+ show(
+ action.action_id === "keychain_allow_once"
+ ? "once"
+ : action.action_id === "keychain_allow_always"
+ ? "standing"
+ : "declined",
+ );
+ card.append(b);
+ }
+ }
+ }
+ }
+ document.querySelector("#reset").onclick = () => show("pending");
+ show("pending");
+ </script>
+</html>
diff --git a/docs/screenshots/message-seq-link.png b/docs/screenshots/message-seq-link.png
new file mode 100644
index 000000000..987c16f9b
Binary files /dev/null and b/docs/screenshots/message-seq-link.png differ
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 38a1ff853..f9f1c2ab5 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -1,3 +1,4 @@
+import { messageEntrySeqs, highlightMessage } from "./message-link.ts";
import { appEditSlug } from "./app-edit";
import { isConnectionReturn } from "./connection-return";
import "./onboarding-welcome";
@@ -42,6 +43,7 @@ import {
FileText,
Files,
GitFork,
+ Link2,
Maximize2,
MessageSquare,
Paperclip,
@@ -123,7 +125,7 @@ import {
} from "./timeline";
import "./slack-setup";
import { connectorLinksIn, stripConnectorLinks, type ConnectorLink } from "./connector-link";
-import { deepLinkPath, UI_BASE } from "./deep-link";
+import { deepLinkPath, sessionLink, UI_BASE } from "./deep-link";
import type { ChatSurface, ConvCtx } from "./conv-types";
import { errMessage, swallow } from "../../chassis/src/errors";
import { showStateError } from "./error-banner";
@@ -1609,7 +1611,11 @@ export function createChatSurface(
const mail = (message as { subagentMail?: SubagentMailRef }).subagentMail;
if (mail) {
return html`
- <article class="message-row subagent-mail-row" data-index=${index}>
+ <article
+ class="message-row subagent-mail-row"
+ data-index=${index}
+ data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ >
${subagentChip(mail.title, mail.sessionId)}
<span class="subagent-mail-note">${SUBAGENT_MAIL_NOTES[mail.kind] ?? mail.kind.replace(/_/g, " ")}</span>
</article>
@@ -1623,7 +1629,11 @@ export function createChatSurface(
const deleted = Boolean((message as { deleted?: boolean }).deleted);
const edited = !deleted && Boolean((message as { edited?: boolean }).edited);
return html`
- <article class="message-row user-row ${steered ? "steered-row" : ""}" data-index=${index}>
+ <article
+ class="message-row user-row ${steered ? "steered-row" : ""}"
+ data-index=${index}
+ data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ >
${steered ? html`<div class="steer-label">↪ steered the running task</div>` : nothing}
${speaker ? html`<div class="speaker-label">${speaker}</div>` : nothing}
<div class="message-bubble user-bubble ${deleted ? "deleted-bubble" : ""}">
@@ -1659,7 +1669,11 @@ export function createChatSurface(
};
label = labels[decision.scope ?? "once"] ?? "Approved";
}
- return html`<article class="message-row system-note-row" data-index=${index}>
+ return html`<article
+ class="message-row system-note-row"
+ data-index=${index}
+ data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ >
<div class="system-note">${label}: <code>${decision.command}</code></div>
</article>`;
}
@@ -1667,7 +1681,11 @@ export function createChatSurface(
const note = message as unknown as HistorySystemNote;
const who = note.speaker ?? "The user";
return html`
- <article class="message-row system-note-row" data-index=${index}>
+ <article
+ class="message-row system-note-row"
+ data-index=${index}
+ data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ >
<div class="system-note">
${
note.action === "deleted"
@@ -1706,7 +1724,11 @@ export function createChatSurface(
msg.content.some((chunk) => chunk.type === "thinking" && chunk.thinking.trim());
if (!hasVisibleContent && msg.stopReason !== "error" && msg.stopReason !== "aborted") return nothing;
return html`
- <article class="message-row assistant-row ${isStreaming ? "streaming" : ""}" data-index=${index}>
+ <article
+ class="message-row assistant-row ${isStreaming ? "streaming" : ""}"
+ data-index=${index}
+ data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ >
<div class="assistant-body">
${workView} ${assistantContent(msg, isStreaming, showWork)} ${assistantFileList(deliveredFiles)}
${msg.stopReason === "error" && msg.errorMessage ? html`<div class="composer-error inline">${msg.errorMessage}</div>` : nothing}
@@ -1749,6 +1771,19 @@ export function createChatSurface(
</button>`
: nothing
}
+ ${
+ chatState.sessionId && messageEntrySeqs(message).length
+ ? html`<button
+ class="msg-copy"
+ type="button"
+ ${tip("Copy message link")}
+ aria-label="Copy message link"
+ @click=${(e: Event) => void copyText(sessionLink(location.origin, UI_BASE, chatState.sessionId!, messageEntrySeqs(message)[0]), e.currentTarget as HTMLButtonElement)}
+ >
+ ${icon(Link2, 13)}${icon(Check, 13)}
+ </button>`
+ : nothing
+ }
${
forkable
? html`<button
@@ -2894,6 +2929,22 @@ export function createChatSurface(
mountReadOnly,
mountLoadingPane,
scrollToBottom,
+ revealEntry: (seq: number) => {
+ if (chatState.inheritedMessages.some((message) => messageEntrySeqs(message).includes(seq))) {
+ chatState.inheritedExpanded = true;
+ if (readonlyRedraw) readonlyRedraw();
+ else drawActiveChat();
+ }
+ const host = chatState.host ?? ctx.container()?.querySelector<HTMLElement>(".custom-chat");
+ transcriptViewport.cancelFollow();
+ const found = host ? highlightMessage(host, seq) : false;
+ if (!found) {
+ ctx.composer.state.error = "The linked message is unavailable or isn't visible in this conversation.";
+ if (readonlyRedraw) readonlyRedraw();
+ else drawActiveChat();
+ }
+ return found;
+ },
drawActiveChat,
setTranscriptWindow,
setPins,
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
index 3460135d0..736d3be96 100644
--- a/plugins/web-ui/src/conv-types.ts
+++ b/plugins/web-ui/src/conv-types.ts
@@ -93,6 +93,7 @@ export interface ChatSurface {
): void;
mountLoadingPane(): void;
scrollToBottom(): void;
+ revealEntry(seq: number): boolean;
drawActiveChat(agent?: Agent | null, opts?: { forceScroll?: boolean }): void;
setTranscriptWindow(anchorSeq: number | null, earlierCount: number, hasEarlier?: boolean): void;
setPins(pins: import("./core-bridge").SessionPin[]): void;
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index 7266cf959..b724400d5 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -1706,7 +1706,7 @@ export interface HistoryApprovalDecision {
}
function approvalDecisionMessage(
- entry: Pick<SessionEntry, "type" | "payload" | "createdAt">,
+ entry: Pick<SessionEntry, "type" | "payload" | "createdAt" | "seq">,
): HistoryApprovalDecision | null {
if (entry.type !== "approval_resolved") return null;
const decision = entry.payload as {
@@ -1718,6 +1718,7 @@ function approvalDecisionMessage(
if (typeof decision?.approved !== "boolean" || typeof decision.command !== "string") return null;
return {
role: "approval-decision",
+ ...(entry.seq !== undefined ? { entrySeq: entry.seq } : {}),
approved: decision.approved,
command: decision.command,
...(typeof decision.requestId === "string" ? { requestId: decision.requestId } : {}),
@@ -1835,8 +1836,10 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
closed = false,
timing?: { startedAt?: number; finishedAt?: number },
stopped = false,
+ entrySeqs: number[] = [],
): void => {
if (!text && !pending.length && !deliveryFiles.length && !stopped) return;
+ entrySeqs = [...entrySeqs, ...pending.map((entry) => entry.seq)];
const deliveredSilence = (a: ToolActivity): boolean => {
if (a.type !== "tool_result") return false;
const p = a.payload as { tool?: string; silent?: boolean; ok?: boolean } | null;
@@ -1858,6 +1861,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
}
const msg: AssistantWork = {
persisted: true,
+ ...(entrySeqs.length ? { entrySeqs } : {}),
role: "assistant",
content: [{ type: "text", text }],
api: model?.api ?? "unknown",
@@ -1930,7 +1934,10 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
heldPosts.delete(payload.callId);
if (postResultOk(e.payload)) {
appendPostFiles(e.payload);
- flushWork(held.text, e.createdAt);
+ flushWork(held.text, e.createdAt, false, undefined, false, [
+ held.activity.seq,
+ ...(e.seq === undefined ? [] : [e.seq]),
+ ]);
posted = true;
} else {
pending.push(held.activity, activity);
@@ -2000,9 +2007,9 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
payload: { text, demoted: true },
createdAt: e.createdAt,
});
- flushWork("", e.createdAt, false, timing, stopped);
+ flushWork("", e.createdAt, false, timing, stopped, e.seq === undefined ? [] : [e.seq]);
} else {
- flushWork(text, e.createdAt, !posted, timing, stopped);
+ flushWork(text, e.createdAt, !posted, timing, stopped, e.seq === undefined ? [] : [e.seq]);
}
}
posted = false;
diff --git a/plugins/web-ui/src/deep-link.ts b/plugins/web-ui/src/deep-link.ts
index 467bf99fc..bfa28df74 100644
--- a/plugins/web-ui/src/deep-link.ts
+++ b/plugins/web-ui/src/deep-link.ts
@@ -70,8 +70,9 @@ export function parseDeepLink(
};
}
-export function sessionLink(origin: string, base: string, sessionId: string): string {
- return `${origin}${deepLinkPath(base, "chats", sessionId)}`;
+export function sessionLink(origin: string, base: string, sessionId: string, seq?: number): string {
+ const suffix = seq !== undefined && Number.isSafeInteger(seq) && seq >= 0 ? `?seq=${seq}` : "";
+ return `${origin}${deepLinkPath(base, "chats", sessionId)}${suffix}`;
}
/** True for an unmodified left click — the case an in-app link should handle itself (SPA nav). Modified clicks (cmd/ctrl/shift/alt, middle-click) fall through to the browser so "open in new tab" works. */
diff --git a/plugins/web-ui/src/message-link.ts b/plugins/web-ui/src/message-link.ts
new file mode 100644
index 000000000..359f9a785
--- /dev/null
+++ b/plugins/web-ui/src/message-link.ts
@@ -0,0 +1,49 @@
+import type { TranscriptPage } from "./core-bridge.ts";
+
+export function messageLinkSeq(search: string): number | null {
+ const value = new URLSearchParams(search).get("seq");
+ if (value === null || !/^(0|[1-9]\d*)$/.test(value)) return null;
+ const seq = Number(value);
+ return Number.isSafeInteger(seq) ? seq : null;
+}
+
+export async function loadMessageTranscript(
+ load: (window: { tailTurns: number; beforeSeq?: number }) => Promise<TranscriptPage>,
+ seq: number | null,
+ tailTurns: number,
+): Promise<TranscriptPage> {
+ let page = await load({ tailTurns });
+ let first = page.entries[0]?.seq;
+ while (seq !== null && first !== undefined && seq < first && (page.earlierEntries ?? 0) > 0) {
+ const older = await load({ tailTurns: Math.max(tailTurns, 40), beforeSeq: first });
+ const next = older.entries[0]?.seq;
+ if (next === undefined || next >= first) break;
+ const entries = new Map([...older.entries, ...page.entries].map((entry) => [entry.seq, entry]));
+ page = { ...page, entries: [...entries.values()], earlierEntries: older.earlierEntries ?? 0 };
+ first = next;
+ }
+ return page;
+}
+
+export function messageEntrySeqs(message: unknown): number[] {
+ const value = message as { entrySeq?: number; entrySeqs?: number[]; work?: { activity?: Array<{ seq: number }> } };
+ return [
+ ...new Set([
+ ...(value.entrySeq !== undefined ? [value.entrySeq] : []),
+ ...(value.entrySeqs ?? []),
+ ...(value.work?.activity ?? []).map((entry) => entry.seq),
+ ]),
+ ];
+}
+
+export function highlightMessage(host: HTMLElement, seq: number): boolean {
+ if (!Number.isSafeInteger(seq) || seq < 0) return false;
+ const row = host.querySelector<HTMLElement>(`.message-row[data-entry-seqs~="${seq}"]`);
+ if (!row) return false;
+ for (const old of host.querySelectorAll(".linked-message")) old.classList.remove("linked-message");
+ row.classList.add("linked-message");
+ row.tabIndex = -1;
+ row.focus({ preventScroll: true });
+ row.scrollIntoView({ block: "center", behavior: "instant" });
+ return true;
+}
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index 056e2c9fe..ab147c66c 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -1639,7 +1639,7 @@ export async function openSessionInto(
}
return;
}
- if (s.id === conv.state.sessionId) return;
+ if (s.id === conv.state.sessionId && !entriesPrefetch) return;
refreshSessionsOnOpen();
@@ -1663,6 +1663,10 @@ export async function openSessionInto(
if (sessionsState.openingKey !== opening) return;
sessionsState.openingKey = null;
}
+ if (!entriesPrefetch && conv.state.sessionId === s.id) {
+ renderList();
+ return;
+ }
if (!entriesRes) {
if (tracked) showMainEmpty("Couldn't load this conversation. Check your connection and click it again.");
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index e69ee84df..d890aa31b 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -12487,3 +12487,9 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {
font-size: 11px;
line-height: 1.5;
}
+
+.message-row.linked-message {
+ outline: 2px solid var(--accent, #6474eb);
+ outline-offset: 6px;
+ border-radius: 8px;
+}
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index f938afd97..19c3b4290 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1,3 +1,4 @@
+import { loadMessageTranscript, messageLinkSeq } from "./message-link.ts";
import { initializeBrowserErrors, stopBrowserErrors } from "./browser-errors";
import { initializeAnalytics, capturePageview, stopAnalytics } from "./product-analytics";
import { captureSlackReturn } from "./slack-account";
@@ -46,7 +47,7 @@ import { brandMark, brandName, icon } from "./ui";
import { PHONE_MAX_WIDTH, trackVisualViewport } from "./viewport";
import { markConnectorConnected } from "./chat";
import { clearSkillsCache, resyncModelSelection } from "./composer";
-import { ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";
+import { allConversations, ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";
import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";
import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";
import {
@@ -152,7 +153,10 @@ export function syncUrlFromState(sessionOverride?: string | null): void {
const fromState =
sessionOverride !== undefined ? sessionOverride : (chatState.sessionId ?? chatState.rememberedSessionId);
const sessionId = splitState.active ? singlePaneSessionId() : fromState;
- const next = deepLinkPath(UI_BASE, appState.currentView, sessionId, contextsState.selected);
+ let next = deepLinkPath(UI_BASE, appState.currentView, sessionId, contextsState.selected);
+ const linked = parseDeepLink(UI_BASE, location.pathname, location.search);
+ const seq = messageLinkSeq(location.search);
+ if (appState.currentView === "chats" && linked.session === sessionId && seq !== null) next += `?seq=${seq}`;
if (`${location.pathname}${location.search}` !== next) history.replaceState(null, "", next);
}
@@ -1009,8 +1013,9 @@ export async function boot(): Promise<void> {
const chatsLink = wanted === null || wanted === "chats";
const linkedId = wantedSession && chatsLink ? wantedSession : null;
let transcriptUnavailable = false;
+ const wantedSeq = messageLinkSeq(location.search);
const loadLinkedTranscript = (id: string) =>
- fetchTranscript(id, { tailTurns: TAIL_TURNS }).catch((error: unknown) => {
+ loadMessageTranscript((window) => fetchTranscript(id, window), wantedSeq, TAIL_TURNS).catch((error: unknown) => {
transcriptUnavailable = !(error instanceof ApiError && (error.status === 404 || error.status === 403));
return null;
});
@@ -1080,6 +1085,11 @@ export async function boot(): Promise<void> {
if (!sessionsState.list.some((s) => s.id === linked.id)) sessionsState.list = [linked, ...sessionsState.list];
revealSessionSurface(linked);
await openSession(linked, transcript, approvalsPrefetch ?? undefined);
+ if (wantedSeq !== null)
+ requestAnimationFrame(() => {
+ for (const conversation of allConversations())
+ if (conversation.state.sessionId === linked.id) conversation.revealEntry(wantedSeq);
+ });
return;
}
await sessions;
diff --git a/plugins/web-ui/src/transcript-viewport.ts b/plugins/web-ui/src/transcript-viewport.ts
index 5ed97456d..c76057943 100644
--- a/plugins/web-ui/src/transcript-viewport.ts
+++ b/plugins/web-ui/src/transcript-viewport.ts
@@ -303,5 +303,5 @@ export function createTranscriptViewport() {
});
}
- return { sync, follow, beforeRender, afterRender, dispose };
+ return { sync, follow, cancelFollow, beforeRender, afterRender, dispose };
}
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
index d6da98fe1..5d635d387 100644
--- a/plugins/web-ui/test/deep-link-boot-fixture.ts
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -18,6 +18,7 @@ export interface Harness {
interface HarnessOptions {
path: string;
+ messageLink?: boolean;
transcriptStatus?: number;
transcriptFailures?: number;
holdTranscript?: boolean;
@@ -82,6 +83,9 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
scrollTop: 0,
}),
);
+ dom.window.HTMLElement.prototype.scrollIntoView = function () {
+ this.setAttribute("data-scrolled", "true");
+ };
const timers = new Set<ReturnType<typeof setTimeout>>();
const realSetTimeout = globalThis.setTimeout;
const realSetInterval = globalThis.setInterval;
@@ -134,6 +138,20 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
failuresLeft--;
return Response.json({ error: "not_found" }, { status: opts.transcriptStatus ?? 500 });
}
+ if (opts.messageLink) {
+ const older = path.includes("beforeSeq=");
+ const seqs = older ? [10, 11] : [80, 81];
+ return Response.json({
+ session: SESSION,
+ entries: seqs.map((seq) => ({
+ seq,
+ type: seq % 2 ? "assistant" : "user",
+ createdAt: Date.now(),
+ payload: { text: `Linked QA message ${seq}` },
+ })),
+ earlierEntries: older ? 0 : 80,
+ });
+ }
return Response.json({ session: SESSION, entries: [] });
}
if (path === "/api/sessions") {
diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.ts
index 7824da456..015e553e0 100644
--- a/plugins/web-ui/test/deep-link-boot.test.ts
+++ b/plugins/web-ui/test/deep-link-boot.test.ts
@@ -228,3 +228,17 @@ test("a failed connection refresh removes previously verified badges", async ()
await h.close();
}
});
+
+test("a message link loads older history and highlights the addressed row", async () => {
+ const h = await harness({ path: "/s/sess-deep?seq=10", messageLink: true });
+ try {
+ await h.boot();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ assert.ok(h.requests.some((p) => p.includes("beforeSeq=80")));
+ assert.ok(document.querySelector('[data-entry-seqs="10"]'));
+ assert.equal(document.querySelector(".linked-message")?.getAttribute("data-entry-seqs"), "10");
+ assert.equal(document.querySelector(".linked-message")?.getAttribute("data-scrolled"), "true");
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/history.test.ts b/plugins/web-ui/test/history.test.ts
index ba41f47d1..9b3ca96e1 100644
--- a/plugins/web-ui/test/history.test.ts
+++ b/plugins/web-ui/test/history.test.ts
@@ -32,8 +32,8 @@ test("approval decisions remain visible history events instead of unresolved too
},
]);
assert.deepEqual(messages.slice(-2), [
- { role: "approval-decision", command: "rm -r --help", approved: false, timestamp: 4 },
- { role: "approval-decision", command: "rm -r --help", approved: true, scope: "once", timestamp: 5 },
+ { role: "approval-decision", command: "rm -r --help", approved: false, timestamp: 4, entrySeq: 4 },
+ { role: "approval-decision", command: "rm -r --help", approved: true, scope: "once", timestamp: 5, entrySeq: 5 },
]);
});
diff --git a/plugins/web-ui/test/inbox-source.test.ts b/plugins/web-ui/test/inbox-source.test.ts
index 1f43b3112..2db85b199 100644
--- a/plugins/web-ui/test/inbox-source.test.ts
+++ b/plugins/web-ui/test/inbox-source.test.ts
@@ -69,7 +69,7 @@ test("the address keeps naming the open item, even after switchView writes the b
assert.match(inbox, /await openSentEmailById\(id, drawAll\);/, "unknown inbox ids resolve through sent mail");
assert.match(
shell,
- /const next = deepLinkPath\(UI_BASE, appState\.currentView, sessionId, contextsState\.selected\);/,
+ /(?:const|let) next = deepLinkPath\(UI_BASE, appState\.currentView, sessionId, contextsState\.selected\);/,
"syncUrlFromState carries no item id, which is what the inbox has to heal after",
);
const draw = inbox.match(/function drawFull\(\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
diff --git a/plugins/web-ui/test/message-link.test.ts b/plugins/web-ui/test/message-link.test.ts
new file mode 100644
index 000000000..d1b3bc9b1
--- /dev/null
+++ b/plugins/web-ui/test/message-link.test.ts
@@ -0,0 +1,75 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { JSDOM } from "jsdom";
+import { messageLinkSeq, loadMessageTranscript, messageEntrySeqs, highlightMessage } from "../src/message-link.ts";
+import { sessionLink } from "../src/deep-link.ts";
+import { entriesToMessages, type TranscriptPage } from "../src/core-bridge.ts";
+
+test("message URLs preserve zero and reject malformed, negative, and unsafe sequences", () => {
+ assert.equal(messageLinkSeq("?seq=120"), 120);
+ assert.equal(messageLinkSeq("?seq=0"), 0);
+ for (const q of ["", "?seq=", "?seq=-1", "?seq=1.5", "?seq=1e2", "?seq=9007199254740992", "?seq=abc"])
+ assert.equal(messageLinkSeq(q), null);
+ assert.equal(sessionLink("https://qm.example", "/web-ui", "s1", 120), "https://qm.example/web-ui/s/s1?seq=120");
+});
+
+test("an old message link loads older pages while retaining the live tail and remaining history", async () => {
+ const calls: unknown[] = [];
+ const page = (seqs: number[], earlierEntries: number): TranscriptPage => ({
+ entries: seqs.map((seq) => ({ type: "user", seq, createdAt: seq, payload: { text: `Message ${seq}` } })),
+ earlierEntries,
+ });
+ const pages = [page([200, 201], 200), page([100, 120, 200], 100)];
+ const result = await loadMessageTranscript(
+ async (window) => {
+ calls.push(window);
+ return pages.shift()!;
+ },
+ 120,
+ 10,
+ );
+ assert.deepEqual(
+ result.entries.map((e) => e.seq),
+ [100, 120, 200, 201],
+ );
+ assert.equal(result.earlierEntries, 100);
+ assert.deepEqual(calls, [{ tailTurns: 10 }, { tailTurns: 40, beforeSeq: 200 }]);
+});
+
+test("unavailable entries terminate without an endless pagination loop", async () => {
+ let calls = 0;
+ await loadMessageTranscript(
+ async () => {
+ calls++;
+ return { entries: [{ type: "user", seq: 200, createdAt: 0, payload: { text: "x" } }], earlierEntries: 20 };
+ },
+ 120,
+ 10,
+ );
+ assert.equal(calls, 2);
+});
+
+test("user, assistant, and collapsed final text entries retain their message target", () => {
+ const messages = entriesToMessages([
+ { type: "user", seq: 120, createdAt: 1, payload: { text: "hi" } },
+ { type: "text", seq: 121, parentSeq: 120, createdAt: 2, payload: { text: "hello" } },
+ { type: "assistant", seq: 122, parentSeq: 120, createdAt: 3, payload: { text: "hello" } },
+ ]);
+ assert.deepEqual(messageEntrySeqs(messages[0]), [120]);
+ assert.deepEqual(messageEntrySeqs(messages[1]), [122, 121]);
+});
+
+test("a linked row is focused, centered and highlighted", () => {
+ const dom = new JSDOM('<main><article class="message-row" data-entry-seqs="120 121"></article></main>');
+ const host = dom.window.document.querySelector("main")!;
+ const row = host.querySelector("article")!;
+ let scrolled = false;
+ row.scrollIntoView = () => {
+ scrolled = true;
+ };
+ assert.equal(highlightMessage(host, 120), true);
+ assert.equal(scrolled, true);
+ assert.equal(row.classList.contains("linked-message"), true);
+ assert.equal(dom.window.document.activeElement, row);
+ assert.equal(highlightMessage(host, 999), false);
+});
diff --git a/plugins/web-ui/test/single-view-navigation.test.ts b/plugins/web-ui/test/single-view-navigation.test.ts
index edac7dd28..5cca93780 100644
--- a/plugins/web-ui/test/single-view-navigation.test.ts
+++ b/plugins/web-ui/test/single-view-navigation.test.ts
@@ -3,7 +3,9 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import { runInNewContext } from "node:vm";
import ts from "typescript";
-import { deepLinkPath } from "../src/deep-link.ts";
+import { deepLinkPath, parseDeepLink } from "../src/deep-link.ts";
+
+import { messageLinkSeq } from "../src/message-link.ts";
const split = readFileSync(new URL("../src/split.ts", import.meta.url), "utf8");
const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");
@@ -36,11 +38,15 @@ test("single-pane navigation follows the pane identity without depending on the
contextsState: { selected: null },
UI_BASE: "",
deepLinkPath,
+ parseDeepLink,
+ messageLinkSeq,
location: {
get pathname() {
- return url;
+ return new URL(url, "https://qm.example").pathname;
+ },
+ get search() {
+ return new URL(url, "https://qm.example").search;
},
- search: "",
},
history: {
replaceState: (_state: unknown, _title: string, next: string) => {
@@ -52,6 +58,9 @@ test("single-pane navigation follows the pane identity without depending on the
dockApi.panels = [{ params: { sessionId: "first" } }];
sync();
assert.equal(url, "/s/first");
+ url = "/s/first?seq=120";
+ sync();
+ assert.equal(url, "/s/first?seq=120");
dockApi.panels = [{ params: { sessionId: "second" } }];
sync("stale-override");
assert.equal(url, "/s/second");
diff --git a/plugins/web-ui/test/transcript-viewport.test.ts b/plugins/web-ui/test/transcript-viewport.test.ts
index b95ae2a73..686f298f3 100644
--- a/plugins/web-ui/test/transcript-viewport.test.ts
+++ b/plugins/web-ui/test/transcript-viewport.test.ts
@@ -419,12 +419,13 @@ test("a prompt stays in flow when pins leave too little room, and can stick agai
test("prompt expansion control belongs inside the bubble in both renderers", () => {
for (const [source, start] of [
- [chat, '<article class="message-row user-row'],
- [readFileSync(new URL("../src/shared-session.ts", import.meta.url), "utf8"), "<article class=${"],
+ [chat, /<article\s+class="message-row user-row/],
+ [readFileSync(new URL("../src/shared-session.ts", import.meta.url), "utf8"), /<article\s+class=\$\{/],
]) {
- const rowStart = source!.indexOf(start!);
+ const rowStart = (source as string).search(start as RegExp);
assert.ok(rowStart >= 0);
- const row = source!.slice(rowStart, source!.indexOf("</article>", rowStart) + "</article>".length);
+ const text = source as string;
+ const row = text.slice(rowStart, text.indexOf("</article>", rowStart) + "</article>".length);
const dom = new JSDOM(row);
try {
const toggle = dom.window.document.querySelector(".pin-toggle");
@@ -932,3 +933,20 @@ test("End inside a nested control retains the control's native behavior", () =>
f.close();
}
});
+
+test("revealing a message cancels pending and future bottom following", () => {
+ const f = fixture();
+ try {
+ f.viewport.follow(true);
+ f.viewport.cancelFollow();
+ f.s.scrollTop = 40;
+ f.flush();
+ assert.equal(f.s.scrollTop, 40);
+ f.grow();
+ f.viewport.follow();
+ f.flush();
+ assert.equal(f.s.scrollTop, 40);
+ } finally {
+ f.close();
+ }
+});
diff --git a/src/api/routes/keychain.ts b/src/api/routes/keychain.ts
index daa24fc22..b26764dba 100644
--- a/src/api/routes/keychain.ts
+++ b/src/api/routes/keychain.ts
@@ -230,7 +230,7 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {
});
void deps
.fireAskResolution?.(ask, grant)
- .then(() => kc.markAskNotified(ask.id))
+ .then(() => kc.markAskNotified(ask.id, ask.status))
.catch((e) => swallow("keychain: ask resolution fire failed (sweep will retry)", e));
return sendJson(res, 200, {
grant,
@@ -331,11 +331,19 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {
const cronId = cronIdOf(capability.threadRef);
const cron = cronId ? await app.getCron(cronId) : null;
const dest = resolveCapabilityDestination(capability, undefined);
+ const originRun = capability.runId ? await deps.runs?.get(capability.runId) : null;
+ const requesterSeq = originRun && originRun.sessionId === capability.threadRef ? originRun?.turnUserSeq : null;
+ const requesterMessageTs =
+ originRun && originRun.sessionId === capability.threadRef && originRun.request.origin.kind === "human"
+ ? originRun.request.origin.messageTs
+ : undefined;
const { ask, existing } = await kc.createAsk({
...(capability.triggered ? { triggered: true } : {}),
credentialId: cred.id,
requesterId: actorId,
requesterScopeId: capability.scopeId,
+ ...(requesterSeq != null ? { requesterSeq } : {}),
+ ...(requesterMessageTs ? { requesterMessageTs } : {}),
...(dest.ok && dest.destination ? { requesterDestination: dest.destination } : {}),
...(capability.threadRef ? { requesterThreadRef: capability.threadRef } : {}),
purpose: b.purpose,
@@ -351,7 +359,7 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {
...(cron?.ownerScopeId === capability.scopeId ? { taskTitle: cron.title ?? cron.id } : {}),
});
await deps.deliveries?.enqueue({
- destination: principalDestination(cred.ownerId, actorId),
+ destination: { ...principalDestination(cred.ownerId, actorId), keychainAskId: ask.id },
text: notice,
idempotencyKey: `ask:${ask.id}:notice`,
});
@@ -394,7 +402,7 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {
});
void deps
.fireAskResolution?.(ask)
- .then(() => kc.markAskNotified(ask.id))
+ .then(() => kc.markAskNotified(ask.id, ask.status))
.catch((e) => swallow("keychain: ask resolution fire failed (sweep will retry)", e));
return sendJson(res, 200, { ask });
}
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index f482edbad..672758b3a 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -1,3 +1,4 @@
+import type { KeychainApprovals } from "../credentials/keychain-approval.ts";
import { createTaskAcknowledgements, type TaskAckState, type TaskAcknowledgements } from "../slack/task-ack.ts";
import { orgId as configOrgId } from "../config.ts";
import type { StagedEnvelope } from "../slack/envelope-staging.ts";
@@ -88,6 +89,7 @@ interface DirectoryPush {
}
export interface SlackCoreClient {
+ keychainApprovals?: KeychainApprovals;
taskAcknowledgements?: TaskAcknowledgements;
externalSlackParticipants(): Promise<boolean>;
internalMemberOverrides(): Promise<string[]>;
@@ -154,6 +156,7 @@ type AckPickInput = {
export type { SurfaceContextRequest };
export interface SlackCoreClientDeps {
+ keychainApprovals?: KeychainApprovals;
taskAcknowledgements?: DurableMap<TaskAckState>;
app: App;
config: ScopedConfigStore;
@@ -228,6 +231,7 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
});
return {
+ ...(deps.keychainApprovals ? { keychainApprovals: deps.keychainApprovals } : {}),
...(deps.taskAcknowledgements
? { taskAcknowledgements: createTaskAcknowledgements(deps.taskAcknowledgements, lease, deps) }
: {}),
diff --git a/src/credentials/keychain-approval.ts b/src/credentials/keychain-approval.ts
new file mode 100644
index 000000000..e00848188
--- /dev/null
+++ b/src/credentials/keychain-approval.ts
@@ -0,0 +1,120 @@
+import { KeychainError, type Keychain, type KeychainAsk, type KeychainGrant } from "./keychain.ts";
+import type { App } from "../api/app.ts";
+import type { IdentityService } from "../identity/identity-service.ts";
+import type { SessionStore } from "../sessions/session-store.ts";
+import type { AuditLog } from "../audit/audit-log.ts";
+import type { ActorAssertion } from "../types.ts";
+import { samePerson } from "../directory/person.ts";
+import { swallow } from "../util/errors.ts";
+
+export interface KeychainApprovalView {
+ ask: KeychainAsk;
+ service: string;
+ accountLabel?: string;
+ conversation: string;
+ sessionId?: string;
+ seq?: number;
+ slack?: { channel: string; ts: string };
+ mode?: "once" | "standing";
+}
+
+export interface KeychainApprovals {
+ get(id: string, ownerId: string): Promise<KeychainApprovalView | null>;
+ decide(id: string, actor: ActorAssertion, decision: "once" | "standing" | "deny"): Promise<KeychainApprovalView>;
+}
+
+export function createKeychainApprovals(deps: {
+ keychain: Keychain;
+ app: Pick<App, "belongsToScope" | "listContexts">;
+ identity: IdentityService;
+ sessions: SessionStore;
+ audit?: AuditLog;
+ resume(ask: KeychainAsk, grant?: KeychainGrant): Promise<unknown>;
+}): KeychainApprovals {
+ const { keychain, app, identity, sessions } = deps;
+ async function get(id: string, ownerId: string): Promise<KeychainApprovalView | null> {
+ const ask = await keychain.getAsk(id);
+ if (!ask || !samePerson(ask.ownerId, ownerId)) return null;
+ const credential = await keychain.getCredential(ask.credentialId);
+ if (!credential) return null;
+ const context = (await app.listContexts(ownerId)).find((c) => c.scopeId === ask.requesterScopeId);
+ let session = ask.requesterThreadRef ? await sessions.getByThread(ask.requesterThreadRef) : null;
+ const seen = new Set<string>();
+ while (session?.parentSessionId && !seen.has(session.id)) {
+ seen.add(session.id);
+ const parent = await sessions.getForParticipant(session.parentSessionId, ownerId);
+ if (!parent || parent.scopeId !== ask.requesterScopeId) break;
+ session = parent;
+ }
+ const visible = session && (await sessions.getForParticipant(session.id, ownerId));
+ const slack =
+ session && (await app.belongsToScope(ownerId, ask.requesterScopeId))
+ ? /^(?:ch|grp|dm):([^:]+)(?::(\d+\.\d+))?$/.exec(session.threadRef)
+ : null;
+ const slackTs =
+ (session?.threadRef === ask.requesterThreadRef ? ask.requesterMessageTs : undefined) ??
+ slack?.[2] ??
+ ask.requesterDestination?.threadTs;
+ const grant = ask.grantId ? await keychain.getGrant(ask.grantId) : null;
+ return {
+ ask,
+ service: credential.service,
+ ...(credential.accountLabel ? { accountLabel: credential.accountLabel } : {}),
+ conversation: context?.name || "the requesting conversation",
+ ...(visible ? { sessionId: visible.id } : {}),
+ ...(ask.requesterSeq !== undefined && visible?.threadRef === ask.requesterThreadRef
+ ? { seq: ask.requesterSeq }
+ : {}),
+ ...(slack && slackTs ? { slack: { channel: slack[1]!, ts: slackTs } } : {}),
+ ...(grant ? { mode: grant.mode } : {}),
+ };
+ }
+ return {
+ get,
+ async decide(id, assertion, decision) {
+ await identity.refresh(true);
+ const actor = identity.resolve(assertion);
+ const current = await get(id, actor.id);
+ if (!identity.isInternal(actor) || !current)
+ throw new KeychainError(403, "Only the credential owner can decide this request.");
+ const { ask } = current;
+ if (ask.status !== "pending") return current;
+ if (
+ !(await app.belongsToScope(actor.id, ask.requesterScopeId)) ||
+ !(await app.belongsToScope(ask.requesterId, ask.requesterScopeId))
+ ) {
+ throw new KeychainError(403, "The owner and requester must still have access to the requesting conversation.");
+ }
+ let resolved: KeychainAsk;
+ let grant: KeychainGrant | undefined;
+ try {
+ if (decision === "deny")
+ resolved = await keychain.declineAsk({ askId: id, ownerId: actor.id, note: "Denied in Slack" });
+ else
+ ({ ask: resolved, grant } = await keychain.approveAsk({
+ askId: id,
+ ownerId: actor.id,
+ mode: decision,
+ purpose: `${decision === "once" ? "Allow once" : "Allow always"}: ${ask.purpose}`,
+ }));
+ } catch (error) {
+ if (!(error instanceof KeychainError) || error.status !== 410) throw error;
+ const latest = await get(id, actor.id);
+ if (!latest || latest.ask.status === "pending") throw error;
+ return latest;
+ }
+ deps.audit?.record({
+ at: Date.now(),
+ principalId: actor.id,
+ action: decision === "deny" ? "keychain.ask.decline" : `keychain.grant.${decision}`,
+ resource: `${id} (${ask.credentialId}→${ask.requesterScopeId})`,
+ scopeLabel: ask.requesterScopeId,
+ });
+ void deps
+ .resume(resolved, grant)
+ .then(() => keychain.markAskNotified(id, resolved.status))
+ .catch((error) => swallow("keychain: native approval resume (sweep will retry)", error));
+ return { ...current, ask: resolved, ...(grant ? { mode: grant.mode } : {}) };
+ },
+ };
+}
diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.ts
index 4d56a4130..4e8254c47 100644
--- a/src/credentials/keychain.ts
+++ b/src/credentials/keychain.ts
@@ -1,3 +1,4 @@
+import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
import { orgId as configOrgId } from "../config.ts";
import { randomBytes } from "node:crypto";
import { scopeId as toScopeId, parseScopeId, type Destination, type ScopeId } from "../types.ts";
@@ -138,6 +139,8 @@ export interface KeychainAsk {
requesterScopeId: ScopeId;
requesterDestination?: Destination;
requesterThreadRef?: string;
+ requesterSeq?: number;
+ requesterMessageTs?: string;
purpose: string;
requestedMode?: GrantMode;
status: AskStatus;
@@ -317,6 +320,8 @@ interface CreateAskInput {
requesterScopeId: ScopeId;
requesterDestination?: Destination;
requesterThreadRef?: string;
+ requesterSeq?: number;
+ requesterMessageTs?: string;
purpose: string;
requestedMode?: GrantMode;
expiresAt?: number;
@@ -409,7 +414,7 @@ export interface Keychain extends ServiceCredentialStore, ConnectorTokenStore {
approveAsk(input: ApproveAskInput): Promise<{ ask: KeychainAsk; grant: KeychainGrant }>;
declineAsk(input: { askId: string; ownerId: string; note?: string }): Promise<KeychainAsk>;
unnotifiedResolvedAsks(now: number): Promise<KeychainAsk[]>;
- markAskNotified(id: string): Promise<void>;
+ markAskNotified(id: string, status: KeychainAsk["status"]): Promise<void>;
resolveAsksForGrant(grant: KeychainGrant): Promise<KeychainAsk[]>;
materialize(grantId: string, scopeId: ScopeId, usedBy: string): Promise<MaterializedCred>;
@@ -498,12 +503,14 @@ export function createKeychain(deps: {
grants: DurableMap<KeychainGrant>;
asks: DurableMap<KeychainAsk>;
key: SecretKey;
+ lock?: AdvisoryLock;
refreshConnector?: OAuthRefresh;
oauthSkewMs?: number;
oauthRefreshMarginMs?: number;
now?: () => number;
}): Keychain {
const now = deps.now ?? Date.now;
+ const lock = deps.lock ?? createMemoryAdvisoryLock();
const oauthSkew = deps.oauthSkewMs ?? 60_000;
const oauthRefreshMargin = Math.max(deps.oauthRefreshMarginMs ?? 10 * 60_000, oauthSkew);
@@ -567,10 +574,27 @@ export function createKeychain(deps: {
}
async function freshAsk(rec: KeychainAsk, t: number): Promise<KeychainAsk> {
+ if (rec.status !== "pending" && rec.status !== "expired") return rec;
+ const grant = await deps.grants.get(hashId([rec.credentialId, "ask", rec.id]));
+ if (grant?.askId === rec.id) {
+ if (!deps.asks.update) throw new KeychainError(503, "ask store does not support atomic resolution");
+ return (
+ (await deps.asks.update(rec.id, (current) =>
+ current.status === "pending" || current.status === "expired"
+ ? { ...current, status: "approved", resolvedAt: grant.createdAt, grantId: grant.id, notifiedAt: undefined }
+ : current,
+ )) ?? rec
+ );
+ }
if (rec.status !== "pending" || rec.expiresAt >= t) return rec;
- const patch = { status: "expired" as const, resolvedAt: t };
- await deps.asks.merge(rec.id, patch);
- return { ...rec, ...patch };
+ if (!deps.asks.update) throw new KeychainError(503, "ask store does not support atomic expiry");
+ return (
+ (await deps.asks.update(rec.id, (current) =>
+ current.status === "pending" && current.expiresAt < t
+ ? { ...current, status: "expired", resolvedAt: t }
+ : current,
+ )) ?? rec
+ );
}
const brokerId = (orgScopeId: string, slug: string) => credId(orgScopeId, slug, "broker");
@@ -964,7 +988,9 @@ export function createKeychain(deps: {
const t = now();
if (!cred.managed && credExpired(cred, t)) throw new KeychainError(410, "credential is expired");
const grant: KeychainGrant = {
- id: hashId([cred.id, input.audienceScopeId, String(t), purpose]),
+ id: input.askId
+ ? hashId([cred.id, "ask", input.askId])
+ : hashId([cred.id, input.audienceScopeId, String(t), purpose]),
credentialId: cred.id,
ownerId: cred.ownerId,
orgId: cred.orgId,
@@ -976,6 +1002,7 @@ export function createKeychain(deps: {
...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
...(input.askId ? { askId: input.askId } : {}),
};
+ if (input.askId) return deps.grants.putIfAbsent(grant.id, grant);
await deps.grants.put(grant.id, grant);
return grant;
}
@@ -1131,6 +1158,8 @@ export function createKeychain(deps: {
requesterScopeId: input.requesterScopeId,
...(input.requesterDestination ? { requesterDestination: input.requesterDestination } : {}),
...(input.requesterThreadRef ? { requesterThreadRef: input.requesterThreadRef } : {}),
+ ...(input.requesterSeq !== undefined ? { requesterSeq: input.requesterSeq } : {}),
+ ...(input.requesterMessageTs ? { requesterMessageTs: input.requesterMessageTs } : {}),
purpose,
...(input.requestedMode ? { requestedMode: input.requestedMode } : {}),
status: "pending",
@@ -1160,37 +1189,41 @@ export function createKeychain(deps: {
},
async approveAsk(input) {
- const rec = await deps.asks.get(input.askId);
- if (!rec) throw new KeychainError(404, "unknown ask");
- const t = now();
- const ask = await freshAsk(rec, t);
- if (ask.status !== "pending") throw new KeychainError(410, `ask already ${ask.status}`);
- const grant = await mintGrant({
- credentialId: ask.credentialId,
- ownerId: input.ownerId,
- audienceScopeId: ask.requesterScopeId,
- mode: input.mode,
- purpose: input.purpose,
- ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
- askId: ask.id,
+ return lock.withLock(`keychain-ask:${input.askId}`, async () => {
+ const rec = await deps.asks.get(input.askId);
+ if (!rec) throw new KeychainError(404, "unknown ask");
+ const t = now();
+ const ask = await freshAsk(rec, t);
+ if (ask.status !== "pending") throw new KeychainError(410, `ask already ${ask.status}`);
+ const grant = await mintGrant({
+ credentialId: ask.credentialId,
+ ownerId: input.ownerId,
+ audienceScopeId: ask.requesterScopeId,
+ mode: input.mode,
+ purpose: input.purpose,
+ ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
+ askId: ask.id,
+ });
+ const patch = { status: "approved" as const, resolvedAt: t, grantId: grant.id, notifiedAt: undefined };
+ await deps.asks.merge(ask.id, patch);
+ return { ask: { ...ask, ...patch }, grant };
});
- const patch = { status: "approved" as const, resolvedAt: t, grantId: grant.id };
- await deps.asks.merge(ask.id, patch);
- return { ask: { ...ask, ...patch }, grant };
},
async declineAsk(input) {
- const rec = await deps.asks.get(input.askId);
- if (!rec) throw new KeychainError(404, "unknown ask");
- if (!samePerson(rec.ownerId, input.ownerId))
- throw new KeychainError(403, "only the credential's owner can decline an ask");
- const t = now();
- const ask = await freshAsk(rec, t);
- if (ask.status !== "pending") throw new KeychainError(410, `ask already ${ask.status}`);
- const note = input.note?.trim();
- const patch = { status: "declined" as const, resolvedAt: t, ...(note ? { note } : {}) };
- await deps.asks.merge(ask.id, patch);
- return { ...ask, ...patch };
+ return lock.withLock(`keychain-ask:${input.askId}`, async () => {
+ const rec = await deps.asks.get(input.askId);
+ if (!rec) throw new KeychainError(404, "unknown ask");
+ if (!samePerson(rec.ownerId, input.ownerId))
+ throw new KeychainError(403, "only the credential's owner can decline an ask");
+ const t = now();
+ const ask = await freshAsk(rec, t);
+ if (ask.status !== "pending") throw new KeychainError(410, `ask already ${ask.status}`);
+ const note = input.note?.trim();
+ const patch = { status: "declined" as const, resolvedAt: t, ...(note ? { note } : {}) };
+ await deps.asks.merge(ask.id, patch);
+ return { ...ask, ...patch };
+ });
},
async unnotifiedResolvedAsks(nowAt) {
@@ -1210,25 +1243,32 @@ export function createKeychain(deps: {
return out;
},
- async markAskNotified(id) {
- await deps.asks.merge(id, { notifiedAt: now() });
+ async markAskNotified(id, status) {
+ if (!deps.asks.update) throw new KeychainError(503, "ask store does not support atomic notification");
+ await deps.asks.update(id, (current) =>
+ current.status === status ? { ...current, notifiedAt: now() } : current,
+ );
},
async resolveAsksForGrant(grant) {
const t = now();
const adopted: KeychainAsk[] = [];
for (const rec of await deps.asks.all()) {
- const a = await freshAsk(rec, t);
- if (
- a.status !== "pending" ||
- a.credentialId !== grant.credentialId ||
- a.requesterScopeId !== grant.audienceScopeId
- )
- continue;
- const patch = { status: "approved" as const, resolvedAt: t, grantId: grant.id, notifiedAt: t };
- await deps.asks.merge(a.id, patch);
- await deps.grants.merge(grant.id, { askId: a.id });
- adopted.push({ ...a, ...patch });
+ await lock.withLock(`keychain-ask:${rec.id}`, async () => {
+ const current = await deps.asks.get(rec.id);
+ if (!current) return;
+ const a = await freshAsk(current, t);
+ if (
+ a.status !== "pending" ||
+ a.credentialId !== grant.credentialId ||
+ a.requesterScopeId !== grant.audienceScopeId
+ )
+ return;
+ const patch = { status: "approved" as const, resolvedAt: t, grantId: grant.id, notifiedAt: t };
+ await deps.asks.merge(a.id, patch);
+ await deps.grants.merge(grant.id, { askId: a.id });
+ adopted.push({ ...a, ...patch });
+ });
}
return adopted;
},
diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.ts
index cc617b617..8389c1614 100644
--- a/src/slack/deliveries.ts
+++ b/src/slack/deliveries.ts
@@ -1,3 +1,4 @@
+import { keychainApprovalMessage, keychainApprovalOrigin } from "./keychain-approvals.ts";
import { errMessage, swallow, swallowAs } from "../util/errors.ts";
import { performance } from "node:perf_hooks";
import {
@@ -361,14 +362,23 @@ export function createDeliveryPoller(deps: {
post: async () => {
const tPost = performance.now();
try {
- const text = toSlackMrkdwn(stripReactionDirectives(d.text));
+ const approval =
+ d.destination.keychainAskId && core.keychainApprovals
+ ? await core.keychainApprovals.get(d.destination.keychainAskId, d.destination.target)
+ : null;
+ const card = approval
+ ? keychainApprovalMessage(approval, await keychainApprovalOrigin(approval, client, deps.webUiPublicUrl))
+ : null;
+ const text = card?.text ?? toSlackMrkdwn(stripReactionDirectives(d.text));
if (!text.trim() && !d.attachments?.length) return undefined;
const channel = await openConversationFor(client, [d.destination.target]);
const threadTs = d.destination.threadTs;
const footer = deliveryFooter(d);
- const blocks = footer.length
- ? [...(text.trim() ? slackSectionBlocks(text) : []), { type: "context", elements: footer }]
- : undefined;
+ const blocks =
+ card?.blocks ??
+ (footer.length
+ ? [...(text.trim() ? slackSectionBlocks(text) : []), { type: "context", elements: footer }]
+ : undefined);
let uploadError: unknown;
let reused = false;
if (text.trim() || blocks) {
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 87d01680f..80d18a897 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -1,3 +1,4 @@
+import { registerKeychainApprovalActions } from "./keychain-approvals.ts";
import { SlackPluginStartCleanupError } from "../surfaces/slack-runtime.ts";
import { createSlackRateLimitNotice } from "./rate-limit-notice.ts";
import { createSlackHistoryReader } from "./history.ts";
@@ -252,6 +253,7 @@ export async function startSlackPlugin(
...(cfg.recentMessages ? { recentMessages: cfg.recentMessages } : {}),
});
const approvals = createApprovals({ core, flow, directory, threads, ids });
+ registerKeychainApprovalActions(app, { core, directory, webUiPublicUrl: cfg.webUiPublicUrl });
const ensureHeader = createSurfaceHeaderEnsurer({
headerFacts: (scope) => core.surfaceHeaderFacts(scope as Parameters<typeof core.surfaceHeaderFacts>[0]),
channelPinEnabled: (scope) =>
diff --git a/src/slack/keychain-approvals.ts b/src/slack/keychain-approvals.ts
new file mode 100644
index 000000000..b253f8354
--- /dev/null
+++ b/src/slack/keychain-approvals.ts
@@ -0,0 +1,122 @@
+import type { SlackCoreClient } from "../api/slack-core-client.ts";
+import type { KeychainApprovalView } from "../credentials/keychain-approval.ts";
+import type { Directory } from "./directory.ts";
+import { parseBlockAction, parseInteractionBody } from "./payloads.ts";
+import { updateSlackMessage } from "./messaging.ts";
+import { errMessage, swallowAs } from "../util/errors.ts";
+
+const ACTIONS = ["keychain_allow_once", "keychain_allow_always", "keychain_deny"] as const;
+const escape = (text: string): string => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
+
+export function keychainApprovalMessage(
+ view: KeychainApprovalView,
+ originUrl?: string,
+): { text: string; blocks: Array<Record<string, unknown>> } {
+ const { ask } = view;
+ const place = `in ${escape(view.conversation).replaceAll("|", "&#124;")}`;
+ const origin =
+ originUrl && /^https?:\/\//.test(originUrl)
+ ? `<${originUrl.replaceAll("|", "%7C").replaceAll(">", "%3E")}|${place}>`
+ : place;
+ const summary = `Use your *${escape(view.service.slice(0, 150))}* credential ${origin}.`;
+ const pending = ask.status === "pending";
+ let status = "This request expired.";
+ if (ask.status === "approved")
+ status = `Approved — ${view.mode === "standing" ? "ongoing access for this conversation" : "one-time access"}.`;
+ if (ask.status === "declined") status = "Denied.";
+ const text = pending
+ ? `Approval needed: use your ${view.service} credential in ${view.conversation}. ${ask.purpose}`
+ : status;
+ const blocks: Array<Record<string, unknown>> = [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `${pending ? ":lock: *Approval needed.*" : `*${status}*`}\n${summary}\n*Why:* ${escape(ask.purpose.slice(0, 900))}`,
+ },
+ },
+ ];
+ if (pending) {
+ blocks.push({
+ type: "context",
+ elements: [
+ {
+ type: "plain_text",
+ text: "Allow once permits one credential use. Allow always permits future use in this conversation until revoked.",
+ },
+ ],
+ });
+ blocks.push({
+ type: "actions",
+ block_id: `keychain_ask:${ask.id}`,
+ elements: [
+ {
+ type: "button",
+ text: { type: "plain_text", text: "Allow once" },
+ action_id: ACTIONS[0],
+ value: ask.id,
+ style: "primary",
+ },
+ { type: "button", text: { type: "plain_text", text: "Allow always" }, action_id: ACTIONS[1], value: ask.id },
+ {
+ type: "button",
+ text: { type: "plain_text", text: "Deny" },
+ action_id: ACTIONS[2],
+ value: ask.id,
+ style: "danger",
+ },
+ ],
+ });
+ }
+ return { text, blocks };
+}
+
+export async function keychainApprovalOrigin(
+ view: KeychainApprovalView,
+ client: any,
+ webUrl?: string,
+): Promise<string | undefined> {
+ if (view.slack) {
+ const result = await client.chat
+ .getPermalink({ channel: view.slack.channel, message_ts: view.slack.ts })
+ .catch(swallowAs("slack: approval origin link", null));
+ if (typeof result?.permalink === "string") return result.permalink;
+ }
+ if (!webUrl || !view.sessionId) return undefined;
+ const url = new URL(`${webUrl.replace(/\/+$/, "")}/s/${encodeURIComponent(view.sessionId)}`);
+ if (view.seq !== undefined) url.searchParams.set("seq", String(view.seq));
+ return url.toString();
+}
+
+export function registerKeychainApprovalActions(
+ app: { action(pattern: RegExp, handler: (args: any) => Promise<void>): void },
+ deps: { core: SlackCoreClient; directory: Directory; webUiPublicUrl?: string },
+): void {
+ app.action(/^keychain_/, async ({ ack, body, action, client }) => {
+ await ack();
+ const parsed = parseBlockAction(action, ACTIONS);
+ const { clickerId, channel, messageTs } = parseInteractionBody(body);
+ if (!parsed || !clickerId || !channel || !messageTs || !deps.core.keychainApprovals) return;
+ try {
+ const actor = await deps.directory.classifyActor(client, clickerId);
+ const decisions = {
+ keychain_allow_once: "once",
+ keychain_allow_always: "standing",
+ keychain_deny: "deny",
+ } as const;
+ const decision = decisions[parsed.actionId as keyof typeof decisions];
+ const view = await deps.core.keychainApprovals.decide(parsed.value, actor, decision);
+ const origin = await keychainApprovalOrigin(view, client, deps.webUiPublicUrl);
+ const card = keychainApprovalMessage(view, origin);
+ await updateSlackMessage(client, channel, messageTs, card.text, card.blocks);
+ } catch (error) {
+ await client.chat
+ .postEphemeral({
+ channel,
+ user: clickerId,
+ text: `Couldn't complete this approval: ${errMessage(error)} You can try the button again.`,
+ })
+ .catch(swallowAs("slack: credential approval failure", undefined));
+ }
+ });
+}
diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.ts
index 74b0667dd..2341eed5c 100644
--- a/src/triggers/keychain-ask.ts
+++ b/src/triggers/keychain-ask.ts
@@ -184,7 +184,7 @@ export function createAskExpirySweep(deps: {
}
try {
await deps.fire(ask);
- await deps.keychain.markAskNotified(ask.id);
+ await deps.keychain.markAskNotified(ask.id, ask.status);
} catch (e) {
swallow(`keychain: ask sweep fire failed for ${ask.id} (will retry next tick)`, e);
}
diff --git a/src/types.ts b/src/types.ts
index cc4d4299f..2d3fe67e5 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -199,6 +199,7 @@ export interface TriggerBase {
}
export interface Destination {
+ keychainAskId?: string;
type: string;
target: string;
audienceScopeId?: ScopeId;
diff --git a/src/wiring.ts b/src/wiring.ts
index 605100c17..e5723a329 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { createKeychainApprovals } from "./credentials/keychain-approval.ts";
import { flushErrorReporting, startTiming } from "../plugins/chassis/src/error-reporting.ts";
import type { TimingStatus } from "../plugins/chassis/src/timing.ts";
import { createProductAnalytics } from "./util/product-analytics.ts";
@@ -1172,6 +1173,7 @@ export function buildApp(
grants: artifactMap<KeychainGrant>("keychain_grants"),
asks: artifactMap<KeychainAsk>("keychain_asks"),
key: credentialKey,
+ lock: advisoryLock,
refreshConnector: (() => {
const base = makeRefresh({ resolveClient });
// AI subscription logins ride the same connector-refresh machinery:
@@ -2084,6 +2086,18 @@ export function buildApp(
requestFire: (loopId) => void loopFire.fire(loopId, `loop:${loopId}:slack-event:${Date.now()}`).catch(() => {}),
});
const slackCore = createSlackCoreClient({
+ ...(keychain
+ ? {
+ keychainApprovals: createKeychainApprovals({
+ keychain,
+ app,
+ identity,
+ sessions,
+ audit: auditLog,
+ resume: (ask, grant) => askResolution!(ask, grant),
+ }),
+ }
+ : {}),
surfaceCache,
taskAcknowledgements: artifactMap<TaskAckState>("slack_task_acknowledgements"),
inboxEvent: (event) => inboxRealtime.onConversationEvent(event),
diff --git a/test/keychain-approval-card.test.ts b/test/keychain-approval-card.test.ts
new file mode 100644
index 000000000..8f27f08e2
--- /dev/null
+++ b/test/keychain-approval-card.test.ts
@@ -0,0 +1,247 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createKeychain, type KeychainAsk, type KeychainGrant } from "../src/credentials/keychain.ts";
+import { createKeychainApprovals } from "../src/credentials/keychain-approval.ts";
+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { createIdentityService } from "../src/identity/identity-service.ts";
+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
+import {
+ keychainApprovalMessage,
+ keychainApprovalOrigin,
+ registerKeychainApprovalActions,
+} from "../src/slack/keychain-approvals.ts";
+import type { App } from "../src/api/app.ts";
+import type { Directory } from "../src/slack/directory.ts";
+import type { SlackCoreClient } from "../src/api/slack-core-client.ts";
+
+async function fixture() {
+ let now = Date.now();
+ let member = true;
+ const grants = createMemoryMap<KeychainGrant>();
+ const asks = createMemoryMap<KeychainAsk>();
+ const keychain = createKeychain({
+ creds: createMemoryMap(),
+ grants,
+ asks,
+ key: deriveConnectorKey("native-approval-test"),
+ now: () => now,
+ });
+ const credential = await keychain.save({ ownerId: "[email protected]", service: "aws", secret: "fixture-secret" });
+ const sessions = createMemorySessionStore();
+ const session = await sessions.getOrCreateByThread("web:alice:fixture", "dm", "personal:[email protected]");
+ await sessions.addParticipant(session.id, "[email protected]");
+ const { ask } = await keychain.createAsk({
+ credentialId: credential.id,
+ requesterId: "[email protected]",
+ requesterScopeId: "personal:[email protected]",
+ requesterThreadRef: session.threadRef,
+ requesterSeq: 120,
+ requestedMode: "standing",
+ purpose: "Read the nightly report",
+ });
+ const resumed: string[] = [];
+ const app = {
+ belongsToScope: async () => member,
+ listContexts: async () => [{ scopeId: ask.requesterScopeId, name: "the Reports conversation" }],
+ } as unknown as Pick<App, "belongsToScope" | "listContexts">;
+ const identity = createIdentityService();
+ const approvals = createKeychainApprovals({
+ keychain,
+ app,
+ sessions,
+ identity,
+ resume: async (resolved) => {
+ resumed.push(resolved.id);
+ },
+ });
+ return {
+ keychain,
+ grants,
+ asks,
+ ask,
+ session,
+ approvals,
+ resumed,
+ revokeMembership: () => {
+ member = false;
+ },
+ expire: () => {
+ now += 25 * 3600_000;
+ },
+ };
+}
+
+test("native approval persists the explicit duration, resumes once, and replays without minting another grant", async () => {
+ const f = await fixture();
+ const outcomes = await Promise.all(
+ ["standing", "standing", "deny"].map((decision) =>
+ f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, decision as "standing" | "deny"),
+ ),
+ );
+ assert.ok(outcomes.every((view) => view.ask.status === "approved"));
+ assert.equal((await f.keychain.getAsk(f.ask.id))?.status, "approved");
+ const grants = await f.grants.all();
+ assert.equal(grants.length, 1);
+ assert.equal(grants[0]!.mode, "standing");
+ assert.equal(grants[0]!.audienceScopeId, f.ask.requesterScopeId);
+ assert.equal(f.resumed.length, 1);
+ assert.equal(outcomes[0]!.seq, 120);
+});
+
+test("one-time and denial decisions keep their exact meaning", async () => {
+ for (const decision of ["once", "deny"] as const) {
+ const f = await fixture();
+ const view = await f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, decision);
+ assert.equal(view.ask.status, decision === "deny" ? "declined" : "approved");
+ assert.equal((await f.grants.all()).length, decision === "deny" ? 0 : 1);
+ if (decision === "once") assert.equal(view.mode, "once");
+ }
+});
+
+test("wrong owner, revoked membership, and expired requests never grant access", async () => {
+ const f = await fixture();
+ await assert.rejects(
+ f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, "standing"),
+ /Only the credential owner/,
+ );
+ f.revokeMembership();
+ await assert.rejects(
+ f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, "standing"),
+ /still have access/,
+ );
+ const expired = await fixture();
+ expired.expire();
+ assert.equal(
+ (await expired.approvals.decide(expired.ask.id, { externalId: "[email protected]" }, "standing")).ask.status,
+ "expired",
+ );
+ assert.equal((await f.grants.all()).length, 0);
+ assert.equal((await expired.grants.all()).length, 0);
+});
+
+test("the card links the conversation inline and omits command-policy fields", async () => {
+ const f = await fixture();
+ const view = (await f.approvals.get(f.ask.id, "[email protected]"))!;
+ const origin = await keychainApprovalOrigin(view, {}, "https://qm.example/web-ui");
+ assert.equal(origin, `https://qm.example/web-ui/s/${f.session.id}?seq=120`);
+ const card = keychainApprovalMessage(view, origin);
+ const wire = JSON.stringify(card);
+ assert.match(wire, /\|in the Reports conversation>/);
+ assert.doesNotMatch(wire, /Command:|Flagged as:|Allow session|fixture-secret/);
+ assert.match(wire, /Allow once/);
+ assert.match(wire, /Allow always/);
+ assert.match(wire, /Deny/);
+ const settled = keychainApprovalMessage(
+ { ...view, ask: { ...view.ask, status: "approved" }, mode: "standing" },
+ origin,
+ );
+ assert.doesNotMatch(JSON.stringify(settled), /action_id/);
+ assert.match(settled.text, /ongoing access/);
+});
+
+test("Slack action records the authenticated clicker before displaying success", async () => {
+ const f = await fixture();
+ let handler: (args: any) => Promise<void> = async () => {};
+ const updates: unknown[] = [];
+ registerKeychainApprovalActions(
+ {
+ action: (_pattern, fn) => {
+ handler = fn;
+ },
+ },
+ {
+ core: { keychainApprovals: f.approvals } as SlackCoreClient,
+ directory: {
+ classifyActor: async (_client, id) => ({
+ externalId: id === "UOWNER" ? "[email protected]" : "[email protected]",
+ }),
+ } as Directory,
+ },
+ );
+ const errors: unknown[] = [];
+ const client = {
+ chat: {
+ update: async (body: any) => {
+ assert.equal((await f.keychain.getAsk(f.ask.id))?.status, "approved");
+ updates.push(body);
+ },
+ postEphemeral: async (body: unknown) => {
+ errors.push(body);
+ },
+ },
+ };
+ const args = {
+ ack: async () => {},
+ body: { user: { id: "UOTHER" }, channel: { id: "D1" }, message: { ts: "1.2" } },
+ action: { action_id: "keychain_allow_always", value: f.ask.id },
+ client,
+ };
+ await handler(args);
+ assert.equal(updates.length, 0);
+ assert.equal(errors.length, 1);
+ await handler({ ...args, body: { ...args.body, user: { id: "UOWNER" } } });
+ assert.equal(updates.length, 1);
+});
+
+test("a crash after grant persistence recovers approval before denial or expiry", async () => {
+ for (const expire of [false, true]) {
+ const f = await fixture();
+ const merge = f.asks.merge.bind(f.asks);
+ let fail = true;
+ f.asks.merge = async (id, patch) => {
+ if (fail && patch.status === "approved") {
+ fail = false;
+ throw new Error("injected persistence failure");
+ }
+ return merge(id, patch);
+ };
+ await assert.rejects(f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, "standing"), /injected/);
+ if (expire) f.expire();
+ const replay = await f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, "deny");
+ assert.equal(replay.ask.status, "approved");
+ assert.equal(replay.mode, "standing");
+ assert.equal((await f.grants.all()).length, 1);
+ assert.equal((await f.keychain.unnotifiedResolvedAsks(Date.now())).length, 1);
+ }
+});
+
+test("an expired notification cannot hide an approval recovered after a failed write", async () => {
+ for (const notifyBeforeRecovery of [true, false]) {
+ const f = await fixture();
+ const put = f.grants.putIfAbsent.bind(f.grants);
+ let release!: () => void;
+ let entered!: () => void;
+ const started = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const paused = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ f.grants.putIfAbsent = async (id, grant) => {
+ entered();
+ await paused;
+ return put(id, grant);
+ };
+ const merge = f.asks.merge.bind(f.asks);
+ f.asks.merge = async (id, patch) => {
+ if (patch.status === "approved") throw new Error("injected persistence failure");
+ return merge(id, patch);
+ };
+ const approving = assert.rejects(
+ f.approvals.decide(f.ask.id, { externalId: "[email protected]" }, "standing"),
+ /injected/,
+ );
+ await started;
+ f.expire();
+ assert.equal((await f.keychain.getAsk(f.ask.id))?.status, "expired");
+ if (notifyBeforeRecovery) await f.keychain.markAskNotified(f.ask.id, "expired");
+ release();
+ await approving;
+ assert.equal((await f.keychain.getAsk(f.ask.id))?.status, "approved");
+ if (!notifyBeforeRecovery) await f.keychain.markAskNotified(f.ask.id, "expired");
+ assert.equal((await f.keychain.unnotifiedResolvedAsks(Date.now())).length, 1);
+ await f.keychain.markAskNotified(f.ask.id, "approved");
+ assert.equal((await f.keychain.unnotifiedResolvedAsks(Date.now())).length, 0);
+ }
+});
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index 4d3f1224a..a76b2250d 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -273,7 +273,7 @@ test("expiry: lazy flip on read, sweep returns each expired ask exactly once", a
[ask.id],
"still returned until the resolution actually fired",
);
- await k.markAskNotified(ask.id);
+ await k.markAskNotified(ask.id, "expired");
assert.deepEqual(await k.unnotifiedResolvedAsks(t), []);
});