fix: reconcile main's round-8 features after the rebase

Re-applies the deltas that mid-stack blob reverts discarded, and merges
main's work into the v2-owned surfaces:

- keybindings: main's STATIC_KEYBINDING_COMMANDS rename plus both new
  commands (rightPanel.toggleMaximized alongside threadPanel.toggle)
- OpenInPicker: main's remote-open/SSH routing and favorite-editor
  shortcut layered onto the branch's panel/toolbar variants; the
  extracted shouldShowOpenInPicker now takes remoteOpenMode
- ChatMarkdown: main's bare-filename resolver (#6297) ported into the
  branch's module-level component factory, plus #4133 title-attribute
  stripping on links and images
- ComposerPrimaryActions: main's #4781 model (stop stays reachable, send
  joins it when Enter-to-send is unavailable) carrying the branch's
  steering send button
- ComposerPendingUserInputPanel: main's collapsible redesign with the v2
  RuntimeRequestId and responseCapability gate
- ChatComposer: main's oversized-prompt submission guard wrapping the
  branch's dispatch-mode send
- preview shell: main's container-aware width clamp ported into the
  branch's usePreviewPanelInlineSize hook
- MessagesTimeline/Sidebar: main's day-aware timestamps, code-font tool
  bodies and provider accent badges on the v2 runtime shell
- index.css: main's @variant dark migration (#6381) replaces the branch's
  standalone .dark block
- contracts: main's send-turn image mime allowlist re-homed to
  chatAttachment.ts, where v2 keeps the other send-turn limits

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 committed 2026-08-15 17:18:32 +02:00
1 parent 4442054fc7
commit 0c68291bc6
33 files changed
+1481 -1133

No files matched your search

@@ -57,6 +57,7 @@ import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/re
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { useNewTaskFlow } from "./new-task-flow-provider";
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import {
@@ -584,11 +585,17 @@ export function NewTaskDraftScreen(props: {
flow.environments.find(
(environment) => environment.environmentId === flow.selectedEnvironmentId,
)?.environmentLabel ?? "Environment";
const currentBranchName =
const availableCurrentBranchName =
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const selectedBranchName = flow.selectedBranchName ?? currentBranchName;
const selectedBranchName = resolveProjectThreadCreationBranch({
workspaceMode: flow.workspaceMode,
selectedBranch:
flow.selectedBranchName ??
(flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
currentCheckoutBranch: flow.currentCheckoutBranchName,
});
const selectedBranchLabel = resolveNewTaskBranchLabel({
branchName: selectedBranchName,
startFromOrigin: flow.startFromOrigin,
@@ -717,11 +724,16 @@ export function NewTaskDraftScreen(props: {
}),
projectTitle: selectedProject.title,
});
const creationBranch = resolveProjectThreadCreationBranch({
workspaceMode,
selectedBranch: selectedBranchName,
currentCheckoutBranch: flow.currentCheckoutBranchName,
});
const result = await createProjectThread({
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
branch: creationBranch,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
startFromOrigin,
runtimeMode,
@@ -327,9 +327,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const showStopAction = props.canStopThread;
const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
? "Queue"
: "Send";
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const connectionStatus = composerConnectionStatus({
+7
View File
@@ -127,6 +127,7 @@ import * as ReviewService from "./review/ReviewService.ts";
import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
import * as ProjectService from "./project/ProjectService.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
@@ -436,6 +437,7 @@ const makeWsRpcLayer = (
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const review = yield* ReviewService.ReviewService;
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
@@ -575,6 +577,11 @@ const makeWsRpcLayer = (
availableEditors: yield* resolveAvailableEditorsForConfig(
externalLauncher.resolveAvailableEditors(),
),
// Same discovery-with-timeout treatment as editors: a slow probe
// must not stall server.getConfig, so it degrades to no targets.
remoteOpenTargets: yield* resolveAvailableEditorsForConfig(
remoteOpenTargets.resolveTargets(),
),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
@@ -17,6 +17,7 @@ import {
resolveLocalCheckoutBranchMismatch,
resolvePreviousWorktreeLabel,
resolvePreviousWorktreeSeed,
sanitizeNewRefName,
shouldIncludeBranchPickerItem,
shouldShowComposerContextStrip,
shouldShowEnvironmentIndicator,
@@ -742,4 +743,93 @@ describe("shouldIncludeBranchPickerItem", () => {
}),
).toBe(false);
});
// Typing a spaced name must still surface the ref it would have been created
// as, or the picker shows nothing at all for that query.
it("surfaces an existing ref matching the sanitized query", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "new-branch",
normalizedQuery: "new branch",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(true);
});
// A partial query has to reach the ref it would have been created as, so
// searching "hello w" still finds an existing hello-world.
it("surfaces a ref from a partial query containing a space", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "hello-world",
normalizedQuery: "hello w",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(true);
});
it("excludes refs matching neither the raw nor the sanitized query", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "main",
normalizedQuery: "new branch",
createBranchItemValue: null,
checkoutPullRequestItemValue: null,
}),
).toBe(false);
});
});
// Git rejects ASCII space and the ASCII control characters in ref names, so a
// typed name like "new branch" can only ever fail. Replacing exactly those can
// turn a failing name into a working one without touching a name git already
// accepts, including one holding non-ASCII whitespace such as U+00A0.
describe("sanitizeNewRefName", () => {
it("replaces a space with a dash", () => {
expect(sanitizeNewRefName("new branch")).toBe("new-branch");
});
it("collapses a run of whitespace into a single dash", () => {
expect(sanitizeNewRefName("new branch")).toBe("new-branch");
});
it("trims surrounding whitespace instead of turning it into dashes", () => {
expect(sanitizeNewRefName(" new branch ")).toBe("new-branch");
});
it("replaces tabs, which git rejects just like spaces", () => {
expect(sanitizeNewRefName("new\tbranch")).toBe("new-branch");
});
// git accepts U+00A0, U+2009 and other non-ASCII whitespace in ref names, so
// rewriting them would silently create a ref the user never typed.
it("preserves whitespace that git accepts", () => {
expect(sanitizeNewRefName("new\u00a0branch")).toBe("new\u00a0branch");
expect(sanitizeNewRefName("new\u2009branch")).toBe("new\u2009branch");
});
it("keeps slashes so nested ref names survive", () => {
expect(sanitizeNewRefName("feature/new thing")).toBe("feature/new-thing");
});
it("preserves case because git ref names are case sensitive", () => {
expect(sanitizeNewRefName("Feature/New Thing")).toBe("Feature/New-Thing");
});
it("leaves an already valid ref name untouched", () => {
expect(sanitizeNewRefName("feature/login")).toBe("feature/login");
});
it("returns an empty string for whitespace-only input", () => {
expect(sanitizeNewRefName(" ")).toBe("");
});
// Scoped deliberately to whitespace: git accepts consecutive dashes, so
// collapsing them would rewrite names the user may have typed on purpose.
it("does not collapse dashes the user typed", () => {
expect(sanitizeNewRefName("new - branch")).toBe("new---branch");
expect(sanitizeNewRefName("foo--bar")).toBe("foo--bar");
});
});
+99 -14
View File
@@ -90,6 +90,13 @@ import { usePreparedConnection } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { projectEnvironment } from "../state/projects";
import {
claimWorkspaceBasenameLookup,
needsWorkspaceBasenameLookup,
pickWorkspaceBasenameMatch,
WORKSPACE_BASENAME_LOOKUP_LIMIT,
} from "../workspaceBasenameLookup";
import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
@@ -110,6 +117,8 @@ interface ChatMarkdownProps {
className?: string;
/** Treat single newlines as hard breaks — chat-style user input. */
lineBreaks?: boolean;
/** Parse sanitized raw HTML instead of displaying its source text. */
parseRawHtml?: boolean;
}
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
@@ -146,6 +155,26 @@ function findTaskListMarkerOffset(markdown: string, listItemStart: number): numb
if (!match?.[1]) return null;
return listItemStart + firstLine.indexOf(match[1]);
}
/**
* The default `1.25rem` marker gutter (`.chat-markdown ol`) fits two-digit
* decimal markers. Once a list's last item reaches three digits (item 100+),
* `list-style-position: outside` paints the marker wider than that gutter and
* the leading digit gets clipped by the item's own overflow. Rather than
* widening the gutter for every list, only lists whose last marker is 3+
* digits get a wider `--list-gutter`, sized to that marker's digit count.
*/
export function orderedListGutterStyle(
itemCount: number,
start: number | undefined,
): { "--list-gutter": string } | undefined {
const firstNumber = typeof start === "number" && Number.isFinite(start) ? start : 1;
const lastNumber = firstNumber + Math.max(itemCount - 1, 0);
const digits = String(Math.abs(lastNumber)).length;
if (digits <= 2) return undefined;
return { "--list-gutter": `${digits + 1}ch` };
}
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
...defaultSchema,
attributes: {
@@ -449,7 +478,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
{children}
</table>
</ScrollArea>
<div className="chat-markdown-table-footer select-none">
<div className="mt-0.5 flex items-center justify-between select-none">
<Tooltip>
<TooltipTrigger
render={
@@ -642,12 +671,12 @@ function MarkdownCodeBlock({
return (
<div
className="chat-markdown-codeblock border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-[var(--radius)] border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
data-language={language}
data-wrap={wrapped ? "true" : "false"}
>
<div className="chat-markdown-codeblock-header select-none">
<span className="chat-markdown-codeblock-title">
<div className="chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none">
<span className="inline-flex min-w-0 items-center gap-[0.4rem] [font-family:var(--font-mono,ui-monospace,SFMono-Regular,monospace)] [font-size:0.6875rem]">
<MarkdownCodeBlockTitleContent
fenceTitle={fenceTitle}
language={language}
@@ -791,6 +820,7 @@ interface MarkdownFileLinkProps {
theme: "light" | "dark";
threadRef?: ScopedThreadRef | undefined;
onOpen: (targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>;
onOpenInPanel: (workspaceRelativePath: string, line: number | undefined) => void;
onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
className?: string | undefined;
}
@@ -897,7 +927,10 @@ const failedFaviconHosts = new Set<string>();
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
const [failedHost, setFailedHost] = useState<string | null>(null);
return (
<span className="chat-markdown-link-favicon" aria-hidden>
<span
className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
aria-hidden
>
{failedHost === host || failedFaviconHosts.has(host) ? (
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
) : (
@@ -1044,7 +1077,7 @@ function MarkdownExternalLinkContent({
const leadingLength = leadingExternalLinkTextLength(plainText);
return (
<>
<span className="chat-markdown-link-leading">
<span className="whitespace-nowrap">
<MarkdownLinkFavicon host={host} />
{plainText.slice(0, leadingLength)}
</span>
@@ -1060,7 +1093,7 @@ function MarkdownExternalLinkContent({
const leadingLength = leadingExternalLinkTextLength(firstChild);
return (
<>
<span className="chat-markdown-link-leading">
<span className="whitespace-nowrap">
<MarkdownLinkFavicon host={host} />
{firstChild.slice(0, leadingLength)}
</span>
@@ -1072,7 +1105,7 @@ function MarkdownExternalLinkContent({
return (
<>
<span className="chat-markdown-link-leading">
<span className="whitespace-nowrap">
<MarkdownLinkFavicon host={host} />
{firstChild}
</span>
@@ -1093,6 +1126,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
theme,
threadRef,
onOpen,
onOpenInPanel,
onOpenInBrowser,
className,
}: MarkdownFileLinkProps) {
@@ -1136,8 +1170,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
handleOpenInEditor();
return;
}
useRightPanelStore.getState().openFile(threadRef, workspaceRelativePath, line);
}, [handleOpenInEditor, line, threadRef, workspaceRelativePath]);
onOpenInPanel(workspaceRelativePath, line);
}, [handleOpenInEditor, line, onOpenInPanel, threadRef, workspaceRelativePath]);
const handleOpenInBrowser = useCallback(() => {
if (!onOpenInBrowser) {
@@ -1289,7 +1323,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
side="top"
className="max-w-[min(40rem,calc(100vw-2rem))] font-mono text-[11px] leading-tight"
>
<div className="markdown-file-link-tooltip-scroll overflow-x-auto whitespace-nowrap">
<div className="overflow-x-auto whitespace-nowrap [scrollbar-color:color-mix(in_srgb,var(--border)_78%,transparent)_transparent] [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-[color-mix(in_srgb,var(--border)_78%,transparent)] [&::-webkit-scrollbar-track]:bg-transparent">
{displayPath}
</div>
</TooltipPopup>
@@ -1313,6 +1347,7 @@ function areMarkdownFileLinkPropsEqual(
previous.theme === next.theme &&
previous.threadRef === next.threadRef &&
previous.onOpen === next.onOpen &&
previous.onOpenInPanel === next.onOpenInPanel &&
previous.onOpenInBrowser === next.onOpenInBrowser &&
previous.className === next.className
);
@@ -1326,6 +1361,7 @@ interface ChatMarkdownComponentsContext {
readonly isStreaming: boolean;
readonly markdownFileLinkMetaByHref: ReadonlyMap<string, MarkdownFileLinkMeta>;
readonly onTaskListChange: ChatMarkdownProps["onTaskListChange"];
readonly onOpenFileInPanel: (workspaceRelativePath: string, line: number | undefined) => void;
readonly openInPreferredEditor: (
targetPath: string,
) => Promise<AtomCommandResult<unknown, unknown>>;
@@ -1352,6 +1388,7 @@ function createChatMarkdownComponents(ctx: ChatMarkdownComponentsContext): Compo
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
onOpenFileInPanel,
openInPreferredEditor,
openExternalLinkInPreview,
openMarkdownFileInPreview,
@@ -1389,6 +1426,7 @@ function createChatMarkdownComponents(ctx: ChatMarkdownComponentsContext): Compo
theme={resolvedTheme}
threadRef={threadRef}
onOpen={openInPreferredEditor}
onOpenInPanel={onOpenFileInPanel}
onOpenInBrowser={
threadRef && isPreviewSupportedInRuntime() && isBrowserPreviewFile(fileLinkMeta.filePath)
? () => openMarkdownFileInPreview(fileLinkMeta.filePath)
@@ -1442,7 +1480,10 @@ function createChatMarkdownComponents(ctx: ChatMarkdownComponentsContext): Compo
/>
);
},
a({ node, href, children, ...props }) {
img({ node: _node, title: _title, ...props }) {
return <img {...props} />;
},
a({ node, href, children, title: _title, ...props }) {
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
@@ -1582,11 +1623,15 @@ function ChatMarkdown({
skills = EMPTY_MARKDOWN_SKILLS,
className,
lineBreaks = false,
parseRawHtml = true,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, {
reportFailure: false,
});
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
@@ -1689,6 +1734,40 @@ function ChatMarkdown({
},
[createAssetUrl, openPreview, preparedConnection, threadRef],
);
// A bare filename resolves to the workspace root, which is rarely where the
// file is, so ask the index before opening.
const openFileInPanel = useCallback(
(workspaceRelativePath: string, line: number | undefined) => {
if (!threadRef) return;
// Claimed on every open so a synchronous one supersedes a lookup already
// in flight.
const isLatestLookup = claimWorkspaceBasenameLookup();
const openAt = (path: string) =>
useRightPanelStore.getState().openFile(threadRef, path, line);
if (!cwd || !needsWorkspaceBasenameLookup(workspaceRelativePath)) {
openAt(workspaceRelativePath);
return;
}
void (async () => {
const result = await searchProjectEntries({
environmentId: threadRef.environmentId,
input: {
cwd,
query: workspaceRelativePath,
limit: WORKSPACE_BASENAME_LOOKUP_LIMIT,
kind: "file",
},
});
const match =
result._tag === "Success"
? pickWorkspaceBasenameMatch(workspaceRelativePath, result.value.entries)
: null;
if (!isLatestLookup()) return;
openAt(match ?? workspaceRelativePath);
})();
},
[cwd, searchProjectEntries, threadRef],
);
const markdownComponents = useMemo<Components>(
() =>
createChatMarkdownComponents({
@@ -1699,6 +1778,7 @@ function ChatMarkdown({
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
onOpenFileInPanel: openFileInPanel,
openInPreferredEditor,
openExternalLinkInPreview,
openMarkdownFileInPreview,
@@ -1715,6 +1795,7 @@ function ChatMarkdown({
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
openFileInPanel,
openInPreferredEditor,
openExternalLinkInPreview,
openMarkdownFileInPreview,
@@ -1725,10 +1806,13 @@ function ChatMarkdown({
],
);
// react-markdown converts unparsed HTML nodes to text when skipHtml is false.
// Keep that behavior explicit because literal mode depends on escaping the
// complete source token instead of dropping it from the rendered message.
return (
<div
className={cn(
"chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80",
"chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80 [overflow-wrap:anywhere] [word-break:break-word]",
className,
)}
onCopy={handleCopy}
@@ -1737,7 +1821,8 @@ function ChatMarkdown({
remarkPlugins={
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
}
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}
skipHtml={false}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
+3
View File
@@ -251,6 +251,7 @@ import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";
import { ChatHeader } from "./chat/ChatHeader";
import { useRemoteOpenState } from "~/remoteOpen";
import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic";
import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut";
import {
@@ -2659,10 +2660,12 @@ function ChatViewContent(props: ChatViewProps) {
);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
const remoteOpenState = useRemoteOpenState(activeThread?.environmentId ?? environmentId);
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName: activeProject?.title,
activeThreadEnvironmentId: activeThread?.environmentId ?? environmentId,
primaryEnvironmentId,
remoteOpenMode: remoteOpenState.mode,
});
useOpenFavoriteEditorShortcut({
enabled: showOpenInPicker,
+184 -80
View File
@@ -144,10 +144,15 @@ import {
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
ThreadWorktreeIndicator,
nextThreadChangeRequestSnapshot,
prStatusIndicator,
resolveThreadPr,
resolveDisplayedThreadPr,
resolveDisplayedThreadPrProvider,
setThreadChangeRequestSnapshot,
settledPrHoverColorClass,
terminalStatusFromRunningIds,
threadChangeRequestSnapshotsAtom,
type ThreadChangeRequestSnapshot,
type TerminalStatusIndicator,
} from "./ThreadStatusIndicators";
import {
@@ -159,7 +164,11 @@ import {
import { ProjectFavicon } from "./ProjectFavicon";
import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";
import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils";
import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances";
import {
deriveProviderInstanceEntries,
shouldShowInstanceBadge,
type ProviderInstanceEntry,
} from "../providerInstances";
import { primaryServerProvidersAtom } from "../state/server";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -248,7 +257,8 @@ function SidebarThreadTooltip({
projectCwd,
projectFaviconPath,
environmentLabel,
driverKind,
providerEntry,
showInstanceBadge,
modelInstanceId,
modelLabel,
branchMismatch,
@@ -260,7 +270,8 @@ function SidebarThreadTooltip({
projectCwd: string | null;
projectFaviconPath: string | null;
environmentLabel: string | null;
driverKind: ProviderInstanceEntry["driverKind"] | null;
providerEntry: ProviderInstanceEntry | null;
showInstanceBadge: boolean;
modelInstanceId: string;
modelLabel: string;
branchMismatch: {
@@ -270,6 +281,7 @@ function SidebarThreadTooltip({
terminalStatus: TerminalStatusIndicator | null;
terminalProcessCount: number;
}) {
const driverKind = providerEntry?.driverKind ?? null;
return (
<TooltipPopup
side="right"
@@ -318,10 +330,21 @@ function SidebarThreadTooltip({
<div className="flex min-w-0 items-center gap-2">
<ProviderInstanceIcon
driverKind={driverKind}
displayName={thread.runtime?.providerName ?? modelInstanceId}
displayName={
providerEntry?.displayName ?? thread.runtime?.providerName ?? modelInstanceId
}
accentColor={providerEntry?.accentColor}
// Initials would swallow a size-3 glyph: accent dot, name in label.
showBadge={showInstanceBadge && providerEntry?.accentColor !== undefined}
badgeContent="none"
badgeClassName="h-2 min-w-2 px-0"
iconClassName="size-3 shrink-0 grayscale opacity-60"
/>
<div className="min-w-0 truncate text-foreground/75">{modelLabel}</div>
<div className="min-w-0 truncate text-foreground/75">
{showInstanceBadge && providerEntry
? `${modelLabel} · ${providerEntry.displayName}`
: modelLabel}
</div>
</div>
) : null}
{terminalStatus ? (
@@ -367,19 +390,26 @@ function SnoozePopoverButton(props: {
);
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger
render={
<button
type="button"
aria-label="Snooze thread"
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
}
>
<ClockIcon className="size-3" />
</PopoverTrigger>
<Tooltip>
<TooltipTrigger
render={
<PopoverTrigger
render={
<button
type="button"
aria-label="Snooze thread"
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
}
/>
}
>
<ClockIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup>Snooze thread</TooltipPopup>
</Tooltip>
<PopoverPopup side="bottom" align="end" className="w-56" viewportClassName="p-1">
{presets.map((preset) => (
<button
@@ -705,11 +735,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
changeRequestSnapshot: ThreadChangeRequestSnapshot | null;
onChangeRequestSnapshot: (
threadKey: string,
snapshot: ThreadChangeRequestSnapshot | null,
) => void;
}) {
const {
isRenaming,
onChangeRequestState,
changeRequestSnapshot,
onChangeRequestSnapshot,
onCancelRename,
onCommitRename,
onContextMenu,
@@ -754,9 +789,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
})
: null,
);
const pr = resolveThreadPr({
const retainTerminalOnBranchMismatch = thread.worktreePath === null;
const pr = resolveDisplayedThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
});
const prState = pr?.state ?? null;
@@ -849,17 +887,38 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
activeThreadBranch: thread.branch,
currentGitBranch: gitStatus.data?.refName ?? null,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const prProvider = resolveDisplayedThreadPrProvider({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
});
const prStatus = prStatusIndicator(pr, prProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state so the parent can apply the configured merge rule
// and the always-on close rule during partitioning.
useEffect(() => {
onChangeRequestState(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
const nextSnapshot = nextThreadChangeRequestSnapshot({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
});
if (nextSnapshot === undefined) return;
onChangeRequestSnapshot(threadKey, nextSnapshot);
}, [
changeRequestSnapshot,
gitStatus.data,
onChangeRequestSnapshot,
retainTerminalOnBranchMismatch,
thread.branch,
threadKey,
]);
const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
const driverKind = providerEntry?.driverKind ?? null;
const showInstanceBadge =
providerEntry !== null &&
shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values());
const selectedModel = providerEntry?.models.find(
(model) => model.slug === thread.modelSelection.model,
);
@@ -877,7 +936,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
projectCwd={props.projectCwd}
projectFaviconPath={props.projectFaviconPath}
environmentLabel={props.environmentLabel}
driverKind={driverKind}
providerEntry={providerEntry}
showInstanceBadge={showInstanceBadge}
modelInstanceId={modelInstanceId}
modelLabel={modelLabel}
branchMismatch={branchMismatch}
@@ -1312,15 +1372,21 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
)}
{props.isPinned ? (
props.pinningSupported ? (
<button
type="button"
aria-label="Unpin thread"
title="Unpin thread"
onClick={handleUnpinClick}
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<PinIcon aria-hidden className="size-3 shrink-0" />
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Unpin thread"
onClick={handleUnpinClick}
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
/>
}
>
<PinIcon aria-hidden className="size-3 shrink-0" />
</TooltipTrigger>
<TooltipPopup>Unpin thread</TooltipPopup>
</Tooltip>
) : (
<PinIcon
aria-label="Pinned"
@@ -1409,15 +1475,22 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
/>
) : null}
{props.settlementSupported ? (
<button
type="button"
aria-label="Settle thread"
onClick={handleSettleClick}
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
>
<CheckIcon className="size-3.5" />
Settle
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Settle thread"
onClick={handleSettleClick}
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
}
>
<CheckIcon className="size-3.5" />
Settle
</TooltipTrigger>
<TooltipPopup>Settle thread</TooltipPopup>
</Tooltip>
) : null}
</span>
) : null}
@@ -1461,11 +1534,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
</span>
) : null}
{driverKind ? (
<span className="inline-flex shrink-0 items-center opacity-60">
<span className="inline-flex shrink-0 items-center">
<ProviderInstanceIcon
driverKind={driverKind}
displayName={thread.runtime?.providerName ?? modelInstanceId}
iconClassName="size-3.5"
displayName={
providerEntry?.displayName ??
thread.runtime?.providerName ??
modelInstanceId
}
accentColor={providerEntry?.accentColor}
showBadge={showInstanceBadge}
// Glyph dims, badge stays saturated; offset matches the composer trigger.
iconClassName="size-3.5 opacity-60"
badgeClassName="right-[-0.1875rem] bottom-[-0.1875rem] h-3 min-w-3 px-0.5 text-[7px]"
/>
</span>
) : null}
@@ -1522,7 +1603,9 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
});
const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
const driverKind = providerEntry?.driverKind ?? null;
const showInstanceBadge =
providerEntry !== null &&
shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values());
const selectedModel = providerEntry?.models.find(
(model) => model.slug === thread.modelSelection.model,
);
@@ -1580,7 +1663,8 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
projectCwd={props.projectCwd}
projectFaviconPath={props.projectFaviconPath}
environmentLabel={props.environmentLabel}
driverKind={driverKind}
providerEntry={providerEntry}
showInstanceBadge={showInstanceBadge}
modelInstanceId={modelInstanceId}
modelLabel={modelLabel}
branchMismatch={branchMismatch}
@@ -1602,6 +1686,7 @@ export default function Sidebar() {
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
@@ -1613,6 +1698,7 @@ export default function Sidebar() {
pinThread,
unpinThread,
reorderPinnedThread,
archiveThread,
deleteThread,
} = useThreadActions();
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
@@ -1803,26 +1889,7 @@ export default function Sidebar() {
// fresh clock whenever it recomputes.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
// Project scope: one menu above the list. Scoping filters the list without
// making the header width depend on the number or length of project names.
@@ -1935,7 +2002,11 @@ export default function Sidebar() {
const supportsSnooze =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
const snapshot = changeRequestSnapshotByKey.get(threadKey);
const changeRequestState =
snapshot != null && (thread.worktreePath === null || snapshot.branch === thread.branch)
? snapshot.pr.state
: null;
// Snooze outranks everything, including a pin: "hide until Tuesday"
// temporarily suspends "keep on top". The pin survives underneath —
// and so does its pinOrderKey, so on wake the thread reappears at
@@ -1993,7 +2064,7 @@ export default function Sidebar() {
}, [
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestStateByKey,
changeRequestSnapshotByKey,
nowMinute,
scopedProjectKeys,
serverConfigs,
@@ -2967,6 +3038,7 @@ export default function Sidebar() {
isSnoozed,
canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
isRegeneratingTitle,
isRunning: thread.runtime?.status === "running" && thread.runtime.activeRunId != null,
supports: {
settlement: supportsSettlement,
snooze: supportsSnooze,
@@ -3070,6 +3142,34 @@ export default function Sidebar() {
case "copy-thread-id":
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
return;
case "archive": {
if (confirmThreadArchive) {
const confirmed = await settlePromise(() =>
api.dialogs.confirm(`Archive thread "${thread.title}"?`),
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
}
let didArchive = false;
const result = await archiveThread(threadRef, {
onArchived: () => {
didArchive = true;
},
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: didArchive
? "Thread archived, but navigation failed"
: "Failed to archive thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
return;
}
case "delete": {
if (confirmThreadDelete) {
const confirmed = await settlePromise(() =>
@@ -3103,12 +3203,14 @@ export default function Sidebar() {
})();
},
[
archiveThread,
attemptPin,
attemptSettle,
attemptSnooze,
attemptUnpin,
attemptUnsettle,
attemptUnsnooze,
confirmThreadArchive,
confirmThreadDelete,
copyBranchToClipboard,
copyPathToClipboard,
@@ -3275,9 +3377,9 @@ export default function Sidebar() {
{isSearchingThreads ? (
<Button
type="button"
size="icon-xs"
size="icon-micro"
variant="ghost"
className="size-5 shrink-0 rounded-sm text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
aria-label="Clear thread search"
onClick={() => {
clearThreadSearch();
@@ -3389,18 +3491,19 @@ export default function Sidebar() {
className="size-4 shrink-0"
/>
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
<button
type="button"
<Button
size="icon-xs"
variant="ghost-muted"
aria-label={`Project settings for ${project.displayName}`}
title={`Project settings for ${project.displayName}`}
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
className="ml-auto size-6 [--control-icon-color:currentColor] text-icon-muted focus-visible:bg-accent focus-visible:text-foreground"
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
void handleProjectSettings(event, project);
}}
>
<SettingsIcon className="size-3.5" />
</button>
</Button>
</MenuRadioItem>
);
})}
@@ -3595,7 +3698,8 @@ export default function Sidebar() {
onUnsnooze={attemptUnsnooze}
onUnpin={attemptUnpin}
onAcknowledgeWoke={acknowledgeWoke}
onChangeRequestState={handleChangeRequestState}
changeRequestSnapshot={changeRequestSnapshotByKey.get(threadKey) ?? null}
onChangeRequestSnapshot={setThreadChangeRequestSnapshot}
/>
);
};
+94 -58
View File
@@ -13,6 +13,7 @@ import type {
RuntimeRequestId,
} from "@t3tools/contracts";
import {
isProviderSendTurnSupportedImageMimeType,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -103,10 +104,17 @@ import {
renderProviderTraitsPicker,
} from "./composerProviderState";
import { ContextWindowMeter } from "./ContextWindowMeter";
import { resolveContextWindowModelDisplayName } from "./ContextWindowMeter.logic";
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
import { basenameOfPath } from "../../pierre-icons";
import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
import { Separator } from "../ui/separator";
import {
getComposerPromptLengthValidationMessage,
getComposerSubmissionValidationMessage,
submitComposerDraft,
} from "./composerSubmission";
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
type ComposerCommandMenuPosition = {
bottom: number;
@@ -205,7 +213,7 @@ import {
XIcon,
} from "lucide-react";
import { proposedPlanTitle } from "../../proposedPlan";
import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../providerModels";
import { getProviderInteractionModeToggle } from "../../providerModels";
import {
applyProviderInstanceSettings,
deriveProviderInstanceEntries,
@@ -397,7 +405,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
activeThreadProviderDisplayName: string | null;
activeThreadModelDisplayName: string | null;
isPreparingWorktree: boolean;
pendingAction: {
questionIndex: number;
@@ -415,6 +423,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
hasSendableContent: boolean;
queueShortcutLabel: string;
preserveComposerFocusOnPointerDown?: boolean;
showSendWhileRunning?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -424,7 +433,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
{props.activeContextWindow ? (
<ContextWindowMeter
usage={props.activeContextWindow}
providerDisplayName={props.activeThreadProviderDisplayName}
modelDisplayName={props.activeThreadModelDisplayName}
/>
) : null}
{props.isPreparingWorktree ? (
@@ -447,6 +456,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
isPreparingWorktree={props.isPreparingWorktree}
hasSendableContent={props.hasSendableContent}
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
showSendWhileRunning={props.showSendWhileRunning ?? false}
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
onInterrupt={props.onInterrupt}
onImplementPlanInNewThread={props.onImplementPlanInNewThread}
@@ -462,6 +472,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
export interface ChatComposerHandle {
focusAtEnd: () => void;
focusAt: (cursor: number) => void;
addDroppedFiles: (files: File[]) => void;
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => boolean;
openModelPicker: () => void;
toggleModelPicker: () => void;
@@ -496,6 +507,8 @@ export interface ChatComposerHandle {
selectedModel: string;
selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;
};
/** Validate the fully composed text immediately before a provider turn starts. */
validateProviderInput: (providerInput: string) => boolean;
}
// --------------------------------------------------------------------------
@@ -953,16 +966,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
() => deriveLatestContextWindowSnapshot(activeThreadVisibleTurnItems ?? []),
[activeThreadVisibleTurnItems],
);
const activeThreadProviderDisplayName = useMemo(() => {
if (!activeThreadModelSelection) return null;
const entry = providerStatuses.find(
(p) => p.instanceId === activeThreadModelSelection.instanceId,
);
if (entry) {
return getProviderDisplayName(providerStatuses, entry.driver);
}
return formatProviderDisplayName(activeThreadModelSelection.instanceId);
}, [providerStatuses, activeThreadModelSelection]);
const activeThreadModelDisplayName = useMemo(
() => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance),
[activeThreadModelSelection, modelOptionsByInstance],
);
// ------------------------------------------------------------------
// Composer-local state
@@ -982,6 +989,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const [composerSubmissionError, setComposerSubmissionError] = useState<string | null>(null);
const [providerInputSubmissionError, setProviderInputSubmissionError] = useState<string | null>(
null,
);
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
@@ -999,6 +1010,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerFormRef = useRef<HTMLFormElement>(null);
const composerSurfaceRef = useRef<HTMLDivElement>(null);
const composerFormHeightRef = useRef(0);
const providerInputRejectedRef = useRef(false);
const composerSelectLockRef = useRef(false);
const composerMenuOpenRef = useRef(false);
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
@@ -1007,7 +1019,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const mobileComposerExpandFrameRef = useRef<number | null>(null);
const mobileComposerExpandReleaseFrameRef = useRef<number | null>(null);
const mobileComposerExpandInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
const stashPulseKeyRef = useRef(0);
const stashPulseTimeoutRef = useRef<number | null>(null);
/**
@@ -1331,6 +1342,27 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing));
}, [prompt, promptRef]);
useEffect(() => {
if (composerSubmissionError === null) return;
const nextError = getComposerPromptLengthValidationMessage(prompt);
if (nextError !== composerSubmissionError) {
setComposerSubmissionError(nextError);
}
}, [composerSubmissionError, prompt]);
useEffect(() => {
setProviderInputSubmissionError(null);
}, [
composerElementContexts,
composerPreviewAnnotations,
composerReviewComments,
composerTerminalContexts,
prompt,
selectedModel,
selectedPromptEffort,
selectedProvider,
]);
useEffect(() => {
composerImagesRef.current = composerImages;
}, [composerImages, composerImagesRef]);
@@ -1422,9 +1454,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
useEffect(() => {
setComposerHighlightedItemId(null);
setComposerSubmissionError(null);
setProviderInputSubmissionError(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
}, [draftId, activeThreadId, promptRef]);
@@ -1862,17 +1895,35 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
});
return;
}
onSend(event, dispatchMode ?? resolveComposerDispatchMode({ phase, queueModifier: false }));
const submission = submitComposerDraft({
prompt: promptRef.current,
submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn",
event,
onSend: (sendEvent) => {
// ChatView reports its final composed-input preflight through the
// composer handle before its first asynchronous send step.
providerInputRejectedRef.current = false;
onSend(
sendEvent,
dispatchMode ?? resolveComposerDispatchMode({ phase, queueModifier: false }),
);
return !providerInputRejectedRef.current;
},
});
setComposerSubmissionError(submission.validationMessage);
if (!submission.didDispatch) return;
if (shouldBlurMobileComposerOnSubmit()) {
blurMobileComposerAfterSend();
}
},
[
activeThreadId,
activePendingProgress,
blurMobileComposerAfterSend,
noProviderAvailable,
onSend,
phase,
promptRef,
shouldBlurMobileComposerOnSubmit,
],
);
@@ -2347,6 +2398,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
continue;
}
if (!isProviderSendTurnSupportedImageMimeType(file.type)) {
error = `'${file.name}' is not a supported image type. Attach GIF, JPEG, PNG, or WebP images.`;
continue;
}
if (reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
@@ -2423,41 +2478,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
void addComposerImages(imageFiles);
};
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) return;
event.preventDefault();
dragDepthRef.current += 1;
setIsDragOverComposer(true);
};
const onComposerDragOver = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setIsDragOverComposer(true);
};
const onComposerDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) return;
event.preventDefault();
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) {
setIsDragOverComposer(false);
}
};
const onComposerDrop = (event: React.DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) return;
event.preventDefault();
dragDepthRef.current = 0;
setIsDragOverComposer(false);
const files = Array.from(event.dataTransfer.files);
void addComposerImages(files);
focusComposer();
};
const insertComposerTextAtEnd = (
text: string,
options?: { ensureLeadingBoundary?: boolean },
@@ -2511,7 +2531,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
useEffect(() => {
if (!isDragOverComposer) return;
const onWindowDragEnd = () => {
dragDepthRef.current = 0;
setIsDragOverComposer(false);
};
window.addEventListener("dragend", onWindowDragEnd);
@@ -2580,6 +2599,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusAt: (cursor: number) => {
composerEditorRef.current?.focusAt(cursor);
},
addDroppedFiles: (files: File[]) => {
void addComposerImages(files);
focusComposer();
},
insertTextAtEnd: insertComposerTextAtEnd,
openModelPicker: () => {
setIsComposerModelPickerOpen(true);
@@ -2659,9 +2682,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
selectedModel,
selectedProviderModels,
}),
validateProviderInput: (providerInput: string) => {
const validationMessage = getComposerSubmissionValidationMessage({
prompt: promptRef.current,
providerInput,
submissionTarget: "provider-turn",
});
providerInputRejectedRef.current = validationMessage !== null;
setProviderInputSubmissionError(validationMessage);
return validationMessage === null;
},
}),
[
activeThread,
addComposerImages,
composerDraftTarget,
composerCursor,
composerTerminalContexts,
@@ -2672,6 +2706,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerElementContextsRef,
composerPreviewAnnotations,
composerReviewComments,
focusComposer,
isConnecting,
isComposerApprovalState,
pendingUserInputs.length,
@@ -2703,10 +2738,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
"group rounded-[22px] p-px transition-colors duration-200",
composerProviderState.composerFrameClassName,
)}
onDragEnter={onComposerDragEnter}
onDragOver={onComposerDragOver}
onDragLeave={onComposerDragLeave}
onDrop={onComposerDrop}
onDragEnterCapture={composerMentionDragHandlers.onDragEnter}
onDragOverCapture={composerMentionDragHandlers.onDragOver}
onDragLeaveCapture={onComposerMentionDragLeaveCapture}
@@ -3132,9 +3163,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</div>
</div>
<ComposerPromptLengthValidation
message={providerInputSubmissionError ?? composerSubmissionError}
/>
{/* Bottom toolbar */}
{isComposerCollapsedMobile ? null : activePendingApproval ? (
<div className="flex items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
<div className="flex flex-wrap items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
@@ -3238,7 +3273,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerFooterPrimaryActions
compact={isComposerPrimaryActionsCompact}
activeContextWindow={activeContextWindow}
activeThreadProviderDisplayName={activeThreadProviderDisplayName}
activeThreadModelDisplayName={activeThreadModelDisplayName}
pendingAction={pendingPrimaryAction}
isRunning={phase === "running"}
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
@@ -3254,6 +3289,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
hasSendableContent={composerSendState.hasSendableContent}
queueShortcutLabel={isMacPlatform(navigator.platform) ? "⌘↵" : "Ctrl+Enter"}
preserveComposerFocusOnPointerDown={isMobileViewport}
showSendWhileRunning={isMobileViewport}
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
@@ -24,7 +24,7 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
: "File change";
return (
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
<div className="min-w-0 px-4 py-3.5 sm:px-5 sm:py-4">
<div className="flex flex-wrap items-center gap-2">
<span className="uppercase text-sm tracking-[0.2em]">PENDING APPROVAL</span>
<span className="text-sm font-medium">{approvalSummary}</span>
@@ -39,11 +39,11 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
</p>
) : null}
{approval.detail ? (
<div className="mt-3 rounded-lg border border-border/65 bg-background/70 p-3">
<div className="mt-3 min-w-0 max-w-full rounded-lg border border-border/65 bg-background/70 p-3">
<p className="text-xs font-medium text-muted-foreground">{detailLabel}</p>
<pre
aria-label={detailLabel}
className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-foreground"
className="mt-2 min-w-0 max-w-full max-h-40 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-foreground"
data-approval-detail="complete"
>
{approval.detail}
@@ -1,4 +1,4 @@
import { ApprovalRequestId } from "@t3tools/contracts";
import { RuntimeRequestId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
@@ -6,7 +6,8 @@ import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import type { PendingUserInput } from "../../session-logic";
const prompt: PendingUserInput = {
requestId: ApprovalRequestId.make("request-1"),
requestId: RuntimeRequestId.make("request-1"),
responseCapability: "live" as const,
createdAt: "2026-08-15T00:00:00.000Z",
questions: [
{
@@ -1,11 +1,12 @@
import { type RuntimeRequestId } from "@t3tools/contracts";
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { type PendingUserInput } from "../../session-logic";
import {
derivePendingUserInputProgress,
type PendingUserInputDraftAnswer,
} from "../../pendingUserInput";
import { CheckIcon } from "lucide-react";
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { cn } from "~/lib/utils";
interface PendingUserInputPanelProps {
@@ -57,16 +58,27 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onToggleOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
// V2 runtime requests carry response capability: a provider process that has
// gone away cannot accept answers, so the card reads read-only until the run
// restarts.
const canRespond = prompt.responseCapability === "live";
const responseDisabled = isResponding || !canRespond;
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
const onAdvanceRef = useRef(onAdvance);
const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
questionId: string;
optionLabel: string;
} | null>(null);
// Collapsing hides everything but the header so a tall prompt stops covering
// the thread the user is trying to read. Scoped to a single question: the card
// is keyed by request id so the next prompt starts expanded, and storing the
// collapsed question's id (rather than a bare flag) reopens the card when the
// prompt advances to its next question, which can happen without a click —
// sending from the composer advances the active question.
const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
useEffect(() => {
onAdvanceRef.current = onAdvance;
@@ -102,27 +114,31 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
}, []);
const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
if (activeQuestion?.multiSelect) {
const handleOptionSelection = useCallback(
(questionId: string, optionLabel: string) => {
if (activeQuestion?.multiSelect) {
onToggleOption(questionId, optionLabel);
return;
}
setOptimisticSingleSelect({ questionId, optionLabel });
onToggleOption(questionId, optionLabel);
return;
}
setOptimisticSingleSelect({ questionId, optionLabel });
onToggleOption(questionId, optionLabel);
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvanceRef.current();
}, 200);
});
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
autoAdvanceTimerRef.current = window.setTimeout(() => {
autoAdvanceTimerRef.current = null;
onAdvanceRef.current();
}, 200);
},
[activeQuestion, onToggleOption],
);
// Keyboard shortcut: number keys 1-9 select corresponding options when focus is
// outside editable fields. Multi-select prompts toggle options in place; single-
// select prompts keep the existing auto-advance behavior.
// select prompts keep the existing auto-advance behavior. Collapsed prompts opt
// out, since the numbers they refer to are not on screen.
useEffect(() => {
if (!activeQuestion || responseDisabled) return;
if (!activeQuestion || responseDisabled || isCollapsed) return;
const handler = (event: globalThis.KeyboardEvent) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
@@ -146,7 +162,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [activeQuestion, responseDisabled]);
}, [activeQuestion, handleOptionSelection, isCollapsed, responseDisabled]);
if (!activeQuestion) {
return null;
@@ -155,83 +171,119 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const customAnswerActive = progress.customAnswer.trim().length > 0;
return (
<div className="px-4 py-3 sm:px-5">
<div className="mb-2 flex items-center gap-3">
<span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase">
{activeQuestion.header}
</span>
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
{questionIndex + 1}/{prompt.questions.length}
<Collapsible
className="py-3"
open={!isCollapsed}
onOpenChange={(open) => {
setCollapsedQuestionId(open ? null : activeQuestion.id);
}}
>
{/* The trigger's wrapper is inset less than the card's text column, and
the trigger pays the difference back as padding: the hover background
and focus ring bleed 10px past that column on both sides, while the
header label and the chevron still line up with the left and right
edges of the question text below. The negative block margin keeps the
taller hit area from pushing the panel down. */}
<div className="px-1.5 sm:px-2.5">
<CollapsibleTrigger
title={
isCollapsed ? "Show the question and its options" : "Hide the question and its options"
}
data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
className="group -my-1 flex w-full items-center gap-3 rounded-md px-2.5 py-1.5 text-left outline-none transition-colors duration-150 hover:bg-muted/40 focus-visible:ring-1 focus-visible:ring-primary/25"
>
<span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase group-hover:text-foreground">
{activeQuestion.header}
</span>
) : null}
{prompt.questions.length > 1 ? (
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
{questionIndex + 1}/{prompt.questions.length}
</span>
) : null}
{/* Collapsed, the header is otherwise just a section label and a
counter, so the question itself is echoed here as a one-line
reminder of what is being asked. */}
{isCollapsed ? (
<span className="min-w-0 flex-1 truncate text-secondary-label text-xs">
{activeQuestion.question}
</span>
) : null}
{/* The chevron points at the body: down while it is open below the
header, up while it is collapsed into it. */}
<ChevronDownIcon
aria-hidden="true"
className={cn(
"ml-auto size-3.5 shrink-0 text-secondary-label transition-transform duration-150 group-hover:text-foreground",
isCollapsed && "rotate-180",
)}
/>
</CollapsibleTrigger>
</div>
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
{!canRespond ? (
<p className="mt-1 text-xs text-muted-foreground">
This request belonged to a provider process that is no longer available. Interrupt or
restart the run to continue.
</p>
) : null}
{activeQuestion.multiSelect ? (
<p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
) : null}
<div className="mt-3 space-y-1.5">
{activeQuestion.options.map((option, index) => {
const isOptimisticallySelected =
optimisticSingleSelect?.questionId === activeQuestion.id &&
optimisticSingleSelect.optionLabel === option.label;
const isSelected =
isOptimisticallySelected ||
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
const shortcutKey = index < 9 ? index + 1 : null;
const className = cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
isSelected
? "border-primary/30 bg-primary/8 text-foreground"
: "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
responseDisabled && "opacity-50 cursor-not-allowed",
!responseDisabled && "cursor-pointer",
);
const content = (
<>
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="text-secondary-label text-xs">{option.description}</span>
) : null}
</div>
{isSelected ? (
<CheckIcon className="size-3.5 shrink-0 text-primary" />
) : shortcutKey !== null ? (
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
"bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
)}
{/* The panel carries the horizontal padding itself: it clips its content
while the height animates, so the option buttons have to sit inside
that padding or their focus rings get shaved off at the edges. */}
<CollapsiblePanel className="px-4 sm:px-5">
<div className="pt-2 pb-0.5">
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
{activeQuestion.multiSelect ? (
<p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
) : null}
<div className="mt-3 space-y-1.5">
{activeQuestion.options.map((option, index) => {
const isOptimisticallySelected =
optimisticSingleSelect?.questionId === activeQuestion.id &&
optimisticSingleSelect.optionLabel === option.label;
const isSelected =
isOptimisticallySelected ||
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
const shortcutKey = index < 9 ? index + 1 : null;
const className = cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
isSelected
? "border-primary/30 bg-primary/8 text-foreground"
: "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
isResponding && "opacity-50 cursor-not-allowed",
!isResponding && "cursor-pointer",
);
const content = (
<>
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="text-secondary-label text-xs">{option.description}</span>
) : null}
</div>
{isSelected ? (
<CheckIcon className="size-3.5 shrink-0 text-primary" />
) : shortcutKey !== null ? (
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
"bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
)}
>
{shortcutKey}
</kbd>
) : null}
</>
);
return (
<button
key={`${activeQuestion.id}:${option.label}`}
type="button"
disabled={isResponding}
onClick={() => {
handleOptionSelection(activeQuestion.id, option.label);
}}
className={className}
>
{shortcutKey}
</kbd>
) : null}
</>
);
return (
<button
key={`${activeQuestion.id}:${option.label}`}
type="button"
disabled={responseDisabled}
aria-disabled={responseDisabled}
onClick={() => {
if (responseDisabled) return;
handleOptionSelection(activeQuestion.id, option.label);
}}
className={className}
>
{content}
</button>
);
})}
</div>
</div>
{content}
</button>
);
})}
</div>
</div>
</CollapsiblePanel>
</Collapsible>
);
});
@@ -72,7 +72,6 @@ function renderRunningActions(showSendWhileRunning: boolean, hasSendableContent:
showPlanFollowUpPrompt: false,
promptHasText: hasSendableContent,
isSendBusy: false,
sendDisabledReason: null,
isConnecting: false,
isEnvironmentUnavailable: false,
isPreparingWorktree: false,
@@ -246,7 +245,7 @@ describe("ComposerPrimaryActions", () => {
const markup = renderRunningActions(true, true);
expect(markup).toContain('aria-label="Stop generation"');
expect(markup).toContain('aria-label="Send message"');
expect(markup).toContain('aria-label="Send message to steer active turn"');
expect(markup).toContain('type="submit"');
expect(markup).toContain("size-9 sm:size-8");
});
@@ -288,7 +287,7 @@ describe("active-turn primary action", () => {
expect(markup).not.toContain("steer active turn");
});
it("replaces stop with send while the active composer has content", () => {
it("keeps stop reachable while the active composer has content", () => {
const markup = renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
...activeTurnProps,
@@ -297,7 +296,21 @@ describe("active-turn primary action", () => {
}),
);
expect(markup).toContain('aria-label="Stop generation"');
expect(markup).not.toContain("steer active turn");
});
it("adds the steering send beside stop when Enter-to-send is unavailable", () => {
const markup = renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
...activeTurnProps,
isRunning: true,
hasSendableContent: true,
showSendWhileRunning: true,
}),
);
expect(markup).toContain('aria-label="Stop generation"');
expect(markup).toContain('aria-label="Send message to steer active turn"');
expect(markup).not.toContain('aria-label="Stop generation"');
});
});
@@ -28,6 +28,9 @@ interface ComposerPrimaryActionsProps {
isPreparingWorktree: boolean;
hasSendableContent: boolean;
preserveComposerFocusOnPointerDown?: boolean;
/** Enter-to-send is disabled on mobile viewports, where stop would otherwise
* be the only primary action and a running turn could not be steered. */
showSendWhileRunning?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -67,6 +70,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
isPreparingWorktree,
hasSendableContent,
preserveComposerFocusOnPointerDown = false,
showSendWhileRunning = false,
onPreviousPendingQuestion,
onInterrupt,
onImplementPlanInNewThread,
@@ -84,7 +88,11 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="button"
className={cn(
"flex cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none",
insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
insidePendingAction
? "size-8 sm:size-7"
: showSendWhileRunning && hasSendableContent
? "size-9 sm:size-8"
: "size-8 sm:h-8 sm:w-8",
)}
{...pointerFocusProps}
onClick={onInterrupt}
@@ -148,10 +156,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
);
}
if (isRunning && !hasSendableContent) {
return renderStopGenerationButton(false);
}
if (showPlanFollowUpPrompt) {
if (promptHasText) {
return (
@@ -252,12 +256,19 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
</button>
);
if (!isRunning) return sendButton;
if (!isRunning) {
return sendButton;
}
return (
<Tooltip>
<TooltipTrigger render={sendButton} />
<TooltipPopup side="top">Send now to steer the active turn</TooltipPopup>
</Tooltip>
<>
{renderStopGenerationButton(false)}
{showSendWhileRunning && hasSendableContent ? (
<Tooltip>
<TooltipTrigger render={sendButton} />
<TooltipPopup side="top">Send now to steer the active turn</TooltipPopup>
</Tooltip>
) : null}
</>
);
});
@@ -6,8 +6,20 @@ import {
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
resolveTimelineToolPresentation,
shouldPreserveAssistantLineBreaks,
} from "./MessagesTimeline.logic";
describe("shouldPreserveAssistantLineBreaks", () => {
it("preserves Claude insight formatting without changing regular markdown", () => {
expect(
shouldPreserveAssistantLineBreaks(
"★ Insight ─────────────────\\nFirst observation\\nSecond observation\\n─────────────────",
),
).toBe(true);
expect(shouldPreserveAssistantLineBreaks("A normal\\nmarkdown paragraph")).toBe(false);
});
});
describe("computeMessageDurationStart", () => {
it("returns message createdAt when there is no preceding user message", () => {
const result = computeMessageDurationStart([
@@ -136,6 +136,7 @@ function matchMedia() {
}
let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
let toolCallExpandedBodyClassName: typeof import("./MessagesTimeline").toolCallExpandedBodyClassName;
beforeAll(async () => {
const classList = {
@@ -169,7 +170,7 @@ beforeAll(async () => {
},
});
({ MessagesTimeline } = await import("./MessagesTimeline"));
({ MessagesTimeline, toolCallExpandedBodyClassName } = await import("./MessagesTimeline"));
}, 30_000);
const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
@@ -230,7 +231,156 @@ function buildUserTimelineEntry(text: string) {
};
}
function buildAssistantTimelineEntry(text: string) {
const entry = buildUserTimelineEntry(text);
return {
...entry,
message: {
...entry.message,
role: "assistant" as const,
},
};
}
describe("MessagesTimeline", () => {
it("sizes expanded tool details with the configured code font size", () => {
expect(toolCallExpandedBodyClassName).toContain("var(--font-size-code");
expect(toolCallExpandedBodyClassName).not.toContain("text-[11px]");
});
it("preserves arbitrary XML-like tags and comparisons in rendered user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
[
'Without reading a file, do you have <global-agent-instructions scope="workspace">',
'Before <nested data-value="a&b">inside</nested> after',
"</global-agent-instructions> in your context?",
"Comparison: 2 < 3 and 5 > 4.",
].join("\n"),
),
]}
/>,
);
expect(markup).toContain("&lt;global-agent-instructions scope=&quot;workspace&quot;&gt;");
expect(markup).toContain(
"Before &lt;nested data-value=&quot;a&amp;b&quot;&gt;inside&lt;/nested&gt; after",
);
expect(markup).toContain("&lt;/global-agent-instructions&gt; in your context?");
expect(markup).toContain("Comparison: 2 &lt; 3 and 5 &gt; 4.");
});
it("preserves XML-like source inside user code spans and fences", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
[
'Inline `<tag attr="x">`',
"",
"```xml",
'<root><child enabled="true" /></root>',
"```",
].join("\n"),
),
]}
/>,
);
expect(markup).toContain('<code data-inline-code="">&lt;tag attr=&quot;x&quot;&gt;</code>');
expect(markup).toContain("&lt;root&gt;&lt;child enabled=&quot;true&quot; /&gt;&lt;/root&gt;");
});
it("does not render markdown title attributes in user messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
'[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
),
]}
/>,
);
expect(markup).toContain('href="https://example.com"');
expect(markup).toContain('src="https://example.com/image.png"');
expect(markup).not.toContain('title="link tip"');
expect(markup).not.toContain('title="image tip"');
});
it("renders unsafe user HTML as inert source text", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildUserTimelineEntry(
'<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">',
),
]}
/>,
);
expect(markup).toContain("&lt;script&gt;globalThis.__t3Xss = 1&lt;/script&gt;");
expect(markup).toContain(
"&lt;img src=&quot;x&quot; onerror=&quot;globalThis.__t3Xss = 2&quot;&gt;",
);
expect(markup).not.toMatch(/<script(?:\s|>)/i);
expect(markup).not.toMatch(/<img(?:\s|>)/i);
});
it("continues to render sanitized raw HTML in assistant messages", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildAssistantTimelineEntry("<details><summary>More</summary>Details</details>"),
]}
/>,
);
expect(markup).toContain('data-markdown-details=""');
expect(markup).toContain("More");
expect(markup).not.toContain("&lt;details&gt;");
});
it("sanitizes executable HTML while preserving supported assistant markup", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
buildAssistantTimelineEntry(
[
'<details open onclick="globalThis.__t3Xss = 1">',
"<summary>Safe details</summary>",
"<script>globalThis.__t3Xss = 2</script>",
'<img src="x" onerror="globalThis.__t3Xss = 3">',
'<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
"</details>",
].join(""),
),
]}
/>,
);
expect(markup).toContain('data-markdown-details=""');
expect(markup).toContain("Safe details");
expect(markup).not.toMatch(/<script(?:\s|>)/i);
expect(markup).not.toContain("onclick=");
expect(markup).not.toContain("onerror=");
expect(markup).not.toContain("javascript:");
expect(markup).not.toContain("globalThis.__t3Xss");
});
it("renders progressive history controls ahead of the bounded timeline", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
@@ -87,6 +87,7 @@ import {
resolveTimelineMinimapIndexFromPointer,
resolveTimelineMinimapInteractiveWidth,
resolveTimelineMinimapTopPercent,
shouldPreserveAssistantLineBreaks,
type StableMessagesTimelineRowsState,
type MessagesTimelineRow,
TIMELINE_MINIMAP_MIN_ITEMS,
@@ -109,7 +110,7 @@ import {
import { cn } from "~/lib/utils";
import { useUiStateStore } from "~/uiStateStore";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
import { V2ItemInspector } from "./V2ItemInspector";
import { useV2ItemSupport } from "../../state/v2ItemSupport";
import { isV2LifecycleItem, V2LifecycleRow, type HandoffTimelineRun } from "./V2LifecycleRow";
@@ -1178,7 +1179,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
<div className="flex shrink-0 items-center gap-2">
<Tooltip>
<TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
{formatShortTimestamp(row.message.createdAt, ctx.timestampFormat)}
{formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
</TooltipTrigger>
<TooltipPopup>
{formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
@@ -1312,6 +1313,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
isStreaming={Boolean(row.message.streaming)}
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
skills={ctx.skills}
/>
<AssistantChangedFilesSection
@@ -1336,7 +1338,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
<TooltipTrigger
render={<p className="text-muted-foreground text-xs tabular-nums" />}
>
{formatShortTimestamp(row.message.updatedAt, ctx.timestampFormat)}
{formatDayAwareTimestamp(row.message.updatedAt, ctx.timestampFormat)}
</TooltipTrigger>
<TooltipPopup>
{formatChatTimestampTooltip(row.message.updatedAt, ctx.timestampFormat)}
@@ -2163,6 +2165,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
skills={props.skills}
className="text-foreground"
lineBreaks
parseRawHtml={false}
/>
) : null}
{trailingWhitespace ? <span aria-hidden="true">{trailingWhitespace}</span> : null}
@@ -2185,6 +2188,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
skills={props.skills}
className="text-foreground"
lineBreaks
parseRawHtml={false}
/>
</div>
) : null
@@ -2273,6 +2277,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
skills={props.skills}
className="text-foreground"
lineBreaks
parseRawHtml={false}
/>,
);
} else if (inlinePrefix.length === 0) {
@@ -2298,6 +2303,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
skills={props.skills}
className="text-foreground"
lineBreaks
parseRawHtml={false}
/>
);
});
@@ -2599,6 +2605,9 @@ function buildToolCallExpandedBody(
return blocks.length > 0 ? blocks.join("\n\n") : null;
}
export const toolCallExpandedBodyClassName =
"max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-[length:var(--font-size-code,0.6875rem)] leading-relaxed select-text";
function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
if (workEntry.itemType === "user_input_request") {
return "message-circle";
@@ -2817,9 +2826,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
onRollbackCheckpoint={ctx.onRollbackCheckpoint}
/>
) : expandedBody ? (
<pre className="max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground select-text">
{expandedBody}
</pre>
<pre className={toolCallExpandedBodyClassName}>{expandedBody}</pre>
) : null}
</div>
) : null}
@@ -1,13 +1,22 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { RemoteOpenMode } from "../../remoteOpen";
export function shouldShowOpenInPicker(input: {
readonly activeProjectName: string | undefined;
readonly activeThreadEnvironmentId: EnvironmentId;
readonly primaryEnvironmentId: EnvironmentId | null;
readonly remoteOpenMode: RemoteOpenMode;
}): boolean {
return (
Boolean(input.activeProjectName) &&
if (!input.activeProjectName) return false;
if (
input.primaryEnvironmentId !== null &&
input.activeThreadEnvironmentId === input.primaryEnvironmentId
);
) {
return true;
}
// Remote environments get the picker in deep-link mode (or its explicit
// "no SSH route" state). Non-primary local backends (e.g. WSL) keep it
// hidden, matching pre-remote behavior.
return input.remoteOpenMode !== "local-exec";
}
+87 -18
View File
@@ -1,7 +1,19 @@
import { EditorId, type EnvironmentId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { memo, useCallback, useMemo, useRef } from "react";
import { shortcutLabelForCommand } from "../../keybindings";
import {
buildRemoteOpenUrl,
EditorId,
type EnvironmentId,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
import { usePreferredEditor } from "../../editorPreferences";
import {
openRemoteEditorUrl,
useRemoteCapableEditors,
useRemoteOpenHint,
useRemoteOpenState,
} from "../../remoteOpen";
import { useEnvironment } from "../../state/environments";
import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
@@ -198,6 +210,7 @@ export const OpenInPicker = memo(function OpenInPicker({
availableEditors,
openInCwd,
compact = false,
enableShortcut = true,
displayMode = "toolbar",
}: {
environmentId: EnvironmentId;
@@ -205,16 +218,24 @@ export const OpenInPicker = memo(function OpenInPicker({
availableEditors: ReadonlyArray<EditorId>;
openInCwd: string | null;
compact?: boolean;
enableShortcut?: boolean;
displayMode?: "toolbar" | "panel";
}) {
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const panelAnchorRef = useRef<HTMLDivElement | null>(null);
const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
const remote = useRemoteOpenState(environmentId);
const remoteCapableEditors = useRemoteCapableEditors();
const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
// Remote mode ignores the server's PATH probe: what matters is what runs on
// the viewing machine, which only the desktop app can probe.
const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
const options = useMemo(
() => resolveOptions(navigator.platform, availableEditors),
[availableEditors],
() => resolveOptions(navigator.platform, effectiveEditors),
[effectiveEditors],
);
const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
@@ -223,6 +244,23 @@ export const OpenInPicker = memo(function OpenInPicker({
if (!openInCwd) return;
const editor = editorId ?? preferredEditor;
if (!editor) return;
if (remote.mode === "remote-unavailable") return;
if (remote.mode === "remote-links") {
const url = buildRemoteOpenUrl({
editor,
host: remote.host.host,
absolutePath: openInCwd,
});
if (url === undefined) return;
// Only record hint-seen/preferred when the shell actually accepted
// the URL (an older desktop build can refuse the editor scheme).
void openRemoteEditorUrl(url).then((opened) => {
if (!opened) return;
markRemoteHintSeen();
setPreferredEditor(editor);
});
return;
}
const result = openInEditorMutation({
environmentId,
input: {
@@ -233,13 +271,35 @@ export const OpenInPicker = memo(function OpenInPicker({
setPreferredEditor(editor);
return result;
},
[environmentId, openInCwd, openInEditorMutation, preferredEditor, setPreferredEditor],
[
environmentId,
markRemoteHintSeen,
openInCwd,
openInEditorMutation,
preferredEditor,
remote,
setPreferredEditor,
],
);
const openFavoriteEditorShortcutLabel = useMemo(
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
[keybindings],
);
useEffect(() => {
if (!enableShortcut) return;
const handler = (e: globalThis.KeyboardEvent) => {
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!openInCwd) return;
if (!preferredEditor) return;
e.preventDefault();
void openInEditor(preferredEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [enableShortcut, keybindings, openInCwd, openInEditor, preferredEditor]);
const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
return (
@@ -254,8 +314,8 @@ export const OpenInPicker = memo(function OpenInPicker({
aria-label={compact ? "Open file in preferred editor" : primaryLabel}
size={isPanel ? "sm" : "xs"}
variant={isPanel ? "ghost" : "outline"}
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS : undefined}
disabled={!preferredEditor || !openInCwd}
className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS : "ps-[8.5px]"}
disabled={!preferredEditor || !openInCwd || remote.mode === "remote-unavailable"}
onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon && (
@@ -304,16 +364,25 @@ export const OpenInPicker = memo(function OpenInPicker({
{...(isPanel ? { anchor: panelAnchorRef } : {})}
className={isPanel ? THREAD_DETAILS_PANEL_ROW_POPUP_CLASS : undefined}
>
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
{options.map(({ label, Icon, value, kind }) => (
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
{label}
{value === preferredEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
{remote.mode === "remote-unavailable" ? (
<MenuItem disabled>No SSH route to {environmentLabel}</MenuItem>
) : (
<>
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
{options.map(({ label, Icon, value, kind }) => (
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
{label}
{value === preferredEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
)}
</MenuItem>
))}
{remote.mode === "remote-links" && !remoteHintSeen && (
<MenuItem disabled>Opens over SSH. Needs your key on {environmentLabel}</MenuItem>
)}
</MenuItem>
))}
</>
)}
</MenuPopup>
</Menu>
</ActionGroup>
@@ -16,7 +16,7 @@ import {
getTriggerDisplayModelLabel,
getTriggerDisplayModelName,
} from "./providerIconUtils";
import type { ProviderInstanceEntry } from "../../providerInstances";
import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances";
import { ComposerControl, ComposerControlChevron } from "./ComposerControl";
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
@@ -67,10 +67,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
selectedInstanceOptions[0];
const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model;
const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model;
const duplicateDriverCount = props.instanceEntries.filter(
(entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind,
).length;
const showInstanceBadge = Boolean(activeEntry?.accentColor) || duplicateDriverCount > 1;
const showInstanceBadge =
activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries);
const setIsMenuOpen = (open: boolean) => {
props.onOpenChange?.(open);
@@ -1,4 +1,4 @@
import { type ReactNode } from "react";
import { type ReactNode, useRef } from "react";
import { isElectron } from "~/env";
import {
@@ -46,8 +46,10 @@ function PreviewPanelShellFrame(
const isInline = props.mode === "inline";
const { width, handlers } = props.inlineSize;
const hostRef = useRef<HTMLDivElement | null>(null);
return (
<div
ref={hostRef}
className={cn(
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
isInline
@@ -2,7 +2,7 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef } from "react";
import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef, useState } from "react";
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
@@ -18,6 +18,7 @@ import {
clampPreviewMiniPlayerSize,
defaultPreviewMiniPlayerPosition,
PREVIEW_MINI_PLAYER_DEFAULT_SIZE,
PREVIEW_MINI_PLAYER_EDGE_GAP,
} from "./previewMiniPlayerLayout";
/**
@@ -52,6 +53,8 @@ interface ResizeState {
readonly pointerId: number;
readonly pointerX: number;
readonly pointerY: number;
readonly playerX: number;
readonly playerY: number;
readonly width: number;
readonly height: number;
}
@@ -66,6 +69,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
const rootRef = useRef<HTMLElement | null>(null);
const dragRef = useRef<DragState | null>(null);
const resizeRef = useRef<ResizeState | null>(null);
const [defaultLayoutVersion, setDefaultLayoutVersion] = useState("");
const miniPlayer = usePreviewMiniPlayerStore((state) =>
selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),
);
@@ -112,8 +116,12 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
bottomInset,
);
usePreviewMiniPlayerStore.getState().resize(threadRef, tabId, nextSize);
if (!position) {
setDefaultLayoutVersion(`${parent.clientWidth}:${parent.clientHeight}`);
return;
}
const next = clampPreviewMiniPlayerPosition(
position ?? initialPreviewMiniPlayerPosition(root, parent),
position,
{ width: parent.clientWidth, height: parent.clientHeight },
nextSize,
bottomInset,
@@ -180,11 +188,16 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
const handleResizePointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) return;
const root = rootRef.current;
if (!root) return;
const parent = root?.offsetParent;
if (!root || !(parent instanceof HTMLElement)) return;
const rootRect = root.getBoundingClientRect();
const parentRect = parent.getBoundingClientRect();
resizeRef.current = {
pointerId: event.pointerId,
pointerX: event.clientX,
pointerY: event.clientY,
playerX: rootRect.left - parentRect.left,
playerY: rootRect.top - parentRect.top,
width: root.offsetWidth,
height: root.offsetHeight,
};
@@ -215,7 +228,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
);
usePreviewMiniPlayerStore.getState().resize(threadRef, tabId, nextSize);
const nextPosition = clampPreviewMiniPlayerPosition(
position ?? { x: root.offsetLeft, y: root.offsetTop },
{ x: resize.playerX, y: resize.playerY },
{ width: parent.clientWidth, height: parent.clientHeight },
nextSize,
bottomInset,
@@ -243,8 +256,8 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
position
? { left: position.x, top: position.y, width: size.width, height: size.height }
: {
right: 16,
top: 16,
right: PREVIEW_MINI_PLAYER_EDGE_GAP,
top: PREVIEW_MINI_PLAYER_EDGE_GAP,
width: size.width,
height: size.height,
}
@@ -311,7 +324,11 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
visible={Boolean(desktopOverlay?.hasWebContents)}
cornerRadius={12}
fitSourceContent
layoutVersion={position ? `${position.x}:${position.y}` : `initial:${bottomInset}`}
layoutVersion={
position
? `${position.x}:${position.y}`
: `initial:${bottomInset}:${defaultLayoutVersion}`
}
className="absolute inset-0"
/>
<div className="pointer-events-none absolute inset-0 z-[31] rounded-xl ring-1 ring-inset ring-border/80" />
@@ -135,7 +135,7 @@ describe("KeybindingsSettings.logic", () => {
expect(options).not.toContain("customModeActive");
});
it("builds command options from built-ins and resolved project bindings", () => {
it("builds command options from built-in commands and resolved project bindings", () => {
const options = buildKeybindingCommandOptions([
{
command: "script.setup-db.run",
@@ -151,7 +151,12 @@ describe("KeybindingsSettings.logic", () => {
] satisfies ResolvedKeybindingsConfig);
expect(options).toEqual(
expect.arrayContaining(["chat.new", "threadPanel.toggle", "script.setup-db.run"]),
expect.arrayContaining([
"chat.new",
"threadPanel.toggle",
"rightPanel.toggleMaximized",
"script.setup-db.run",
]),
);
});
@@ -1,5 +1,5 @@
import {
BUILT_IN_KEYBINDING_COMMANDS,
STATIC_KEYBINDING_COMMANDS,
type KeybindingCommand,
type KeybindingShortcut,
type KeybindingWhenNode,
@@ -256,7 +256,7 @@ export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
export function buildKeybindingCommandOptions(
keybindings: ResolvedKeybindingsConfig,
): ReadonlyArray<KeybindingCommandOption> {
const commands = new Set<KeybindingCommand>(BUILT_IN_KEYBINDING_COMMANDS);
const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
for (const binding of keybindings) {
commands.add(binding.command);
}
+5 -1
View File
@@ -6,7 +6,7 @@ import type * as React from "react";
import { cn } from "~/lib/utils";
type InputProps = Omit<InputPrimitive.Props & React.RefAttributes<HTMLInputElement>, "size"> & {
size?: "sm" | "default" | "lg" | number;
size?: "sm" | "compact" | "default" | "lg" | number;
unstyled?: boolean;
nativeInput?: boolean;
};
@@ -20,6 +20,7 @@ function Input({
}: InputProps) {
const inputClassName = cn(
"h-8.5 w-full min-w-0 rounded-[inherit] px-[calc(--spacing(3)-1px)] leading-8.5 outline-none placeholder:text-placeholder sm:h-7.5 sm:leading-7.5 [transition:background-color_5000000s_ease-in-out_0s]",
size === "compact" && "h-7 px-[calc(--spacing(2.5)-1px)] text-xs leading-7 sm:h-7 sm:leading-7",
size === "sm" && "h-7.5 px-[calc(--spacing(2.5)-1px)] leading-7.5 sm:h-6.5 sm:leading-6.5",
size === "lg" && "h-9.5 leading-9.5 sm:h-8.5 sm:leading-8.5",
props.type === "search" &&
@@ -59,6 +60,9 @@ function Input({
cn(
!unstyled &&
"relative inline-flex w-full rounded-lg border border-input bg-background not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-aria-invalid:border-destructive/36 has-focus-visible:border-ring has-autofill:bg-foreground/4 has-disabled:opacity-64 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none has-focus-visible:ring-[3px] sm:text-sm dark:bg-input/32 dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",
!unstyled &&
size === "compact" &&
"rounded-md before:rounded-[calc(var(--radius-md)-1px)]",
className,
) || undefined
}
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { type RefObject, useEffect, useLayoutEffect, useState } from "react";
import { type ResizableWidthHandlers, useResizableWidth } from "./useResizableWidth";
@@ -9,12 +9,23 @@ export interface PreviewPanelInlineSize {
const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
const PREVIEW_PANEL_MIN_WIDTH = 360;
/** Fraction of the viewport allowed, preserving the remaining space for chat. */
/**
* Upper bound as a fraction of the viewport; only binds on wide screens.
* On narrow windows the container clamp below is what preserves the
* sibling column's usable width.
*/
const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
/**
* Floor for the column beside the panel: below this the chat column's
* composer overflows, so the panel yields instead.
*/
const SIBLING_COLUMN_MIN_WIDTH = 360;
const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
export function usePreviewPanelInlineSize(): PreviewPanelInlineSize {
const maxWidth = useViewportClampedMaxWidth();
export function usePreviewPanelInlineSize(
hostRef?: RefObject<HTMLElement | null>,
): PreviewPanelInlineSize {
const maxWidth = useViewportClampedMaxWidth(hostRef);
return useResizableWidth({
storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
@@ -24,9 +35,14 @@ export function usePreviewPanelInlineSize(): PreviewPanelInlineSize {
});
}
/** Keep the resizable panel's upper bound in sync with the current window. */
function useViewportClampedMaxWidth(): number {
/**
* Keep the resizable panel's upper bound in sync with the window AND the row
* it sits in. Resize-aware so dragging the OS window narrower (or expanding
* the app sidebar) re-clamps the stored width on the next render.
*/
function useViewportClampedMaxWidth(hostRef?: RefObject<HTMLElement | null>): number {
const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
useEffect(() => {
if (typeof window === "undefined") return;
let frame = 0;
@@ -43,8 +59,33 @@ function useViewportClampedMaxWidth(): number {
if (frame !== 0) window.cancelAnimationFrame(frame);
};
}, []);
return getPreviewPanelMaxWidth(vw);
useLayoutEffect(() => {
const parent = hostRef?.current?.parentElement;
if (!parent) return;
// Measure before first paint: the persisted width must be clamped against
// the row on the initial render, not one observer tick later (the panel
// would flash over-wide on every mount). clientWidth is integral, so
// sub-pixel resize deltas bail out of re-rendering.
const measure = () => {
setContainerWidth(parent.clientWidth);
};
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(parent);
return () => {
observer.disconnect();
};
}, [hostRef]);
return getPreviewPanelMaxWidth(vw, containerWidth);
}
export function getPreviewPanelMaxWidth(viewportWidth: number): number {
return Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
export function getPreviewPanelMaxWidth(viewportWidth: number, containerWidth?: number): number {
const fractionCap = Math.floor(viewportWidth * PREVIEW_PANEL_MAX_WIDTH_FRACTION);
const containerCap =
containerWidth === undefined ? Infinity : Math.floor(containerWidth) - SIBLING_COLUMN_MIN_WIDTH;
// Never below the panel's own minimum: when the row cannot fit both
// columns' minimums the sibling yields, and useResizableWidth's clamp must
// not see max < min (it would resolve the inversion to min and, via
// drag-end persistence, overwrite the user's stored width).
return Math.max(PREVIEW_PANEL_MIN_WIDTH, Math.min(fractionCap, containerCap));
}
+1 -1
View File
@@ -141,7 +141,7 @@ export function useThreadActionMenu(input: {
isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
isRegeneratingTitle,
isRunning: thread.session?.status === "running" && thread.session.activeTurnId != null,
isRunning: thread.runtime?.status === "running" && thread.runtime.activeRunId != null,
supports,
snoozePresets,
});
+382 -716
View File
File diff suppressed because it is too large. Load diff
@@ -1,85 +0,0 @@
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { deriveWorkLogEntries } from "./session-logic";
function makeCommandActivity(
id: string,
payload: Record<string, unknown>,
): OrchestrationThreadActivity {
return {
id: EventId.make(id),
createdAt: "2026-07-17T10:00:00.000Z",
kind: "tool.completed",
summary: "Ran command",
tone: "tool",
payload,
turnId: TurnId.make("turn-1"),
};
}
describe("deriveWorkLogEntries command output", () => {
it("uses Codex aggregated output instead of repeating the command", () => {
const [entry] = deriveWorkLogEntries([
makeCommandActivity("codex-command", {
itemType: "command_execution",
title: "Ran command",
detail: "/bin/zsh -lc \"printf 'hello\\n'\"",
data: {
item: {
type: "commandExecution",
command: "/bin/zsh -lc \"printf 'hello\\n'\"",
commandActions: [{ command: "printf 'hello\\n'", type: "unknown" }],
aggregatedOutput: "hello\n<exited with exit code 0>",
status: "completed",
},
},
}),
]);
expect(entry).toMatchObject({
command: "printf 'hello\\n'",
rawCommand: "/bin/zsh -lc \"printf 'hello\\n'\"",
detail: "hello",
});
});
it("uses a projected Claude output summary instead of repeating the command", () => {
const [entry] = deriveWorkLogEntries([
makeCommandActivity("claude-command", {
itemType: "command_execution",
title: "Ran command",
detail: "printf hello",
data: {
kind: "execute",
command: "printf hello",
rawOutput: {
content: "hello from claude",
},
},
}),
]);
expect(entry).toMatchObject({
command: "printf hello",
detail: "hello from claude",
});
});
it("drops duplicated command detail when the command has no output", () => {
const [entry] = deriveWorkLogEntries([
makeCommandActivity("empty-command", {
itemType: "command_execution",
title: "Ran command",
detail: "true",
data: {
kind: "execute",
command: "true",
},
}),
]);
expect(entry?.command).toBe("true");
expect(entry?.detail).toBeUndefined();
});
});
+14
View File
@@ -5,6 +5,20 @@ import { MessageId, NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./ba
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
export const PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES = [
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
] as const;
const PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPE_SET = new Set<string>(
PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
);
/** Whether a pasted or picked image mime type can be sent on a provider turn. */
export function isProviderSendTurnSupportedImageMimeType(mimeType: string): boolean {
return PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPE_SET.has(mimeType.toLowerCase());
}
const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
const CHAT_ATTACHMENT_ID_MAX_CHARS = 128;
+21
View File
@@ -89,6 +89,7 @@ import { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } fr
import { AdvertisedEndpoint } from "./remoteAccess.ts";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
import type { ClientSettings } from "./settings.ts";
import type { EditorId } from "./editor.ts";
import type {
SourceControlCloneRepositoryInput,
SourceControlCloneRepositoryResult,
@@ -1017,6 +1018,13 @@ export const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
/**
* The OS locale as a BCP-47 tag, which the renderer cannot read for itself:
* the packaged app ships only the `en-US` Chromium locale pak, so
* `navigator.language` and the default `Intl` locale are pinned to `en-US`
* regardless of OS settings.
*/
getSystemLocale?: () => string | null;
// One bootstrap per pool instance currently registered with bootstrap
// info (omits instances whose backend hasn't produced a config yet).
// The primary backend is identified by id === PRIMARY_LOCAL_ENVIRONMENT_ID.
@@ -1069,7 +1077,19 @@ export interface DesktopBridge {
position?: { x: number; y: number },
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
/**
* Probe this desktop machine for installed remote-capable editor CLIs
* (used for remote open-in-editor deep links). Optional: older desktop
* builds lack it; callers fall back to VS Code only.
*/
probeRemoteEditors?: () => Promise<readonly EditorId[]>;
onMenuAction: (listener: (action: string) => void) => () => void;
/**
* Hold-to-quit hint pushes: "down" when the quit shortcut is first pressed,
* "up" when it is released before the hold completes. Optional: older
* desktop builds never emit it.
*/
onQuitShortcut?: (listener: (state: "down" | "up") => void) => () => void;
getWindowFullscreenState: () => boolean;
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
@@ -1186,6 +1206,7 @@ export interface LocalApi {
items: readonly ContextMenuItem<T>[],
position?: { x: number; y: number },
) => Promise<T | null>;
close: () => Promise<void>;
};
persistence: {
getClientSettings: () => Promise<ClientSettings | null>;
@@ -47,6 +47,11 @@ it.effect("parses keybinding rules", () =>
command: "threadPanel.toggle",
});
assert.strictEqual(parsedThreadPanelToggle.command, "threadPanel.toggle");
const parsedRightPanelToggleMaximized = yield* decode(KeybindingRule, {
key: "mod+shift+m",
command: "rightPanel.toggleMaximized",
});
assert.strictEqual(parsedRightPanelToggleMaximized.command, "rightPanel.toggleMaximized");
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
+3 -2
View File
@@ -47,7 +47,7 @@ export const MODEL_PICKER_KEYBINDING_COMMANDS = [
] as const;
export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];
export const BUILT_IN_KEYBINDING_COMMANDS = [
export const STATIC_KEYBINDING_COMMANDS = [
"sidebar.toggle",
"terminal.toggle",
"terminal.split",
@@ -56,6 +56,7 @@ export const BUILT_IN_KEYBINDING_COMMANDS = [
"terminal.close",
"rightPanel.toggle",
"threadPanel.toggle",
"rightPanel.toggleMaximized",
"diff.toggle",
"preview.toggle",
"preview.refresh",
@@ -85,7 +86,7 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([
]);
export const KeybindingCommand = Schema.Union([
Schema.Literals(BUILT_IN_KEYBINDING_COMMANDS),
Schema.Literals(STATIC_KEYBINDING_COMMANDS),
SCRIPT_RUN_COMMAND_PATTERN,
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;
+1 -1
View File
@@ -20,8 +20,8 @@ import {
ThreadCreatedPayload,
ThreadTurnDiff,
ThreadTurnStartRequestedPayload,
isProviderSendTurnSupportedImageMimeType,
} from "./orchestration.ts";
import { isProviderSendTurnSupportedImageMimeType } from "./chatAttachment.ts";
import { ModelSelection } from "./modelSelection.ts";
import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "./providerPolicy.ts";
import { ProviderInstanceId } from "./providerInstance.ts";