From a762e5ad699f7a9b9eebae2ad3e461233714920f Mon Sep 17 00:00:00 2001 From: dilrukshax Date: Mon, 24 Aug 2026 18:43:04 +0530 Subject: [PATCH] feat: enhance TUI theme with distinct color roles and update color values feat: add user configuration persistence with saveLocalConfig and userConfigPath feat: implement update check functionality with caching and registry fetching feat: introduce bypass mode in PolicyEngine for auto-approving actions fix: improve error handling in provider responses with providerHttpError utility test: add comprehensive tests for local config persistence and update check functionality test: implement tests for new bypass mode in policy decisions and TUI interactions test: add tests for slash commands and theme validation --- .env.example | 5 + .github/workflows/publish.yml | 19 +- README.md | 72 ++++--- package.json | 3 +- src/cli/agentRunner.ts | 17 ++ src/cli/replCommands.ts | 7 +- src/cli/tui/App.tsx | 87 ++++++++- src/cli/tui/components/Footer.tsx | 10 +- src/cli/tui/components/ModelDialog.tsx | 16 +- src/cli/tui/components/PromptInput.tsx | 129 +++++++++---- src/cli/tui/components/WelcomeBanner.tsx | 92 +++++---- src/cli/tui/slashCommands.ts | 11 +- src/cli/tui/theme.ts | 66 ++++--- src/config/index.ts | 17 +- src/config/localConfig.ts | 53 +++++- src/config/updateCheck.ts | 175 ++++++++++++++++++ src/policy/PolicyEngine.ts | 16 +- src/protocol/risk.ts | 6 +- src/providers/anthropic/AnthropicProvider.ts | 4 +- src/providers/errors.ts | 16 ++ src/providers/index.ts | 2 +- .../openai/OpenAiCompatibleProvider.ts | 4 +- src/runtime/RuntimeFacade.ts | 8 + tests/api-key.test.ts | 64 ++++++- tests/local-config-write.test.ts | 55 ++++++ tests/policy.test.ts | 22 +++ tests/slash-commands.test.ts | 38 ++++ tests/theme.test.ts | 39 ++++ tests/tui-app.test.tsx | 47 +++++ tests/update-check.test.ts | 146 +++++++++++++++ 30 files changed, 1088 insertions(+), 158 deletions(-) create mode 100644 src/config/updateCheck.ts create mode 100644 tests/local-config-write.test.ts create mode 100644 tests/slash-commands.test.ts create mode 100644 tests/theme.test.ts create mode 100644 tests/update-check.test.ts diff --git a/.env.example b/.env.example index 822cb13..8ce2a80 100644 --- a/.env.example +++ b/.env.example @@ -43,6 +43,11 @@ ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Disable the network fetch entirely (use only the bundled snapshot): # PARALLAX_DISABLE_MODELS_FETCH=1 +# --- Updates --- +# On startup Parallax checks npm for a newer version and shows the upgrade +# command (it never installs anything itself). Disable the check: +# PARALLAX_NO_UPDATE_CHECK=1 + # --- Interface --- # On a TTY, `parallax` opens the interactive TUI. Force the plain line-based # renderer instead (e.g. for logging): diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 38b2f03..b832426 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -158,17 +158,20 @@ jobs: - name: Publish to npm with provenance if: ${{ steps.release.outputs.needs_publish == 'true' }} - env: - PACKAGE_VERSION: ${{ steps.release.outputs.package_version }} run: | set -euo pipefail - if [[ "${PACKAGE_VERSION}" == *-* ]]; then - npm_tag=next - else - npm_tag=latest - fi - npm publish --provenance --tag "${npm_tag}" --access public + # Pre-1.0 policy: the newest build IS the release, so publish it under + # `latest` even when it is a prerelease (0.1.0-beta.N). This is what makes + # a plain `npm install --global @singularitycolabs/parallax` fetch the + # newest version — the default install resolves the `latest` dist-tag. + # + # We deliberately set a single tag here: trusted publishing (OIDC) + # authorizes only `npm publish`, not a follow-up `npm dist-tag add`, so we + # can't also move `next` in the same run. That's fine pre-1.0 — the app's + # update notice points at the plain (latest) install command. When a + # stable 1.0.0 line begins, reintroduce a `next` channel for prereleases. + npm publish --provenance --access public --tag latest - name: Create GitHub Release env: diff --git a/README.md b/README.md index b220082..4ce920e 100644 --- a/README.md +++ b/README.md @@ -21,25 +21,29 @@ proposes actions; deterministic code validates, authorizes, and executes them. ## Install -Install the beta CLI globally: +Install the CLI globally: ```bash -npm install --global @singularitycolabs/parallax@next +npm install --global @singularitycolabs/parallax parallax --help ``` Or run it without a global installation: ```bash -npx --yes @singularitycolabs/parallax@next --help +npx --yes @singularitycolabs/parallax --help ``` Install the SDK in a Node.js project: ```bash -npm install @singularitycolabs/parallax@next +npm install @singularitycolabs/parallax ``` +Parallax checks npm on startup and prints an upgrade line when a newer version +is out (re-run the install command above to update; disable the check with +`PARALLAX_NO_UPDATE_CHECK=1`). + ## Uninstall Parallax keeps its state in `~/.parallax` (sessions database). The CLI can clean @@ -141,16 +145,36 @@ the history carries over to the new model: > /models list models for the current provider (with price/context) > /provider openai switch provider (uses its default model) > /model anthropic/claude-sonnet-4-6 switch provider + model in one step -> /model gpt-4o switch model on the current provider -> /mode plan switch permission mode (or Shift+Tab to cycle) +> /model open the interactive model picker +> /tools list the available agent tools +> /theme light switch the color theme (toggles with no arg) +> /mode plan set permission mode (or /plan, /workspace, /read-only, /bypass) > /sessions list persisted sessions > /help show all commands ``` -Keys: **Shift+Tab** cycles the permission mode (`workspace → plan → read-only`), -**Esc**/**Ctrl-C** cancels the in-flight turn (or quits when idle), **↑/↓** walk -input history, **Tab** completes a slash command. At an approval prompt, choose -**Yes**, **Yes and don't ask again** (remembers the tool for the session), or **No**. +The chosen provider/model (and theme) are remembered in +`~/.parallax/parallax.json`, and an API key entered in the `/model` picker is +saved to `~/.parallax/credentials.json` (mode 0600) by default — so the next +launch opens ready, with no reconfiguration. Environment variables still take +precedence over the saved values. + +Keys: **Shift+Tab** cycles the permission mode +(`workspace → plan → read-only → bypass`), **Esc**/**Ctrl-C** cancels the +in-flight turn (or quits when idle), **↑/↓** move through the slash-command menu +(or walk input history when it's closed), **Enter/Tab** apply the highlighted +command. At an approval prompt, choose **Yes**, **Yes and don't ask again** +(remembers the tool for the session), or **No**. + +Permission modes (deterministic `ALLOW / ASK / DENY`): + +- **workspace** (default) — reads are allowed; writes/shell/network **ask** first. +- **plan** — research & propose: reads allowed, side effects blocked, until you + approve a plan via the `present_plan` gate (which flips you to workspace). +- **read-only** — reads only; every side effect blocked. +- **bypass** — auto-approve **everything** with no prompts. The one guardrail + that still holds: a path escaping the workspace root is always denied. The + footer turns red so this state is obvious — use it deliberately. Resume a past session straight into the UI, transcript and all: @@ -171,16 +195,17 @@ cp .env.example .env # then fill in your key Config resolves as `CLI flag > env > parallax.json > built-in default`: -| Variable | Purpose | Default | -| ----------------------------------------- | --------------------------------------- | ----------------------------- | -| `PARALLAX_PROVIDER` (or `-p`) | provider id (see table above) | `fake` | -| `_API_KEY` / `PARALLAX_API_KEY` | API key for the provider | — | -| `TAVILY_API_KEY` | API key for the `web_search` tool | — | -| `PARALLAX_MODEL` (or `-m`) | model id | provider's default | -| `PARALLAX_API_BASE_URL` | override the OpenAI-compatible endpoint | provider's default | -| `PARALLAX_MODELS_URL` | models.dev catalog endpoint | `https://models.dev/api.json` | -| `PARALLAX_DISABLE_MODELS_FETCH` | use only the bundled catalog snapshot | (fetch enabled) | -| `PARALLAX_NO_TUI` | force the plain renderer on a TTY | (TUI on a TTY) | +| Variable | Purpose | Default | +| ----------------------------------------- | ----------------------------------------- | ----------------------------- | +| `PARALLAX_PROVIDER` (or `-p`) | provider id (see table above) | `fake` | +| `_API_KEY` / `PARALLAX_API_KEY` | API key for the provider | — | +| `TAVILY_API_KEY` | API key for the `web_search` tool | — | +| `PARALLAX_MODEL` (or `-m`) | model id | provider's default | +| `PARALLAX_API_BASE_URL` | override the OpenAI-compatible endpoint | provider's default | +| `PARALLAX_MODELS_URL` | models.dev catalog endpoint | `https://models.dev/api.json` | +| `PARALLAX_DISABLE_MODELS_FETCH` | use only the bundled catalog snapshot | (fetch enabled) | +| `PARALLAX_NO_UPDATE_CHECK` | skip the startup "update available" check | (check enabled) | +| `PARALLAX_NO_TUI` | force the plain renderer on a TTY | (TUI on a TTY) | ### Model catalog & custom providers (OpenCode-style) @@ -243,9 +268,10 @@ approval → execute → persist → model`. - Web tools: `web_search` (via Tavily) and `web_fetch` (URL → readable text), classified as `network` risk with SSRF guards (localhost / private / link-local and cloud-metadata targets are refused, redirects re-validated). -- Deterministic `ALLOW / ASK / DENY` policy with `read-only`, `workspace`, and - `plan` modes; approvals support "allow once" and "allow always" (remembered - per session). +- Deterministic `ALLOW / ASK / DENY` policy with `read-only`, `workspace`, + `plan`, and `bypass` modes; approvals support "allow once" and "allow always" + (remembered per session). `bypass` auto-approves everything but still denies + any path outside the workspace root. - SQLite session persistence + resume (interactive or `--print`). - A **Claude Code-like terminal UI** (React + Ink): streaming transcript, tool blocks with live output + diffs, an interactive approval menu, a bordered diff --git a/package.json b/package.json index c7ebfd8..26f77e2 100644 --- a/package.json +++ b/package.json @@ -56,8 +56,7 @@ }, "publishConfig": { "access": "public", - "registry": "https://registry.npmjs.org/", - "tag": "next" + "registry": "https://registry.npmjs.org/" }, "dependencies": { "commander": "^12.1.0", diff --git a/src/cli/agentRunner.ts b/src/cli/agentRunner.ts index 3f82499..a47e35c 100644 --- a/src/cli/agentRunner.ts +++ b/src/cli/agentRunner.ts @@ -10,13 +10,17 @@ import { } from '../app/index.ts'; import { loadConfig, + loadLocalConfig, databasePath, effectiveModel, getProvider, refreshCatalog, + refreshUpdateInfo, + upgradeCommand, type Config, } from '../config/index.ts'; import type { ApprovalDecision, PermissionMode } from '../protocol/index.ts'; +import type { ThemeName } from './tui/theme.ts'; import { CliRenderer } from './renderer.ts'; import { parseCommand, @@ -47,6 +51,11 @@ function buildConfig(options: AgentCliOptions): Config { return loadConfig(overrides); } +/** The persisted TUI theme from `parallax.json`, or `dark` when unset/invalid. */ +function resolvedThemeName(): ThemeName { + return loadLocalConfig().theme === 'light' ? 'light' : 'dark'; +} + function makeApprovalHandler( yes: boolean, rl: Interface | undefined, @@ -208,6 +217,7 @@ export async function chatLoop(options: AgentCliOptions): Promise { model: desiredModel, mode, cwd: options.cwd, + themeName: resolvedThemeName(), needsSetup, }); return; @@ -226,6 +236,12 @@ export async function chatLoop(options: AgentCliOptions): Promise { // offline run keeps the bundled snapshot. void refreshCatalog(); + // Best-effort update check (headless): print one line if a newer version is out. + void refreshUpdateInfo().then((u) => { + if (u) + process.stderr.write(`\nUpdate available ${u.current} → ${u.latest}: ${upgradeCommand(u)}\n`); + }); + let activeTurn: string | undefined; const unsubscribe = wire(agent, renderer, makeApprovalHandler(options.yes, rl), (t) => { activeTurn = t; @@ -315,6 +331,7 @@ export async function resumeChat( model: match.model, mode: match.permissionMode, cwd: match.cwd, + themeName: resolvedThemeName(), seedEvents, }); return true; diff --git a/src/cli/replCommands.ts b/src/cli/replCommands.ts index 39f426f..e25db62 100644 --- a/src/cli/replCommands.ts +++ b/src/cli/replCommands.ts @@ -120,12 +120,17 @@ export function formatModels(providerId: string, currentModel?: string): string export function formatHelp(): string { return [ 'commands:', - ' /model switch model (e.g. /model claude-sonnet-4-6)', + ' /model [id] switch model, or open the picker (e.g. /model claude-sonnet-4-6)', ' /model / switch provider + model (e.g. /model openai/gpt-4o)', ' /provider switch provider, using its default model', ' /models [provider] list models for the current (or named) provider', ' /providers list providers and key status', + ' /tools list the available agent tools', + ' /theme [dark|light] switch the color theme (toggles if no arg)', + ' /mode set permission mode (workspace|plan|read-only|bypass)', + ' /workspace /plan /read-only /bypass shortcuts for each permission mode', ' /help show this help', + ' /exit | /quit leave Parallax', ' exit | quit leave the REPL', ].join('\n'); } diff --git a/src/cli/tui/App.tsx b/src/cli/tui/App.tsx index 676a798..47b40d8 100644 --- a/src/cli/tui/App.tsx +++ b/src/cli/tui/App.tsx @@ -5,10 +5,15 @@ import { applyModelSelection, MissingApiKeyError, type Agent } from '../../app/i import { getProvider, listProviders, + readUpdateCache, + refreshUpdateInfo, resolveApiKey, saveCredential, + saveLocalConfig, + upgradeCommand, type Config, type ProviderInfo, + type UpdateInfo, } from '../../config/index.ts'; import { VERSION } from '../../version.ts'; import { @@ -27,7 +32,10 @@ import { WelcomeBanner, AnimatedWelcome } from './components/WelcomeBanner.tsx'; import { ModelDialog, type ModelSelection } from './components/ModelDialog.tsx'; /** Permission-mode cycle order for Shift+Tab (Claude Code style). */ -const MODE_CYCLE: PermissionMode[] = ['workspace', 'plan', 'read-only']; +const MODE_CYCLE: PermissionMode[] = ['workspace', 'plan', 'read-only', 'bypass']; + +/** The permission modes settable by name (the `/workspace`, `/bypass`, … shortcuts). */ +const MODE_NAMES: readonly PermissionMode[] = ['workspace', 'plan', 'read-only', 'bypass']; export interface AppProps { agent: Agent; @@ -64,7 +72,8 @@ export interface AppProps { export function App(props: AppProps): React.ReactElement { const { agent, sessionId } = props; const { exit } = useApp(); - const theme = getTheme(props.themeName); + const [themeName, setThemeName] = useState(props.themeName ?? 'dark'); + const theme = getTheme(themeName); const state = useRuntimeEvents(agent, props.seedEvents); const [provider, setProvider] = useState(props.initialProvider); @@ -88,6 +97,21 @@ export function App(props: AppProps): React.ReactElement { const [dialogProviders, setDialogProviders] = useState([]); const [dialogInitialProvider, setDialogInitialProvider] = useState(undefined); const [sessionKeys, setSessionKeys] = useState>({}); + // "Update available" banner data: read the local cache immediately, then do a + // best-effort network refresh. Both are non-blocking and never throw. + const [update, setUpdate] = useState(undefined); + useEffect(() => { + let live = true; + void readUpdateCache().then((u) => { + if (live && u) setUpdate(u); + }); + void refreshUpdateInfo().then((u) => { + if (live && u) setUpdate(u); + }); + return () => { + live = false; + }; + }, []); /** True when a provider already has a usable key (env, on-disk, or session). */ const hasKey = useCallback( @@ -117,6 +141,17 @@ export function App(props: AppProps): React.ReactElement { setSystemLines((prev) => [...prev.slice(-40), ...text.split('\n')]); }, []); + /** Set the permission mode for subsequent turns (used by /mode, the mode + * shortcuts, and Shift+Tab). Updates the local indicator and the session. */ + const applyMode = useCallback( + async (next: PermissionMode) => { + setMode(next); + await agent.facade.setPermissionMode(sessionId, next); + pushSystem(`permission mode → ${next}`); + }, + [agent, pushSystem, sessionId], + ); + const resolveApproval = useCallback( (id: string, decision: ApprovalDecision) => { agent.facade.resolveApproval(id, decision); @@ -157,6 +192,8 @@ export function App(props: AppProps): React.ReactElement { setProvider(applied.provider); setModel(applied.model); setNeedsSetup(false); + // Remember the choice so the next launch opens on it (env still wins). + saveLocalConfig({ provider: applied.provider, model: applied.model }); pushSystem(`switched → ${applied.provider}:${applied.model}`); } catch (err) { if (err instanceof MissingApiKeyError) { @@ -222,13 +259,39 @@ export function App(props: AppProps): React.ReactElement { setSystemLines([]); return; } + if (command.name === 'exit' || command.name === 'quit') { + exit(); + return; + } + // Permission-mode shortcuts: `/workspace`, `/plan`, `/read-only`, `/bypass`. + if ((MODE_NAMES as readonly string[]).includes(command.name)) { + await applyMode(command.name as PermissionMode); + return; + } if (command.name === 'mode') { const arg = line.split(/\s+/)[1] as PermissionMode | undefined; - const next = arg && MODE_CYCLE.includes(arg) ? arg : undefined; - if (!next) return pushSystem('usage: /mode workspace|plan|read-only'); - await agent.facade.setPermissionMode(sessionId, next); - setMode(next); - pushSystem(`permission mode → ${next}`); + const next = arg && MODE_NAMES.includes(arg) ? arg : undefined; + if (!next) return pushSystem('usage: /mode workspace|plan|read-only|bypass'); + await applyMode(next); + return; + } + if (command.name === 'theme') { + const arg = line.split(/\s+/)[1]; + const next: ThemeName = + arg === 'dark' || arg === 'light' ? arg : themeName === 'dark' ? 'light' : 'dark'; + setThemeName(next); + saveLocalConfig({ theme: next }); + pushSystem(`theme → ${next}`); + return; + } + if (command.name === 'tools') { + const tools = agent.facade.listTools(); + pushSystem( + [ + 'available tools:', + ...tools.map((t) => ` ${t.name.padEnd(16)} ${t.description}`), + ].join('\n'), + ); return; } if (command.name === 'sessions') { @@ -270,7 +333,7 @@ export function App(props: AppProps): React.ReactElement { return; } }, - [agent, model, openDialog, provider, pushSystem, sessionId, submitTurn, switchTo], + [agent, applyMode, model, openDialog, provider, pushSystem, submitTurn, switchTo, themeName], ); const submit = useCallback( @@ -342,6 +405,13 @@ export function App(props: AppProps): React.ReactElement { // The launch splash. While the intro animates it lives in the dynamic frame // (so the ✻ mark can pulse); once frozen it becomes the timeline's static // header, printed once at the top and scrolling up as the conversation grows. + const updateProps = + update && update.latest !== update.current + ? { + updateNotice: `update available ${update.current} → ${update.latest}`, + upgradeCmd: upgradeCommand(update), + } + : {}; const banner = ( ); diff --git a/src/cli/tui/components/Footer.tsx b/src/cli/tui/components/Footer.tsx index 458399a..2302217 100644 --- a/src/cli/tui/components/Footer.tsx +++ b/src/cli/tui/components/Footer.tsx @@ -7,9 +7,15 @@ import { glyphs, type Theme } from '../theme.ts'; function modeColor(mode: string, theme: Theme): string { if (mode === 'read-only') return theme.subtle; if (mode === 'plan') return theme.permission; + if (mode === 'bypass') return theme.accent; // red — auto-approves everything return theme.warning; // workspace: side effects possible } +/** The mode label shown in the footer; bypass is made loud. */ +function modeLabel(mode: string): string { + return mode === 'bypass' ? 'bypass · no prompts' : mode; +} + /** * The status footer beneath the prompt: provider:model, permission mode, a * running-cost hint, and the key hints. Mirrors Claude Code's @@ -49,7 +55,9 @@ export function Footer({ )} · - {mode} + + {modeLabel(mode)} + {tokens > 0 && · {tokens} tok} diff --git a/src/cli/tui/components/ModelDialog.tsx b/src/cli/tui/components/ModelDialog.tsx index aba1177..c53df86 100644 --- a/src/cli/tui/components/ModelDialog.tsx +++ b/src/cli/tui/components/ModelDialog.tsx @@ -97,7 +97,9 @@ export function ModelDialog({ const [selected, setSelected] = useState(0); const [providerId, setProviderId] = useState(preset?.id ?? ''); const [keyText, setKeyText] = useState(''); - const [remember, setRemember] = useState(false); + // Default ON: a key entered here is saved to the 0600 credentials store so the + // next launch reuses it (toggle off with Tab to keep it for this run only). + const [remember, setRemember] = useState(true); const [hint, setHint] = useState(''); // The model chosen while we detour through the key step (its default when we // jumped straight to key entry for a preset provider). @@ -313,9 +315,9 @@ function ProviderList({ const statusColor = !p.supported ? theme.subtle : keyed ? theme.success : theme.warning; return ( - {active ? '❯ ' : ' '} + {active ? '❯ ' : ' '} {statusGlyph} - + {p.label} @@ -361,8 +363,8 @@ function ModelList({ if (isCustom) { return ( - {active ? '❯ ' : ' '} - + {active ? '❯ ' : ' '} + Use “{customModel}” (custom id) @@ -372,8 +374,8 @@ function ModelList({ const meta = formatModelMeta(modelInfo?.[row]); return ( - {active ? '❯ ' : ' '} - + {active ? '❯ ' : ' '} + {row} {meta !== '' && · {meta}} diff --git a/src/cli/tui/components/PromptInput.tsx b/src/cli/tui/components/PromptInput.tsx index ee8255e..0c66a3d 100644 --- a/src/cli/tui/components/PromptInput.tsx +++ b/src/cli/tui/components/PromptInput.tsx @@ -1,18 +1,24 @@ import React, { useState } from 'react'; import { Box, Text, useInput } from 'ink'; import { glyphs, type Theme } from '../theme.ts'; -import { completionsFor } from '../slashCommands.ts'; +import { completionsFor, type SlashCommand } from '../slashCommands.ts'; /** * The bordered prompt input, styled after Claude Code's PromptInput: a round * border in the accent color, a caret, a placeholder when empty, in-session * history (↑/↓), and a slash-command autocomplete menu that appears while typing - * a `/command`. Tab/Enter on a sole completion fills it in. + * a `/command`. * - * Built on Ink's `useInput` rather than a text-input dependency so we fully own - * the slash-completion + history behavior. Disabled (dimmed) while a turn is in - * flight or an approval is pending — those own the keyboard. + * While the completion menu is open, ↑/↓ move the highlighted command (wrapping), + * **Enter** runs the highlighted command, and **Tab** completes its name (adding + * a space so an argument can follow). When the menu is closed, ↑/↓ recall input + * history. Built on Ink's `useInput` so we fully own this behavior; disabled + * (dimmed) while a turn is in flight or an approval is pending. */ + +/** Rows shown in the completion menu at once (windowed around the selection). */ +const MENU_VISIBLE = 8; + export function PromptInput({ theme, disabled, @@ -27,26 +33,57 @@ export function PromptInput({ const [value, setValue] = useState(''); const [history, setHistory] = useState([]); const [histIdx, setHistIdx] = useState(undefined); + // Highlighted row in the slash-command menu (only meaningful while it's open). + const [selected, setSelected] = useState(0); const completions = completionsFor(value); + const menuOpen = completions.length > 0; + + /** Edit the input text and reset the menu highlight to the top. */ + const edit = (next: string): void => { + setValue(next); + setSelected(0); + }; + + const submitLine = (line: string): void => { + const trimmed = line.trim(); + if (trimmed === '') return; + setHistory((h) => [...h, trimmed]); + setHistIdx(undefined); + setValue(''); + setSelected(0); + onSubmit(trimmed); + }; useInput( (input, key) => { if (disabled) return; - if (key.return) { - // Tab-like completion: a single slash match becomes the value first. - const line = value.trim(); - if (line === '') return; - setHistory((h) => [...h, line]); - setHistIdx(undefined); - setValue(''); - onSubmit(line); + // --- Completion menu is open: ↑/↓ select, Enter runs, Tab completes. --- + if (menuOpen && (key.upArrow || key.downArrow || key.return || key.tab)) { + const count = completions.length; + if (key.upArrow) { + setSelected((i) => (i - 1 + count) % count); + return; + } + if (key.downArrow) { + setSelected((i) => (i + 1) % count); + return; + } + const chosen = completions[Math.min(selected, count - 1)] ?? completions[0]!; + if (key.return) { + // Run the highlighted command as-is; the handler decides what a bare + // command means (e.g. `/model` opens the picker). + submitLine(`/${chosen.name}`); + return; + } + // Tab: complete the name and add a space so an argument can be typed. + edit(`/${chosen.name} `); return; } - if (key.tab && completions.length > 0) { - setValue(`/${completions[0]!.name} `); + if (key.return) { + submitLine(value); return; } @@ -54,7 +91,7 @@ export function PromptInput({ if (history.length === 0) return; const next = histIdx === undefined ? history.length - 1 : Math.max(0, histIdx - 1); setHistIdx(next); - setValue(history[next] ?? ''); + edit(history[next] ?? ''); return; } if (key.downArrow) { @@ -62,22 +99,22 @@ export function PromptInput({ const next = histIdx + 1; if (next >= history.length) { setHistIdx(undefined); - setValue(''); + edit(''); } else { setHistIdx(next); - setValue(history[next] ?? ''); + edit(history[next] ?? ''); } return; } if (key.backspace || key.delete) { - setValue((v) => v.slice(0, -1)); + edit(value.slice(0, -1)); return; } // Ignore other control keys (ctrl/meta chords handled at the App level). - if (key.ctrl || key.meta || key.escape) return; - if (input) setValue((v) => v + input); + if (key.ctrl || key.meta || key.escape || key.tab) return; + if (input) edit(value + input); }, { isActive: !disabled }, ); @@ -95,16 +132,46 @@ export function PromptInput({ )} - {completions.length > 0 && ( - - {completions.slice(0, 6).map((c, i) => ( - - /{c.name} - {c.arg !== undefined && {c.arg}} - — {c.summary} - - ))} - + {menuOpen && } + + ); +} + +/** The slash-command autocomplete list, windowed so the selection stays visible. */ +function CompletionMenu({ + theme, + rows, + selected, +}: { + theme: Theme; + rows: SlashCommand[]; + selected: number; +}): React.ReactElement { + const sel = Math.min(selected, rows.length - 1); + const start = + rows.length <= MENU_VISIBLE + ? 0 + : Math.min(Math.max(0, sel - Math.floor(MENU_VISIBLE / 2)), rows.length - MENU_VISIBLE); + const slice = rows.slice(start, start + MENU_VISIBLE); + return ( + + {slice.map((c, i) => { + const active = start + i === sel; + return ( + + {active ? '❯ ' : ' '} + + /{c.name} + + {c.arg !== undefined && {c.arg}} + — {c.summary} + + ); + })} + {rows.length > slice.length && ( + + {' '}… {rows.length - slice.length} more + )} ); diff --git a/src/cli/tui/components/WelcomeBanner.tsx b/src/cli/tui/components/WelcomeBanner.tsx index 1239fe6..7e18e5a 100644 --- a/src/cli/tui/components/WelcomeBanner.tsx +++ b/src/cli/tui/components/WelcomeBanner.tsx @@ -30,6 +30,7 @@ const WORDMARK: readonly string[] = [ function modeColor(mode: string, theme: Theme): string { if (mode === 'read-only') return theme.subtle; if (mode === 'plan') return theme.permission; + if (mode === 'bypass') return theme.accent; // red — auto-approves everything return theme.warning; // workspace: side effects possible } @@ -44,6 +45,10 @@ export interface WelcomeBannerProps { markColor?: string; /** No usable model configured yet — show a call to action instead of provider:model. */ needsSetup?: boolean; + /** One-line "update available …" notice, shown when a newer version exists. */ + updateNotice?: string; + /** The reinstall command to run for that update. */ + upgradeCmd?: string; } export function WelcomeBanner({ @@ -55,6 +60,8 @@ export function WelcomeBanner({ cwd, markColor, needsSetup, + updateNotice, + upgradeCmd, }: WelcomeBannerProps): React.ReactElement { return ( @@ -66,42 +73,65 @@ export function WelcomeBanner({ ))} - - {glyphs.star} - - Welcome to Parallax - - · v{version} - - - - {' '} - {needsSetup ? ( - - {provider === 'fake' ? 'no model configured' : `${provider} (needs key)`} · type /model - to set one up + + + {glyphs.star} + + Welcome to Parallax - ) : ( - <> - - {provider}:{model} + · v{version} + + + + {' '}a secure, extensible coding agent + + + + {' '} + {needsSetup ? ( + + {provider === 'fake' ? 'no model configured' : `${provider} (needs key)`} · type + /model to set one up - · - {mode} - - )} - + ) : ( + <> + + {provider}:{model} + + · + {mode} + + )} + - - - {' '} - {cwd} - - + + + {' '} + {cwd} + + - - {' '}/help for help · shift+tab to switch mode + + {' /help'} + for commands · + shift+tab + to switch mode + + + {updateNotice !== undefined && ( + + {glyphs.star} + {updateNotice} + {upgradeCmd !== undefined && · {upgradeCmd}} + + )} ); } diff --git a/src/cli/tui/slashCommands.ts b/src/cli/tui/slashCommands.ts index af2014b..7767a60 100644 --- a/src/cli/tui/slashCommands.ts +++ b/src/cli/tui/slashCommands.ts @@ -20,12 +20,19 @@ export const SLASH_COMMANDS: SlashCommand[] = [ { name: 'models', summary: 'List models for a provider', arg: '[provider]' }, { name: 'provider', summary: 'Switch provider (uses its default model)', arg: 'id' }, { name: 'providers', summary: 'List providers and key status' }, - { name: 'mode', summary: 'Set permission mode', arg: 'workspace|plan|read-only' }, + { name: 'tools', summary: 'List the available agent tools' }, + { name: 'theme', summary: 'Switch color theme', arg: '[dark|light]' }, + { name: 'mode', summary: 'Set permission mode', arg: 'workspace|plan|read-only|bypass' }, + { name: 'workspace', summary: 'Permission mode: ask before side effects' }, + { name: 'plan', summary: 'Permission mode: research & propose (read-only)' }, + { name: 'read-only', summary: 'Permission mode: reads only, block side effects' }, + { name: 'bypass', summary: 'Permission mode: auto-approve everything (careful)' }, { name: 'sessions', summary: 'List persisted sessions' }, { name: 'resume', summary: 'Resume a session', arg: '[id]' }, { name: 'clear', summary: 'Clear the on-screen transcript' }, { name: 'init', summary: 'Summarize the project into a note' }, - { name: 'help', summary: 'Show commands and shortcuts' }, + { name: 'exit', summary: 'Quit Parallax' }, + { name: 'quit', summary: 'Quit Parallax' }, ]; /** De-duplicated command list (the array above is authored for menu ordering). */ diff --git a/src/cli/tui/theme.ts b/src/cli/tui/theme.ts index 3048370..a549558 100644 --- a/src/cli/tui/theme.ts +++ b/src/cli/tui/theme.ts @@ -1,20 +1,24 @@ /** - * TUI color palette, ported from the Claude Code snapshot's theme - * (`claude-code/src/utils/theme.ts`) so Parallax's terminal UI shares its visual - * language. Values are truecolor `rgb(...)` strings that Ink passes through to - * the terminal; on terminals without truecolor Ink degrades gracefully. + * TUI color palette. Parallax's identity is a **red** accent (brand marks, + * borders, bullets, prompt), **purple** for the selected/highlighted row in + * menus, and **blue** for links, the permission/approval color, and the mode + * indicator. Primary body text stays high-contrast (near-white on dark, + * near-black on light) for readability — only secondary text is tinted. * - * These are the semantic roles the components reference — not every Claude Code - * key, just the ones Parallax renders. + * Values are truecolor `rgb(...)` strings that Ink passes through to the + * terminal; on terminals without truecolor Ink degrades gracefully. These are + * the semantic roles the components reference. */ export interface Theme { - /** Brand accent (assistant bullet, prompt border). Claude orange. */ + /** Brand accent (wordmark, prompt border, bullets). Red. */ accent: string; - /** Lighter accent for secondary emphasis. */ + /** Lighter accent for secondary emphasis / intro pulse. */ accentDim: string; - /** Permission/approval + suggestions. Medium blue. */ + /** Highlighted/selected row in menus & completions. Purple. */ + selection: string; + /** Permission/approval, links, and the mode indicator. Blue. */ permission: string; - /** Primary body text. */ + /** Primary body text (high contrast). */ text: string; /** De-emphasized text (metadata, hints, tool output). */ subtle: string; @@ -26,32 +30,34 @@ export interface Theme { diffRemoved: string; } -/** Dark theme (default) — matches Claude Code's dark palette. */ +/** Dark theme (default) — red accent, purple selection, blue links. */ export const darkTheme: Theme = { - accent: 'rgb(215,119,87)', // Claude orange - accentDim: 'rgb(245,149,117)', - permission: 'rgb(120,138,255)', // medium blue, slightly brightened for dark bg - text: 'rgb(230,230,230)', - subtle: 'rgb(140,140,140)', - success: 'rgb(65,160,85)', - error: 'rgb(220,90,110)', - warning: 'rgb(220,170,60)', + accent: 'rgb(235,75,75)', // brand red + accentDim: 'rgb(250,130,130)', + selection: 'rgb(180,140,255)', // purple — selected row + permission: 'rgb(95,155,255)', // blue — approvals, links, mode + text: 'rgb(232,232,232)', + subtle: 'rgb(140,150,170)', // blue-tinted gray for secondary text + success: 'rgb(70,180,110)', + error: 'rgb(255,105,125)', // pink-red, distinct from the accent red + warning: 'rgb(225,175,70)', diffAdded: 'rgb(80,180,110)', - diffRemoved: 'rgb(220,90,110)', + diffRemoved: 'rgb(255,105,125)', }; -/** Light theme — the Claude Code light palette. */ +/** Light theme — deeper red/purple/blue for contrast on a light background. */ export const lightTheme: Theme = { - accent: 'rgb(215,119,87)', - accentDim: 'rgb(180,90,60)', - permission: 'rgb(87,105,247)', - text: 'rgb(30,30,30)', - subtle: 'rgb(110,110,110)', - success: 'rgb(44,122,57)', - error: 'rgb(171,43,63)', + accent: 'rgb(200,40,40)', // brand red + accentDim: 'rgb(170,55,55)', + selection: 'rgb(120,70,200)', // purple — selected row + permission: 'rgb(40,90,210)', // blue — approvals, links, mode + text: 'rgb(28,28,28)', + subtle: 'rgb(95,105,120)', + success: 'rgb(38,120,60)', + error: 'rgb(190,40,70)', warning: 'rgb(150,110,20)', - diffAdded: 'rgb(44,122,57)', - diffRemoved: 'rgb(171,43,63)', + diffAdded: 'rgb(38,120,60)', + diffRemoved: 'rgb(190,40,70)', }; export type ThemeName = 'dark' | 'light'; diff --git a/src/config/index.ts b/src/config/index.ts index 6cd9a33..97ccc14 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -36,7 +36,14 @@ export { resetCatalog, localDefaults, } from './catalog.ts'; -export { loadLocalConfig, localConfigSchema, type LocalConfig } from './localConfig.ts'; +export { + loadLocalConfig, + saveLocalConfig, + userConfigPath, + localConfigSchema, + type LocalConfig, + type PersistablePrefs, +} from './localConfig.ts'; export { refreshFromNetwork, parseModelsDev, @@ -45,3 +52,11 @@ export { fetchDisabled, type ModelsDevCatalog, } from './modelsDev.ts'; +export { + refreshUpdateInfo, + readUpdateCache, + isNewer, + upgradeCommand, + updateCheckDisabled, + type UpdateInfo, +} from './updateCheck.ts'; diff --git a/src/config/localConfig.ts b/src/config/localConfig.ts index f70eff9..f00cc20 100644 --- a/src/config/localConfig.ts +++ b/src/config/localConfig.ts @@ -1,7 +1,8 @@ -import { readFileSync } from 'node:fs'; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; import { z } from 'zod'; import { childLogger } from '../observability/index.ts'; -import { localConfigPaths } from './paths.ts'; +import { configHome, localConfigPaths } from './paths.ts'; /** * User/project config file (`parallax.json`), opencode-style. This is the layer @@ -103,3 +104,51 @@ export function loadLocalConfig(): LocalConfig { } return merged; } + +/** The user-scoped `parallax.json` (`~/.parallax/parallax.json`), which persists + * across projects — where saved defaults live (a project file still overrides). */ +export function userConfigPath(): string { + return `${configHome()}/parallax.json`; +} + +/** The subset of settings the app persists automatically (provider/model/theme). */ +export type PersistablePrefs = Pick; + +/** + * Persist chosen defaults to the **user** `parallax.json`, so the next launch + * opens on the same provider/model/theme without reconfiguration (blueprint + * §28.3 — this is the write side of `localDefaults`). Reads the existing file + * raw and shallow-merges the patch, so unrelated keys (e.g. custom `providers`) + * and hand-written comments-as-values are preserved. Written atomically + * (temp+rename) with mode `0644` — this holds no secrets (API keys live in the + * separate 0600 `credentials.json`). Best-effort: a failure is logged and + * swallowed, exactly like the credentials store, so a read-only home can't brick + * a switch. + */ +export function saveLocalConfig(patch: PersistablePrefs): void { + const path = userConfigPath(); + + // Start from whatever is already there (raw, to keep unknown keys), tolerating + // a missing or malformed file — we overwrite only the keys in `patch`. + let current: Record = {}; + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf8')); + if (parsed && typeof parsed === 'object') current = parsed as Record; + } catch { + /* missing or invalid — start fresh */ + } + + const next = { ...current }; + if (patch.provider !== undefined) next.provider = patch.provider; + if (patch.model !== undefined) next.model = patch.model; + if (patch.theme !== undefined) next.theme = patch.theme; + + try { + mkdirSync(dirname(path), { recursive: true }); + const tmp = `${path}.${process.pid}.tmp`; + writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o644 }); + renameSync(tmp, path); + } catch (err) { + log.warn({ err }, 'could not persist parallax.json'); + } +} diff --git a/src/config/updateCheck.ts b/src/config/updateCheck.ts new file mode 100644 index 0000000..8daa28f --- /dev/null +++ b/src/config/updateCheck.ts @@ -0,0 +1,175 @@ +import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { z } from 'zod'; +import { childLogger } from '../observability/index.ts'; +import { PACKAGE_NAME, VERSION } from '../version.ts'; +import { configHome } from './paths.ts'; + +/** + * Lightweight "update available" check (opt-in network, mirrors `modelsDev.ts`). + * On startup Parallax asks the npm registry for the package's `latest`/`next` + * dist-tags, compares them to the running `VERSION`, and caches the result to + * `~/.parallax/update.json` for a day. The UI reads the cache synchronously and, + * when a newer version exists, shows the exact reinstall command — Parallax + * never installs anything itself. + * + * Never blocks and never throws: offline, a slow registry, or a malformed + * response just leaves the cache untouched. Opt out entirely with + * `PARALLAX_NO_UPDATE_CHECK=1` (and it self-disables for `-dev`/`0.0.0` builds). + */ + +const log = childLogger({ mod: 'update-check' }); + +const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24h +const FETCH_TIMEOUT_MS = 3_000; + +/** What the UI needs: the running version, the newest available, and its channel. */ +export interface UpdateInfo { + current: string; + latest: string; + /** `latest` for a stable release, `next` for a prerelease-channel newest. */ + channel: 'latest' | 'next'; + checkedAt: number; +} + +const cacheSchema = z.object({ + current: z.string(), + latest: z.string(), + channel: z.enum(['latest', 'next']), + checkedAt: z.number(), +}); + +function cachePath(): string { + return process.env.PARALLAX_UPDATE_CACHE ?? join(configHome(), 'update.json'); +} + +export function updateCheckDisabled(): boolean { + if (process.env.PARALLAX_NO_UPDATE_CHECK === '1') return true; + // Dev/unreleased builds have nothing meaningful to compare against. + return VERSION === '0.0.0' || VERSION.includes('-dev.'); +} + +/** Split a semver-ish version into numeric release parts + a prerelease tail. */ +function parseVersion(v: string): { release: number[]; pre: string | undefined } { + const [core, ...preParts] = v.split('-'); + const release = (core ?? '').split('.').map((n) => Number(n) || 0); + return { release, pre: preParts.length > 0 ? preParts.join('-') : undefined }; +} + +/** Compare prerelease tails dot-by-dot (numeric-aware), SemVer §11 style. */ +function comparePre(a: string, b: string): number { + const as = a.split('.'); + const bs = b.split('.'); + for (let i = 0; i < Math.max(as.length, bs.length); i += 1) { + const x = as[i]; + const y = bs[i]; + if (x === undefined) return -1; + if (y === undefined) return 1; + const xn = Number(x); + const yn = Number(y); + const bothNum = !Number.isNaN(xn) && !Number.isNaN(yn); + if (bothNum) { + if (xn !== yn) return xn < yn ? -1 : 1; + } else if (x !== y) { + return x < y ? -1 : 1; + } + } + return 0; +} + +/** + * True if `candidate` is a newer version than `current` (SemVer precedence, + * incl. prerelease rules: `1.0.0-beta.2` > `1.0.0-beta.1`, and `1.0.0` > + * `1.0.0-beta.9`). Not-newer or unparseable → false, so a weird tag never + * nags the user. + */ +export function isNewer(candidate: string, current: string): boolean { + if (candidate === current) return false; + const a = parseVersion(candidate); + const b = parseVersion(current); + const len = Math.max(a.release.length, b.release.length); + for (let i = 0; i < len; i += 1) { + const x = a.release[i] ?? 0; + const y = b.release[i] ?? 0; + if (x !== y) return x > y; + } + // Same release numbers → a release outranks a prerelease; else compare tails. + if (a.pre === undefined && b.pre === undefined) return false; + if (a.pre === undefined) return true; // candidate is stable, current is pre + if (b.pre === undefined) return false; // candidate is pre, current is stable + return comparePre(a.pre, b.pre) > 0; +} + +/** Read the cached result if present and fresh (mtime within TTL). */ +export async function readUpdateCache(): Promise { + try { + const path = cachePath(); + const info = await stat(path); + if (Date.now() - info.mtimeMs > CACHE_TTL_MS) return undefined; + const parsed = cacheSchema.parse(JSON.parse(await readFile(path, 'utf8'))); + // Only surface if it still describes the running version (a fresh install + // would otherwise show a stale "newer" line from a previous version). + return parsed.current === VERSION ? parsed : undefined; + } catch { + return undefined; + } +} + +async function writeCache(info: UpdateInfo): Promise { + const path = cachePath(); + await mkdir(dirname(path), { recursive: true }); + const tmp = `${path}.${process.pid}.tmp`; + await writeFile(tmp, `${JSON.stringify(info)}\n`, 'utf8'); + await rename(tmp, path); +} + +const distTagsSchema = z.object({ latest: z.string().optional(), next: z.string().optional() }); + +function registryUrl(): string { + const base = process.env.PARALLAX_REGISTRY_URL ?? 'https://registry.npmjs.org'; + return `${base.replace(/\/$/, '')}/-/package/${PACKAGE_NAME}/dist-tags`; +} + +/** + * Refresh the update cache from the npm registry, returning the newer version + * (if any) so the caller can show it immediately on first run. Best-effort: + * returns `undefined` on opt-out, offline, timeout, or when already current. + */ +export async function refreshUpdateInfo(): Promise { + if (updateCheckDisabled()) return undefined; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const res = await fetch(registryUrl(), { + signal: controller.signal, + headers: { accept: 'application/json', 'user-agent': 'parallax' }, + }); + if (!res.ok) return undefined; + const tags = distTagsSchema.parse(await res.json()); + // Prefer a newer stable `latest`; fall back to the prerelease `next` channel + // when the running build is itself a prerelease (e.g. a `-beta` user). + const candidates: Array<{ v: string; channel: 'latest' | 'next' }> = []; + if (tags.latest) candidates.push({ v: tags.latest, channel: 'latest' }); + if (tags.next) candidates.push({ v: tags.next, channel: 'next' }); + let best: UpdateInfo | undefined; + for (const c of candidates) { + if (!isNewer(c.v, VERSION)) continue; + if (!best || isNewer(c.v, best.latest)) { + best = { current: VERSION, latest: c.v, channel: c.channel, checkedAt: Date.now() }; + } + } + if (best) await writeCache(best); + return best; + } catch (err) { + log.debug({ err }, 'update check failed (offline?) — ignoring'); + return undefined; + } finally { + clearTimeout(timer); + } +} + +/** The reinstall command to show the user for a given update. */ +export function upgradeCommand(info: UpdateInfo): string { + const suffix = info.channel === 'next' ? '@next' : ''; + return `npm install --global ${PACKAGE_NAME}${suffix}`; +} diff --git a/src/policy/PolicyEngine.ts b/src/policy/PolicyEngine.ts index 05b1543..2077f61 100644 --- a/src/policy/PolicyEngine.ts +++ b/src/policy/PolicyEngine.ts @@ -7,10 +7,11 @@ const READ_RISKS: ReadonlySet = new Set(['read']); /** * Deterministic ALLOW / ASK / DENY engine (blueprint §16). The model proposes, * this decides (Principle 1). Rules, in order: - * 1. Any path escaping the workspace → DENY (blueprint §17). - * 2. The `present_plan` gate: ASK in plan mode, ALLOW elsewhere. - * 3. read-only / plan mode → allow reads, DENY every mutating/side-effecting tool. - * 4. workspace mode → allow reads, ASK for writes/shell/destructive/network. + * 1. Any path escaping the workspace → DENY (blueprint §17). Always first. + * 2. `bypass` mode → ALLOW everything (the escape guardrail above still holds). + * 3. The `present_plan` gate: ASK in plan mode, ALLOW elsewhere. + * 4. read-only / plan mode → allow reads, DENY every mutating/side-effecting tool. + * 5. workspace mode → allow reads, ASK for writes/shell/destructive/network. * The engine never executes; it only classifies. */ export class PolicyEngine { @@ -22,6 +23,13 @@ export class PolicyEngine { }; } + // `bypass` auto-approves every in-workspace action with no prompt. The + // workspace-escape DENY above is the one guardrail that still applies, so a + // tool can never reach outside the workspace root even here. + if (ctx.mode === 'bypass') { + return { kind: 'allow', reason: 'bypass mode: auto-approved (no prompts)' }; + } + // The plan-mode "exit gate". `present_plan` has no side effects of its own // (risk `read`), but in plan mode it is the deliberate hand-off point: we ASK // so approving it can flip the session to workspace mode (TurnController). In diff --git a/src/protocol/risk.ts b/src/protocol/risk.ts index c7a8edf..818a216 100644 --- a/src/protocol/risk.ts +++ b/src/protocol/risk.ts @@ -33,11 +33,15 @@ export const resourceClassSchema: z.ZodType = z.enum([ * - `plan`: like `read-only` for *gating* (no side effects), but semantically a * "research & propose" mode — the agent inspects and drafts a plan without * touching anything. Toggled with Shift+Tab in the TUI. + * - `bypass`: auto-approve every tool with no prompts (writes/shell/network), + * for when the user wants to move fast. The one hard guardrail still holds — + * a path escaping the workspace root is always denied (see PolicyEngine). */ -export type PermissionMode = 'read-only' | 'workspace' | 'plan'; +export type PermissionMode = 'read-only' | 'workspace' | 'plan' | 'bypass'; export const permissionModeSchema: z.ZodType = z.enum([ 'read-only', 'workspace', 'plan', + 'bypass', ]); diff --git a/src/providers/anthropic/AnthropicProvider.ts b/src/providers/anthropic/AnthropicProvider.ts index 01c3928..7e223ad 100644 --- a/src/providers/anthropic/AnthropicProvider.ts +++ b/src/providers/anthropic/AnthropicProvider.ts @@ -2,7 +2,7 @@ import { newToolCallId, type ToolCall } from '../../protocol/index.ts'; import type { ModelEvent } from '../ModelEvent.ts'; import type { ModelRequest } from '../ModelRequest.ts'; import type { ModelCapabilities, ModelProvider } from '../ModelProvider.ts'; -import { ProviderHttpError, redactSecrets, safeText } from '../errors.ts'; +import { ProviderHttpError, providerHttpError, redactSecrets, safeText } from '../errors.ts'; import { parseSseStream } from '../openai/sse.ts'; import { toMessagesRequest } from './messagesRequest.ts'; @@ -93,7 +93,7 @@ export class AnthropicProvider implements ModelProvider { if (!res.ok) { const detail = await safeText(res); - throw new ProviderHttpError(res.status, `${this.name} API error ${res.status}: ${detail}`); + throw providerHttpError(this.name, res.status, detail); } if (!res.body) { throw new ProviderHttpError(res.status, `${this.name} API returned no response body`); diff --git a/src/providers/errors.ts b/src/providers/errors.ts index 0d1e1c3..927aa2f 100644 --- a/src/providers/errors.ts +++ b/src/providers/errors.ts @@ -6,6 +6,8 @@ export class ProviderHttpError extends Error { readonly status: number; + /** Classifies this in `turn.failed` as a provider issue, not a Parallax bug. */ + readonly code = 'provider_error'; constructor(status: number, message: string) { super(message); this.name = 'ProviderHttpError'; @@ -13,6 +15,20 @@ export class ProviderHttpError extends Error { } } +/** + * Build a `ProviderHttpError` from a non-2xx model response, adding a "pick + * another model" hint for the statuses that almost always mean the model id is + * wrong or retired (404 Not Found, 410 Gone — e.g. an end-of-life model). Keeps + * both adapters' error surfaces identical and actionable. + */ +export function providerHttpError(name: string, status: number, detail: string): ProviderHttpError { + const hint = + status === 404 || status === 410 + ? ` — this model may be unavailable; run \`/models ${name}\` or \`/model\` to pick another.` + : ''; + return new ProviderHttpError(status, `${name} API error ${status}: ${detail}${hint}`); +} + /** Read up to 500 chars of an error body without throwing. */ export async function safeText(res: Response): Promise { try { diff --git a/src/providers/index.ts b/src/providers/index.ts index 26b42e6..c07c1d0 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -15,4 +15,4 @@ export { type FetchLike, } from './openai/OpenAiCompatibleProvider.ts'; export { AnthropicProvider, type AnthropicOptions } from './anthropic/AnthropicProvider.ts'; -export { ProviderHttpError, redactSecrets } from './errors.ts'; +export { ProviderHttpError, providerHttpError, redactSecrets } from './errors.ts'; diff --git a/src/providers/openai/OpenAiCompatibleProvider.ts b/src/providers/openai/OpenAiCompatibleProvider.ts index 2a351b3..a2f42e9 100644 --- a/src/providers/openai/OpenAiCompatibleProvider.ts +++ b/src/providers/openai/OpenAiCompatibleProvider.ts @@ -2,7 +2,7 @@ import { newToolCallId, type ToolCall } from '../../protocol/index.ts'; import type { ModelEvent } from '../ModelEvent.ts'; import type { ModelRequest } from '../ModelRequest.ts'; import type { ModelCapabilities, ModelProvider } from '../ModelProvider.ts'; -import { ProviderHttpError, redactSecrets, safeText } from '../errors.ts'; +import { ProviderHttpError, providerHttpError, redactSecrets, safeText } from '../errors.ts'; import { toChatRequest } from './chatRequest.ts'; import { parseSseStream } from './sse.ts'; @@ -88,7 +88,7 @@ export class OpenAiCompatibleProvider implements ModelProvider { if (!res.ok) { const detail = await safeText(res); - throw new ProviderHttpError(res.status, `${this.name} API error ${res.status}: ${detail}`); + throw providerHttpError(this.name, res.status, detail); } if (!res.body) { throw new ProviderHttpError(res.status, `${this.name} API returned no response body`); diff --git a/src/runtime/RuntimeFacade.ts b/src/runtime/RuntimeFacade.ts index e1d4f5b..dc46b85 100644 --- a/src/runtime/RuntimeFacade.ts +++ b/src/runtime/RuntimeFacade.ts @@ -136,6 +136,14 @@ export class RuntimeFacade { return this.cfg.store.listSessions(); } + /** The registered tools (name + one-line description), for the `/tools` command. */ + listTools(): Array<{ name: string; description: string }> { + return this.cfg.registry.modelSchemas().map((t) => ({ + name: t.name, + description: t.description, + })); + } + resolveApproval(approvalId: string, decision: ApprovalDecision): boolean { return this.approvals.resolve(approvalId, decision); } diff --git a/tests/api-key.test.ts b/tests/api-key.test.ts index d56e491..c8d4160 100644 --- a/tests/api-key.test.ts +++ b/tests/api-key.test.ts @@ -1,6 +1,12 @@ import { describe, it, expect } from 'vitest'; import { sanitizeApiKey } from '../src/config/index.ts'; -import { redactSecrets, OpenAiCompatibleProvider, type FetchLike } from '../src/providers/index.ts'; +import { + redactSecrets, + providerHttpError, + OpenAiCompatibleProvider, + ProviderHttpError, + type FetchLike, +} from '../src/providers/index.ts'; import type { ModelRequest } from '../src/providers/index.ts'; describe('sanitizeApiKey', () => { @@ -90,3 +96,59 @@ describe('provider never leaks the key in a transport error', () => { expect(message).toContain(''); }); }); + +describe('providerHttpError classification', () => { + it('carries a provider_error code (not internal_error) for turn.failed', () => { + const err = providerHttpError('nvidia', 500, 'boom'); + expect(err).toBeInstanceOf(ProviderHttpError); + expect(err.code).toBe('provider_error'); + expect(err.status).toBe(500); + }); + + it('adds a "pick another model" hint for 404/410 (retired/unknown model)', () => { + const gone = providerHttpError('nvidia', 410, '{"detail":"end of life"}'); + expect(gone.message).toMatch(/end of life/); + expect(gone.message).toMatch(/\/models nvidia|\/model/); + const notFound = providerHttpError('openai', 404, 'no such model'); + expect(notFound.message).toMatch(/pick another/i); + }); + + it('omits the hint for other statuses (e.g. 401 auth)', () => { + const unauth = providerHttpError('nvidia', 401, 'unauthorized'); + expect(unauth.message).not.toMatch(/pick another/i); + }); + + it('surfaces a 410 through the provider stream with the hint', async () => { + const fetchImpl: FetchLike = () => + Promise.resolve( + new Response('{"status":410,"detail":"The model has reached its end of life."}', { + status: 410, + }), + ); + const provider = new OpenAiCompatibleProvider({ + name: 'nvidia', + baseUrl: 'https://x.test/v1', + apiKey: 'nvapi-ok', + fetchImpl, + }); + let caught: unknown; + try { + for await (const _ of provider.stream( + { + model: 'z-ai/glm-5.2', + system: 's', + messages: [{ role: 'user', content: 'hi' }], + tools: [], + }, + new AbortController().signal, + )) + void _; + } catch (e) { + caught = e; + } + expect(caught).toBeInstanceOf(ProviderHttpError); + expect((caught as ProviderHttpError).code).toBe('provider_error'); + expect((caught as Error).message).toMatch(/end of life/); + expect((caught as Error).message).toMatch(/\/model/); + }); +}); diff --git a/tests/local-config-write.test.ts b/tests/local-config-write.test.ts new file mode 100644 index 0000000..b1fc222 --- /dev/null +++ b/tests/local-config-write.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { saveLocalConfig, loadLocalConfig, userConfigPath } from '../src/config/localConfig.ts'; + +let home: string; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'parallax-home-')); + process.env.PARALLAX_HOME = home; +}); + +afterEach(() => { + rmSync(home, { recursive: true, force: true }); + delete process.env.PARALLAX_HOME; +}); + +describe('saveLocalConfig', () => { + it('persists provider/model/theme and reads back via loadLocalConfig', () => { + saveLocalConfig({ provider: 'nvidia', model: 'meta/llama-3.3-70b-instruct', theme: 'light' }); + const loaded = loadLocalConfig(); + expect(loaded.provider).toBe('nvidia'); + expect(loaded.model).toBe('meta/llama-3.3-70b-instruct'); + expect(loaded.theme).toBe('light'); + }); + + it('merges into an existing file, preserving unrelated keys', () => { + writeFileSync( + userConfigPath(), + JSON.stringify({ theme: 'dark', providers: { custom: { baseURL: 'http://x' } } }, null, 2), + ); + saveLocalConfig({ provider: 'openai', model: 'gpt-4o' }); + const raw = JSON.parse(readFileSync(userConfigPath(), 'utf8')); + expect(raw.provider).toBe('openai'); + expect(raw.model).toBe('gpt-4o'); + expect(raw.theme).toBe('dark'); // untouched + expect(raw.providers.custom.baseURL).toBe('http://x'); // untouched + }); + + it('applies only the keys present in the patch', () => { + saveLocalConfig({ provider: 'openai', model: 'gpt-4o' }); + saveLocalConfig({ theme: 'light' }); // must not wipe provider/model + const loaded = loadLocalConfig(); + expect(loaded.provider).toBe('openai'); + expect(loaded.model).toBe('gpt-4o'); + expect(loaded.theme).toBe('light'); + }); + + it('recovers from a malformed existing file by overwriting cleanly', () => { + writeFileSync(userConfigPath(), '{ not valid json'); + saveLocalConfig({ provider: 'openai' }); + expect(loadLocalConfig().provider).toBe('openai'); + }); +}); diff --git a/tests/policy.test.ts b/tests/policy.test.ts index 4097687..d9e050c 100644 --- a/tests/policy.test.ts +++ b/tests/policy.test.ts @@ -82,6 +82,21 @@ const cases: Case[] = [ { name: 'plan + destructive', mode: 'plan', risk: 'destructive', expected: 'deny' }, { name: 'plan + network', mode: 'plan', risk: 'network', expected: 'deny' }, { name: 'plan + external_write', mode: 'plan', risk: 'external_write', expected: 'deny' }, + + // bypass mode: auto-approve everything in-workspace (no prompts). + { name: 'bypass + read', mode: 'bypass', risk: 'read', expected: 'allow' }, + { name: 'bypass + write', mode: 'bypass', risk: 'write', expected: 'allow' }, + { name: 'bypass + destructive', mode: 'bypass', risk: 'destructive', expected: 'allow' }, + { name: 'bypass + network', mode: 'bypass', risk: 'network', expected: 'allow' }, + { name: 'bypass + external_write', mode: 'bypass', risk: 'external_write', expected: 'allow' }, + // …but the workspace-escape guardrail still applies. + { + name: 'bypass + escape', + mode: 'bypass', + risk: 'write', + outsideWorkspace: true, + expected: 'deny', + }, ]; describe('PolicyEngine decision table', () => { @@ -168,6 +183,13 @@ describe('present_plan gate', () => { ); expect(decision.kind).toBe('deny'); }); + + it('does not gate present_plan in bypass mode (auto-approved like everything else)', () => { + const decision = engine.evaluate( + ctx({ toolName: 'present_plan', risk: 'read', mode: 'bypass' }), + ); + expect(decision.kind).toBe('allow'); + }); }); describe('classifyCommand', () => { diff --git a/tests/slash-commands.test.ts b/tests/slash-commands.test.ts new file mode 100644 index 0000000..f0cb068 --- /dev/null +++ b/tests/slash-commands.test.ts @@ -0,0 +1,38 @@ +import { describe, it, expect } from 'vitest'; +import { SLASH_COMMANDS, slashCommands, completionsFor } from '../src/cli/tui/slashCommands.ts'; + +describe('slash-command catalog', () => { + it('has no duplicate command names', () => { + const names = SLASH_COMMANDS.map((c) => c.name); + expect(new Set(names).size).toBe(names.length); + }); + + it('includes the new commands (modes, theme, tools, exit/quit)', () => { + const names = new Set(slashCommands().map((c) => c.name)); + for (const n of [ + 'plan', + 'workspace', + 'read-only', + 'bypass', + 'theme', + 'tools', + 'exit', + 'quit', + ]) { + expect(names.has(n)).toBe(true); + } + }); + + it('completes by prefix while typing a command name', () => { + const forWork = completionsFor('/wo').map((c) => c.name); + expect(forWork).toContain('workspace'); + const forB = completionsFor('/b').map((c) => c.name); + expect(forB).toContain('bypass'); + }); + + it('offers all commands for a bare slash, and none once a space is typed', () => { + expect(completionsFor('/').length).toBe(slashCommands().length); + expect(completionsFor('/model ')).toEqual([]); // typing an argument, not a name + expect(completionsFor('hello')).toEqual([]); // not a command + }); +}); diff --git a/tests/theme.test.ts b/tests/theme.test.ts new file mode 100644 index 0000000..f70474b --- /dev/null +++ b/tests/theme.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from 'vitest'; +import { darkTheme, lightTheme, getTheme, glyphs } from '../src/cli/tui/theme.ts'; + +describe('theme', () => { + it('exposes the red/blue/purple identity roles on both themes', () => { + for (const theme of [darkTheme, lightTheme]) { + // Every semantic role the components reference must be a defined color. + for (const key of [ + 'accent', + 'accentDim', + 'selection', + 'permission', + 'text', + 'subtle', + 'success', + 'error', + 'warning', + ] as const) { + expect(theme[key]).toMatch(/^rgb\(\d+,\d+,\d+\)$/); + } + // selection (purple) is distinct from accent (red) and permission (blue). + expect(theme.selection).not.toBe(theme.accent); + expect(theme.selection).not.toBe(theme.permission); + expect(theme.accent).not.toBe(theme.permission); + } + }); + + it('getTheme defaults to dark and resolves light by name', () => { + expect(getTheme()).toBe(darkTheme); + expect(getTheme('dark')).toBe(darkTheme); + expect(getTheme('light')).toBe(lightTheme); + }); + + it('keeps the glyph set the components rely on', () => { + expect(glyphs.star).toBeTruthy(); + expect(glyphs.bullet).toBeTruthy(); + expect(glyphs.caret).toBeTruthy(); + }); +}); diff --git a/tests/tui-app.test.tsx b/tests/tui-app.test.tsx index 59f121b..8ab4dd4 100644 --- a/tests/tui-app.test.tsx +++ b/tests/tui-app.test.tsx @@ -79,6 +79,7 @@ const tick = (ms = 60): Promise => new Promise((r) => setTimeout(r, ms)); // Keystrokes for ink-testing-library's mock stdin. const ENTER = '\r'; +const DOWN = ''; // down-arrow escape sequence const ESC = ''; let tmpHome: string; @@ -86,6 +87,9 @@ const savedEnv: Record = {}; beforeEach(() => { process.env.PARALLAX_DISABLE_MODELS_FETCH = '1'; + // Keep the TUI tests hermetic: no live npm registry call on mount. + savedEnv['PARALLAX_NO_UPDATE_CHECK'] = process.env.PARALLAX_NO_UPDATE_CHECK; + process.env.PARALLAX_NO_UPDATE_CHECK = '1'; // Isolate credential/key resolution so `hasKey` is deterministic regardless of // the developer's shell or `~/.parallax`. tmpHome = mkdtempSync(join(tmpdir(), 'parallax-tui-')); @@ -175,6 +179,49 @@ describe('TUI App render', () => { // timeline reducer test.) expect(lastFrame ?? '').toBeDefined(); }); + + it('arrow-selects a slash command and runs the highlighted one on Enter', async () => { + const agent = makeAgent([[modelText('hi')]]); + const session = await agent.facade.createSession({ + cwd: '/demo/project', + permissionMode: 'workspace', + }); + const { lastFrame, stdin, unmount } = renderApp(agent, session.id); + await tick(); + // Open the completion menu; the first row is `/help`, the second `/model`. + stdin.write('/'); + await tick(); + expect(lastFrame() ?? '').toContain('/model'); + // Move the highlight down to `/model` and run it — that opens the picker. + stdin.write(DOWN); + await tick(); + stdin.write(ENTER); + await tick(); + // Enter on the *highlighted* row ran `/model` (not the top row `/help`), + // proving arrow selection works. + expect(lastFrame() ?? '').toContain('Configure model'); + unmount(); + }); + + it('switches to bypass mode via /bypass and shows the loud footer', async () => { + const agent = makeAgent([[modelText('hi')]]); + const session = await agent.facade.createSession({ + cwd: '/demo/project', + permissionMode: 'workspace', + }); + const { lastFrame, stdin, unmount } = renderApp(agent, session.id); + await tick(); + stdin.write('/bypass'); + await tick(); + stdin.write(ENTER); + await tick(); + const frame = lastFrame() ?? ''; + expect(frame).toContain('bypass'); + // The session's mode actually changed for subsequent turns. + const s = await agent.store.getSession(session.id); + expect(s?.permissionMode).toBe('bypass'); + unmount(); + }); }); describe('TUI model configuration', () => { diff --git a/tests/update-check.test.ts b/tests/update-check.test.ts new file mode 100644 index 0000000..1169226 --- /dev/null +++ b/tests/update-check.test.ts @@ -0,0 +1,146 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + isNewer, + readUpdateCache, + refreshUpdateInfo, + upgradeCommand, + updateCheckDisabled, +} from '../src/config/updateCheck.ts'; +import { VERSION } from '../src/version.ts'; + +let dir: string; +let cachePath: string; +const savedFetch = globalThis.fetch; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'parallax-upd-')); + cachePath = join(dir, 'update.json'); + process.env.PARALLAX_UPDATE_CACHE = cachePath; + delete process.env.PARALLAX_NO_UPDATE_CHECK; +}); + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + delete process.env.PARALLAX_UPDATE_CACHE; + delete process.env.PARALLAX_NO_UPDATE_CHECK; + globalThis.fetch = savedFetch; +}); + +describe('isNewer (semver precedence, prerelease-aware)', () => { + it('compares release numbers', () => { + expect(isNewer('0.2.0', '0.1.9')).toBe(true); + expect(isNewer('1.0.0', '0.9.9')).toBe(true); + expect(isNewer('0.1.0', '0.1.0')).toBe(false); + expect(isNewer('0.1.0', '0.2.0')).toBe(false); + }); + + it('orders prereleases within the same release', () => { + expect(isNewer('0.1.0-beta.12', '0.1.0-beta.8')).toBe(true); + expect(isNewer('0.1.0-beta.8', '0.1.0-beta.12')).toBe(false); + expect(isNewer('0.1.0-beta.2', '0.1.0-beta.2')).toBe(false); + }); + + it('treats a stable release as newer than its prerelease', () => { + expect(isNewer('0.1.0', '0.1.0-beta.9')).toBe(true); + expect(isNewer('0.1.0-beta.9', '0.1.0')).toBe(false); + }); +}); + +describe('updateCheckDisabled', () => { + it('honors the opt-out env var', () => { + process.env.PARALLAX_NO_UPDATE_CHECK = '1'; + expect(updateCheckDisabled()).toBe(true); + }); +}); + +describe('upgradeCommand', () => { + it('is the plain global install for a latest-channel update', () => { + const cmd = upgradeCommand({ + current: VERSION, + latest: '9.9.9', + channel: 'latest', + checkedAt: 0, + }); + expect(cmd).toContain('npm install --global'); + expect(cmd).not.toContain('@next'); + }); + it('appends @next for a next-channel update', () => { + const cmd = upgradeCommand({ + current: VERSION, + latest: '9.9.9', + channel: 'next', + checkedAt: 0, + }); + expect(cmd).toContain('@next'); + }); +}); + +describe('readUpdateCache', () => { + it('returns a fresh entry that matches the running version', async () => { + writeFileSync( + cachePath, + JSON.stringify({ + current: VERSION, + latest: '9.9.9', + channel: 'latest', + checkedAt: Date.now(), + }), + ); + const info = await readUpdateCache(); + expect(info?.latest).toBe('9.9.9'); + }); + + it('ignores a cache written for a different (old) version', async () => { + writeFileSync( + cachePath, + JSON.stringify({ + current: '0.0.1', + latest: '9.9.9', + channel: 'latest', + checkedAt: Date.now(), + }), + ); + expect(await readUpdateCache()).toBeUndefined(); + }); + + it('returns undefined when there is no cache file', async () => { + expect(await readUpdateCache()).toBeUndefined(); + }); +}); + +describe('refreshUpdateInfo', () => { + it('reports and caches a newer version from the registry dist-tags', async () => { + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify({ latest: '9.9.9', next: '9.9.9' }), { status: 200 }), + ) as unknown as typeof fetch; + const info = await refreshUpdateInfo(); + expect(info?.latest).toBe('9.9.9'); + expect(existsSync(cachePath)).toBe(true); + expect(JSON.parse(readFileSync(cachePath, 'utf8')).latest).toBe('9.9.9'); + }); + + it('returns undefined when the registry only has the current version', async () => { + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify({ latest: VERSION }), { status: 200 }), + ) as unknown as typeof fetch; + expect(await refreshUpdateInfo()).toBeUndefined(); + }); + + it('never throws when offline (returns undefined)', async () => { + globalThis.fetch = vi.fn(async () => { + throw new Error('offline'); + }) as unknown as typeof fetch; + expect(await refreshUpdateInfo()).toBeUndefined(); + }); + + it('respects the opt-out (no network call)', async () => { + process.env.PARALLAX_NO_UPDATE_CHECK = '1'; + const spy = vi.fn(); + globalThis.fetch = spy as unknown as typeof fetch; + expect(await refreshUpdateInfo()).toBeUndefined(); + expect(spy).not.toHaveBeenCalled(); + }); +});