Jump a thread with End and Home, as its button does

This commit is contained in:
2026-11-21 13:20:16 +01:00
parent e3f5b37764
commit ac244174f7
8 changed files with 190 additions and 21 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **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).
- **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. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (`ScrollToBottomButton`) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (`typingInField`, `scrollThreadToTop`). 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. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` holds the tools to `PlanModeToolNames` (reads and the plan/question/suggestion cards, never `load_tools`), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and asks with `ask_user` whether to save it (the answer runs without the mode), and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
- **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]`, `[secret:ID]` (masked env, Reveal/Copy), `[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). A plan, questions, a proposal, a hook proposal and a secret request show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. 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.
+1 -8
View File
@@ -1,12 +1,5 @@
import { useEffect, useRef } from "react";
function typingInField({ target }: { target: EventTarget | null }) {
if (!(target instanceof HTMLElement)) return false;
if (target.isContentEditable) return true;
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
}
import typingInField from "@/src/utils/typing-in-field";
/**
* The left and right arrow keys step a preview's gallery back and forth,
+1 -8
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState, type PointerEvent, type RefObject } from "react";
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
import type { ImageViewerPoint } from "./use-image-viewer";
import typingInField from "@/src/utils/typing-in-field";
type Params = {
container_ref: RefObject<HTMLDivElement | null>;
@@ -16,14 +17,6 @@ type Params = {
*/
const WheelZoomRate = 0.0025;
function typingInField({ target }: { target: EventTarget | null }) {
if (!(target instanceof HTMLElement)) return false;
if (target.isContentEditable) return true;
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
}
/**
* The image preview's hands: Ctrl/Cmd + wheel (and a trackpad pinch) zooms
* at the pointer, a plain wheel scrolls, dragging with the mouse moves a
@@ -1,9 +1,11 @@
import { useLayoutEffect, useRef, useState, type RefObject } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
import type { BotMessageWithAttachments } from "@/src/types";
import typingInField from "@/src/utils/typing-in-field";
import {
ThreadJumpWindowMs,
atThreadEnd,
scrollThreadToBottom,
scrollThreadToTop,
shouldFollowThread,
threadOffset,
} from "../(utils)/thread-scroll";
@@ -19,7 +21,8 @@ type Params = {
* Keeps the thread's bottom in view: a chat sitting at the bottom follows
* every new message, a chat scrolled up stays where it is (except for a
* message the user just sent, which brings the thread to it) and offers a
* button to get back down. Whether it sits at the bottom is read from where
* button to get back down. End does what that button does and Home goes
* back to the thread's top. Whether it sits at the bottom is read from where
* the content ends, not from `scrollTop`, whose sign a reversed column
* reports differently across engines. Content that grows while the thread
* is at the bottom (images landing, a wider window) is followed too.
@@ -89,7 +92,7 @@ export default function useThreadScroll({ messages }: Params) {
setJumpVisible(!offset.near_bottom);
};
const jumpToBottom = () => {
const jumpToBottom = useCallback(() => {
const column = column_ref.current;
if (!column) return;
@@ -110,7 +113,56 @@ export default function useThreadScroll({ messages }: Params) {
element: column,
behavior: reduced ? "auto" : "smooth",
});
};
}, []);
const scrollToTop = useCallback(() => {
const column = column_ref.current;
if (!column) return;
const reduced = Boolean(
globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches,
);
/**
* A jump the press before was still animating belongs to the other
* direction: this one takes over, and the thread stops following,
* so a message landing on the way doesn't drag it back down. The
* scrolling itself raises the jump button, as any scroll up does.
*/
jump.current.active = false;
following.current = false;
scrollThreadToTop({
element: column,
behavior: reduced ? "auto" : "smooth",
});
}, []);
/**
* End and Home on the page do what the thread's own controls do: End
* jumps to the latest message, Home to the top of the messages loaded
* so far. A field the user is typing in (the composer, a form) keeps
* its own End and Home, and an open menu or modal keeps the keys too.
*/
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
if (event.key != "End" && event.key != "Home") return;
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
if (typingInField({ target: event.target })) return;
if (document.querySelector('[role="listbox"], [role="dialog"]')) return;
event.preventDefault();
if (event.key == "End") jumpToBottom();
else scrollToTop();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [jumpToBottom, scrollToTop]);
useLayoutEffect(() => {
const column = column_ref.current;
@@ -3,6 +3,8 @@ import { AppData } from "@/src/data/app-data";
import {
ThreadBottomSlack,
atThreadEnd,
scrollThreadToBottom,
scrollThreadToTop,
shouldFollowThread,
threadOffset,
} from "./thread-scroll";
@@ -131,3 +133,44 @@ describe("shouldFollowThread", () => {
).toBe(true);
});
});
/** A scrolling column that records where it was sent, as a fake scroll. */
function column({ scroll_height }: { scroll_height: number }) {
const calls: ScrollToOptions[] = [];
return {
calls,
element: {
scrollHeight: scroll_height,
scrollTo: (options: ScrollToOptions) => calls.push(options),
} as unknown as HTMLElement,
};
}
describe("scrollThreadToTop", () => {
test("asks for a position past the start, which clamps onto it", () => {
const { calls, element } = column({ scroll_height: 1200 });
scrollThreadToTop({ element });
expect(calls).toEqual([{ top: -1200, behavior: "auto" }]);
});
test("animates when asked, the caller deciding on reduced motion", () => {
const { calls, element } = column({ scroll_height: 800 });
scrollThreadToTop({ element, behavior: "smooth" });
expect(calls).toEqual([{ top: -800, behavior: "smooth" }]);
});
});
describe("scrollThreadToBottom", () => {
test("asks for a position past the end, which clamps onto it", () => {
const { calls, element } = column({ scroll_height: 900 });
scrollThreadToBottom({ element });
expect(calls).toEqual([{ top: 900, behavior: "auto" }]);
});
});
@@ -100,3 +100,20 @@ export function scrollThreadToBottom({
}) {
element.scrollTo({ top: element.scrollHeight, behavior });
}
/**
* Puts the thread at its start, animated or at once, showing the oldest
* message it has loaded. A reversed column reports its start differently
* across engines (0 where the column's own direction reads normally, a
* negative `scrollTop` where its bottom is 0), so a value past the start
* clamps back onto it either way, the mirror of `scrollThreadToBottom`.
*/
export function scrollThreadToTop({
element,
behavior = "auto",
}: {
element: HTMLElement;
behavior?: ScrollBehavior;
}) {
element.scrollTo({ top: -element.scrollHeight, behavior });
}
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import typingInField from "./typing-in-field";
/** A field-shaped target, as a key press sees it. */
function field({
tagName,
content_editable,
}: {
tagName: string;
content_editable?: boolean;
}) {
return {
tagName,
isContentEditable: Boolean(content_editable),
} as unknown as EventTarget;
}
describe("typingInField", () => {
test("inputs, text areas and selects are fields", () => {
expect(typingInField({ target: field({ tagName: "INPUT" }) })).toBe(true);
expect(typingInField({ target: field({ tagName: "TEXTAREA" }) })).toBe(
true,
);
expect(typingInField({ target: field({ tagName: "SELECT" }) })).toBe(
true,
);
});
test("contenteditable elements are fields, whatever their tag", () => {
expect(
typingInField({
target: field({ tagName: "DIV", content_editable: true }),
}),
).toBe(true);
});
test("buttons, links and other elements are not", () => {
expect(typingInField({ target: field({ tagName: "BUTTON" }) })).toBe(
false,
);
expect(typingInField({ target: field({ tagName: "DIV" }) })).toBe(false);
});
test("a missing or non-element target is not a field", () => {
expect(typingInField({ target: null })).toBe(false);
expect(typingInField({ target: new EventTarget() })).toBe(false);
});
});
+23
View File
@@ -0,0 +1,23 @@
/**
* Whether a key press belongs to a field the user types in, whose own
* meaning for it (End moving the caret to the line's end, Home back to its
* start) must win over the page's shortcuts.
*/
const FieldTags = ["INPUT", "TEXTAREA", "SELECT"];
export default function typingInField({
target,
}: {
target: EventTarget | null;
}) {
/**
* Read by shape rather than `instanceof HTMLElement`: the check runs on
* every key press, including ones a window or a document dispatches.
*/
const field = target as Partial<HTMLElement> | null;
if (!field || typeof field.tagName != "string") return false;
if (field.isContentEditable) return true;
return FieldTags.includes(field.tagName);
}