Compare commits

..
2 Commits
Author SHA1 Message Date
tben ca070ccc35 v0.21.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 17:36:23 +01:00
tben 3268f049f9 Retry a ref chip's read, so its steps and card show without a reload
A failed or hung read was kept as a miss for the life of the page, so a [suggestion:ID] or [question:ID] pushed with a run showed 'not available', or nothing at all, until the page was reloaded. One loader now keeps only what was read, aborts a read that hangs, and tries again.
2026-11-15 17:36:23 +01:00
11 changed files with 305 additions and 175 deletions
+1 -1
View File
@@ -95,7 +95,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.21.3",
"version": "0.21.4",
"module": "index.ts",
"type": "module",
"private": true,
+12
View File
@@ -832,6 +832,18 @@ export const AppData = {
* How many of a session's latest messages that check reads.
*/
BotReplyCatchUpMessages: 20,
/**
* How long one read of a chip's view (the next steps a bot suggested,
* the questions it asked) may hang before it is dropped and asked
* again: a chip read as its message was pushed, on a phone waking up,
* once said "(not available)" until the page was reloaded.
*/
BotRefViewTimeoutMs: 8000,
/**
* How long to wait between those reads, one more read after each, so
* a ref named before its row was written heals itself in seconds.
*/
BotRefViewRetryDelaysMs: [800, 2500],
/**
* A window regaining focus and its tab becoming visible are often one
* return, and each may fire more than once: a second signal this soon
@@ -1,39 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { BotQuestionView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
question_id: number;
};
/**
* Questions already read, by id, so a thread naming them twice asks once.
* An answer replaces their entry.
*/
const loaded = new Map<number, Promise<BotQuestionView | null>>();
function loadQuestion({ question_id }: Params) {
const cached = loaded.get(question_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<BotQuestionView>>(
`/api/admin/bot-questions/get-question?question_id=${question_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(question_id, pending);
return pending;
}
/**
* Questions a bot asked (`[question:ID]`), for their chip and card: read
* when the chip renders, so it shows whether they're still waiting. Only
* the user they were asked of can read them; anyone else gets null.
* the user they were asked of can read them; anyone else gets null. A
* read that failed or hung is tried again (`loadRefView`) instead of
* leaving the card unopenable until the page is reloaded.
*/
export default function useBotQuestion({ question_id }: Params) {
const [view, setViewState] = useState<BotQuestionView | null>(null);
@@ -42,7 +20,12 @@ export default function useBotQuestion({ question_id }: Params) {
useEffect(() => {
let live = true;
loadQuestion({ question_id }).then((result) => {
setLoading(true);
loadRefView<BotQuestionView>({
key: `question:${question_id}`,
url: `/api/admin/bot-questions/get-question?question_id=${question_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -53,13 +36,17 @@ export default function useBotQuestion({ question_id }: Params) {
};
}, [question_id]);
/**
* The card's own answers replace what was read, so its chip says they
* were answered without asking the app again.
*/
const setView = useCallback(
(next: BotQuestionView) => {
loaded.set(question_id, Promise.resolve(next));
primeRefView({ key: `question:${question_id}`, view: next });
setViewState(next);
},
[question_id],
);
return { view, loading, setView };
}
}
@@ -1,38 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useEffect, useState } from "react";
import type { BotSuggestionView } from "@/src/types";
import loadRefView from "../(utils)/ref-view-loader";
type Params = {
suggestion_id: number;
};
/**
* Next steps already read, by id, so a thread naming them twice asks once.
*/
const loaded = new Map<number, Promise<BotSuggestionView | null>>();
function loadSuggestion({ suggestion_id }: Params) {
const cached = loaded.get(suggestion_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<BotSuggestionView>>(
`/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(suggestion_id, pending);
return pending;
}
/**
* Next steps a bot suggested (`[suggestion:ID]`): read when their buttons
* render. Only the user they were suggested to can read them; anyone else
* gets null.
* gets null. A read that failed or hung is tried again before the buttons
* give up on it (`loadRefView`), so a missed push or a sleeping phone no
* longer needs the page reloaded.
*/
export default function useBotSuggestion({ suggestion_id }: Params) {
const [view, setView] = useState<BotSuggestionView | null>(null);
@@ -41,7 +20,12 @@ export default function useBotSuggestion({ suggestion_id }: Params) {
useEffect(() => {
let live = true;
loadSuggestion({ suggestion_id }).then((result) => {
setLoading(true);
loadRefView<BotSuggestionView>({
key: `suggestion:${suggestion_id}`,
url: `/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
}).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
@@ -1,40 +1,18 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { ExtensionProposalView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
proposal_id: number;
};
/**
* Proposals already read, by id, so a thread naming one twice (or a
* re-render) asks once. A decision replaces its entry.
*/
const loaded = new Map<number, Promise<ExtensionProposalView | null>>();
function loadProposal({ proposal_id }: Params) {
const cached = loaded.get(proposal_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<ExtensionProposalView>>(
`/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(proposal_id, pending);
return pending;
}
/**
* An MCP server or tool the coordinator proposed (`[proposal:ID]`), for
* its chip and confirm card: read when the chip renders, so it shows
* whether it's still waiting. Only the super admin it was proposed to can
* read it; anyone else gets null.
* An extension a bot proposed (`[proposal:ID]`), for its chip and confirm
* card: read when the chip renders, so it shows whether it's still
* waiting. Only the super admin it was proposed to can read it; anyone
* else gets null. A read that failed or hung is tried again
* (`loadRefView`), so the card isn't unopenable until the page is
* reloaded.
*/
export default function useExtensionProposal({ proposal_id }: Params) {
const [view, setViewState] = useState<ExtensionProposalView | null>(null);
@@ -43,7 +21,12 @@ export default function useExtensionProposal({ proposal_id }: Params) {
useEffect(() => {
let live = true;
loadProposal({ proposal_id }).then((result) => {
setLoading(true);
loadRefView<ExtensionProposalView>({
key: `extension-proposal:${proposal_id}`,
url: `/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -56,11 +39,11 @@ export default function useExtensionProposal({ proposal_id }: Params) {
const setView = useCallback(
(next: ExtensionProposalView) => {
loaded.set(proposal_id, Promise.resolve(next));
primeRefView({ key: `extension-proposal:${proposal_id}`, view: next });
setViewState(next);
},
[proposal_id],
);
return { view, loading, setView };
}
}
@@ -1,40 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { HookProposalView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
proposal_id: number;
};
/**
* Hook proposals already read, by id, so a thread naming one twice (or a
* re-render) asks once. A decision replaces its entry.
*/
const loaded = new Map<number, Promise<HookProposalView | null>>();
function loadProposal({ proposal_id }: Params) {
const cached = loaded.get(proposal_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<HookProposalView>>(
`/api/admin/hook-proposals/get-proposal?proposal_id=${proposal_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(proposal_id, pending);
return pending;
}
/**
* A hook a bot proposed (`[hook-proposal:ID]`), for its chip and confirm
* card: read when the chip renders, so it shows whether it's still
* waiting. Only the user it was proposed to can read it; anyone else gets
* null.
* null. A read that failed or hung is tried again (`loadRefView`), so the
* card isn't unopenable until the page is reloaded.
*/
export default function useHookProposal({ proposal_id }: Params) {
const [view, setViewState] = useState<HookProposalView | null>(null);
@@ -43,7 +20,12 @@ export default function useHookProposal({ proposal_id }: Params) {
useEffect(() => {
let live = true;
loadProposal({ proposal_id }).then((result) => {
setLoading(true);
loadRefView<HookProposalView>({
key: `hook-proposal:${proposal_id}`,
url: `/api/admin/hook-proposals/get-proposal?proposal_id=${proposal_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -56,11 +38,11 @@ export default function useHookProposal({ proposal_id }: Params) {
const setView = useCallback(
(next: HookProposalView) => {
loaded.set(proposal_id, Promise.resolve(next));
primeRefView({ key: `hook-proposal:${proposal_id}`, view: next });
setViewState(next);
},
[proposal_id],
);
return { view, loading, setView };
}
}
@@ -1,37 +1,16 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useEffect, useState } from "react";
import type { SecretRefView } from "@/src/types";
import loadRefView from "../(utils)/ref-view-loader";
type Params = {
env_id: number;
};
/**
* Secret refs already read, by id. Only the key and whether the viewer may
* reveal it: the value is fetched on Reveal or Copy and never cached here.
*/
const loaded = new Map<number, Promise<SecretRefView | null>>();
function loadSecret({ env_id }: Params) {
const cached = loaded.get(env_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<SecretRefView>>(
`/api/admin/secrets/get-secret?env_id=${env_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(env_id, pending);
return pending;
}
/**
* A secret a bot showed (`[secret:ID]`), for its masked chip.
* A secret a bot showed (`[secret:ID]`), for its masked chip. Only the key
* and whether the viewer may reveal it: the value is fetched on Reveal or
* Copy and never read here. A read that failed or hung is tried again
* (`loadRefView`), so the chip isn't left saying nothing until a reload.
*/
export default function useSecretRef({ env_id }: Params) {
const [view, setView] = useState<SecretRefView | null>(null);
@@ -40,7 +19,12 @@ export default function useSecretRef({ env_id }: Params) {
useEffect(() => {
let live = true;
loadSecret({ env_id }).then((result) => {
setLoading(true);
loadRefView<SecretRefView>({
key: `secret:${env_id}`,
url: `/api/admin/secrets/get-secret?env_id=${env_id}`,
}).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
@@ -52,4 +36,4 @@ export default function useSecretRef({ env_id }: Params) {
}, [env_id]);
return { view, loading };
}
}
@@ -1,39 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { SecretRequestView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
request_id: number;
};
/**
* Secret requests already read, by id, so a thread naming one twice asks
* once. An answer replaces its entry.
*/
const loaded = new Map<number, Promise<SecretRequestView | null>>();
function loadRequest({ request_id }: Params) {
const cached = loaded.get(request_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<SecretRequestView>>(
`/api/admin/secret-requests/get-request?request_id=${request_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(request_id, pending);
return pending;
}
/**
* A secret a bot asked for (`[secret-request:ID]`), for its chip and card:
* read when the chip renders, so it shows whether it's still waiting.
* Only the user it was asked of can read it; anyone else gets null.
* Only the user it was asked of can read it; anyone else gets null. A
* read that failed or hung is tried again (`loadRefView`), so the card
* isn't unopenable until the page is reloaded.
*/
export default function useSecretRequest({ request_id }: Params) {
const [view, setViewState] = useState<SecretRequestView | null>(null);
@@ -42,7 +20,12 @@ export default function useSecretRequest({ request_id }: Params) {
useEffect(() => {
let live = true;
loadRequest({ request_id }).then((result) => {
setLoading(true);
loadRefView<SecretRequestView>({
key: `secret-request:${request_id}`,
url: `/api/admin/secret-requests/get-request?request_id=${request_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -55,11 +38,11 @@ export default function useSecretRequest({ request_id }: Params) {
const setView = useCallback(
(next: SecretRequestView) => {
loaded.set(request_id, Promise.resolve(next));
primeRefView({ key: `secret-request:${request_id}`, view: next });
setViewState(next);
},
[request_id],
);
return { view, loading, setView };
}
}
@@ -0,0 +1,103 @@
import { describe, expect, test } from "bun:test";
import loadRefView, { primeRefView } from "./ref-view-loader";
/**
* A read standing in for the app's: one answer per call, in order, and a
* count of how many times it was asked.
*/
function reader({ answers }: { answers: (unknown | null)[] }) {
const asked: string[] = [];
const readOnce = async ({ url }: { url: string }) => {
asked.push(url);
return answers[Math.min(asked.length - 1, answers.length - 1)] ?? null;
};
return { asked, readOnce };
}
describe("loadRefView", () => {
test("reads a view once and keeps it, so a thread naming it twice asks once", async () => {
const { asked, readOnce } = reader({ answers: [{ id: 5, steps: ["One"] }] });
const first = await loadRefView({ key: "test:kept", url: "/get?id=5", readOnce, retryDelaysMs: [] });
const second = await loadRefView({ key: "test:kept", url: "/get?id=5", readOnce, retryDelaysMs: [] });
expect(first).toEqual({ id: 5, steps: ["One"] });
expect(second).toEqual(first);
expect(asked).toEqual(["/get?id=5"]);
});
test("forgets a read that failed, so the next chip asks again instead of showing nothing", async () => {
const { asked, readOnce } = reader({ answers: [null, null, { id: 7 }] });
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toBeNull();
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toBeNull();
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toEqual({
id: 7,
});
expect(asked).toHaveLength(3);
});
test("tries a failed read again before giving up on it", async () => {
const { asked, readOnce } = reader({ answers: [null, { id: 9, steps: ["Two"] }] });
const view = await loadRefView({ key: "test:retried", url: "/get?id=9", readOnce, retryDelaysMs: [0] });
expect(view).toEqual({ id: 9, steps: ["Two"] });
expect(asked).toHaveLength(2);
await loadRefView({ key: "test:retried", url: "/get?id=9", readOnce, retryDelaysMs: [0] });
expect(asked).toHaveLength(2);
});
test("shares one read between callers asking for the same view at once", async () => {
let release: (value: unknown) => void = () => {};
let asked = 0;
const readOnce = () => {
asked += 1;
return new Promise<unknown | null>((resolve) => {
release = resolve;
});
};
const first = loadRefView({ key: "test:shared", url: "/get?id=11", readOnce, retryDelaysMs: [] });
const second = loadRefView({ key: "test:shared", url: "/get?id=11", readOnce, retryDelaysMs: [] });
release({ id: 11 });
expect(await first).toEqual({ id: 11 });
expect(await second).toEqual({ id: 11 });
expect(asked).toBe(1);
});
test("hands back a view the page already has, without asking", async () => {
let asked = 0;
const readOnce = async () => {
asked += 1;
return { id: 13 };
};
primeRefView({ key: "test:primed", view: { id: 13, status: "answered" } });
expect(await loadRefView({ key: "test:primed", url: "/get?id=13", readOnce, retryDelaysMs: [] })).toEqual({
id: 13,
status: "answered",
});
expect(asked).toBe(0);
});
test("reads one view per key, not one per id string", async () => {
const { asked, readOnce } = reader({ answers: [{ id: 15 }, { id: 16 }] });
await loadRefView({ key: "question:15", url: "/get-question?question_id=15", readOnce, retryDelaysMs: [] });
await loadRefView({ key: "suggestion:15", url: "/get-suggestion?suggestion_id=15", readOnce, retryDelaysMs: [] });
expect(asked).toEqual(["/get-question?question_id=15", "/get-suggestion?suggestion_id=15"]);
});
});
@@ -0,0 +1,112 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { AppData } from "@/src/data/app-data";
type RefView = { [k: string]: any };
type Params = {
/**
* What the view is, e.g. `suggestion:12`, so two chips naming the same
* one ask once.
*/
key: string;
url: string;
/**
* How to read it once. The real one asks the app over HTTP.
*/
readOnce?: (params: { url: string }) => Promise<unknown | null>;
/**
* Waits between tries, the last one after the final try; tests pass
* their own.
*/
retryDelaysMs?: readonly number[];
};
/**
* Views already read, by key, so a thread naming one twice asks once, and
* the reads in flight. Only what was read is kept: a read that failed is
* forgotten, so the next chip naming it asks again instead of sitting on
* "(not available)" for the life of the page.
*/
const known = new Map<string, unknown>();
const inFlight = new Map<string, Promise<unknown | null>>();
/**
* Keeps a view the page already has (a question answered in its card, its
* chip now saying so) without asking the app for it again.
*/
export function primeRefView({ key, view }: { key: string; view: unknown }) {
known.set(key, view);
}
/**
* Reads a ref's view (`[suggestion:ID]`, `[question:ID]`, ...), once here
* and over HTTP after. A read that fails or hangs is tried again, since
* the ref can be named before its row is written (a bot writing its own
* id, a page woken from a long sleep mid-request), and the reload that
* used to be the only cure is what this saves the user.
*/
export default async function loadRefView<T extends RefView>({
key,
url,
readOnce = readRefViewOnce,
retryDelaysMs = AppData.BotRefViewRetryDelaysMs,
}: Params): Promise<T | null> {
const cached = known.get(key);
if (cached) return cached as T;
const reading = inFlight.get(key);
if (reading) return reading as Promise<T | null>;
const request = readWithRetries({ url, readOnce, retryDelaysMs })
.then((view) => {
inFlight.delete(key);
if (view) known.set(key, view);
return view as T | null;
})
.catch(() => {
inFlight.delete(key);
return null;
});
inFlight.set(key, request);
return request;
}
async function readWithRetries({ url, readOnce, retryDelaysMs }: Required<Pick<Params, "url" | "readOnce" | "retryDelaysMs">>) {
for (let attempt = 0; ; attempt += 1) {
if (attempt) await sleep({ ms: retryDelaysMs[attempt - 1] || 0 });
const view = await readOnce({ url }).catch(() => null);
if (view || attempt >= retryDelaysMs.length) return view;
}
}
async function readRefViewOnce({ url }: { url: string }): Promise<unknown | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), AppData.BotRefViewTimeoutMs);
try {
const res = await fetchApi<{}, APIResponseObject<RefView>>(url, {
method: "GET",
fetchOptions: { signal: controller.signal },
});
return res?.success && res.singleRes ? res.singleRes : null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
function sleep({ ms }: { ms: number }) {
return new Promise((resolve) => setTimeout(resolve, ms));
}