Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions UPSTREAM_SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ em volta. Use `git grep "VERBOO-BRAND"` para localizar todos os pontos editados.
- `src/commands/provider/` — arquivos **NÃO foram deletados** (upstream
continua mexendo neles; deletar gera conflitos "deleted file modified upstream").

#### Nada gravado nas pastas de outros apps
- `src/utils/envUtils.ts` — `getProjectsDir()` = `~/.verboo/projects` (ou
`VERBOO_CONFIG_DIR/projects`); `~/.claude/projects` e `~/.openclaude/projects`
entram em `getAdditionalProjectsDirs()` só para leitura.
- `src/utils/sessionStorage.ts` — `mirrorTranscriptToAdditionalDirs` virou
no-op; retomar sessão de diretório somente leitura copia o arquivo
(`adoptReadOnlyTranscriptForResume`, usado em `sessionRestore.ts`).
- `src/utils/completionCache.ts` — cache em `~/.verboo/completion.<shell>`.
- `scripts/postinstall.mjs` — não copia nada de `~/.claude`.

#### Mensagens reescritas
- `src/utils/providerValidation.ts` (3 ocorrências)
- `src/services/api/withRetry.ts`
Expand Down
104 changes: 47 additions & 57 deletions scripts/postinstall.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,87 +6,77 @@
* /usr/local ou ~/.npm-global). Shells bash/zsh geralmente já têm esse bin no
* PATH via .bashrc/.zshrc, mas o fish não herda essas configs — é preciso
* chamar `fish_add_path` explicitamente.
*
* A instalação não lê nem copia arquivos de outros apps (como ~/.claude): a
* CLI já lê skills e plugins do Claude Code em modo somente leitura.
*/

import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, readdirSync, statSync, copyFileSync } from 'node:fs'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { homedir } from 'os'
import { pathToFileURL } from 'node:url'

function isFishShell() {
const shell = process.env.SHELL ?? ''
const parent = process.env.FISH_VERSION // set by fish itself
export function isFishShell(env = process.env) {
const shell = env.SHELL ?? ''
const parent = env.FISH_VERSION // set by fish itself
return shell.endsWith('/fish') || parent !== undefined
}

function getNpmGlobalBin() {
/**
* Only a global install by a regular user touches the shell: never as root
* (it would write root-owned fish config) and never in CI.
*/
export function shouldConfigureShell({
env = process.env,
uid = process.getuid?.(),
} = {}) {
if (uid === 0) return false
if (env.CI) return false
if (env.npm_config_global !== 'true') return false
return isFishShell(env)
}

export function getNpmGlobalBin(exec = execFileSync) {
try {
const prefix = execFileSync('npm', ['prefix', '-g'], { encoding: 'utf8' }).trim()
const prefix = exec('npm', ['prefix', '-g'], { encoding: 'utf8' }).trim()
return join(prefix, 'bin')
} catch {
return null
}
}

function fishAddPath(dir) {
const result = spawnSync('fish', ['-c', `fish_add_path ${dir}`], {
/**
* The directory is passed to fish as an argument, never interpolated into
* the command string, so a prefix with spaces or shell characters stays a
* single path.
*/
export function fishAddPath(dir, spawn = spawnSync) {
const result = spawn('fish', ['-c', 'fish_add_path -- $argv[1]', '--', dir], {
stdio: 'inherit',
timeout: 5000,
})
return result.status === 0
}

function copyDirRecursive(src, dest) {
let copied = false
if (!existsSync(dest)) mkdirSync(dest, { recursive: true })
for (const entry of readdirSync(src)) {
const srcPath = join(src, entry)
const destPath = join(dest, entry)
if (existsSync(destPath)) continue
const stat = statSync(srcPath)
if (stat.isDirectory()) {
if (copyDirRecursive(srcPath, destPath)) copied = true
} else {
copyFileSync(srcPath, destPath)
copied = true
}
}
return copied
}

function importFromClaudeCode() {
const claude = join(homedir(), '.claude')
const verboo = join(homedir(), '.verboo')
for (const asset of ['skills', 'plugins']) {
const src = join(claude, asset)
const dest = join(verboo, asset)
if (!existsSync(src)) continue
try {
if (copyDirRecursive(src, dest)) {
process.stdout.write(`[verboo] ${asset} imported from Claude Code.\n`)
export function main({ env = process.env, write = text => process.stdout.write(text) } = {}) {
if (shouldConfigureShell({ env })) {
const binDir = getNpmGlobalBin()
if (binDir && existsSync(binDir)) {
if (fishAddPath(binDir)) {
write(`[verboo] fish_add_path ${binDir} — feito.\n`)
} else {
write(
`[verboo] Não foi possível adicionar ${binDir} ao fish automaticamente.\n` +
` Execute manualmente: fish_add_path ${binDir}\n`,
)
}
} catch (err) {
process.stdout.write(`[verboo] Import of ${asset} from Claude Code failed: ${err.message}. Proceeding without import.\n`)
}
}
}

if (isFishShell()) {
const binDir = getNpmGlobalBin()
if (binDir && existsSync(binDir)) {
const ok = fishAddPath(binDir)
if (ok) {
process.stdout.write(`[verboo] fish_add_path ${binDir} — feito.\n`)
} else {
process.stdout.write(
`[verboo] Não foi possível adicionar ${binDir} ao fish automaticamente.\n` +
` Execute manualmente: fish_add_path ${binDir}\n`,
)
}
}
write('Verboo Code instalado com sucesso!\n')
write('Para começar, digite verboo no seu terminal.\n')
}

importFromClaudeCode()

process.stdout.write('Verboo Code instalado com sucesso!\n')
process.stdout.write('Para começar, digite verboo no seu terminal.\n')
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
main()
}
45 changes: 45 additions & 0 deletions scripts/postinstall.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict'
import { mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'

import { fishAddPath, main, shouldConfigureShell } from './postinstall.mjs'

test('never copies anything from ~/.claude', () => {
const home = mkdtempSync(join(tmpdir(), 'verboo-postinstall-'))
try {
mkdirSync(join(home, '.claude', 'skills', 'my-skill'), { recursive: true })
mkdirSync(join(home, '.claude', 'plugins'), { recursive: true })
const output = []
main({ env: { HOME: home, SHELL: '/bin/bash' }, write: text => output.push(text) })
assert.deepEqual(readdirSync(home), ['.claude'])
assert.ok(output.join('').includes('Verboo Code instalado com sucesso!'))
} finally {
rmSync(home, { recursive: true, force: true })
}
})

test('passes the npm prefix to fish as one argument', () => {
const calls = []
const spawn = (file, args) => {
calls.push([file, ...args])
return { status: 0 }
}
assert.equal(fishAddPath('/opt/my prefix; rm -rf ~/bin', spawn), true)
assert.deepEqual(calls, [
['fish', '-c', 'fish_add_path -- $argv[1]', '--', '/opt/my prefix; rm -rf ~/bin'],
])
})

test('only configures fish for a global install by a regular user outside CI', () => {
const fish = { SHELL: '/usr/bin/fish', npm_config_global: 'true' }
assert.equal(shouldConfigureShell({ env: fish, uid: 1000 }), true)
assert.equal(shouldConfigureShell({ env: fish, uid: 0 }), false)
assert.equal(shouldConfigureShell({ env: { ...fish, CI: '1' }, uid: 1000 }), false)
assert.equal(shouldConfigureShell({ env: { SHELL: '/usr/bin/fish' }, uid: 1000 }), false)
assert.equal(
shouldConfigureShell({ env: { SHELL: '/bin/zsh', npm_config_global: 'true' }, uid: 1000 }),
false,
)
})
12 changes: 9 additions & 3 deletions src/cli/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { parseAgentUsageMetadata } from '../utils/agentUsageSchema.js'
// biome-ignore-all assist/source/organizeImports: internal-only import markers must not be reordered
import { feature } from 'bun:bundle'
import { readFile, stat } from 'fs/promises'
import { dirname } from 'path'
import {
downloadUserSettings,
redownloadUserSettings,
Expand Down Expand Up @@ -211,6 +210,7 @@ import { parseSessionIdentifier } from 'src/utils/sessionUrl.js'
import {
hydrateRemoteSession,
hydrateFromCCRv2InternalEvents,
adoptReadOnlyTranscriptForResume,
resetSessionFilePointer,
doesMessageExistInSession,
findUnresolvedToolUse,
Expand Down Expand Up @@ -4960,7 +4960,10 @@ async function loadInitialMessages(
if (result.sessionId) {
switchSession(
asSessionId(result.sessionId),
result.fullPath ? dirname(result.fullPath) : null,
// VERBOO-BRAND: an old session in a read-only dir is resumed from a copy.
result.fullPath
? await adoptReadOnlyTranscriptForResume(result.fullPath)
: null,
)
if (persistSession) {
await resetSessionFilePointer()
Expand Down Expand Up @@ -5161,7 +5164,10 @@ async function loadInitialMessages(
if (!options.forkSession && result.sessionId) {
switchSession(
asSessionId(result.sessionId),
result.fullPath ? dirname(result.fullPath) : null,
// VERBOO-BRAND: an old session in a read-only dir is resumed from a copy.
result.fullPath
? await adoptReadOnlyTranscriptForResume(result.fullPath)
: null,
)
if (persistSession) {
await resetSessionFilePointer()
Expand Down
5 changes: 3 additions & 2 deletions src/screens/REPL.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ import type { ContentBlockParam, ImageBlockParam } from '@anthropic-ai/sdk/resou
import type { ProcessUserInputContext } from '../utils/processUserInput/processUserInput.js';
import type { PastedContent } from '../utils/config.js';
import { copyPlanForFork, copyPlanForResume, getPlanSlug, setPlanSlug } from '../utils/plans.js';
import { clearSessionMetadata, resetSessionFilePointer, adoptResumedSessionFile, removeTranscriptMessage, restoreSessionMetadata, getCurrentSessionTitle, isEphemeralToolProgress, isLoggableMessage, saveWorktreeState, getAgentTranscript, recordAiGeneratedTitle } from '../utils/sessionStorage.js';
import { adoptReadOnlyTranscriptForResume, clearSessionMetadata, resetSessionFilePointer, adoptResumedSessionFile, removeTranscriptMessage, restoreSessionMetadata, getCurrentSessionTitle, isEphemeralToolProgress, isLoggableMessage, saveWorktreeState, getAgentTranscript, recordAiGeneratedTitle } from '../utils/sessionStorage.js';
import { deserializeMessages } from '../utils/conversationRecovery.js';
import { extractReadFilesFromMessages, extractBashToolsFromMessages } from '../utils/queryHelpers.js';
import { resetMicrocompactState } from '../services/compact/microCompact.js';
Expand Down Expand Up @@ -1929,7 +1929,8 @@ export function REPL({
// Switch session (id + project dir atomically). fullPath may point to
// a different project (cross-worktree, /branch); null derives from
// current originalCwd.
switchSession(asSessionId(sessionId), log.fullPath ? dirname(log.fullPath) : null);
// VERBOO-BRAND: an old session in a read-only dir is resumed from a copy.
switchSession(asSessionId(sessionId), log.fullPath ? await adoptReadOnlyTranscriptForResume(log.fullPath) : null);
// Rename asciicast recording to match the resumed session ID
const {
renameRecordingForSession
Expand Down
6 changes: 3 additions & 3 deletions src/screens/ResumeConversation.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { c as _c } from "react-compiler-runtime";
import { feature } from 'bun:bundle';
import { dirname } from 'path';
import React from 'react';
import { useTerminalSize } from 'src/hooks/useTerminalSize.js';
import { getOriginalCwd, switchSession } from '../bootstrap/state.js';
Expand Down Expand Up @@ -31,7 +30,7 @@ import { logError } from '../utils/log.js';
import { handoffToResume } from '../utils/resumeHandoff.js';
import { createSystemMessage } from '../utils/messages.js';
import { computeStandaloneAgentContext, restoreAgentFromSession, restoreWorktreeForResume } from '../utils/sessionRestore.js';
import { adoptResumedSessionFile, enrichLogs, getSessionIdFromLog, isCustomTitleEnabled, loadAllProjectsMessageLogsProgressive, loadSameRepoMessageLogsProgressive, recordContentReplacement, resetSessionFilePointer, restoreSessionMetadata, type SessionLogResult } from '../utils/sessionStorage.js';
import { adoptReadOnlyTranscriptForResume, adoptResumedSessionFile, enrichLogs, getSessionIdFromLog, isCustomTitleEnabled, loadAllProjectsMessageLogsProgressive, loadSameRepoMessageLogsProgressive, recordContentReplacement, resetSessionFilePointer, restoreSessionMetadata, type SessionLogResult } from '../utils/sessionStorage.js';
import type { ThinkingConfig } from '../utils/thinking.js';
import type { ContentReplacementRecord } from '../utils/toolResultStorage.js';
import { REPL } from './REPL.js';
Expand Down Expand Up @@ -232,7 +231,8 @@ export function ResumeConversation({
// Prefer the resolved fullPath: for imported sessions (Codex) it
// points to the converted native file, not the foreign source.
const sessionDirPath = result_3.fullPath ?? log_0.fullPath;
switchSession(asSessionId(result_3.sessionId), sessionDirPath ? dirname(sessionDirPath) : null);
// VERBOO-BRAND: an old session in a read-only dir is resumed from a copy.
switchSession(asSessionId(result_3.sessionId), sessionDirPath ? await adoptReadOnlyTranscriptForResume(sessionDirPath) : null);
await renameRecordingForSession();
await resetSessionFilePointer();
restoreCostStateForSession(result_3.sessionId);
Expand Down
22 changes: 22 additions & 0 deletions src/utils/completionCache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* VERBOO-BRAND: the shell completion cache must not live in ~/.claude, where
* it overwrote Claude Code's own completion files on every `verboo update`.
* detectShell is private and setupShellCompletion edits the real rc file, so
* the wiring is asserted structurally.
*/
import { expect, test } from 'bun:test'
import { resolve } from 'path'

const source = () => Bun.file(resolve(import.meta.dir, 'completionCache.ts')).text()

test('completion cache lives in the Verboo config dir', async () => {
const content = await source()
expect(content).toContain('const claudeDir = getClaudeConfigHomeDir()')
expect(content).not.toMatch(/join\(home, '\.claude'\)/)
})

test('a Claude Code completion line in the rc file does not count as ours', async () => {
const content = await source()
expect(content).not.toContain("existing.includes('claude completion')")
expect(content).toContain('# Verboo Code shell completions')
})
18 changes: 10 additions & 8 deletions src/utils/completionCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { pathToFileURL } from 'url'
import { color } from '../components/design-system/color.js'
import { supportsHyperlinks } from '../ink/supports-hyperlinks.js'
import { logForDebugging } from './debug.js'
import { getClaudeConfigHomeDir } from './envUtils.js'
import { isENOENT } from './errors.js'
import { execFileNoThrow } from './execFileNoThrow.js'
import { logError } from './log.js'
Expand All @@ -24,7 +25,9 @@ type ShellInfo = {
function detectShell(): ShellInfo | null {
const shell = process.env.SHELL || ''
const home = homedir()
const claudeDir = join(home, '.claude')
// VERBOO-BRAND: o cache fica no diretório da Verboo. ~/.claude/completion.*
// é do Claude Code e era sobrescrito a cada `verboo update`.
const claudeDir = getClaudeConfigHomeDir()

if (shell.endsWith('/zsh') || shell.endsWith('/zsh.exe')) {
const cacheFile = join(claudeDir, 'completion.zsh')
Expand Down Expand Up @@ -89,7 +92,7 @@ export async function setupShellCompletion(theme: ThemeName): Promise<string> {
// Generate the completion script by writing directly to the cache file.
// Using --output avoids piping through stdout where process.exit() can
// truncate output before the pipe buffer drains.
const claudeBin = process.argv[1] || 'claude'
const claudeBin = process.argv[1] || 'verboo'
const result = await execFileNoThrow(claudeBin, [
'completion',
shell.shellFlag,
Expand All @@ -104,10 +107,9 @@ export async function setupShellCompletion(theme: ThemeName): Promise<string> {
let existing = ''
try {
existing = await readFile(shell.rcFile, { encoding: 'utf-8' })
if (
existing.includes('claude completion') ||
existing.includes(shell.cacheFile)
) {
// VERBOO-BRAND: só o nosso cache conta; uma linha do Claude Code no rc não
// significa que as completions da Verboo estão instaladas.
if (existing.includes(shell.cacheFile)) {
return `${EOL}${color('success', theme)(`Shell completions updated for ${shell.name}`)}${EOL}${chalk.dim(`See ${formatPathLink(shell.rcFile)}`)}${EOL}`
}
} catch (e: unknown) {
Expand All @@ -123,7 +125,7 @@ export async function setupShellCompletion(theme: ThemeName): Promise<string> {
await mkdir(configDir, { recursive: true })

const separator = existing && !existing.endsWith('\n') ? '\n' : ''
const content = `${existing}${separator}\n# Claude Code shell completions\n${shell.completionLine}\n`
const content = `${existing}${separator}\n# Verboo Code shell completions\n${shell.completionLine}\n`
await writeFile(shell.rcFile, content, { encoding: 'utf-8' })

return `${EOL}${color('success', theme)(`Installed ${shell.name} shell completions`)}${EOL}${chalk.dim(`Added to ${formatPathLink(shell.rcFile)}`)}${EOL}${chalk.dim(`Run: source ${shell.rcFile}`)}${EOL}`
Expand All @@ -145,7 +147,7 @@ export async function regenerateCompletionCache(): Promise<void> {

logForDebugging(`update: Regenerating ${shell.name} completion cache`)

const claudeBin = process.argv[1] || 'claude'
const claudeBin = process.argv[1] || 'verboo'
const result = await execFileNoThrow(claudeBin, [
'completion',
shell.shellFlag,
Expand Down
Loading
Loading