Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec999cccc3 | ||
|
|
352f11b5d1 |
@@ -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; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `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), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[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.
|
||||
- **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), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[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, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). 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.
|
||||
- **Message images:** a bot message shows the images it's about under its text (`MessageImages` in `(partials)/`, on `BotMessageLine` and `CrewMessageLine`): its image attachments plus every image `[file:ID]` it names (`liveFileRefIds`, which keeps the renderer's code rules), deduped when a named file is also attached (`file_id`). Each is a `MessageAttachment` thumbnail opening the shared `FilePreviewModal`; in a thread its gallery is the whole conversation (`sessionImageGallery` + `SessionGalleryContext` from `MessageThread`): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through `useBotFile`/`useReferencedFiles` (page props first, then the cached `api/admin/bots/files` read shared with `FileRefChip`). A thumbnail URL serves the original when no smaller copy was made (`mediaServeWritePath`), since bot files keep no thumbnail.
|
||||
- **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`, `delete_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 conversation's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next (side arrows at the far middle left/right, the header's stepper, 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.
|
||||
@@ -108,7 +108,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteAskRows`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; a retry whose message carries `failed_job_id` also reads that job's `last_error` (`grabRetryFailure` -> `RetryFailureNote`), so it knows what the failed attempt claimed and never did instead of setting off on the same premise; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **Debug view:** what a run did in order: each turn with what the model reasoned (`stripThinkTags`'s `reasoning`, or the provider's `reasoning`/`reasoning_content`) and answered, each tool call with the arguments it was sent and the answer it got (and its duration), and the loop's own events (`wrap_up`, `redraft`, `review`, `incoming`, `steps_low`). `runTextLoop` emits them through `Params.trace` into `bot_job_traces` (never `bots_queue_updates`, which the `clear-job-steps` cron deletes a minute after a job ends). While a run works, the thinking row's bug button, beside Stop (`BotThinkingRow`), toggles a 250px strip under it (`(partials)/trace-panel.tsx`, `(partials)/trace-log-line.tsx`: one line per step, following its newest line while scrolled to the bottom), read live through `(hooks)/use-bot-trace.ts` and `api/admin/bots/trace`; that toggle stays as the user left it in every conversation (on this device, per user: `useDebugOpen` over `readDebugOpen`/`rememberDebugOpen`, `AppData.DebugViewStorageKey`). When the run ends its logs are tied to the message it answered (`attachJobTracesToMessage`, from the job helpers) and read in that message's Details modal, under a **Debug logs** tab beside Details (`(partials)/message-debug-logs.tsx`, `(hooks)/use-message-trace.ts`, `api/admin/bots/message-trace`), which copies itself as one markdown document (`CopyDebugLogsButton` over `messageDebugLogsMarkdown`), which checks the message's session for the user or a super admin). Every entry is redacted before storage (`insertBotJobTrace` with the run's reachable envs, plus the task run's computer redaction for what the bot captured), cut to `AppData.BotTraceTextMaxChars`/`BotTraceArgumentsMaxChars`/`BotTraceResultMaxChars` (an argument's `path` survives whole, `toolArgumentPath`: a write's path is what a reader needs), at most `BotTraceRowsPerJob` entries per run and `BotTraceJobsPerSession` runs shown, kept for the app setting `bot_trace_keep_days` (default `AppData.BotTraceKeepDays`, daily `prune-bot-traces`). Pushes carry only `BotTraceData` (`job_id`, `session_id`): an open view reads the entries it doesn't have.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
|
||||
@@ -198,7 +198,8 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
|
||||
|
||||
- Files live on the data volume, not on computers: `DATA_DIR/bots/<id>` and `DATA_DIR/workspaces/<id>`. Catalog `bot_files`, bytes in private `media` (`bot-file`) written by `recordBotFile`. Reach via `grabStorageScopes`; paths via `resolveBotPath` (no absolute, `..`, NUL, symlink escape); quota checked by `assertStorageRoom`.
|
||||
- Tools in `src/harness/tools/storage/` (every run). `attach` puts a file on the reply. `grabConversationFiles` must list the **whole** folder tree, or nested `[file:ID]` refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (`api/admin/bots/files?file_id=` with `bot_id` and `workspace_id`).
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked.
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked. A chat reply has it too (`grab-bot-chat-tools`, its computers to choose from), so what a reply made on a computer comes into its files the same way a task's does.
|
||||
- `list_files` with `search` matches names and paths in **every** folder (leaving `folder` out lists every folder too): scoping a search to the root hid `images/summit-hero-pil.png` and made a bot believe its file was never saved. `write_file` refuses a binary extension, since text saved under `.png` reached the user as a file that would not open.
|
||||
- **Only knowledgebases store text.** Bot files and uploads are never indexed and keep no extracted text (`media.text_content` only for knowledgebase documents); bots find files by name or path (`list_files` `search`) and read them with `read_file`, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. `dropStoredFileText` clears what older versions stored, at boot, and vacuums when much of the file is free.
|
||||
- **Foreign keys are off per connection** unless `enableForeignKeys` ran (only `src/server.ts` does). Scripts never fire `ON DELETE CASCADE`, so **any helper that deletes a parent row must delete its children explicitly** (as `deleteBotFile`, `purgeStorage`, `deleteSkill` do). A leftover child fails the next `bun run db:schema` with a foreign key violation.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.25.0",
|
||||
"version": "0.25.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
botFilesNote,
|
||||
chatReplyNote,
|
||||
RerunReplyNote,
|
||||
RetryFailureNote,
|
||||
ComputerFilesNote,
|
||||
coordinatorReplyNote,
|
||||
longSessionNote,
|
||||
@@ -73,6 +74,7 @@ import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
|
||||
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
|
||||
@@ -151,6 +153,14 @@ export default async function runBotReply({
|
||||
* session's last message and nothing looks unanswered.
|
||||
*/
|
||||
const is_retry = Number(job_params.retry_of) > 0;
|
||||
/**
|
||||
* Why the attempt before this one ended without an answer
|
||||
* (`grabRetryFailure`): what it claimed to have done may be exactly
|
||||
* what it never did, so the retry is told rather than repeating it.
|
||||
*/
|
||||
const retry_failure = is_retry
|
||||
? await grabRetryFailure({ message_id: Number(job_params.retry_of) }).catch(() => null)
|
||||
: null;
|
||||
|
||||
if (!on_plan_step && !is_retry && !hasUnansweredMessage({ history, answered_id })) {
|
||||
return { result: "", silent: true };
|
||||
@@ -369,6 +379,7 @@ export default async function runBotReply({
|
||||
led = admin;
|
||||
},
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
onAttach: ({ media_id }) => attachments.push(media_id),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -465,8 +476,9 @@ export default async function runBotReply({
|
||||
long_session_note,
|
||||
chatReplyNote({ bot_id: bot.id }),
|
||||
is_retry ? RerunReplyNote : "",
|
||||
retry_failure ? RetryFailureNote({ reason: retry_failure.reason }) : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: computers.length > 0 }),
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
|
||||
@@ -182,6 +182,19 @@ export default async function runBotTask({
|
||||
try {
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
const computers = await grabBotComputers({ bot_id: bot.id, workspace_id });
|
||||
/**
|
||||
* `import_file` reads only the computer this run works on: what it
|
||||
* made is there. The row is read again when the list no longer has
|
||||
* it, so the tool still names the job's computer.
|
||||
*/
|
||||
const job_computers = job.computer_id
|
||||
? computers.filter((row) => Number(row.id) == Number(job.computer_id))
|
||||
: [];
|
||||
const import_computers = job_computers.length
|
||||
? job_computers
|
||||
: job.computer_id
|
||||
? [{ id: job.computer_id }]
|
||||
: [];
|
||||
|
||||
/**
|
||||
* What the bot's types let it do here. A coordinator's task can
|
||||
@@ -395,7 +408,7 @@ export default async function runBotTask({
|
||||
...(job.computer_id
|
||||
? [
|
||||
importFileTool({
|
||||
computer_id: job.computer_id,
|
||||
computers: import_computers,
|
||||
scopes,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
PlanActiveNote,
|
||||
PlanPausedNote,
|
||||
ScheduledPlanNote,
|
||||
RetryFailureNote,
|
||||
} from "./harness-prompts";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
@@ -96,6 +97,26 @@ describe("harness prompts", () => {
|
||||
expect(TasksNote).not.toContain("[folder:bot:");
|
||||
expect(TasksNote).not.toContain("[bot:");
|
||||
});
|
||||
|
||||
test("a retry is told why the attempt before it failed", () => {
|
||||
const note = RetryFailureNote({ reason: "The answer didn't hold up against the app's record." });
|
||||
|
||||
expect(note).toContain("The answer didn't hold up against the app's record.");
|
||||
expect(note).toContain("list_files");
|
||||
expect(note).toContain("correct the premise first");
|
||||
});
|
||||
|
||||
test("a retry outside the few hundred characters that matter keeps the start of the failure", () => {
|
||||
const reason = `${"first".repeat(80)}${"last".repeat(10)}`;
|
||||
const note = RetryFailureNote({ reason });
|
||||
|
||||
expect(note).toContain(`first${"first".repeat(78)}`);
|
||||
expect(note).not.toContain("lastlastlastlast");
|
||||
});
|
||||
|
||||
test("a retry with no reason recorded still reads as a failure", () => {
|
||||
expect(RetryFailureNote({ reason: "" })).toContain("It ended without sending an answer.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("openRunsNote", () => {
|
||||
|
||||
@@ -116,6 +116,19 @@ The user asked for this reply again. Work from their latest messages and write i
|
||||
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
|
||||
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
|
||||
|
||||
/**
|
||||
* Added beside `RerunReplyNote` when the attempt before this one failed:
|
||||
* `reason` is the job's `last_error` (`grabRetryFailure`), so the run knows
|
||||
* what went wrong instead of starting from the same wrong premise. Cut
|
||||
* short: the note is guidance, not the failure log.
|
||||
*/
|
||||
export const RetryFailureNote = ({ reason }: { reason: string }) => `# The attempt before this one
|
||||
|
||||
It ended without sending an answer${reason ? `: ${reason.slice(0, 400)}` : "."}
|
||||
|
||||
- Check what that attempt actually left on record before you repeat it: list_files for what it says it saved, and the computer's own folders for what it says it made there. Take its word for nothing.
|
||||
- If it set off on a premise that wasn't true (a file that wasn't saved, a script that never existed), correct the premise first: that is the reason this attempt exists.`;
|
||||
|
||||
export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your files
|
||||
|
||||
You have a folder of your own, kept with the app (not on a computer), and it stays between runs and conversations.
|
||||
@@ -137,8 +150,9 @@ You have a folder of your own, kept with the app (not on a computer), and it sta
|
||||
|
||||
/**
|
||||
* Added to a run that has a computer: what it leaves there is not in its
|
||||
* files, but the user can still open it. `can_import` is false in a chat
|
||||
* reply, where the import only happens inside a task.
|
||||
* files, but the user can still open it. `can_import` is false when the run
|
||||
* has no computer to read from (a reply whose bot has none): then file work
|
||||
* on one is a task.
|
||||
*
|
||||
* A folder ref is always a folder, so a file left on the computer is named
|
||||
* by the folder that holds it, never by the file's own path.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { Database } from "bun:sqlite";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
/**
|
||||
* `list_files` with a search looked only at the root, so a bot that had
|
||||
* just saved `images/summit-hero-pil.png` was told it had no matching file,
|
||||
* believed its own save had never happened, and sent a task hunting the
|
||||
* filesystem for it. A search now looks through every folder.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_files (id INTEGER PRIMARY KEY, scope TEXT, owner_id INTEGER, folder TEXT, name TEXT, path TEXT)`);
|
||||
db.run(
|
||||
`INSERT INTO bot_files VALUES
|
||||
(1, 'bot', 20, '', 'root.md', 'root.md'),
|
||||
(2, 'bot', 20, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(3, 'bot', 20, 'scripts', 'render-hero.py', 'scripts/render-hero.py'),
|
||||
(4, 'bot', 20, 'reports', 'render.md', 'reports/render.md'),
|
||||
(5, 'bot', 21, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(6, 'workspace', 2, 'shared', 'summit-hero-pil.png', 'shared/summit-hero-pil.png')`,
|
||||
);
|
||||
|
||||
const scopes: StorageScope[] = [{ scope: "bot", owner_id: 20 }];
|
||||
|
||||
function ids({ folder, recursive, search }: { folder?: string | null; recursive?: boolean; search?: string | null }) {
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
return db
|
||||
.query(`SELECT id FROM bot_files WHERE ${where.join(" AND ")} ORDER BY id`)
|
||||
.all(...values)
|
||||
.map((row) => (row as { id: number }).id);
|
||||
}
|
||||
|
||||
describe("the file listing filter", () => {
|
||||
test("a search with no folder finds a file saved in a subfolder", () => {
|
||||
expect(ids({ search: "summit-hero" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a search across folders finds every match, wherever it is saved", () => {
|
||||
expect(ids({ search: "render" })).toEqual([3, 4]);
|
||||
});
|
||||
|
||||
test("a named empty folder is still only that folder's own files", () => {
|
||||
expect(ids({ folder: "" })).toEqual([1]);
|
||||
});
|
||||
|
||||
test("a named folder lists what it holds", () => {
|
||||
expect(ids({ folder: "images" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a named folder searched looks through it, not the rest of the tree", () => {
|
||||
expect(ids({ folder: "images", search: "render" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a recursive folder takes everything under it", () => {
|
||||
expect(ids({ folder: "reports", recursive: true })).toEqual([4]);
|
||||
expect(ids({ folder: "bot", recursive: true })).toEqual([]);
|
||||
});
|
||||
|
||||
test("another bot's file with the same name is never in it", () => {
|
||||
expect(ids({ search: "summit-hero" })).not.toContain(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
search?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The WHERE clause listing a run's files: its directories, one folder (or
|
||||
* its whole tree), and a name or path match. A search with no folder looks
|
||||
* through every folder, which is what a bot means by "list_files search":
|
||||
* scoping it to the root hid `images/summit-hero-pil.png` from the bot that
|
||||
* had just written it, and the bot went on to say the file was never saved.
|
||||
*/
|
||||
export default function botFilesFilter({ scopes, folder, recursive, search }: Params) {
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
if (target) {
|
||||
where.push(recursive ? `(folder = ? OR folder LIKE ?)` : `folder = ?`);
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (typeof folder == "string" && !recursive) {
|
||||
/**
|
||||
* A folder was named (even as ""), so this is that folder's own
|
||||
* listing. No folder at all means every folder, not just the root.
|
||||
*/
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
|
||||
return { where, values };
|
||||
}
|
||||
@@ -2,17 +2,18 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
/**
|
||||
* Only this directory's files (a folder path), or, with `recursive`,
|
||||
* everything under it.
|
||||
* Only this folder's files (a folder path), or, with `recursive`,
|
||||
* everything under it. Left out, every folder is listed.
|
||||
*/
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
/**
|
||||
* Match the name or the path, case-insensitive.
|
||||
* Match the name or the path, case-insensitive, in every folder.
|
||||
*/
|
||||
search?: string | null;
|
||||
limit?: number;
|
||||
@@ -31,32 +32,7 @@ export default async function listBotFiles({
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_FILES[]> {
|
||||
if (!scopes.length) return [];
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const owner_values = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = [...owner_values];
|
||||
|
||||
if (target) {
|
||||
where.push(
|
||||
recursive
|
||||
? `(folder = ? OR folder LIKE ?)`
|
||||
: `folder = ?`,
|
||||
);
|
||||
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (!recursive) {
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_FILES>({
|
||||
sql: `SELECT * FROM bot_files WHERE ${where.join(" AND ")} ORDER BY updated_at DESC, id DESC LIMIT ?`,
|
||||
|
||||
@@ -6,7 +6,10 @@ import type {
|
||||
} from "@/db/types/db";
|
||||
import type { BotFilePurpose, BotFileScope, BotFileSource } from "@/src/dict/bot-file-dict";
|
||||
import type { MediaType } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import extensionOf from "@/src/utils/extension-of";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import looksLikeImage from "@/src/utils/looks-like-image";
|
||||
import resolveBotPath from "@/src/utils/resolve-bot-path";
|
||||
import assertStorageRoom from "./assert-storage-room";
|
||||
import grabStorageDir from "./grab-storage-dir";
|
||||
@@ -71,6 +74,24 @@ export default async function recordBotFile({
|
||||
const existing = await grabBotFileRow({ scope, owner_id, path: resolved.relative });
|
||||
const previous_size = Number(existing?.size) || 0;
|
||||
|
||||
/**
|
||||
* What `write_file` saved as an image has to look like one: text under
|
||||
* `.png` became a 2.6 KB "image" the user could not open, while the
|
||||
* reply said a 1376x768 PNG was attached. Other writers make real bytes
|
||||
* (`generate_image`, an import, an upload), so only a bot's own write is
|
||||
* checked here.
|
||||
*/
|
||||
if (
|
||||
media_type_resolved == "image" &&
|
||||
source == "bot-write" &&
|
||||
extensionOf({ name: resolved.name }) != "svg" &&
|
||||
!looksLikeImage({ bytes })
|
||||
) {
|
||||
throw new AppError(
|
||||
`${resolved.relative} isn't an image: it was saved as text, so the user would get a file that does not open. Make it with generate_image (or transform_image), or bring it in with import_file.`,
|
||||
);
|
||||
}
|
||||
|
||||
await assertStorageRoom({
|
||||
scope,
|
||||
owner_id,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The bot message the retry runs again: a failure notice carries the
|
||||
* job that ended without an answer (`failed_job_id`).
|
||||
*/
|
||||
message_id: number | string;
|
||||
};
|
||||
|
||||
type Row = {
|
||||
failed_job_id: number | null;
|
||||
last_error: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the run behind a message ended without sending its answer: its
|
||||
* `failed_job_id` and that job's `last_error`. A retry reads it so it
|
||||
* doesn't set off on the same wrong premise a second time (the failure
|
||||
* notices themselves are app records, left out of the history the run
|
||||
* reads).
|
||||
*/
|
||||
export default async function grabRetryFailure({ message_id }: Params): Promise<{ job_id: number; reason: string } | null> {
|
||||
const res = await BunSQLite.sql<Row>({
|
||||
sql: `SELECT m.failed_job_id, q.last_error
|
||||
FROM bot_messages m
|
||||
LEFT JOIN bots_queue q ON q.id = m.failed_job_id
|
||||
WHERE m.id = ?
|
||||
LIMIT 1`,
|
||||
values: [Number(message_id) || 0],
|
||||
});
|
||||
|
||||
const row = res.payload?.[0];
|
||||
if (!row?.failed_job_id) return null;
|
||||
|
||||
return {
|
||||
job_id: Number(row.failed_job_id),
|
||||
reason: String(row.last_error || "").trim(),
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import grabCrewWorkers from "@/src/functions/backend/db/bots/grab-crew-workers";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import askToTakeOverTool from "../computer/ask-to-take-over-tool";
|
||||
import importFileTool from "../computer/import-file-tool";
|
||||
import searchComputersTool from "../computer/search-computers-tool";
|
||||
import addBotToWorkspaceTool from "./add-bot-to-workspace-tool";
|
||||
import assignComputerTool from "./assign-computer-tool";
|
||||
@@ -103,13 +104,19 @@ type Params = {
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
/**
|
||||
* Called with a file the reply sent, so the message carries it.
|
||||
*/
|
||||
onAttach?: (params: { media_id: number; name: string }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools a bot replies in chat with: its own (memory, instructions, and
|
||||
* in a workspace switching its default computer), send_reply for the message
|
||||
* and the longer work it queues, search_computers to find what's on its computers,
|
||||
* ask_user_to_take_over when only the user can do something on one, and
|
||||
* and the longer work it queues, search_computers to find what's on its
|
||||
* computers, import_file to keep a file one of them made (an image, a PDF,
|
||||
* an export) in its own files, ask_user_to_take_over when only the user can
|
||||
* do something on one, and
|
||||
* for the coordinator (the super admin's alone) create_workspace and
|
||||
* update_workspace (a workspace and its shared context, which
|
||||
* find_workspace reads back wherever the coordinator works), create_bot to
|
||||
@@ -129,8 +136,9 @@ type Params = {
|
||||
* workspace admin, in the workspace it leads, gets
|
||||
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
|
||||
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
|
||||
* a computer goes through a task, never mid-reply.
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Longer work on
|
||||
* a computer, and anything that changes it, still goes through a task,
|
||||
* never mid-reply.
|
||||
*/
|
||||
export default async function grabBotChatTools({
|
||||
bot,
|
||||
@@ -149,8 +157,10 @@ export default async function grabBotChatTools({
|
||||
onPropose,
|
||||
onWorkspaceAdmin,
|
||||
onTask,
|
||||
onAttach,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const bot_id = bot.id || 0;
|
||||
const dirs = computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id });
|
||||
const tools = [
|
||||
...(await grabBotTools({
|
||||
user_id,
|
||||
@@ -182,7 +192,15 @@ export default async function grabBotChatTools({
|
||||
user_id,
|
||||
computers,
|
||||
workspace_id,
|
||||
dirs: computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id }),
|
||||
dirs,
|
||||
}),
|
||||
importFileTool({
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
dirs,
|
||||
onAttach,
|
||||
}),
|
||||
askToTakeOverTool({ computers, onAsk: (params) => onTakeOver?.(params) }),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
/**
|
||||
* A reply now imports from a computer, and a bot may reach several: the one
|
||||
* it names wins, and one it does not have is refused rather than quietly
|
||||
* reading the first machine's folder.
|
||||
*/
|
||||
const computers = [
|
||||
{ id: 4, name: "Main" },
|
||||
{ id: 9, name: "Build" },
|
||||
];
|
||||
|
||||
describe("picking the computer to import from", () => {
|
||||
test("no computer is null", () => {
|
||||
expect(pickImportComputer({ computers: [] })).toBeNull();
|
||||
});
|
||||
|
||||
test("nothing named means the first one", () => {
|
||||
expect(pickImportComputer({ computers })?.id).toEqual(4);
|
||||
expect(pickImportComputer({ computers, wanted: " " })?.id).toEqual(4);
|
||||
});
|
||||
|
||||
test("an id picks that computer", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 9 })?.id).toEqual(9);
|
||||
expect(pickImportComputer({ computers, wanted: "9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("a computer ref picks it too", () => {
|
||||
expect(pickImportComputer({ computers, wanted: "computer:9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("one it does not have is null, not the first one", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 2 })).toBeNull();
|
||||
expect(pickImportComputer({ computers, wanted: "elsewhere" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
type ComputerLike = {
|
||||
id?: number | string | null;
|
||||
name?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Which computer an import reads from: the one the bot named (an id, or a
|
||||
* `computer:<id>` ref), else the first it has. Null when it named one it
|
||||
* does not have, so the tool says so instead of reading the wrong machine.
|
||||
*/
|
||||
export default function pickImportComputer<T extends ComputerLike>({
|
||||
computers,
|
||||
wanted,
|
||||
}: {
|
||||
computers: T[];
|
||||
wanted?: number | string | null;
|
||||
}): T | null {
|
||||
if (!computers.length) return null;
|
||||
|
||||
if (wanted === undefined || wanted === null || String(wanted).trim() == "") return computers[0] ?? null;
|
||||
|
||||
const id = Number(String(wanted).trim().replace(/^computer:/, ""));
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
return computers.find((computer) => Number(computer.id) == id) ?? null;
|
||||
}
|
||||
@@ -20,12 +20,14 @@ import downloadComputerFile, { type ComputerDownload } from "@/src/functions/bac
|
||||
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import walkRegularFiles from "@/src/utils/walk-regular-files";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The computer the run is on: what it made is in its workspace.
|
||||
* The computers the run reaches (`grabBotComputers`), the current one
|
||||
* first: the import reads from the one the bot names, else this one.
|
||||
*/
|
||||
computer_id: number | string;
|
||||
computers: { id?: number | string | null; name?: string | null }[];
|
||||
/**
|
||||
* The directories the run may write to (`grabStorageScopes`): the first
|
||||
* is where an import lands.
|
||||
@@ -44,13 +46,18 @@ type Params = {
|
||||
type Args = {
|
||||
path: string;
|
||||
name?: string;
|
||||
/**
|
||||
* Which of the run's computers to read from (its id); the first one
|
||||
* when left out.
|
||||
*/
|
||||
computer?: number | string;
|
||||
attach?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies what a bot made on its computer into its own files: one file, or
|
||||
* a whole folder (taken as a gzipped tar and unpacked into one row per
|
||||
* file). The copies are kept with the app, stay after the computer is
|
||||
* Copies what a bot made on one of its computers into its own files: one
|
||||
* file, or a whole folder (taken as a gzipped tar and unpacked into one row
|
||||
* per file). The copies are kept with the app, stay after the computer is
|
||||
* rebuilt, and are readable at once; the originals stay on the computer,
|
||||
* where the message's folder ref points at the folder holding them.
|
||||
*
|
||||
@@ -60,7 +67,7 @@ type Args = {
|
||||
* import at 30,047 characters.
|
||||
*/
|
||||
export default function importFileTool({
|
||||
computer_id,
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
@@ -69,10 +76,20 @@ export default function importFileTool({
|
||||
}: Params): HarnessTool<Args> {
|
||||
const own = scopes[0];
|
||||
const max_mb = Math.round(AppData.BotFileImportMaxBytes / (1024 * 1024));
|
||||
const first = computers[0];
|
||||
const choices = computers
|
||||
.map((computer) => `${computer.id}${computer.name ? ` (${computer.name})` : ""}`)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
name: "import_file",
|
||||
description: `Copy a file or folder from this computer into your own files, so it is kept with the app and stays after the computer is rebuilt. Give its path on the computer, relative to your folder there (${dirs.cwd}), e.g. "seo/coderank/raw/crawl.json" or "seo/coderank/raw"; a folder comes in as it is, in one go. Up to ${max_mb} MB. Check with list_files and the computer's own tools what you already imported: importing the same thing twice just writes over the copy, so do it once.${
|
||||
description: `Copy a file or folder from one of your computers into your own files, so it is kept with the app and stays after the computer is rebuilt.${
|
||||
computers.length > 1
|
||||
? ` Your computers: ${choices}; "computer" picks one, the first by default.`
|
||||
: first
|
||||
? ` It reads computer ${first.id}${first.name ? ` (${first.name})` : ""}.`
|
||||
: ""
|
||||
} Give its path on the computer, relative to your folder there (${dirs.cwd}), e.g. "seo/coderank/raw/crawl.json" or "seo/coderank/raw"; a folder comes in as it is, in one go. Up to ${max_mb} MB. Check with list_files and the computer's own tools what you already imported: importing the same thing twice just writes over the copy, so do it once.${
|
||||
own?.scope == "workspace" ? " The copies land in the workspace's shared files." : ""
|
||||
} Imports are readable at once. Name a copy with its [file:ID] ref. Import the report you wrote before the last long steps of a run, so it is never lost to the step limit. The other direction is export_file, which puts one of your own files back on the computer.`,
|
||||
schema: z.object({
|
||||
@@ -86,11 +103,23 @@ export default function importFileTool({
|
||||
.max(AppData.BotFilePathMaxChars)
|
||||
.optional()
|
||||
.describe(`Where to save it in your files, e.g. "reports/coderank-audit.md"`),
|
||||
computer: z
|
||||
.union([z.string(), z.number()])
|
||||
.optional()
|
||||
.describe(`Which of your computers (its id); the first one when left out`),
|
||||
attach: z.boolean().optional().describe(`Also send it to the user with this reply`),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
if (!own) return `You have no files folder to import into.`;
|
||||
|
||||
const chosen = pickImportComputer({ computers, wanted: args.computer });
|
||||
|
||||
if (!chosen) {
|
||||
return computers.length
|
||||
? `That isn't one of your computers. Yours: ${choices}.`
|
||||
: `You have no computer to import from.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace-relative from here on, which is what a folder ref
|
||||
* names.
|
||||
@@ -100,6 +129,7 @@ export default function importFileTool({
|
||||
|
||||
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
|
||||
|
||||
const computer_id = chosen.id || 0;
|
||||
const target = await grabComputerMcpUrl({ computer_id });
|
||||
|
||||
if (!target) return `Computer #${computer_id} has no container to copy from.`;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
|
||||
/**
|
||||
* A `.png` path and a truncated base64 string became a 2.6 KB "image" the
|
||||
* user could not open, while the reply said a 1376x768 PNG was attached.
|
||||
* `write_file` saves text: a binary extension is refused, with the tool that
|
||||
* makes the real file named.
|
||||
*/
|
||||
describe("writing a binary file as text", () => {
|
||||
test("an image is refused", () => {
|
||||
expect(binaryWriteProblem({ path: "images/summit-hero.png" })).toContain("binary file (.png)");
|
||||
});
|
||||
|
||||
test("the refusal names a way to make it", () => {
|
||||
const problem = binaryWriteProblem({ path: "report.pdf" }) || "";
|
||||
|
||||
expect(problem).toContain("generate_image");
|
||||
expect(problem).toContain("make_pdf");
|
||||
expect(problem).toContain("import_file");
|
||||
});
|
||||
|
||||
test("an uppercase extension is refused too", () => {
|
||||
expect(binaryWriteProblem({ path: "SCREENSHOT.PNG" })).toContain(".png");
|
||||
});
|
||||
|
||||
test("a zip, an office document and a font are refused", () => {
|
||||
for (const path of ["bundle.zip", "notes.docx", "font.woff2"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test("text files pass", () => {
|
||||
for (const path of ["notes.md", "data.csv", "run.py", "page.svg", "README"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { BotImageFileExtensions } from "@/src/dict/bot-file-dict";
|
||||
import { extensionOf } from "@/src/functions/backend/db/bot-files/media-type-for-file";
|
||||
|
||||
/**
|
||||
* Extensions that hold bytes rather than text. `write_file` stores what the
|
||||
* model passes as it is, so a `.png` path and a truncated `base64` string
|
||||
* became a 2.6 KB "image" the user could not open, while the reply said a
|
||||
* 1376x768 PNG was attached. SVG stays out: it is text, and a bot can write
|
||||
* one by hand.
|
||||
*/
|
||||
export const BinaryWriteExtensions = [
|
||||
...BotImageFileExtensions.filter((extension) => extension != "svg"),
|
||||
"pdf",
|
||||
"doc",
|
||||
"docx",
|
||||
"xls",
|
||||
"xlsx",
|
||||
"ppt",
|
||||
"pptx",
|
||||
"zip",
|
||||
"gz",
|
||||
"tgz",
|
||||
"tar",
|
||||
"7z",
|
||||
"rar",
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"ogg",
|
||||
"flac",
|
||||
"mp4",
|
||||
"mov",
|
||||
"mkv",
|
||||
"avi",
|
||||
"webm",
|
||||
"sqlite",
|
||||
"db",
|
||||
"exe",
|
||||
"bin",
|
||||
"woff",
|
||||
"woff2",
|
||||
"ttf",
|
||||
"otf",
|
||||
];
|
||||
|
||||
/**
|
||||
* Why `write_file` refuses a path, or null when it can save it: a binary
|
||||
* extension would turn text into a file that does not open, and the tool
|
||||
* that makes the real one is one of the named ones.
|
||||
*/
|
||||
export default function binaryWriteProblem({ path }: { path: string }) {
|
||||
const extension = extensionOf({ name: path });
|
||||
|
||||
if (!extension || !BinaryWriteExtensions.includes(extension)) return null;
|
||||
|
||||
return `write_file saves text, and ${path} is a binary file (.${extension}): the text would be stored as it is, so the user would get a file that does not open. Make an image with generate_image (or transform_image), a PDF with make_pdf, a video with generate_video, or build the file on a computer and bring it in with import_file.`;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ type Args = {
|
||||
export default function listFilesTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
return {
|
||||
name: "list_files",
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search". Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search" (in every folder, so a file saved deep in a tree is found). Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
schema: z.object({
|
||||
folder: z.string().max(AppData.BotFilePathMaxChars).optional(),
|
||||
search: z.string().max(120).optional(),
|
||||
@@ -34,18 +34,23 @@ export default function listFilesTool(context: StorageToolContext): HarnessTool<
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const folder = args.folder?.trim() || "";
|
||||
const search = args.search?.trim() || "";
|
||||
|
||||
const files = await listBotFiles({
|
||||
scopes: context.scopes,
|
||||
folder,
|
||||
folder: folder || undefined,
|
||||
recursive: args.recursive,
|
||||
search: args.search,
|
||||
search: search || undefined,
|
||||
});
|
||||
|
||||
if (!files.length) {
|
||||
return folder
|
||||
? `Nothing in ${folder}.`
|
||||
: `You have no files yet. Write one with write_file.`;
|
||||
if (folder) return `Nothing in ${folder}.`;
|
||||
|
||||
if (search) {
|
||||
return `Nothing matches "${search}" in your files. Try a shorter name, or list_files with no arguments to see everything.`;
|
||||
}
|
||||
|
||||
return `You have no files yet. Write one with write_file.`;
|
||||
}
|
||||
|
||||
const lines = files.map((file) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { BotFilePurpose } from "@/src/dict/bot-file-dict";
|
||||
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
import {
|
||||
describeScope,
|
||||
fileRef,
|
||||
@@ -22,7 +23,8 @@ type Args = {
|
||||
/**
|
||||
* Writes a text file (markdown, CSV, JSON, code, plain text) into one of
|
||||
* the bot's directories, making folders as needed. The file stays for
|
||||
* later runs.
|
||||
* later runs. A binary extension is refused: text saved under `.png`
|
||||
* reached the user as a file that would not open.
|
||||
*/
|
||||
export default function writeFileTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
const own = context.scopes[0];
|
||||
@@ -31,7 +33,7 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
name: "write_file",
|
||||
description: `Save a text file for later: markdown, CSV, JSON, code or plain text. Give it a path like "reports/q3.md"; folders are made as needed. Files belong to ${
|
||||
own?.scope == "workspace" ? "the workspace you're working in" : "you"
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once.${
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once. It saves text only: an image comes from generate_image, a PDF from make_pdf, and a file a computer made from import_file, never from writing base64 here.${
|
||||
context.scopes.length > 1
|
||||
? ` "scope" picks a directory: ${context.scopes.map((s) => `${s.scope}:${s.owner_id}`).join(", ")}.`
|
||||
: ""
|
||||
@@ -62,6 +64,9 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
.join(", ")}.`;
|
||||
}
|
||||
|
||||
const binary = binaryWriteProblem({ path: args.path });
|
||||
if (binary) return binary;
|
||||
|
||||
const file = await recordBotFile({
|
||||
bot_id: context.bot_id,
|
||||
scope: named.scope,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
question_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* 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. A
|
||||
* read that failed or hung is tried again (`loadRefView`) instead of
|
||||
* leaving the card unopenable until the page is reloaded.
|
||||
* leaving the card unopenable until the page is reloaded, and answering
|
||||
* one card tells the thread's other cards of the same question.
|
||||
*/
|
||||
export default function useBotQuestion({ question_id }: Params) {
|
||||
const [view, setViewState] = useState<BotQuestionView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useBotQuestion({ question_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `question:${question_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as BotQuestionView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<BotQuestionView>({
|
||||
key: `question:${question_id}`,
|
||||
key,
|
||||
url: `/api/admin/bot-questions/get-question?question_id=${question_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useBotQuestion({ question_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [question_id]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { ExtensionProposalView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
proposal_id: number;
|
||||
@@ -12,7 +12,8 @@ type Params = {
|
||||
* 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.
|
||||
* reloaded, and deciding on one card tells the thread's other cards of
|
||||
* the same proposal, so none of them goes on saying "Waiting for you".
|
||||
*/
|
||||
export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
const [view, setViewState] = useState<ExtensionProposalView | null>(null);
|
||||
@@ -20,11 +21,21 @@ export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `extension-proposal:${proposal_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as ExtensionProposalView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<ExtensionProposalView>({
|
||||
key: `extension-proposal:${proposal_id}`,
|
||||
key,
|
||||
url: `/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -34,6 +45,7 @@ export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [proposal_id]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { HookProposalView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
proposal_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* 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. A read that failed or hung is tried again (`loadRefView`), so the
|
||||
* card isn't unopenable until the page is reloaded.
|
||||
* card isn't unopenable until the page is reloaded, and deciding on one
|
||||
* card tells the thread's other cards of the same proposal.
|
||||
*/
|
||||
export default function useHookProposal({ proposal_id }: Params) {
|
||||
const [view, setViewState] = useState<HookProposalView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `hook-proposal:${proposal_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as HookProposalView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<HookProposalView>({
|
||||
key: `hook-proposal:${proposal_id}`,
|
||||
key,
|
||||
url: `/api/admin/hook-proposals/get-proposal?proposal_id=${proposal_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [proposal_id]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { SecretRequestView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
request_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* 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. A
|
||||
* read that failed or hung is tried again (`loadRefView`), so the card
|
||||
* isn't unopenable until the page is reloaded.
|
||||
* isn't unopenable until the page is reloaded, and answering one card
|
||||
* tells the thread's other cards of the same request.
|
||||
*/
|
||||
export default function useSecretRequest({ request_id }: Params) {
|
||||
const [view, setViewState] = useState<SecretRequestView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `secret-request:${request_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as SecretRequestView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<SecretRequestView>({
|
||||
key: `secret-request:${request_id}`,
|
||||
key,
|
||||
url: `/api/admin/secret-requests/get-request?request_id=${request_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [request_id]);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import loadRefView, { primeRefView } from "./ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "./ref-view-loader";
|
||||
|
||||
/**
|
||||
* A read standing in for the app's: one answer per call, in order, and a
|
||||
@@ -100,4 +100,65 @@ describe("loadRefView", () => {
|
||||
|
||||
expect(asked).toEqual(["/get-question?question_id=15", "/get-suggestion?suggestion_id=15"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("subscribeRefView", () => {
|
||||
test("tells every chip naming a view when one of them changes it", () => {
|
||||
const first: unknown[] = [];
|
||||
const second: unknown[] = [];
|
||||
|
||||
const stopFirst = subscribeRefView({ key: "test:shared-chip", listener: (view) => first.push(view) });
|
||||
const stopSecond = subscribeRefView({ key: "test:shared-chip", listener: (view) => second.push(view) });
|
||||
|
||||
primeRefView({ key: "test:shared-chip", view: { id: 21, status: "confirmed" } });
|
||||
|
||||
expect(first).toEqual([{ id: 21, status: "confirmed" }]);
|
||||
expect(second).toEqual([{ id: 21, status: "confirmed" }]);
|
||||
|
||||
stopFirst();
|
||||
stopSecond();
|
||||
});
|
||||
|
||||
test("tells only the chips naming that view", () => {
|
||||
const mine: unknown[] = [];
|
||||
const other: unknown[] = [];
|
||||
|
||||
const stopMine = subscribeRefView({ key: "test:mine", listener: (view) => mine.push(view) });
|
||||
const stopOther = subscribeRefView({ key: "test:other", listener: (view) => other.push(view) });
|
||||
|
||||
primeRefView({ key: "test:mine", view: { id: 23 } });
|
||||
|
||||
expect(mine).toEqual([{ id: 23 }]);
|
||||
expect(other).toEqual([]);
|
||||
|
||||
stopMine();
|
||||
stopOther();
|
||||
});
|
||||
|
||||
test("stops following once the chip is gone", () => {
|
||||
const seen: unknown[] = [];
|
||||
|
||||
const stop = subscribeRefView({ key: "test:unsubscribed", listener: (view) => seen.push(view) });
|
||||
|
||||
stop();
|
||||
primeRefView({ key: "test:unsubscribed", view: { id: 25 } });
|
||||
|
||||
expect(seen).toEqual([]);
|
||||
});
|
||||
|
||||
test("tells the chips already showing it when a read lands", async () => {
|
||||
const seen: unknown[] = [];
|
||||
|
||||
const stop = subscribeRefView({ key: "test:read-lands", listener: (view) => seen.push(view) });
|
||||
|
||||
await loadRefView({
|
||||
key: "test:read-lands",
|
||||
url: "/get?id=27",
|
||||
readOnce: async () => ({ id: 27 }),
|
||||
retryDelaysMs: [],
|
||||
});
|
||||
|
||||
expect(seen).toEqual([{ id: 27 }]);
|
||||
|
||||
stop();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,12 +31,48 @@ type Params = {
|
||||
const known = new Map<string, unknown>();
|
||||
const inFlight = new Map<string, Promise<unknown | null>>();
|
||||
|
||||
type RefViewListener = (view: RefView) => void;
|
||||
|
||||
/**
|
||||
* Who is showing one view on the page now, by key. A bot's message can
|
||||
* carry the same card twice (the one that made it, and a later one saying
|
||||
* it's still waiting), and each chip keeps its own state, so without this
|
||||
* the other card went on saying "Waiting for you" after the user decided
|
||||
* on it, until a reload.
|
||||
*/
|
||||
const listeners = new Map<string, Set<RefViewListener>>();
|
||||
|
||||
/**
|
||||
* Follows one view, so a change another chip made reaches this one:
|
||||
* returns the unsubscribe. Called before the read, since a card decided
|
||||
* while it loads must not be overwritten by the answer already in flight.
|
||||
*/
|
||||
export function subscribeRefView({ key, listener }: { key: string; listener: RefViewListener }) {
|
||||
const listening = listeners.get(key) || new Set<RefViewListener>();
|
||||
|
||||
listening.add(listener);
|
||||
listeners.set(key, listening);
|
||||
|
||||
return () => {
|
||||
listening.delete(listener);
|
||||
|
||||
if (!listening.size) listeners.delete(key);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* chip now saying so) without asking the app for it again, and tells every
|
||||
* chip naming it, so they all say so.
|
||||
*/
|
||||
export function primeRefView({ key, view }: { key: string; view: unknown }) {
|
||||
remember({ key, view });
|
||||
}
|
||||
|
||||
function remember({ key, view }: { key: string; view: unknown }) {
|
||||
known.set(key, view);
|
||||
|
||||
for (const listener of listeners.get(key) || []) listener(view as RefView);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,7 +100,7 @@ export default async function loadRefView<T extends RefView>({
|
||||
.then((view) => {
|
||||
inFlight.delete(key);
|
||||
|
||||
if (view) known.set(key, view);
|
||||
if (view) remember({ key, view });
|
||||
|
||||
return view as T | null;
|
||||
})
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import looksLikeImage from "./looks-like-image";
|
||||
|
||||
const bytes = (...values: number[]) => new Uint8Array(values);
|
||||
|
||||
/**
|
||||
* A real PNG, JPEG, GIF, WEBP and BMP pass; text does not. The check exists
|
||||
* because a truncated base64 string saved under `.png` was attached as a
|
||||
* 1376x768 image and the user got a file that would not open.
|
||||
*/
|
||||
describe("reading image bytes", () => {
|
||||
test("a PNG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a JPEG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0xff, 0xd8, 0xff, 0xe0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a GIF", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a WEBP", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x45, 0x42, 0x50),
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("a BMP", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x42, 0x4d, 0, 0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a RIFF that isn't WEBP is not an image", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x41, 0x56, 0x45),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("base64 text is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new TextEncoder().encode("iVBORw0KGgo=") })).toBe(false);
|
||||
});
|
||||
|
||||
test("nothing at all is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new Uint8Array() })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Whether bytes start like a real image, by its signature. Enough to catch
|
||||
* text saved under an image's name (a truncated base64 string once reached
|
||||
* the user as a 2.6 KB "PNG" that would not open): a real PNG, JPEG, GIF,
|
||||
* WEBP or BMP always starts with its own magic. SVG is text and is checked
|
||||
* by the caller's extension, not here.
|
||||
*/
|
||||
export default function looksLikeImage({ bytes }: { bytes: Uint8Array }) {
|
||||
const head = bytes.subarray(0, 12);
|
||||
const starts = (...expected: number[]) => expected.every((byte, index) => head[index] == byte);
|
||||
|
||||
if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true;
|
||||
if (starts(0xff, 0xd8, 0xff)) return true;
|
||||
if (starts(0x47, 0x49, 0x46, 0x38)) return true;
|
||||
if (starts(0x42, 0x4d)) return true;
|
||||
|
||||
return starts(0x52, 0x49, 0x46, 0x46) && head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50;
|
||||
}
|
||||
Reference in New Issue
Block a user