π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(worktree): unwrap Codex login-shell wrapper before git command detection (#17033)
Arvin Xu504802f635f3
diff --git a/packages/builtin-tools/src/codex/commandExecutionUtils.ts b/packages/builtin-tools/src/codex/commandExecutionUtils.tsindex 3f09d8e0bb3..65159e7e640 100644--- a/packages/builtin-tools/src/codex/commandExecutionUtils.ts+++ b/packages/builtin-tools/src/codex/commandExecutionUtils.ts@@ -1,3 +1,5 @@+// The parse-side unwrap in src/store/tool/slices/builtin/executors/worktreeDetection.ts+// mirrors this wrapper shape β keep the accepted forms in sync.const SHELL_WRAPPER_PATTERN =/^(?:\/usr\/bin\/env\s+)?(?:\/\S+\/)?(?:bash|sh|zsh)\s+(?:-lc|-c|-l\s+-c)\s+(\S[\s\S]*)$/;diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.tsindex 6bfdbc2b34c..642f0be5c20 100644--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts@@ -126,6 +126,42 @@ describe('parseWorktreeAddPath', () => {expect(parseWorktreeAddPath('git worktree add $(mktemp -d) feat/x', '/repo')).toBeUndefined();expect(parseWorktreeAddPath('git worktree add ~/wt feat/x', '/repo')).toBeUndefined();});++ it('unwraps the Codex login-shell wrapper', () => {+ expect(parseWorktreeAddPath('/bin/zsh -lc "git worktree add -b feat/x ../wt"', '/repo')).toBe(+ '/wt',+ );+ expect(parseWorktreeAddPath("bash -lc 'git worktree add /tmp/wt'", '/repo')).toBe('/tmp/wt');+ expect(parseWorktreeAddPath('sh -c "git worktree add wt"', '/repo')).toBe('/repo/wt');+ expect(parseWorktreeAddPath('/usr/bin/env bash -l -c "git worktree add /wt"', '/repo')).toBe(+ '/wt',+ );+ });++ it('unwraps the argv form of the shell wrapper', () => {+ expect(+ parseWorktreeAddPath(['/bin/zsh', '-lc', 'git worktree add -b feat/x /tmp/wt'], '/repo'),+ ).toBe('/tmp/wt');+ expect(parseWorktreeAddPath(['bash', '-l', '-c', 'git worktree add ../wt'], '/repo')).toBe(+ '/wt',+ );+ });++ it('handles separators, escaped quotes, and nesting inside the wrapper payload', () => {+ expect(+ parseWorktreeAddPath('/bin/zsh -lc "cd /repo && git worktree add \\"/tmp/my wt\\""', '/repo'),+ ).toBe('/tmp/my wt');+ expect(parseWorktreeAddPath(`zsh -lc 'bash -c "git worktree add /tmp/wt"'`, '/repo')).toBe(+ '/tmp/wt',+ );+ });++ it('still rejects non-git payloads inside a wrapper', () => {+ expect(+ parseWorktreeAddPath('/bin/zsh -lc "echo git worktree add /wt"', '/repo'),+ ).toBeUndefined();+ expect(parseWorktreeAddPath(`/bin/zsh -lc "rg 'git worktree add' ."`, '/repo')).toBeUndefined();+ });});const PR_TOPIC = {@@ -346,6 +382,72 @@ describe('recordGitCommandEffects', () => {});});+ it('records a worktree add shipped through the Codex zsh wrapper', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({+ command: '/bin/zsh -lc "git worktree add -b feat/agent-testing-s3rver /Users/me/wt canary"',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: {+ activeWorktree: '/Users/me/wt',+ branch: 'feat/agent-testing-s3rver',+ isWorktree: true,+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('updates the branch from a wrapped git switch', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({+ command: 'bash -lc "git switch fix/topic"',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: { branch: 'fix/topic' },+ path: '/repo',+ repoType: 'github',+ },+ });+ });++ it('binds a created PR from a wrapped gh pr create', async () => {+ chatMocks.topics = { t1: PR_TOPIC };++ await recordGitCommandEffects({+ command: `/bin/zsh -lc "gh pr create --title 'Fix topic'"`,+ resultContent: 'https://github.com/lobehub/lobehub/pull/456',+ topicId: 't1',+ });++ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {+ workingDirectoryConfig: {+ git: {+ github: {+ pullRequest: {+ number: 456,+ state: 'OPEN',+ title: 'Fix topic',+ url: 'https://github.com/lobehub/lobehub/pull/456',+ },+ pullRequestStatus: 'ok',+ },+ },+ path: '/repo',+ repoType: 'github',+ },+ });+ });+it('does not query the device when the worktree path parses statically', async () => {chatMocks.topics = { t1: PR_TOPIC };diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex 294ef45c72e..1966db4fdcf 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -16,7 +16,8 @@ import { getElectronStoreState } from '@/store/electron';* (renderer-side, fired on `tool_end`). The CLI session cwd stays anchored to* the source repo; selected worktree / branch / linked PR are topic metadata.*- * Command parsing is a trigger + hint, not the source of truth: `$VAR`+ * Command parsing is a trigger + hint, not the source of truth: a Codex-style+ * login-shell wrapper (`/bin/zsh -lc "β¦"`) is peeled off first, `$VAR`* references are expanded from assignments earlier in the same command, and a* path that still carries shell syntax after that is never recorded literally β* the real path is read back from the device's `git worktree list` (matched by@@ -207,12 +208,17 @@ const findInCommand = <T>(parser: (tokens: string[], env?: ShellEnv) => T | undefined,): T | undefined => {if (Array.isArray(command)) {- return command.every((t) => typeof t === 'string') ? parser(command) : undefined;+ if (!command.every((t) => typeof t === 'string')) return undefined;+ // A shell-wrapped argv carries a raw shell string as its payload β recurse so+ // it gets the same separator splitting and `$VAR` expansion as the string form.+ const wrapped = unwrapShellArgv(command);+ if (wrapped !== undefined) return findInCommand(wrapped, parser);+ return parser(command);}if (typeof command !== 'string') return undefined;const env: ShellEnv = {};- for (const segment of command.split(/[\n;|&]/)) {+ for (const segment of unwrapShellCommand(command).split(/[\n;|&]/)) {const tokens = tokenize(segment);const result = parser(tokens, env);if (result) return result;@@ -562,6 +568,63 @@ const GIT_VALUE_OPTS = new Set([/** Command wrappers that may precede the real `git` executable. */const WRAPPERS = new Set(['sudo', 'env', 'command', 'nice', 'nohup', 'time']);+/**+ * Codex ships every shell tool call wrapped in a login shell β the wire command is+ * `/bin/zsh -lc "git worktree add β¦"` (or the argv form `['bash', '-lc', 'git β¦']`)+ * β so the head token is the shell, never `git`/`gh`, and the real command hides+ * inside a single quoted token. The display layer strips this wrapper+ * (`stripShellWrapper` in `packages/builtin-tools/src/codex/commandExecutionUtils.ts`+ * β keep the accepted shapes in sync), so parsing must strip it too, or the UI shows+ * a bare git command that this module silently rejected.+ */+const SHELL_WRAPPER_PATTERN =+ /^(?:\/usr\/bin\/env\s+)?(?:\/\S+\/)?(?:bash|sh|zsh)\s+(?:-lc|-c|-l\s+-c)\s+(\S[\s\S]*)$/;+const SHELL_EXECUTABLES = new Set(['bash', 'sh', 'zsh']);++/** Undo the shell's own quoting of the wrapper payload (`-lc "git \"β¦\""` β `git "β¦"`). */+const stripOuterShellQuotes = (value: string): string => {+ const trimmed = value.trim();+ if (trimmed.length < 2) return trimmed;++ const quote = trimmed[0];+ if ((quote !== '"' && quote !== "'") || trimmed.at(-1) !== quote) return trimmed;++ const body = trimmed.slice(1, -1);+ if (quote === "'") return body.replaceAll("'\\''", "'");++ return body+ .replaceAll('\\"', '"')+ .replaceAll('\\`', '`')+ .replaceAll('\\$', '$')+ .replaceAll('\\\\', '\\');+};++/** `['/bin/zsh', '-lc', 'git β¦']` β `git β¦`; undefined when argv is not a shell wrapper. */+const unwrapShellArgv = (tokens: string[]): string | undefined => {+ let i = getExecutableName(tokens[0] ?? '') === 'env' ? 1 : 0;+ if (!SHELL_EXECUTABLES.has(getExecutableName(tokens[i] ?? '') ?? '')) return undefined;+ i += 1;+ if (stripQuotes(tokens[i] ?? '') === '-l') i += 1;+ const flag = stripQuotes(tokens[i] ?? '');+ if (flag !== '-c' && flag !== '-lc') return undefined;+ return tokens[i + 1];+};++/** Peel `bash|sh|zsh -lc "β¦"` layers off a raw command string until none remain. */+const unwrapShellCommand = (command: string): string => {+ let current = command;+ // Wrappers can nest (`zsh -lc 'bash -c "git β¦"'`) but only shallowly; each peel+ // strictly shortens the string, so the depth cap is a formality.+ for (let depth = 0; depth < 4; depth += 1) {+ const match = SHELL_WRAPPER_PATTERN.exec(current.trim());+ if (!match) break;+ const inner = stripOuterShellQuotes(match[1]);+ if (!inner) break;+ current = inner;+ }+ return current;+};+/*** If ONE command's tokens are a real `git β¦ worktree add <path>` invocation, return* the path (resolved against the source cwd, honoring a `-C <dir>` override).@@ -643,16 +706,22 @@ const parseWorktreeAddInfo = (cwd?: string,): WorktreeAddParseResult | undefined => {if (Array.isArray(command)) {+ if (!command.every((t) => typeof t === 'string')) return undefined;+ // A shell-wrapped argv carries a raw shell string as its payload β recurse so+ // it gets the same separator splitting and `$VAR` expansion as the string form.+ const wrapped = unwrapShellArgv(command);+ if (wrapped !== undefined) return parseWorktreeAddInfo(wrapped, cwd);// Already-tokenized argv β a single command, boundaries preserved. No shell// ran, so tokens are literal β no assignments to collect or vars to expand.- return command.every((t) => typeof t === 'string')- ? parseGitWorktreeAddTokens(command, cwd)- : undefined;+ return parseGitWorktreeAddTokens(command, cwd);}- if (typeof command !== 'string' || !/\bworktree\s+add\b/.test(command)) return undefined;+ if (typeof command !== 'string') return undefined;++ const unwrapped = unwrapShellCommand(command);+ if (!/\bworktree\s+add\b/.test(unwrapped)) return undefined;const env: ShellEnv = {};- for (const segment of command.split(/[\n;|&]/)) {+ for (const segment of unwrapped.split(/[\n;|&]/)) {const tokens = tokenize(segment);const info = parseGitWorktreeAddTokens(tokens, cwd, env);if (info) return info;