Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): add prompt stashing to bot threads (#101)

Leof2d35003309a
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index 1f0560493..6b1eeb9bf 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -204,6 +204,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
+ assert.isFalse(
+ Keybindings.DEFAULT_KEYBINDINGS.some(
+ (binding) =>
+ binding.key === "mod+n" &&
+ binding.command === "chat.new" &&
+ binding.when === "!terminalFocus",
+ ),
+ );
+ assert.isTrue(
+ Keybindings.DEFAULT_KEYBINDINGS.some(
+ (binding) =>
+ binding.key === "mod+n" &&
+ binding.command === "terminal.new" &&
+ binding.when === "terminalFocus",
+ ),
+ );
+ assert.equal(defaultsByCommand.get("chat.new"), "mod+shift+o");
assert.isFalse(defaultsByCommand.has("rightPanel.toggleMaximized"));
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
@@ -211,6 +228,34 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}),
);
+ it.effect("removes the retired Command+N chat default without removing user shortcuts", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [
+ { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
+ { key: "mod+alt+n", command: "chat.new", when: "!terminalFocus" },
+ ]);
+
+ yield* Effect.gen(function* () {
+ const keybindings = yield* Keybindings.Keybindings;
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ });
+
+ const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
+ assert.isFalse(
+ persisted.some(
+ (binding) =>
+ binding.key === "mod+n" &&
+ binding.command === "chat.new" &&
+ binding.when === "!terminalFocus",
+ ),
+ );
+ assert.isTrue(
+ persisted.some((binding) => binding.key === "mod+alt+n" && binding.command === "chat.new"),
+ );
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
index 7f8929f57..9c3c36ed6 100644
--- a/apps/server/src/keybindings.ts
+++ b/apps/server/src/keybindings.ts
@@ -58,6 +58,11 @@ export {
parseKeybindingShortcut,
};
+/** Exact former defaults that startup removes without touching user overrides. */
+const RETIRED_DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
+ { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
+];
+
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Schema.decodeTo(
Schema.toType(ResolvedKeybindingRule),
@@ -492,7 +497,12 @@ const make = Effect.gen(function* () {
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
- const customConfig = runtimeConfig.keybindings;
+ const persistedConfig = runtimeConfig.keybindings;
+ const customConfig = persistedConfig.filter(
+ (entry) =>
+ !RETIRED_DEFAULT_KEYBINDINGS.some((retired) => isSameKeybindingRule(entry, retired)),
+ );
+ const removedRetiredDefaults = customConfig.length !== persistedConfig.length;
const existingCommands = new Set(customConfig.map((entry) => entry.command));
const missingDefaults: KeybindingRule[] = [];
const shortcutConflictWarnings: Array<{
@@ -530,6 +540,9 @@ const make = Effect.gen(function* () {
});
}
if (missingDefaults.length === 0) {
+ if (removedRetiredDefaults) {
+ yield* writeConfigAtomically(customConfig);
+ }
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
@@ -559,6 +572,9 @@ const make = Effect.gen(function* () {
});
}
if (defaultsToAppend.length === 0) {
+ if (removedRetiredDefaults) {
+ yield* writeConfigAtomically(customConfig);
+ }
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 5df077219..7951dcd3a 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -66,6 +66,7 @@ import {
} from "../../promptStashStore";
import { ComposerStashBadge } from "./ComposerStashBadge";
import { ComposerStashMenu } from "./ComposerStashMenu";
+import { ComposerBanner } from "./ComposerBanner";
import {
ComposerTasksBadge,
ComposerTasksDrawer,
@@ -89,7 +90,7 @@ import {
} from "../../lib/attachmentUploadState";
import { isCommandPaletteOpen } from "../../commandPaletteBus";
import { getTerminalFocusOwner } from "../../lib/terminalFocus";
-import { resolveShortcutCommand } from "../../keybindings";
+import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings";
import {
type TerminalContextDraft,
type TerminalContextSelection,
@@ -2279,10 +2280,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
!isComposerCollapsedMobile;
const hasShoulderTab =
showShoulderTabs &&
- (stashQueue.length > 0 ||
- (visibleTasksProgress !== null &&
- visibleTaskSteps !== null &&
- visibleTasksProgress.totalSteps > 0));
+ visibleTasksProgress !== null &&
+ visibleTaskSteps !== null &&
+ visibleTasksProgress.totalSteps > 0;
useEffect(() => {
if (visibleTasksProgress === null || visibleTaskSteps === null) {
setIsTasksDrawerOpen(false);
@@ -2874,6 +2874,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
steps={visibleTaskSteps}
/>
) : null}
+ {showShoulderTabs ? (
+ <ComposerBanner.Dock className="relative z-0">
+ <ComposerBanner.Column />
+ <ComposerStashBadge
+ count={stashQueue.length}
+ menuOpen={isStashMenuOpen}
+ pulseKey={stashPulse.key}
+ pulsing={stashPulse.active}
+ onToggleMenu={toggleStashMenu}
+ />
+ </ComposerBanner.Dock>
+ ) : null}
<div className="relative">
{showShoulderTabs && visibleTasksProgress && visibleTaskSteps ? (
<ComposerTasksBadge
@@ -2885,15 +2897,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
steps={visibleTaskSteps}
/>
) : null}
- {showShoulderTabs ? (
- <ComposerStashBadge
- count={stashQueue.length}
- menuOpen={isStashMenuOpen}
- pulseKey={stashPulse.key}
- pulsing={stashPulse.active}
- onToggleMenu={toggleStashMenu}
- />
- ) : null}
<div
data-chat-composer-main-surface="true"
className={cn(
@@ -2971,6 +2974,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
<ComposerStashMenu
entries={stashQueue}
+ stashShortcutLabel={shortcutLabelForCommand(keybindings, "composer.stash")}
onRestore={restoreStashEntry}
onDelete={deleteStashEntry}
onClose={() => setIsStashMenuOpen(false)}
diff --git a/apps/web/src/components/chat/ComposerBanner.tsx b/apps/web/src/components/chat/ComposerBanner.tsx
new file mode 100644
index 000000000..f81565718
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerBanner.tsx
@@ -0,0 +1,352 @@
+import { mergeProps } from "@base-ui/react/merge-props";
+import { useRender } from "@base-ui/react/use-render";
+import { ChevronDownIcon, XIcon } from "lucide-react";
+import type { ComponentProps } from "react";
+
+import { cn } from "~/lib/utils";
+import { Button, buttonVariants } from "../ui/button";
+import { ScrollArea } from "../ui/scroll-area";
+
+export type ComposerBannerVariant = "default" | "error" | "info" | "success" | "warning";
+
+const surfaceColors = cn(
+ "[--chat-composer-attached-surface:var(--chat-composer-glass-surface,var(--card))]",
+ "dark:[--chat-composer-attached-surface:var(--chat-composer-glass-surface,color-mix(in_srgb,var(--background)_96%,var(--color-white)))]",
+ "[html[data-theme-id]_&]:[--chat-composer-attached-surface:var(--app-theme-surface-raised)]",
+);
+
+const neutralOutline = cn(
+ "[--chat-composer-attached-outline:var(--chat-composer-outline,color-mix(in_srgb,var(--contrast-foreground)_8%,transparent))]",
+ "dark:[--chat-composer-attached-outline:var(--chat-composer-outline,color-mix(in_srgb,var(--color-white)_5%,transparent))]",
+ "[html[data-theme-id]_&]:[--chat-composer-attached-outline:var(--chat-composer-outline,var(--app-theme-toolbar-border))]",
+ "dark:[html[data-theme-id]:not([data-theme-id=t3-chat])_&]:[--chat-composer-attached-outline:var(--chat-composer-outline,color-mix(in_srgb,var(--app-theme-input)_30%,var(--background)))]",
+ "dark:[html[data-theme-id=t3-chat]_&]:[--chat-composer-attached-outline:#241e28]",
+);
+
+const variantColors: Record<ComposerBannerVariant, string> = {
+ default: neutralOutline,
+ error:
+ "[--chat-composer-attached-outline:color-mix(in_srgb,var(--error)_32%,transparent)] [--chat-composer-attached-tint:color-mix(in_srgb,var(--error)_8%,transparent)]",
+ info: "[--chat-composer-attached-outline:color-mix(in_srgb,var(--info)_32%,transparent)] [--chat-composer-attached-tint:color-mix(in_srgb,var(--info)_4%,transparent)]",
+ success:
+ "[--chat-composer-attached-outline:color-mix(in_srgb,var(--success)_32%,transparent)] [--chat-composer-attached-tint:color-mix(in_srgb,var(--success)_4%,transparent)]",
+ warning:
+ "[--chat-composer-attached-outline:color-mix(in_srgb,var(--warning)_28%,transparent)] [--chat-composer-attached-tint:color-mix(in_srgb,var(--warning)_8%,transparent)]",
+};
+
+/** Shared glass and attachment seam, also used by the command menu without banner row padding. */
+function Surface({
+ placement = "attached",
+ variant = "default",
+ className,
+ ...props
+}: ComponentProps<"div"> & {
+ placement?: "attached" | "floating";
+ variant?: ComposerBannerVariant;
+}) {
+ return (
+ <div
+ data-composer-banner-surface={placement}
+ data-variant={variant}
+ className={cn(
+ surfaceColors,
+ "relative isolate border-0 bg-transparent shadow-none [--chat-composer-attached-tint:transparent]",
+ variantColors[variant],
+ placement === "attached"
+ ? "[--chat-composer-attachment-overlap:calc(1rem+1px)] before:rounded-t-[16px]"
+ : "[--chat-composer-attachment-overlap:0px] before:rounded-[1rem]",
+ "before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:border before:border-(--chat-composer-attached-outline)",
+ "before:bg-[color-mix(in_srgb,var(--chat-composer-attached-surface)_var(--glass-opacity),transparent)] before:bg-[linear-gradient(var(--chat-composer-attached-tint),var(--chat-composer-attached-tint))] before:backdrop-blur-(--glass-blur) before:backdrop-saturate-(--glass-saturation)",
+ "before:mask-[linear-gradient(to_top,transparent_0_var(--chat-composer-attachment-overlap),black_var(--chat-composer-attachment-overlap))] before:shadow-[0_12px_28px_-18px_rgb(0_0_0/40%)] dark:before:shadow-[0_14px_32px_-18px_rgb(0_0_0/75%)]",
+ "dark:supports-[(backdrop-filter:blur(1px))_or_(-webkit-backdrop-filter:blur(1px))]:before:bg-[linear-gradient(var(--chat-composer-attached-tint),var(--chat-composer-attached-tint)),linear-gradient(to_top,transparent_0_var(--chat-composer-attachment-overlap),rgb(0_0_0/18%)_var(--chat-composer-attachment-overlap),transparent_calc(var(--chat-composer-attachment-overlap)+10px))]",
+ "not-supports-[(backdrop-filter:blur(1px))_or_(-webkit-backdrop-filter:blur(1px))]:before:bg-(--chat-composer-attached-surface)",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+// A peeking notice uses the first hidden notice's severity, never the attached row's.
+const peekBorder: Record<ComposerBannerVariant, string> = {
+ default: "border-(--chat-composer-attached-outline)",
+ error: "border-destructive/24",
+ info: "border-info/24",
+ success: "border-success/24",
+ warning: "border-warning/24",
+};
+
+function Peek({
+ className,
+ variant = "default",
+ ...props
+}: ComponentProps<"button"> & { variant?: ComposerBannerVariant }) {
+ return (
+ <button
+ type="button"
+ data-slot="composer-banner-peek"
+ className={cn(
+ surfaceColors,
+ neutralOutline,
+ "absolute inset-x-0 bottom-0 z-0 mx-auto h-3 w-[96%] cursor-pointer rounded-t-2xl border border-b-0 shadow-[0_6px_18px_rgb(0_0_0/6%)]",
+ "bg-[color-mix(in_srgb,var(--chat-composer-attached-surface)_var(--glass-opacity),transparent)] backdrop-blur-(--glass-blur) backdrop-saturate-(--glass-saturation)",
+ "not-supports-[(backdrop-filter:blur(1px))_or_(-webkit-backdrop-filter:blur(1px))]:bg-(--chat-composer-attached-surface)",
+ "transition-opacity duration-150 ease-out focus-visible:outline-2 focus-visible:outline-ring",
+ peekBorder[variant],
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Attachment({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="composer-banner-attachment"
+ className={cn(
+ "mx-auto -mb-[calc(1rem+1px)] w-[calc(100%-2*var(--chat-composer-drawer-inset))]",
+ // Adjacent attachments share their outline, including notices outside the form.
+ "[&+[data-slot=composer-banner-attachment]_[data-composer-banner-surface=attached]]:before:rounded-none [&+[data-slot=composer-banner-attachment]_[data-composer-banner-surface=attached]]:before:border-t-0",
+ "[&+:has([data-chat-composer-form])_[data-chat-composer-form]>[data-slot=composer-banner-attachment]:first-child_[data-composer-banner-surface=attached]]:before:rounded-none [&+:has([data-chat-composer-form])_[data-chat-composer-form]>[data-slot=composer-banner-attachment]:first-child_[data-composer-banner-surface=attached]]:before:border-t-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Dock({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <Attachment
+ className={cn(
+ "flex items-end gap-1 not-has-data-[composer-banner-surface=attached]:hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+/** Attachments share a column while neighboring tabs keep their own surface. */
+function Column({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <div
+ className={cn(
+ "flex min-w-0 flex-1 flex-col empty:hidden",
+ "[&>[data-slot=composer-banner-attachment]]:w-full [&>[data-slot=composer-banner-attachment]:last-child]:mb-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Root({
+ className,
+ placement = "attached",
+ variant = "default",
+ width = "fill",
+ ...props
+}: ComponentProps<"div"> & {
+ placement?: "attached" | "floating";
+ variant?: ComposerBannerVariant;
+ width?: "fill" | "content";
+}) {
+ return (
+ <Surface
+ className={cn(
+ "min-w-0 p-1 pb-[calc(var(--chat-composer-attachment-overlap)+(--spacing(1)))] text-xs/4 [--composer-banner-icon-column:--spacing(7)] sm:[--composer-banner-icon-column:--spacing(6)]",
+ width === "content" ? "w-fit max-w-full flex-none" : "@container",
+ className,
+ )}
+ data-slot="composer-banner"
+ placement={placement}
+ data-composer-banner-width={width}
+ variant={variant}
+ {...props}
+ />
+ );
+}
+
+/** The same row can be a status, a list item, or an entire disclosure button. */
+function Row({
+ className,
+ render,
+ layout = "inline",
+ ...props
+}: useRender.ComponentProps<"div"> & {
+ layout?: "inline" | "wrap-actions";
+}) {
+ const rowProps = {
+ className: cn(
+ "group/banner-row grid min-h-(--composer-banner-icon-column) w-full min-w-0 grid-cols-[var(--composer-banner-icon-column)_minmax(0,1fr)_auto] items-center gap-x-1 text-start",
+ "not-has-[>[data-slot=composer-banner-actions]]:grid-cols-[var(--composer-banner-icon-column)_minmax(0,1fr)]",
+ "[&:is(button)]:cursor-pointer [&:is(button)]:rounded-[0.5rem] [&:is(button)]:focus-visible:outline-2 [&:is(button)]:focus-visible:-outline-offset-2 [&:is(button)]:focus-visible:outline-ring",
+ layout === "wrap-actions" &&
+ "@max-[400px]:flex @max-[400px]:flex-wrap @max-[400px]:gap-y-1 @max-[400px]:*:data-[slot=composer-banner-actions]:ms-auto @max-[400px]:*:data-[slot=composer-banner-actions]:max-w-full @max-[400px]:has-[>[data-slot=composer-banner-icon]]:*:data-[slot=composer-banner-actions]:max-w-[calc(100%-var(--composer-banner-icon-column)-(--spacing(1)))] @max-[400px]:*:data-[slot=composer-banner-content]:min-h-(--composer-banner-icon-column) @max-[400px]:*:data-[slot=composer-banner-content]:flex-[1_1_10rem]",
+ className,
+ ),
+ "data-composer-banner-row": "true",
+ "data-composer-banner-layout": layout,
+ };
+ return useRender({
+ defaultTagName: "div",
+ render,
+ props: mergeProps<"div">(rowProps, props),
+ });
+}
+
+function Icon({ className, ...props }: ComponentProps<"span">) {
+ return (
+ <span
+ aria-hidden
+ data-slot="composer-banner-icon"
+ className={cn(
+ "col-start-1 row-start-1 flex w-(--composer-banner-icon-column) min-w-0 flex-none items-center justify-center text-muted-foreground [&>svg]:size-3",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Content({ className, ...props }: ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="composer-banner-content"
+ className={cn(
+ "col-start-2 row-start-1 flex min-w-0 items-center gap-1 *:data-[slot=composer-banner-separator]:mx-0",
+ "group-not-has-[>[data-slot=composer-banner-icon]]/banner-row:col-[1/3] group-not-has-[>[data-slot=composer-banner-icon]]/banner-row:ps-2 sm:group-not-has-[>[data-slot=composer-banner-icon]]/banner-row:ps-1.5",
+ "group-not-has-[>[data-slot=composer-banner-icon],>[data-slot=composer-banner-actions]]/banner-row:pe-2 sm:group-not-has-[>[data-slot=composer-banner-icon],>[data-slot=composer-banner-actions]]/banner-row:pe-1.5",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Separator() {
+ return (
+ <span
+ aria-hidden
+ data-slot="composer-banner-separator"
+ className="mx-1 inline-block flex-none text-muted-foreground/40"
+ >
+ ·
+ </span>
+ );
+}
+
+function Actions({ className, ...props }: ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="composer-banner-actions"
+ className={cn(
+ "col-start-3 row-start-1 flex flex-wrap items-center justify-end gap-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+/** Child rows keep their parent's columns and begin immediately after its header. */
+function Children({ className, render, ...props }: useRender.ComponentProps<"div">) {
+ return useRender({
+ defaultTagName: "div",
+ render,
+ props: mergeProps<"div">(
+ { className: cn("grid gap-px [&_[data-composer-banner-row]]:min-h-5", className) },
+ props,
+ ),
+ });
+}
+
+/** Bounded banner content uses the app's scroll area and fades only overflowing edges. */
+function Scroll({ className, ...props }: ComponentProps<typeof ScrollArea>) {
+ return (
+ <ScrollArea
+ scrollFade
+ className={cn(
+ "h-auto max-h-[min(24rem,40dvh)] rounded-none [&>[data-slot=scroll-area-viewport][data-has-overflow-y]]:pe-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Count({ className, ...props }: ComponentProps<"span">) {
+ return (
+ <span
+ className={cn(
+ "inline-flex min-w-(--composer-banner-icon-column,1em) flex-none justify-center font-medium text-muted-foreground tabular-nums",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Body({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <div
+ className={cn(
+ "min-w-0 ps-[calc(var(--composer-banner-icon-column)+(--spacing(1)))]",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function Dot({ className, ...props }: ComponentProps<"span">) {
+ return (
+ <span className={cn("size-1.5 flex-none rounded-full bg-current", className)} {...props} />
+ );
+}
+
+function ToggleIcon({ expanded, className }: { expanded: boolean; className?: string }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ buttonVariants({ size: "icon-xs", variant: "ghost" }),
+ "pointer-events-none",
+ className,
+ )}
+ >
+ <ChevronDownIcon className={cn("size-3.5", !expanded && "rotate-180")} />
+ </span>
+ );
+}
+
+function Dismiss({ className, children, ...props }: ComponentProps<typeof Button>) {
+ return (
+ <Button size="icon-xs" variant="ghost" className={className} {...props}>
+ {children ?? <XIcon className="size-3.5" />}
+ </Button>
+ );
+}
+
+export const ComposerBanner = {
+ Surface,
+ Peek,
+ Attachment,
+ Dock,
+ Column,
+ Root,
+ Row,
+ Icon,
+ Content,
+ Separator,
+ Actions,
+ Children,
+ Scroll,
+ Count,
+ Body,
+ Dot,
+ ToggleIcon,
+ Dismiss,
+};
diff --git a/apps/web/src/components/chat/ComposerStashBadge.test.tsx b/apps/web/src/components/chat/ComposerStashBadge.test.tsx
index 0e3839e6e..a350436cf 100644
--- a/apps/web/src/components/chat/ComposerStashBadge.test.tsx
+++ b/apps/web/src/components/chat/ComposerStashBadge.test.tsx
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
import { ComposerStashBadge } from "./ComposerStashBadge";
describe("ComposerStashBadge", () => {
- it("renders as an attached composer tab instead of a floating pill", () => {
+ it("renders as a compact composer banner tab", () => {
const markup = renderToStaticMarkup(
<ComposerStashBadge
count={3}
@@ -15,14 +15,11 @@ describe("ComposerStashBadge", () => {
/>,
);
- expect(markup).toContain("chat-composer-stash-tab");
- expect(markup).toContain("rounded-t-xl");
- expect(markup).toContain("border-b-0");
- expect(markup).toContain("items-center");
- expect(markup).not.toContain("items-start");
- expect(markup).not.toContain("rounded-full");
- expect(markup).not.toContain("opacity-70");
- expect(markup).not.toContain("border-border");
+ expect(markup).toContain('data-composer-banner-surface="attached"');
+ expect(markup).toContain('data-composer-shoulder-tab="true"');
+ expect(markup).toContain('data-prompt-stash-badge="true"');
+ expect(markup).toContain("Stash");
+ expect(markup).toContain("Stashed prompts: 3. Open stash.");
expect(markup).toContain('aria-expanded="false"');
});
@@ -61,8 +58,7 @@ describe("ComposerStashBadge", () => {
expect(markup).toContain("pointer-coarse:after:min-h-11");
expect(markup).toContain("Stashed prompts: 3. Open stash.");
expect(markup).toContain('aria-expanded="true"');
- expect(markup).not.toContain("chat-composer-stash-tab");
- expect(markup).not.toContain("rounded-t-xl");
+ expect(markup).not.toContain('data-composer-banner-surface="attached"');
expect(markup).not.toContain(" pointer-events-none ");
});
});
diff --git a/apps/web/src/components/chat/ComposerStashBadge.tsx b/apps/web/src/components/chat/ComposerStashBadge.tsx
index 493cebbd5..3aca17dca 100644
--- a/apps/web/src/components/chat/ComposerStashBadge.tsx
+++ b/apps/web/src/components/chat/ComposerStashBadge.tsx
@@ -3,11 +3,11 @@ import { memo } from "react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
+import { ComposerBanner } from "./ComposerBanner";
/**
- * Bookmark control that shows the stash count and opens the stash menu. It
- * sits behind the composer's shoulder unless another drawer needs that space,
- * then moves into the composer's existing controls.
+ * Bookmark tab that shows the stash count beside the composer's other attachments
+ * and opens the stash menu.
*
* On save the badge gives one quiet acknowledgement: it lifts to full
* opacity and the count ticks over. `pulseKey` changes per stash, remounting
@@ -24,17 +24,16 @@ export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
if (props.count === 0) return null;
const inline = props.placement === "inline";
const count = (
- <span
+ <ComposerBanner.Count
key={props.pulseKey}
className={cn(
- "text-[10px] font-medium leading-none tabular-nums",
props.pulsing
? "animate-[prompt-stash-count-enter_180ms_ease-out_both] text-primary motion-reduce:animate-none"
: "text-muted-foreground",
)}
>
{props.count}
- </span>
+ </ComposerBanner.Count>
);
if (inline) {
@@ -60,28 +59,28 @@ export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
}
return (
- <button
- type="button"
- data-prompt-stash-badge="true"
- aria-label={`Stashed prompts: ${props.count}. Open stash.`}
- aria-expanded={props.menuOpen}
- className={cn(
- "chat-composer-shoulder-tab chat-composer-stash-tab absolute -top-7 right-4 z-0 inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-t-xl border border-b-0 px-3 pb-1 text-xs leading-none",
- "transition-[color,border-color] duration-200",
- props.menuOpen && "pointer-events-none",
- props.menuOpen || props.pulsing
- ? "text-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
- onPointerDown={(event) => {
- // Keep composer focus so Escape/typing flows stay intact.
- event.preventDefault();
- }}
- onClick={props.onToggleMenu}
- >
- <BookmarkIcon className="size-3 shrink-0" aria-hidden="true" />
- Stash
- {count}
- </button>
+ <ComposerBanner.Root width="content" data-composer-shoulder-tab className="ml-auto">
+ <ComposerBanner.Row
+ render={<button type="button" />}
+ data-prompt-stash-badge="true"
+ aria-label={`Stashed prompts: ${props.count}. Open stash.`}
+ aria-expanded={props.menuOpen}
+ className={cn(
+ "transition-colors duration-200",
+ props.menuOpen && "pointer-events-none",
+ props.menuOpen || props.pulsing
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={props.onToggleMenu}
+ >
+ <ComposerBanner.Icon>
+ <BookmarkIcon />
+ </ComposerBanner.Icon>
+ <ComposerBanner.Content>Stash</ComposerBanner.Content>
+ <ComposerBanner.Actions>{count}</ComposerBanner.Actions>
+ </ComposerBanner.Row>
+ </ComposerBanner.Root>
);
});
diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.test.tsx
index 7ab8005af..7be1c6aec 100644
--- a/apps/web/src/components/chat/ComposerStashMenu.test.tsx
+++ b/apps/web/src/components/chat/ComposerStashMenu.test.tsx
@@ -15,11 +15,10 @@ describe("ComposerStashMenu", () => {
);
expect(markup).toContain('data-composer-stash-drawer="true"');
- expect(markup).toContain("chat-composer-drawer-surface");
- expect(markup).toContain("chat-composer-drawer-attached");
+ expect(markup).toContain('data-composer-banner-surface="attached"');
expect(markup).toContain('aria-label="Close stash"');
- expect(markup).not.toContain("dropdown-glass");
- expect(markup).not.toContain("Stashed prompts");
+ expect(markup).toContain('aria-label="Stashed prompts"');
+ expect(markup).toContain("Nothing stashed yet.");
});
it("shows saved image thumbnails and incomplete image states", () => {
@@ -62,13 +61,9 @@ describe("ComposerStashMenu", () => {
expect(markup).toContain('src="data:image/png;base64,AA=="');
expect(markup).toContain("1 image dropped");
expect(markup).toContain("saving 1 image");
- expect(markup).not.toContain("absolute top-1/2 right-2");
- expect(markup).toContain("pointer-events-none");
- expect(markup).toContain("pointer-coarse:pointer-events-auto");
- expect(markup).toContain("pointer-coarse:opacity-100");
- expect(markup).not.toContain("bg-popover!");
- expect(markup).toContain("[--control-icon-color:currentColor]");
- expect(markup).toContain("size-3.5 stroke-2");
- expect(markup).not.toContain("bg-background/90");
+ expect(markup).toContain('data-stash-restore="with-images"');
+ expect(markup).toContain('aria-label="Restore stashed prompt: Compare these screenshots"');
+ expect(markup).toContain('aria-label="Delete stashed prompt"');
+ expect(markup).toContain('dateTime="1970-01-01T00:00:00.000Z"');
});
});
diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx
index fc1283102..7b5eaa781 100644
--- a/apps/web/src/components/chat/ComposerStashMenu.tsx
+++ b/apps/web/src/components/chat/ComposerStashMenu.tsx
@@ -1,11 +1,10 @@
-import { XIcon } from "lucide-react";
+import { BookmarkIcon, FileTextIcon } from "lucide-react";
import { memo, useEffect, useRef, useState } from "react";
import { formatRelativeTimeLabel } from "../../timestampFormat";
import { cn } from "~/lib/utils";
import { type PromptStashEntry } from "../../promptStashStore";
-import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command";
-import { Button } from "../ui/button";
+import { ComposerBanner } from "./ComposerBanner";
const SNIPPET_MAX_CHARS = 90;
@@ -24,18 +23,19 @@ function stashEntrySnippet(entry: PromptStashEntry): string {
}
/**
- * Popover listing the stashed prompts. Keyboard-first: opened by ⌘S on an
+ * Attached banner listing the stashed prompts. Keyboard-first: opened by ⌘S on an
* empty composer, navigated with arrows, restored with Enter, dismissed
* with Escape. The listener runs capture-phase on window so it wins over
* the Lexical editor's handlers while the menu is open.
*/
export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
entries: ReadonlyArray<PromptStashEntry>;
+ stashShortcutLabel?: string | null;
onRestore: (entry: PromptStashEntry) => void;
onDelete: (entry: PromptStashEntry) => void;
onClose: () => void;
}) {
- const { entries, onRestore, onDelete, onClose } = props;
+ const { entries, stashShortcutLabel = null, onRestore, onDelete, onClose } = props;
const drawerRef = useRef<HTMLDivElement>(null);
const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
@@ -57,13 +57,6 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
}, [onClose]);
- useEffect(() => {
- if (entries.length === 0) return;
- if (!entries.some((entry) => entry.id === highlightedId)) {
- setHighlightedId(entries[0]?.id ?? null);
- }
- }, [entries, highlightedId]);
-
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.key === "Escape") {
@@ -76,11 +69,17 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
if (entries.length === 0) return;
event.preventDefault();
event.stopPropagation();
- const currentIndex = entries.findIndex((entry) => entry.id === highlightedId);
+ const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
const offset = event.key === "ArrowDown" ? 1 : -1;
const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
setHighlightedId(entries[nextIndex]?.id ?? null);
+ const nextButton =
+ drawerRef.current?.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
+ nextButton?.scrollIntoView({ block: "nearest" });
+ if (drawerRef.current?.contains(document.activeElement)) {
+ nextButton?.focus({ preventScroll: true });
+ }
return;
}
if (event.key === "Enter") {
@@ -104,61 +103,77 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
};
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
- }, [entries, highlightedEntry, highlightedId, onClose, onDelete, onRestore]);
+ }, [entries, highlightedEntry, onClose, onDelete, onRestore]);
return (
- <Command autoHighlight={false} mode="none">
- <div
- ref={drawerRef}
- className="chat-composer-drawer-surface chat-composer-drawer-attached relative w-full overflow-hidden"
- data-composer-stash-drawer="true"
+ <ComposerBanner.Root ref={drawerRef} data-composer-stash-drawer="true">
+ <ComposerBanner.Row
+ render={<button type="button" />}
+ aria-label="Close stash"
+ aria-expanded="true"
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={onClose}
>
- <div className="flex h-7 items-center justify-end px-2 pt-1">
- <Button
- variant="ghost-muted"
- size="icon-micro"
- aria-label="Close stash"
- onPointerDown={(event) => event.preventDefault()}
- onClick={onClose}
- >
- <XIcon className="size-3" />
- </Button>
- </div>
- <CommandList className="max-h-64 scroll-pb-6">
- <CommandGroup>
- {entries.length === 0 ? (
- <p className="px-3 py-1.5 text-secondary-label text-xs">
- Nothing stashed yet. Press ⌘S with a prompt in the composer to stash it.
- </p>
- ) : (
- entries.map((entry) => (
- <CommandItem
- key={entry.id}
- value={entry.id}
- className={cn(
- "group/stash relative cursor-pointer select-none gap-3 rounded-lg px-3 py-1.5! hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
- highlightedId === entry.id && "bg-accent! text-accent-foreground!",
- )}
- onMouseMove={() => {
- if (highlightedId !== entry.id) setHighlightedId(entry.id);
- }}
- onMouseDown={(event) => {
- event.preventDefault();
- }}
- onClick={() => {
- onRestore(entry);
- }}
- >
- <span className="min-w-0 flex-1 truncate text-xs">
+ <ComposerBanner.Icon>
+ <BookmarkIcon />
+ </ComposerBanner.Icon>
+ <ComposerBanner.Content className="text-muted-foreground">Stash</ComposerBanner.Content>
+ <ComposerBanner.Actions>
+ <ComposerBanner.Count>{entries.length}</ComposerBanner.Count>
+ <ComposerBanner.ToggleIcon expanded />
+ </ComposerBanner.Actions>
+ </ComposerBanner.Row>
+ <ComposerBanner.Scroll>
+ <ComposerBanner.Children render={<ul role="list" />} aria-label="Stashed prompts">
+ {entries.length === 0 ? (
+ <ComposerBanner.Row render={<li />}>
+ <ComposerBanner.Icon />
+ <ComposerBanner.Content className="text-muted-foreground">
+ Nothing stashed yet.
+ {stashShortcutLabel
+ ? ` Press ${stashShortcutLabel} with a prompt in the composer to stash it.`
+ : null}
+ </ComposerBanner.Content>
+ </ComposerBanner.Row>
+ ) : (
+ entries.map((entry) => (
+ <ComposerBanner.Row
+ render={<li />}
+ key={entry.id}
+ data-stash-entry={entry.id}
+ data-highlighted={highlightedEntry?.id === entry.id || undefined}
+ className={cn(
+ "relative rounded-sm",
+ highlightedEntry?.id === entry.id && "bg-accent text-accent-foreground",
+ )}
+ onMouseMove={() => {
+ if (highlightedId !== entry.id) setHighlightedId(entry.id);
+ }}
+ onFocus={() => setHighlightedId(entry.id)}
+ >
+ <ComposerBanner.Icon>
+ <FileTextIcon />
+ </ComposerBanner.Icon>
+ <ComposerBanner.Content>
+ <button
+ type="button"
+ className="min-w-0 flex-1 cursor-pointer truncate text-left text-foreground/80 outline-none before:absolute before:inset-0 before:rounded-sm focus-visible:before:ring-2 focus-visible:before:ring-ring"
+ data-stash-restore={entry.id}
+ aria-label={`Restore stashed prompt: ${stashEntrySnippet(entry)}`}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={() => onRestore(entry)}
+ >
{stashEntrySnippet(entry)}
- </span>
+ </button>
+ </ComposerBanner.Content>
+ <ComposerBanner.Actions>
{entry.pendingImageCount ? (
- <span className="shrink-0 text-[10px] text-secondary-label">
+ <span className="shrink-0 text-muted-foreground">
saving {entry.pendingImageCount} image
{entry.pendingImageCount === 1 ? "" : "s"}…
</span>
) : missingImageCount(entry) > 0 ? (
- <span className="shrink-0 text-[10px] text-warning-foreground">
+ <span className="shrink-0 text-warning-foreground">
{missingImageCount(entry)} image
{missingImageCount(entry) === 1 ? "" : "s"} dropped
</span>
@@ -171,32 +186,29 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
src={attachment.dataUrl}
alt=""
aria-hidden="true"
- className="size-5 rounded border border-border/70 object-cover"
+ className="size-4 rounded border border-border/70 object-cover"
/>
))}
</span>
) : null}
- <span className="shrink-0 text-secondary-label text-xs max-sm:hidden">
+ <time
+ dateTime={entry.createdAt}
+ className="shrink-0 text-muted-foreground tabular-nums max-sm:hidden"
+ >
{formatRelativeTimeLabel(entry.createdAt)}
- </span>
- <Button
- variant="ghost"
- size="icon-xs"
- className="pointer-events-none shrink-0 [--control-icon-color:currentColor] opacity-0 shadow-none! transition-opacity pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 group-hover/stash:pointer-events-auto group-hover/stash:opacity-100 group-focus-within/stash:pointer-events-auto group-focus-within/stash:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100"
+ </time>
+ <ComposerBanner.Dismiss
+ className="z-10"
aria-label="Delete stashed prompt"
- onClick={(event) => {
- event.stopPropagation();
- onDelete(entry);
- }}
- >
- <XIcon className="size-3.5 stroke-2" />
- </Button>
- </CommandItem>
- ))
- )}
- </CommandGroup>
- </CommandList>
- </div>
- </Command>
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={() => onDelete(entry)}
+ />
+ </ComposerBanner.Actions>
+ </ComposerBanner.Row>
+ ))
+ )}
+ </ComposerBanner.Children>
+ </ComposerBanner.Scroll>
+ </ComposerBanner.Root>
);
});
diff --git a/apps/web/src/components/roster/BotPromptComposer.test.tsx b/apps/web/src/components/roster/BotPromptComposer.test.tsx
index caa5c9eeb..0e137364b 100644
--- a/apps/web/src/components/roster/BotPromptComposer.test.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.test.tsx
@@ -18,6 +18,7 @@ import {
findMentionedBotId,
isBotPromptSubmissionCurrent,
isBotPromptExpanded,
+ restoreBotStashPrompt,
shouldFocusBotPromptForKey,
} from "./BotPromptComposer";
@@ -80,6 +81,15 @@ describe("bot prompt composer", () => {
expect(shouldFocusBotPromptForKey({ ...baseInput, isComposing: true })).toBe(false);
});
+ it("restores stashed text after the current draft", () => {
+ expect(restoreBotStashPrompt("Current draft ", "Stashed follow-up")).toBe(
+ "Current draft\n\nStashed follow-up",
+ );
+ expect(restoreBotStashPrompt("", "Stashed follow-up")).toBe("Stashed follow-up");
+ expect(restoreBotStashPrompt(" ", "Stashed follow-up")).toBe("Stashed follow-up");
+ expect(restoreBotStashPrompt("Current draft", "")).toBe("Current draft");
+ });
+
it("uses the available chat width", () => {
const markup = renderToStaticMarkup(
<BotPromptComposer
@@ -90,7 +100,7 @@ describe("bot prompt composer", () => {
/>,
);
- expect(markup).toContain('<form class="w-full ');
+ expect(markup).toContain('class="w-full px-4');
expect(markup).not.toContain("max-w-4xl");
});
diff --git a/apps/web/src/components/roster/BotPromptComposer.tsx b/apps/web/src/components/roster/BotPromptComposer.tsx
index 6201863b0..73276d726 100644
--- a/apps/web/src/components/roster/BotPromptComposer.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.tsx
@@ -1,9 +1,29 @@
+import { useAtomValue } from "@effect/atom-react";
+import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
import { ArrowUpIcon, AtSignIcon, PaperclipIcon, PlusIcon } from "lucide-react";
-import { type ComponentProps, useEffect, useRef, useState } from "react";
+import { type ComponentProps, useCallback, useEffect, useRef, useState } from "react";
-import { cn } from "../../lib/utils";
+import {
+ hydrateImagesFromPersisted,
+ type PersistedComposerImageAttachment,
+} from "../../composerDraftStore";
+import { isCommandPaletteOpen } from "../../commandPaletteBus";
+import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings";
+import { compressImageForStash } from "../../lib/imageCompression";
+import { cn, randomUUID } from "../../lib/utils";
+import {
+ MAX_STASH_ENTRIES,
+ partitionStashAttachments,
+ usePromptStashStore,
+ type PromptStashEntry,
+} from "../../promptStashStore";
+import { primaryServerKeybindingsAtom } from "../../state/server";
+import { ComposerBanner } from "../chat/ComposerBanner";
import { ExpandedImageDialog } from "../chat/ExpandedImageDialog";
+import { ComposerStashBadge } from "../chat/ComposerStashBadge";
+import { ComposerStashMenu } from "../chat/ComposerStashMenu";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { toastManager } from "../ui/toast";
import { clearBotDraft, readBotDraft, writeBotDraft } from "./botDraftStore";
import { BotModelPicker } from "./BotModelPicker";
import {
@@ -82,6 +102,13 @@ export function findMentionedBotId(
return mentions.toSorted((left, right) => right.index - left.index)[0]?.id;
}
+export function restoreBotStashPrompt(currentPrompt: string, stashedPrompt: string): string {
+ if (stashedPrompt.length === 0) return currentPrompt;
+ return currentPrompt.trim().length > 0
+ ? `${currentPrompt.trimEnd()}\n\n${stashedPrompt}`
+ : stashedPrompt;
+}
+
export function BotPromptComposer({
botName,
draftKey,
@@ -97,18 +124,27 @@ export function BotPromptComposer({
modelPicker: BotModelPickerProps | null;
onSubmit: (prompt: string, files: readonly File[], respondingBotId?: string) => Promise<boolean>;
}) {
+ const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const [draft, setDraft] = useState(() => (draftKey ? readBotDraft(draftKey) : ""));
const [attachments, setAttachments] = useState<BotPromptAttachment[]>([]);
const [failedAttachmentIds, setFailedAttachmentIds] = useState<ReadonlySet<string>>(
() => new Set(),
);
const [expandedAttachmentId, setExpandedAttachmentId] = useState<string | null>(null);
+ const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
+ const [stashPulse, setStashPulse] = useState({ key: 0, active: false });
const attachmentsRef = useRef<BotPromptAttachment[]>([]);
const releasedPreviewUrlsRef = useRef(new Set<string>());
const fileInputRef = useRef<HTMLInputElement>(null);
const promptInputRef = useRef<HTMLTextAreaElement>(null);
const revisionRef = useRef(0);
- const releaseAttachments = (items: readonly BotPromptAttachment[]) => {
+ const stashPulseTimeoutRef = useRef<number | null>(null);
+ const stashInFlightRef = useRef<Set<string>>(new Set());
+ const stashQueue = usePromptStashStore((state) => state.entries);
+ const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
+ const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
+ const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
+ const releaseAttachments = useCallback((items: readonly BotPromptAttachment[]) => {
const unreleased = items.filter((attachment) => {
if (
attachment.previewUrl === null ||
@@ -120,12 +156,16 @@ export function BotPromptComposer({
return true;
});
releaseBotPromptAttachments(unreleased);
- };
- const persistDraft = (next: string) => {
- revisionRef.current += 1;
- setDraft(next);
- if (draftKey) writeBotDraft(draftKey, next);
- };
+ }, []);
+ const persistDraft = useCallback(
+ (next: string) => {
+ revisionRef.current += 1;
+ setDraft(next);
+ setIsStashMenuOpen(false);
+ if (draftKey) writeBotDraft(draftKey, next);
+ },
+ [draftKey],
+ );
const persistDraftRef = useRef(persistDraft);
persistDraftRef.current = persistDraft;
@@ -135,10 +175,13 @@ export function BotPromptComposer({
}, [draftKey]);
useEffect(
() => () => {
+ if (stashPulseTimeoutRef.current !== null) {
+ window.clearTimeout(stashPulseTimeoutRef.current);
+ }
releaseAttachments(attachmentsRef.current);
attachmentsRef.current = [];
},
- [],
+ [releaseAttachments],
);
const expanded = modelPicker !== null || attachments.length > 0 || isBotPromptExpanded(draft);
@@ -172,8 +215,217 @@ export function BotPromptComposer({
? null
: buildBotPromptAttachmentPreview(attachments, expandedAttachmentId, failedAttachmentIds);
+ const pulseStashBadge = useCallback(() => {
+ if (stashPulseTimeoutRef.current !== null) {
+ window.clearTimeout(stashPulseTimeoutRef.current);
+ }
+ setStashPulse((current) => ({ key: current.key + 1, active: true }));
+ stashPulseTimeoutRef.current = window.setTimeout(() => {
+ setStashPulse((current) => ({ ...current, active: false }));
+ stashPulseTimeoutRef.current = null;
+ }, 220);
+ }, []);
+
+ const restoreStashEntry = useCallback(
+ (candidate: PromptStashEntry) => {
+ const { entry, durable } = takeStashEntry(candidate.id);
+ if (!entry) return;
+ persistDraft(restoreBotStashPrompt(draft, entry.prompt));
+
+ const hydrated = hydrateImagesFromPersisted(entry.attachments).map((image) => image.file);
+ const currentAttachments = attachmentsRef.current;
+ const existingKeys = new Set(
+ currentAttachments.map(
+ (attachment) =>
+ `${attachment.file.type}\0${attachment.file.size}\0${attachment.file.name}`,
+ ),
+ );
+ const unique = hydrated.filter((file) => {
+ const key = `${file.type}\0${file.size}\0${file.name}`;
+ if (existingKeys.has(key)) return false;
+ existingKeys.add(key);
+ return true;
+ });
+ const capacity = Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - currentAttachments.length);
+ const restoredFiles = unique.slice(0, capacity);
+ const restoredAttachments = createBotPromptAttachments(restoredFiles);
+ const updated = [...currentAttachments, ...restoredAttachments];
+ attachmentsRef.current = updated;
+ setAttachments(updated);
+ setIsStashMenuOpen(false);
+
+ const missingImageCount =
+ entry.droppedImageNames.length +
+ (entry.unreadableImageNames?.length ?? 0) +
+ (entry.pendingImageCount ?? 0) +
+ (entry.attachments.length - hydrated.length) +
+ (unique.length - restoredFiles.length);
+ if (missingImageCount > 0) {
+ toastManager.add({
+ type: "warning",
+ title: "Some images were not restored",
+ description: `${missingImageCount} image${missingImageCount === 1 ? " was" : "s were"} unavailable or over the attachment limit.`,
+ });
+ }
+ if (!durable) {
+ toastManager.add({
+ type: "warning",
+ title: "Stash entry may come back",
+ description: "Browser storage rejected the update.",
+ });
+ }
+ window.requestAnimationFrame(() => promptInputRef.current?.focus());
+ },
+ [draft, persistDraft, takeStashEntry],
+ );
+
+ const deleteStashEntry = useCallback(
+ (entry: PromptStashEntry) => {
+ const { durable } = takeStashEntry(entry.id);
+ if (!durable) {
+ toastManager.add({
+ type: "warning",
+ title: "Stash entry may come back",
+ description: "Browser storage rejected the delete.",
+ });
+ }
+ },
+ [takeStashEntry],
+ );
+
+ const stashCurrentPrompt = useCallback(async () => {
+ const prompt = draft.trim();
+ const stashedAttachments = [...attachmentsRef.current];
+ const stashedFiles = stashedAttachments.map((attachment) => attachment.file);
+ if (prompt.length === 0 && stashedFiles.length === 0) {
+ setIsStashMenuOpen((open) => !open);
+ return;
+ }
+ const snapshotKey = `${draftKey ?? ""}\0${prompt}\0${stashedFiles
+ .map((file) => `${file.name}:${file.size}:${file.lastModified}`)
+ .join("\0")}`;
+ if (stashInFlightRef.current.has(snapshotKey)) return;
+ stashInFlightRef.current.add(snapshotKey);
+
+ const entryId = randomUUID();
+ try {
+ const { evicted, written, durable } = stashEntryToQueue({
+ id: entryId,
+ createdAt: new Date().toISOString(),
+ prompt,
+ attachments: [],
+ droppedImageNames: [],
+ unreadableImageNames: [],
+ pendingImageCount: stashedFiles.length,
+ });
+ if (!written) {
+ toastManager.add({
+ type: "error",
+ title: "Could not stash this prompt",
+ description: "Browser storage rejected the write, so the message was left in place.",
+ });
+ return;
+ }
+
+ persistDraft("");
+ const stashedIds = new Set(stashedAttachments.map((attachment) => attachment.id));
+ const remaining = attachmentsRef.current.filter(
+ (attachment) => !stashedIds.has(attachment.id),
+ );
+ attachmentsRef.current = remaining;
+ setAttachments(remaining);
+ setFailedAttachmentIds(
+ (current) => new Set([...current].filter((id) => !stashedIds.has(id))),
+ );
+ if (expandedAttachmentId && stashedIds.has(expandedAttachmentId)) {
+ setExpandedAttachmentId(null);
+ }
+ releaseAttachments(stashedAttachments);
+ setIsStashMenuOpen(false);
+ pulseStashBadge();
+ if (!durable) {
+ toastManager.add({
+ type: "warning",
+ title: "Stashed prompt will not survive a reload",
+ description: "Browser storage is unavailable, so the stash is kept for this session.",
+ });
+ }
+ if (evicted) {
+ toastManager.add({
+ type: "warning",
+ title: "Oldest stashed prompt discarded",
+ description: `The stash holds ${MAX_STASH_ENTRIES} prompts.`,
+ });
+ }
+
+ const persistedImages: PersistedComposerImageAttachment[] = [];
+ const droppedImageNames: string[] = [];
+ const unreadableImageNames: string[] = [];
+ for (const file of stashedFiles) {
+ const result = await compressImageForStash(file);
+ if (!result.ok) {
+ (result.reason === "too-large" ? droppedImageNames : unreadableImageNames).push(
+ file.name,
+ );
+ continue;
+ }
+ persistedImages.push({
+ id: randomUUID(),
+ name: file.name,
+ mimeType: result.image.mimeType,
+ sizeBytes: result.image.sizeBytes,
+ dataUrl: result.image.dataUrl,
+ });
+ }
+ const { kept, droppedNames } = partitionStashAttachments(persistedImages);
+ const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, {
+ attachments: kept,
+ droppedImageNames: [...droppedImageNames, ...droppedNames],
+ unreadableImageNames,
+ });
+ if (attached && !imagesDurable && durable && stashedFiles.length > 0) {
+ toastManager.add({
+ type: "warning",
+ title: "Stashed images were not saved",
+ description: "The text was saved, but the images may be missing after a reload.",
+ });
+ } else if (!attached && kept.length > 0) {
+ toastManager.add({
+ type: "warning",
+ title: "Stashed images did not attach",
+ description: "The prompt was restored or deleted before its images finished saving.",
+ });
+ }
+ } finally {
+ stashInFlightRef.current.delete(snapshotKey);
+ }
+ }, [
+ draft,
+ draftKey,
+ expandedAttachmentId,
+ finalizeStashEntryImages,
+ persistDraft,
+ pulseStashBadge,
+ releaseAttachments,
+ stashEntryToQueue,
+ ]);
+
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
+ const shortcutCommand = resolveShortcutCommand(event, keybindings, {
+ context: {
+ terminalFocus: false,
+ terminalOpen: false,
+ modelPickerOpen: false,
+ },
+ });
+ if (shortcutCommand === "composer.stash") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!event.repeat && !isCommandPaletteOpen()) void stashCurrentPrompt();
+ return;
+ }
+
const target = event.target;
const editableTarget =
target instanceof Element &&
@@ -200,12 +452,13 @@ export function BotPromptComposer({
promptInputRef.current?.focus();
};
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, []);
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [keybindings, stashCurrentPrompt]);
return (
<form
+ data-chat-composer-form="true"
className="w-full px-4 pb-4 pt-2 sm:px-6 sm:pb-6"
onSubmit={(event) => {
event.preventDefault();
@@ -224,24 +477,48 @@ export function BotPromptComposer({
prompt,
submittedAttachments.map((attachment) => attachment.file),
findMentionedBotId(prompt, mentionBots),
- ).then((sent) => {
- if (sent) {
- releaseAttachments(submittedAttachments);
- return;
- }
- if (!isBotPromptSubmissionCurrent(submissionRevision, revisionRef.current)) {
- releaseAttachments(submittedAttachments);
- return;
- }
- revisionRef.current += 1;
- setDraft(prompt);
- if (draftKey) writeBotDraft(draftKey, prompt);
- attachmentsRef.current = submittedAttachments;
- setAttachments(submittedAttachments);
- setFailedAttachmentIds(submittedFailedIds);
- });
+ ).then(
+ (sent) => {
+ if (sent) {
+ releaseAttachments(submittedAttachments);
+ setIsStashMenuOpen(false);
+ return;
+ }
+ if (!isBotPromptSubmissionCurrent(submissionRevision, revisionRef.current)) {
+ releaseAttachments(submittedAttachments);
+ return;
+ }
+ revisionRef.current += 1;
+ setDraft(prompt);
+ if (draftKey) writeBotDraft(draftKey, prompt);
+ attachmentsRef.current = submittedAttachments;
+ setAttachments(submittedAttachments);
+ setFailedAttachmentIds(submittedFailedIds);
+ },
+ () => undefined,
+ );
}}
>
+ <ComposerBanner.Dock className="relative z-0">
+ <ComposerBanner.Column>
+ {isStashMenuOpen ? (
+ <ComposerStashMenu
+ entries={stashQueue}
+ stashShortcutLabel={shortcutLabelForCommand(keybindings, "composer.stash")}
+ onRestore={restoreStashEntry}
+ onDelete={deleteStashEntry}
+ onClose={() => setIsStashMenuOpen(false)}
+ />
+ ) : null}
+ </ComposerBanner.Column>
+ <ComposerStashBadge
+ count={stashQueue.length}
+ menuOpen={isStashMenuOpen}
+ pulseKey={stashPulse.key}
+ pulsing={stashPulse.active}
+ onToggleMenu={() => setIsStashMenuOpen((open) => !open)}
+ />
+ </ComposerBanner.Dock>
<div
data-testid="bot-prompt-composer"
data-expanded={expanded || undefined}
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
index b9d042f51..31475b209 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -171,34 +171,28 @@ describe("KeybindingsSettings.logic", () => {
const rows = buildKeybindingRows(
[
{
- command: "chat.new",
+ command: "preview.zoomIn",
shortcut: {
- key: "n",
+ key: "=",
modKey: true,
metaKey: false,
ctrlKey: false,
altKey: false,
shiftKey: false,
},
- whenAst: {
- type: "not",
- node: { type: "identifier", name: "terminalFocus" },
- },
+ whenAst: { type: "identifier", name: "previewFocus" },
},
{
- command: "chat.new",
+ command: "preview.zoomIn",
shortcut: {
- key: "o",
+ key: "+",
modKey: true,
metaKey: false,
ctrlKey: false,
altKey: false,
- shiftKey: true,
- },
- whenAst: {
- type: "not",
- node: { type: "identifier", name: "terminalFocus" },
+ shiftKey: false,
},
+ whenAst: { type: "identifier", name: "previewFocus" },
},
] satisfies ResolvedKeybindingsConfig,
"",
diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts
index 1e6e4f5f3..b40e09209 100644
--- a/packages/shared/src/keybindings.ts
+++ b/packages/shared/src/keybindings.ts
@@ -39,7 +39,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+shift+f", command: "projectSearch.toggle", when: "!terminalFocus" },
{ key: "mod+alt+shift+t", command: "themeEditor.toggle" },
{ key: "mod+s", command: "composer.stash", when: "!terminalFocus" },
- { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },