Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(web): unwrap windows shell command wrappers (#1719)
legs340dbbb36e51
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex e823569c1..9be521b3b 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -48,6 +48,7 @@ import {type MessagesTimelineRow,} from "./MessagesTimeline.logic";import { TerminalContextInlineChip } from "./TerminalContextInlineChip";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import {deriveDisplayedUserMessageState,type ParsedTerminalContextEntry,@@ -792,6 +793,16 @@ function workEntryPreview(: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;}+function workEntryRawCommand(+ workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,+): string | null {+ const rawCommand = workEntry.rawCommand?.trim();+ if (!rawCommand || !workEntry.command) {+ return null;+ }+ return rawCommand === workEntry.command.trim() ? null : rawCommand;+}+function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {if (workEntry.requestKind === "command") return TerminalIcon;if (workEntry.requestKind === "file-read") return EyeIcon;@@ -840,6 +851,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {const EntryIcon = workEntryIcon(workEntry);const heading = toolWorkEntryHeading(workEntry);const preview = workEntryPreview(workEntry);+ const rawCommand = workEntryRawCommand(workEntry);const displayText = preview ? `${heading} - ${preview}` : heading;const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;@@ -853,19 +865,46 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {<EntryIcon className="size-3" /></span><div className="min-w-0 flex-1 overflow-hidden">- <p- className={cn(- "truncate text-[11px] leading-5",- workToneClass(workEntry.tone),- preview ? "text-muted-foreground/70" : "",- )}- title={displayText}- >- <span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>- {heading}- </span>- {preview && <span className="text-muted-foreground/55"> - {preview}</span>}- </p>+ <div className="max-w-full">+ <p+ className={cn(+ "truncate text-[11px] leading-5",+ workToneClass(workEntry.tone),+ preview ? "text-muted-foreground/70" : "",+ )}+ title={rawCommand ? undefined : displayText}+ >+ <span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>+ {heading}+ </span>+ {preview &&+ (rawCommand ? (+ <Tooltip>+ <TooltipTrigger+ closeDelay={0}+ delay={75}+ render={+ <span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">+ {" "}+ - {preview}+ </span>+ }+ />+ <TooltipPopup+ align="start"+ className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"+ side="top"+ >+ <div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">+ {rawCommand}+ </div>+ </TooltipPopup>+ </Tooltip>+ ) : (+ <span className="text-muted-foreground/55"> - {preview}</span>+ ))}+ </p>+ </div></div></div>{hasChangedFiles && !previewIsChangedFiles && (diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex e05c3b5e9..1c976a53c 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -709,6 +709,97 @@ describe("deriveWorkLogEntries", () => {expect(entry?.command).toBe("bun run lint");});+ it("unwraps PowerShell command wrappers for displayed command text", () => {+ const activities: OrchestrationThreadActivity[] = [+ makeActivity({+ id: "command-tool-windows-wrapper",+ kind: "tool.completed",+ summary: "Ran command",+ payload: {+ itemType: "command_execution",+ data: {+ item: {+ command: "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",+ },+ },+ },+ }),+ ];++ const [entry] = deriveWorkLogEntries(activities, undefined);+ expect(entry?.command).toBe("bun run lint");+ expect(entry?.rawCommand).toBe(+ "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",+ );+ });++ it("unwraps PowerShell command wrappers from argv-style command payloads", () => {+ const activities: OrchestrationThreadActivity[] = [+ makeActivity({+ id: "command-tool-windows-wrapper-argv",+ kind: "tool.completed",+ summary: "Ran command",+ payload: {+ itemType: "command_execution",+ data: {+ item: {+ command: ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n foo ."],+ },+ },+ },+ }),+ ];++ const [entry] = deriveWorkLogEntries(activities, undefined);+ expect(entry?.command).toBe("rg -n foo .");+ expect(entry?.rawCommand).toBe(+ '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."',+ );+ });++ it("extracts command text from command detail when structured command metadata is missing", () => {+ const activities: OrchestrationThreadActivity[] = [+ makeActivity({+ id: "command-tool-windows-detail-fallback",+ kind: "tool.completed",+ summary: "Ran command",+ payload: {+ itemType: "command_execution",+ detail:+ '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command \'rg -n -F "new Date()" .\' <exited with exit code 0>',+ },+ }),+ ];++ const [entry] = deriveWorkLogEntries(activities, undefined);+ expect(entry?.command).toBe('rg -n -F "new Date()" .');+ expect(entry?.rawCommand).toBe(+ `"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`,+ );+ });++ it("does not unwrap shell commands when no wrapper flag is present", () => {+ const activities: OrchestrationThreadActivity[] = [+ makeActivity({+ id: "command-tool-shell-script",+ kind: "tool.completed",+ summary: "Ran command",+ payload: {+ itemType: "command_execution",+ data: {+ item: {+ command: "bash script.sh",+ },+ },+ },+ }),+ ];++ const [entry] = deriveWorkLogEntries(activities, undefined);+ expect(entry?.command).toBe("bash script.sh");+ expect(entry?.rawCommand).toBeUndefined();+ });+it("keeps compact Codex tool metadata used for icons and labels", () => {const activities: OrchestrationThreadActivity[] = [makeActivity({diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex fc3382701..b818dc106 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -38,6 +38,7 @@ export interface WorkLogEntry {label: string;detail?: string;command?: string;+ rawCommand?: string;changedFiles?: ReadonlyArray<string>;tone: "thinking" | "tool" | "info" | "error";toolTitle?: string;@@ -489,7 +490,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoactivity.payload && typeof activity.payload === "object"? (activity.payload as Record<string, unknown>): null;- const command = extractToolCommand(payload);+ const commandPreview = extractToolCommand(payload);const changedFiles = extractChangedFiles(payload);const title = extractToolTitle(payload);const entry: DerivedWorkLogEntry = {@@ -507,8 +508,11 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWoentry.detail = detail;}}- if (command) {- entry.command = command;+ if (commandPreview.command) {+ entry.command = commandPreview.command;+ }+ if (commandPreview.rawCommand) {+ entry.rawCommand = commandPreview.rawCommand;}if (changedFiles.length > 0) {entry.changedFiles = changedFiles;@@ -567,6 +571,7 @@ function mergeDerivedWorkLogEntries(const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);const detail = next.detail ?? previous.detail;const command = next.command ?? previous.command;+ const rawCommand = next.rawCommand ?? previous.rawCommand;const toolTitle = next.toolTitle ?? previous.toolTitle;const itemType = next.itemType ?? previous.itemType;const requestKind = next.requestKind ?? previous.requestKind;@@ -576,6 +581,7 @@ function mergeDerivedWorkLogEntries(...next,...(detail ? { detail } : {}),...(command ? { command } : {}),+ ...(rawCommand ? { rawCommand } : {}),...(changedFiles.length > 0 ? { changedFiles } : {}),...(toolTitle ? { toolTitle } : {}),...(itemType ? { itemType } : {}),@@ -636,7 +642,121 @@ function asTrimmedString(value: unknown): string | null {return trimmed.length > 0 ? trimmed : null;}-function normalizeCommandValue(value: unknown): string | null {+function trimMatchingOuterQuotes(value: string): string {+ const trimmed = value.trim();+ if (+ (trimmed.startsWith("'") && trimmed.endsWith("'")) ||+ (trimmed.startsWith('"') && trimmed.endsWith('"'))+ ) {+ const unquoted = trimmed.slice(1, -1).trim();+ return unquoted.length > 0 ? unquoted : trimmed;+ }+ return trimmed;+}++function executableBasename(value: string): string | null {+ const trimmed = trimMatchingOuterQuotes(value);+ if (trimmed.length === 0) {+ return null;+ }+ const normalized = trimmed.replace(/\\/g, "/");+ const segments = normalized.split("/");+ const last = segments.at(-1)?.trim() ?? "";+ return last.length > 0 ? last.toLowerCase() : null;+}++function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {+ const trimmed = value.trim();+ if (trimmed.length === 0) {+ return null;+ }++ if (trimmed.startsWith('"') || trimmed.startsWith("'")) {+ const quote = trimmed.charAt(0);+ const closeIndex = trimmed.indexOf(quote, 1);+ if (closeIndex <= 0) {+ return null;+ }+ return {+ executable: trimmed.slice(0, closeIndex + 1),+ rest: trimmed.slice(closeIndex + 1).trim(),+ };+ }++ const firstWhitespace = trimmed.search(/\s/);+ if (firstWhitespace < 0) {+ return {+ executable: trimmed,+ rest: "",+ };+ }++ return {+ executable: trimmed.slice(0, firstWhitespace),+ rest: trimmed.slice(firstWhitespace).trim(),+ };+}++const SHELL_WRAPPER_SPECS = [+ {+ executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],+ wrapperFlagPattern: /(?:^|\s)-command\s+/i,+ },+ {+ executables: ["cmd", "cmd.exe"],+ wrapperFlagPattern: /(?:^|\s)\/c\s+/i,+ },+ {+ executables: ["bash", "sh", "zsh"],+ wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,+ },+] as const;++function findShellWrapperSpec(shell: string) {+ return SHELL_WRAPPER_SPECS.find((spec) =>+ (spec.executables as ReadonlyArray<string>).includes(shell),+ );+}++function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {+ const match = wrapperFlagPattern.exec(value);+ if (!match) {+ return null;+ }++ const command = value.slice(match.index + match[0].length).trim();+ if (command.length === 0) {+ return null;+ }++ const unwrapped = trimMatchingOuterQuotes(command);+ return unwrapped.length > 0 ? unwrapped : null;+}++function unwrapKnownShellCommandWrapper(value: string): string {+ const split = splitExecutableAndRest(value);+ if (!split || split.rest.length === 0) {+ return value;+ }++ const shell = executableBasename(split.executable);+ if (!shell) {+ return value;+ }++ const spec = findShellWrapperSpec(shell);+ if (!spec) {+ return value;+ }++ return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;+}++function formatCommandArrayPart(value: string): string {+ return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;+}++function formatCommandValue(value: unknown): string | null {const direct = asTrimmedString(value);if (direct) {return direct;@@ -647,21 +767,58 @@ function normalizeCommandValue(value: unknown): string | null {const parts = value.map((entry) => asTrimmedString(entry)).filter((entry): entry is string => entry !== null);- return parts.length > 0 ? parts.join(" ") : null;+ if (parts.length === 0) {+ return null;+ }+ return parts.map((part) => formatCommandArrayPart(part)).join(" ");}-function extractToolCommand(payload: Record<string, unknown> | null): string | null {+function normalizeCommandValue(value: unknown): string | null {+ const formatted = formatCommandValue(value);+ return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;+}++function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {+ const formatted = formatCommandValue(value);+ if (!formatted || normalizedCommand === null) {+ return null;+ }+ return formatted === normalizedCommand ? null : formatted;+}++function extractToolCommand(payload: Record<string, unknown> | null): {+ command: string | null;+ rawCommand: string | null;+} {const data = asRecord(payload?.data);const item = asRecord(data?.item);const itemResult = asRecord(item?.result);const itemInput = asRecord(item?.input);- const candidates = [- normalizeCommandValue(item?.command),- normalizeCommandValue(itemInput?.command),- normalizeCommandValue(itemResult?.command),- normalizeCommandValue(data?.command),+ const itemType = asTrimmedString(payload?.itemType);+ const detail = asTrimmedString(payload?.detail);+ const candidates: unknown[] = [+ item?.command,+ itemInput?.command,+ itemResult?.command,+ data?.command,+ itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,];- return candidates.find((candidate) => candidate !== null) ?? null;++ for (const candidate of candidates) {+ const command = normalizeCommandValue(candidate);+ if (!command) {+ continue;+ }+ return {+ command,+ rawCommand: toRawToolCommand(candidate, command),+ };+ }++ return {+ command: null,+ rawCommand: null,+ };}function extractToolTitle(payload: Record<string, unknown> | null): string | null {