diff --git a/CLAUDE.md b/CLAUDE.md index 5c85551..a9b3eff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -143,7 +143,7 @@ npm test # Vitest tests npm run test:packaging # Packaging helper tests ``` -Also run `npm run test:security` and the documented dependency gates when relevant. For packaging changes, run `npm run package` and `npm run verify:package`; releases also require `npm run make` and packaged runtime smoke. CI separately builds/audits Helm and audits root/runtime dependencies; see `.github/workflows/ci.yml` and `docs/DEPENDENCY_SECURITY.md`. Settings has nine sections, including CLI tools. See `src/docs/settings.md` for controls and save behavior. +Also run `npm run test:security` and the documented dependency gates when relevant. For packaging changes, run `npm run package` and `npm run verify:package`; releases also require `npm run make` and packaged runtime smoke. CI separately builds/audits Helm and audits root/runtime dependencies; see `.github/workflows/ci.yml` and `docs/DEPENDENCY_SECURITY.md`. Settings has ten sections, including CLI tools and Pip. See `src/docs/settings.md` for controls and save behavior. **Native packaging:** Forge uses pinned prebuilt node-pty binaries instead of rebuilding with unsupported Visual Studio toolchains. Windows local/Coder PTYs use bundled ConPTY DLL support so shutdown works with `RunAsNode` disabled. Keep the packaged verifier and real PTY startup/stop smoke green; app state remains JSON. @@ -275,7 +275,7 @@ src/ MigrateToVaultDialog.tsx Notifications.tsx PaneStatusStrip.tsx # Per-session cost/token strip - SettingsDialog.tsx # Nine searchable settings sections + SettingsDialog.tsx # Ten searchable settings sections CanvasLayout.tsx # Movable/resizable session panels SetupWizard.tsx # First-run wizard SplitDivider.tsx # Split pane drag handle diff --git a/README.md b/README.md index 55130ee..8774473 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Tether gives you a **single window** with a sidebar to manage it all — while e - **Update notifications** — checks GitHub Releases on launch and links to downloads; stable/beta channels and an opt-out live in Settings → General - **Diagnostics export** — one-click bundle of scrubbed `data.json` (SSH passwords, tokens, sensitive env-var values redacted) plus rotated logs, for triaging support issues - **CLI maintenance** — check and update installed Claude Code, Codex CLI, and OpenCode tools on local, SSH, or Coder targets through temporary terminals -- **Optional sidebar companions** — local GIF panel and Pip pet, off by default. Pip's local reactions use status metadata; generated Codex or Claude quips and submitted-prompt sharing have separate opt-ins +- **Optional sidebar companions** — local GIF panel and Pip pet, off by default. Pip's local reactions use status metadata; generated Codex or Claude quips and submitted-prompt sharing have separate opt-ins, with adjustable hourly limits, in **Settings → Pip** - **J.O.B.S. Office** — optional external office view, off for new setups, with separate connection, remote-session sharing and automatic-launch controls - **Helm** *(opt-in, personal-experimental)* — designate a session as "helm" so it can dispatch pre-briefed child sessions through the `tether-helm` MCP, including spawning Coder workspaces. Off by default behind a two-level gate. Not on the 1.0 roadmap. diff --git a/docs/README.md b/docs/README.md index e71d098..b0a08d8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,7 +12,7 @@ both on GitHub and inside Tether. - [Getting started](../src/docs/getting-started.md) — installation, setup and layouts. - [Sessions](../src/docs/sessions.md) — launch, resume, restore, recipes, search and child viewers. - [Environments](../src/docs/environments.md) — local, SSH and Coder requirements. -- [Settings](../src/docs/settings.md) — all nine sections, defaults and consent controls. +- [Settings](../src/docs/settings.md) — all ten sections, defaults and consent controls. - [Keyboard shortcuts](../src/docs/keyboard-shortcuts.md) — navigation, clipboard and multiline input. - [Usage and quota](../src/docs/usage-quota.md) — estimates, remote collection, exports and privacy. - [Vault](../src/docs/vault.md), [Git providers](../src/docs/git-providers.md) and [Helm](../src/docs/helm.md). diff --git a/src/docs-renderer/index.test.ts b/src/docs-renderer/index.test.ts index 9333449..be96228 100644 --- a/src/docs-renderer/index.test.ts +++ b/src/docs-renderer/index.test.ts @@ -57,7 +57,7 @@ it('opens and navigates settings help anchors in the rendered docs', async () => await import('./index'); expect(document.getElementById('appearance')?.classList.contains('docs-anchor-flash')).toBe(true); - for (const anchor of ['general', 'appearance', 'terminal', 'sessions', 'notifications', 'shortcuts', 'integrations', 'usage']) { + for (const anchor of ['general', 'appearance', 'terminal', 'sessions', 'notifications', 'shortcuts', 'integrations', 'usage', 'cli-tools', 'pip-sidebar-pet']) { navigate({ page: 'settings', anchor }); expect(document.getElementById(anchor)?.classList.contains('docs-anchor-flash'), anchor).toBe(true); } diff --git a/src/docs/sessions.md b/src/docs/sessions.md index 284c081..98e967e 100644 --- a/src/docs/sessions.md +++ b/src/docs/sessions.md @@ -11,7 +11,7 @@ updates** for installation methods and cancellation behavior. A **session** in Tether is a running CLI process in a specific directory and environment. You can have many sessions open at once, each with its own terminal. Tether is a "dumb pipe" — the PTY stream flows byte-for-byte into the terminal; nothing is parsed, rewritten, or intercepted. -The optional **[Pip sidebar pet](settings.md#pip-sidebar-pet)** follows the focused session, reacts to its status, and taps a tiny keyboard while you type. Enable it from **View → Pip Sidebar Pet**. Its **waiting** button opens another session that needs input, with permission prompts first. Optional AI quips and submitted-prompt sharing have separate controls in **Pip options**, using your Codex or Claude sign-in. +The optional **[Pip sidebar pet](settings.md#pip-sidebar-pet)** follows the focused session, reacts to its status, and taps a tiny keyboard while you type. Enable it from **View → Pip Sidebar Pet**. Its **waiting** button opens another session that needs input, with permission prompts first. Optional AI quips and submitted-prompt sharing have separate controls in **Settings → Pip**, using your Codex or Claude sign-in. ## Creating Sessions diff --git a/src/docs/settings.md b/src/docs/settings.md index 974fff1..7c6695e 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -29,19 +29,20 @@ stops the maintenance terminal. Interrupted updates may need to be retried. Maintenance terminals are temporary: they are not saved as conversations and do not install Tether status hooks or contribute session usage statistics. -Open Settings with **Ctrl+,**, the button at the bottom of the sidebar, or **File → Settings…** in the menu bar. Search for a settings section by name or topic, such as “theme”, “hooks”, or “usage”. The dialog has nine sections: +Open Settings with **Ctrl+,**, the button at the bottom of the sidebar, or **File → Settings…** in the menu bar. Search for a settings section by name or topic, such as “theme”, “hooks”, or “usage”. The dialog has ten sections: - [General](#general) — session restore and update checks - [Appearance](#appearance) — theme previews, UI font, and interface density - [Terminal](#terminal) — terminal font, cursor shape, and scrollback - [Sessions](#sessions) — launch profiles, default env vars, Helm and status hooks +- [CLI tools](#cli-tools) — Claude, Codex, OpenCode and Copilot launch defaults, updates and native controls - [Notifications](#notifications) — desktop notification triggers and suppression - [Shortcuts](#shortcuts) — keyboard shortcut customization - [Integrations](#integrations) — Vault, Git providers, SSH known hosts, J.O.B.S. office -- [CLI tools](#cli-tools) — Claude, Codex, OpenCode and Copilot launch defaults, updates and native controls - [Usage](#usage) — cost tracking, history dialog, exports, subscription quota +- [Pip](#pip-sidebar-pet) — the optional sidebar pet: personality, nudges, AI quips and their limits -Use **Save** to apply settings changes. Theme selection previews immediately and reverts on **Cancel**. Actions with their own buttons apply immediately: shortcut edits, profile and provider changes, known-host revocation, Vault login/logout and migration, **Test now** for J.O.B.S., exports, and resetting session font sizes. The dialog's **Cancel** button does not undo those actions. +Use **Save** to apply settings changes. Theme selection previews immediately and reverts on **Cancel**. Actions with their own buttons apply immediately: shortcut edits, every control in **Pip**, profile and provider changes, known-host revocation, Vault login/logout and migration, **Test now** for J.O.B.S., exports, and resetting session font sizes. The dialog's **Cancel** button does not undo those actions. ## General @@ -156,7 +157,7 @@ On by default. Lists the subagents a Claude Code session (local, SSH or Coder) h ## Sidebar panels -The GIF panel and Pip are not controls in the Settings dialog. Turn each one on from the **View** menu; its options are in the panel itself and save immediately. +Turn the GIF panel and Pip on from the **View** menu. The GIF panel's options are in the panel itself. Pip's are in **Settings → Pip**, which the gear button in Pip's header opens. Both save immediately. ### GIF panel @@ -174,28 +175,28 @@ The panel is off by default and ships without media. Files stay on your computer ### Pip sidebar pet -Choose **View → Pip Sidebar Pet** to invite Pip into the sidebar. Pip is a small cable gremlin with a terminal face, a linked-cable badge, and a looped tether tail. Its colors follow your Tether theme. It is off by default and can live alongside the GIF panel. +Choose **View → Pip Sidebar Pet** to invite Pip into the sidebar. Pip is a small cable gremlin with a terminal face, a linked-cable badge, and a looped tether tail. Its colors follow your Tether theme. It is off by default and can live alongside the GIF panel. **Show Pip in the sidebar** in **Settings → Pip** is the same switch. - Pip follows your focused session in single, split, and Canvas layouts. It reacts to starting or working agents, input and permission waits, idle sessions, stopped sessions, and sessions that ended unexpectedly. A ready-for-input reaction means the agent is waiting for you; it does not certify that a task or test succeeded. - When a turn Pip watched from its start runs five minutes or longer, the ready reaction mentions how long it took. Pip also notices when the focused Claude or Codex session starts its first subagent or `codex exec` run; this follows **Show subagents in sidebar**, and OpenCode sessions have no child rows to notice. - When another session is waiting, the **waiting** button switches to it, prioritizing permission prompts. The button stays in the header while the panel is collapsed. While any session is blocked on a permission prompt, Pip stays alert until it is answered. Switching sessions quickly can make Pip dizzy. Click Pip, or focus it and press **Enter** or **Space**, to pet it. - Pip perks up and taps a tiny keyboard while you type in the focused terminal. Pressing **Enter** gets an occasional reaction; this signals a keypress, not proof that the CLI accepted a prompt. Keys, pasted text, and composed text count as typing; focus changes, mouse movement, and the terminal's own replies do not. Draft text is never collected for this animation. -- **Quiet** keeps the expressions and silences local and AI comments. **Pip options** lets you choose **Dry little gremlin** or **Cozy companion**, and turn ambient motion off. Your system's reduced-motion preference also stops animations and cursor tracking. +- **Quiet**, in Pip's header and in **Settings → Pip**, keeps the expressions and silences local and AI comments. **Settings → Pip** also lets you choose **Dry little gremlin** or **Cozy companion**, and turn ambient motion off. Your system's reduced-motion preference also stops animations and cursor tracking. - Routine comments appear at most once every 25 seconds. A session becoming ready or stopping can replace a routine comment, and a permission prompt or another session needing you always gets one. A comment stays for 12 seconds, or until what it describes is no longer true, then returns to a greeting. Petting gets an immediate response. - After 90 seconds without mouse, keyboard, or scroll activity in Tether, Pip takes a nap. Using the app wakes it, and so does a session that needs you. Pip does not nap while a permission prompt is pending. - Screen readers announce only comments about a session that needs you: a permission prompt, or another session waiting. Other comments, including AI quips, stay visible and silent. -- **Operational nudges** in **Pip options** is off by default. When on, Pip comments once when Vault sign-in is within 30 minutes of expiring, a Claude or Codex quota window passes 90%, a daily or weekly usage budget is crossed, or a Tether update is available. Each occurrence is mentioned once per launch, a nudge waits for the current comment to end, and several quota windows over the mark share one comment. Every nudge repeats an indicator the sidebar already shows; Pip is never the only place a warning appears. Nudges are local lines and are never sent to an AI quip backend. With **Quiet** on, Pip changes expression without the comment. +- **Operational nudges** in **Settings → Pip** is off by default. When on, Pip comments once when Vault sign-in is within 30 minutes of expiring, a Claude or Codex quota window passes 90%, a daily or weekly usage budget is crossed, or a Tether update is available. Each occurrence is mentioned once per launch, a nudge waits for the current comment to end, and several quota windows over the mark share one comment. Every nudge repeats an indicator the sidebar already shows; Pip is never the only place a warning appears. Nudges are local lines and are never sent to an AI quip backend. With **Quiet** on, Pip changes expression without the comment. - Preferences save immediately and persist across launches. Click **Pip** to collapse the panel, or **Hide Pip** to remove it. Reopen it from **View → Pip Sidebar Pet**. Collapsing it, hiding the sidebar, or minimizing the window suspends its timers and cursor tracking; reopening it does not replay missed reactions. Local reactions use session labels, focus, status metadata, and a text-free typing signal. They make no model or network requests and work with local, SSH, and Coder sessions. How accurately Pip reacts depends on that session's status detection. Pip never parses or alters terminal output. #### Optional AI quips -- Choose a backend under **AI quips** in **Pip options** to get occasional generated comments: **Codex (ChatGPT sign-in)** uses your local Codex CLI, and **Claude (Claude subscription)** uses your local Claude Code. Either way the quip uses that subscription's allowance; API-key, proxy, and cloud-provider sign-ins are not used for Pip. **Off** keeps local quips only and remembers your last backend. AI quips are off by default. OpenCode is not supported as a quip backend, because `opencode run` gives no error and never exits when a model call fails. -- The backend is always your explicit choice, not the focused session's CLI, because it decides which company receives the request. When you pick one, a status line shows its sign-in and model, or why it cannot be used. **Try a quip** asks for one immediately so you can confirm it works; it skips the two-minute wait but counts toward the hourly limit. +- Choose a **Backend** under **AI quips** in **Settings → Pip** to get occasional generated comments: **Codex (ChatGPT sign-in)** uses your local Codex CLI, and **Claude (Claude subscription)** uses your local Claude Code. Either way the quip uses that subscription's allowance; API-key, proxy, and cloud-provider sign-ins are not used for Pip. **Off** keeps local quips only and remembers your last backend. AI quips are off by default. OpenCode is not supported as a quip backend, because `opencode run` gives no error and never exits when a model call fails. +- The backend is always your explicit choice, not the focused session's CLI, because it decides which company receives the request. When you pick one, a status line shows its sign-in and model, or why it cannot be used. **Try a quip** asks for one immediately and shows the line, or the reason none came back, beside the button; it skips the gap between quips but counts toward the hourly limit. It needs Pip shown, expanded, and not on Quiet. - With Codex, Pip selects **GPT-6 Luna**, or **GPT-5.6 Luna** if the current model is absent from the installed CLI's catalog, with the lowest supported reasoning effort and standard speed. With Claude, Pip uses **Claude Haiku** at low effort and accepts a reply only if it was a single Haiku turn. Neither backend silently falls back to a larger model. If sign-in, model access, or the connection is unavailable, local quips continue. - Pip can ask for a quip when the focused session starts working, waits for input or a permission, finishes a turn (including a long one), or stops; when another session needs you; when you press **Enter**; and when it gets dizzy. Crashes, helpers joining, and operational nudges keep local lines. -- Requests are limited to one every two minutes and twelve attempts per hour, including failures. Tether enforces both limits outside the panel, and the status line under **Share submitted prompts** shows why a moment got a local line instead. A moment that ends within a fraction of a second, before its request is sent, does not count. Each request is a fresh, temporary conversation. Quiet, collapse, hide, and minimize cancel pending requests; missed events are not replayed. +- Requests are limited to one every two minutes and twelve attempts per hour by default, including failures. **Quips per hour** (up to 2 to 30) and **Shortest gap between quips** (30 seconds to 30 minutes) change both limits. Tether enforces them outside the window, so a reload does not reset them, and a moment over a limit gets a local line instead. A moment that ends within a fraction of a second, before its request is sent, does not count. Each request is a fresh, temporary conversation. Quiet, collapse, hide, and minimize cancel pending requests; missed events are not replayed. - While a quip is on its way, the local line stays up rather than expiring under it. A quip that arrives gets its own 12 seconds; if none arrives, the local line keeps the rest of its time. A newer comment, or the end of what the line describes, discards a reply that is still pending. - By default Pip supplies only the event (for example, an input wait or Enter press) and chosen personality. Session labels, project paths, draft text, and terminal output are excluded from that context. Both backends run in Tether's neutral app directory rather than your project. Codex uses a temporary conversation with tools, hooks, apps, plugins, and MCP servers off. Claude runs one prompt with no tools, no MCP servers or skills, and none of your user, project, or local settings, so no hooks run (Tether's included); it saves no session, so nothing is added to your Claude history. Claude Code adds its own environment context, including your account email and that neutral folder. - Separately enable **Share submitted prompts** for specific jokes. Pip reads up to 400 characters of the latest available prompt submitted within the past five minutes from an already-attributed **local Claude or Codex transcript**, or from a **local OpenCode session's** own database, opened read-only, when native OpenCode usage has attributed that session. For OpenCode, only the text you typed counts: OpenCode's own reminders, attached files, and tool output are skipped. SSH and Coder sessions, Copilot, and Custom CLIs use activity only. Common credentials are scrubbed, but arbitrary private text may remain; enabling this sends that excerpt to the backend's company: OpenAI for Codex, Anthropic for Claude. Choosing another backend turns sharing off, so consent always names the current recipient. Pip does not collect draft keystrokes or inspect project files. Tether does not save excerpts or generated comments. Quips are not counted in Tether's usage totals: Codex quips are temporary conversations and Claude quips save no transcript. diff --git a/src/main/pip/comment-service.test.ts b/src/main/pip/comment-service.test.ts index 3ae3419..28eb62e 100644 --- a/src/main/pip/comment-service.test.ts +++ b/src/main/pip/comment-service.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect, vi } from 'vitest'; import { PipCommentService } from './comment-service'; -import { DEFAULT_PIP_SETTINGS, PIP_AI_COOLDOWN_MS, type PipCommentResult } from '../../shared/pip'; +import { DEFAULT_PIP_SETTINGS, type PipCommentResult } from '../../shared/pip'; + +const PIP_AI_COOLDOWN_MS = DEFAULT_PIP_SETTINGS.aiCooldownSeconds * 1000; const reply: PipCommentResult = { status: 'ready', line: 'The keyboard has opinions.', model: 'gpt-6-luna', reason: null }; const request = { event: 'submitted' as const, sessionId: 'a' }; @@ -31,6 +33,20 @@ describe('Pip subscription limits', () => { await f.service.comment(request); expect(f.generate).toHaveBeenCalledTimes(13); }); + it('uses the saved hourly limit and gap, and picks up a change on the next request', async () => { + const f = fixture(); + f.settings({ aiHourlyLimit: 2, aiCooldownSeconds: 30 }); + await f.service.comment(request); + f.time(29_000); + expect((await f.service.comment(request)).reason).toContain('breather'); + f.time(1_000); + expect((await f.service.comment(request)).status).toBe('ready'); + f.time(30_000); + expect((await f.service.comment(request)).reason).toContain('Hourly'); + f.settings({ aiHourlyLimit: 3 }); + expect((await f.service.comment(request)).status).toBe('ready'); + expect(f.generate).toHaveBeenCalledTimes(3); + }); it('allows only one pending request and discards a reply after cancellation', async () => { const f = fixture(); let resolve!: (value: PipCommentResult) => void; diff --git a/src/main/pip/comment-service.ts b/src/main/pip/comment-service.ts index 52f43f9..e60bcd4 100644 --- a/src/main/pip/comment-service.ts +++ b/src/main/pip/comment-service.ts @@ -1,4 +1,4 @@ -import { PIP_AI_COOLDOWN_MS, PIP_AI_HOURLY_LIMIT, type PipCommentRequest, type PipCommentResult, type PipSettings } from '../../shared/pip'; +import { type PipCommentRequest, type PipCommentResult, type PipSettings } from '../../shared/pip'; const paused = (reason: string): PipCommentResult => ({ status: 'paused', line: null, model: null, reason }); export interface PipCommentDependencies { @@ -7,7 +7,10 @@ export interface PipCommentDependencies { now?: () => number; } -/** Main-process limits survive renderer remounts and cannot be bypassed by UI requests. */ +/** + * Main-process limits survive renderer remounts and cannot be bypassed by UI requests. The limits + * themselves are the person's saved, bounded settings, read fresh for every request. + */ export class PipCommentService { private attempts: number[] = []; private pending: AbortController | null = null; @@ -21,9 +24,9 @@ export class PipCommentService { if (this.pending) return paused('Pip is already thinking of a quip.'); const now = this.dependencies.now?.() ?? Date.now(); this.attempts = this.attempts.filter(time => now - time < 3_600_000); - if (this.attempts.length >= PIP_AI_HOURLY_LIMIT) return paused('Hourly limit reached. Local quips for now.'); + if (this.attempts.length >= settings.aiHourlyLimit) return paused('Hourly limit reached. Local quips for now.'); // Try a quip is asked for by the person, so it skips the cooldown. It still counts toward the hourly limit. - if (request.event !== 'hello' && this.attempts.length && now - this.attempts.at(-1)! < PIP_AI_COOLDOWN_MS) { + if (request.event !== 'hello' && this.attempts.length && now - this.attempts.at(-1)! < settings.aiCooldownSeconds * 1000) { return paused('Taking a breather between AI comments.'); } this.attempts.push(now); diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index d2ae46d..2017d56 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -119,7 +119,7 @@ export function App() { const [envDialogOpen, setEnvDialogOpen] = useState(false); const [settingsOpen, setSettingsOpen] = useState(false); const [maintenanceTarget, setMaintenanceTarget] = useState<{ environmentId?: string; sessionId?: string } | null>(null); - const [settingsInitialSection, setSettingsInitialSection] = useState<'integrations' | undefined>(); + const [settingsInitialSection, setSettingsInitialSection] = useState<'integrations' | 'pip' | undefined>(); const [collapsedGroups, setCollapsedGroups] = useState>(new Set()); /** * Sessions whose current waiting cycle the user has already acknowledged @@ -2168,7 +2168,8 @@ export function App() { {sidebarVisible && gifPanel.settings?.enabled && } {sidebarVisible && pip.settings?.enabled && } + activeSessionId={activeSessionId} busy={pip.busy} onSettingsChange={pip.update} + onOpenSettings={() => { setSettingsInitialSection('pip'); setSettingsOpen(true); }} onActivateSession={handleActivateFromSearch} />} setUsageHistoryOpen(true)} @@ -2302,6 +2303,7 @@ export function App() { { setSettingsOpen(false); setMaintenanceTarget({}); }} initialSection={settingsInitialSection} + pip={pip} isOpen={settingsOpen} onClose={() => { setSettingsOpen(false); diff --git a/src/renderer/components/PipSettingsSection.test.ts b/src/renderer/components/PipSettingsSection.test.ts new file mode 100644 index 0000000..ab34b60 --- /dev/null +++ b/src/renderer/components/PipSettingsSection.test.ts @@ -0,0 +1,159 @@ +// @vitest-environment jsdom +import { act, createElement } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PipSettingsSection } from './PipSettingsSection'; +import { DEFAULT_PIP_SETTINGS, type PipSettings } from '../../shared/pip'; + +let container: HTMLDivElement; +let root: Root; +let settings: PipSettings | null; +const update = vi.fn(async () => {}); + +async function render(busy = false) { + await act(async () => root.render(createElement(PipSettingsSection, { settings, busy, update }))); +} +function control(label: string): T { + const found = Array.from(container.querySelectorAll('label')).find(item => item.textContent?.trim().startsWith(label)); + if (!found) throw new Error(`No control labelled ${label}`); + return (found.querySelector('input') ?? document.getElementById(found.htmlFor)) as T; +} +async function choose(label: string, value: string) { + await act(async () => { + const select = control(label); + select.value = value; + select.dispatchEvent(new Event('change', { bubbles: true })); + }); +} +async function toggle(label: string) { await act(async () => control(label).click()); } +function tryButton() { return Array.from(container.querySelectorAll('button')).find(button => /Try a quip|Asking/.test(button.textContent ?? ''))!; } + +beforeEach(() => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + update.mockClear(); + settings = { ...DEFAULT_PIP_SETTINGS, enabled: true }; + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); + +describe('Settings → Pip', () => { + it('waits for preferences before showing controls', async () => { + settings = null; + await render(); + expect(container.textContent).toContain('Loading Pip preferences'); + expect(container.querySelector('select')).toBeNull(); + }); + + it('saves each presentation control as it changes', async () => { + await render(); + await toggle('Show Pip in the sidebar'); + expect(update).toHaveBeenLastCalledWith({ enabled: false }); + await choose('Personality', 'sweet'); + expect(update).toHaveBeenLastCalledWith({ personality: 'sweet' }); + await toggle('Quiet'); + expect(update).toHaveBeenLastCalledWith({ quiet: true }); + await toggle('Ambient motion'); + expect(update).toHaveBeenLastCalledWith({ motion: false }); + await toggle('Operational nudges'); + expect(update).toHaveBeenLastCalledWith({ nudges: true }); + }); + + it('keeps AI quips off by default, with limits and prompt consent locked until a backend is chosen', async () => { + const backendStatus = vi.fn(); + vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), backendStatus } }); + await render(); + expect(control('Backend').value).toBe('off'); + expect(backendStatus).not.toHaveBeenCalled(); + expect(control('Quips per hour').disabled).toBe(true); + expect(control('Shortest gap between quips').disabled).toBe(true); + expect(control('Share submitted prompts').disabled).toBe(true); + expect(tryButton().disabled).toBe(true); + await choose('Backend', 'codex'); + expect(update).toHaveBeenLastCalledWith({ aiComments: true, aiBackend: 'codex' }); + }); + + it('checks the chosen backend and names the company that receives shared prompts', async () => { + const backendStatus = vi.fn(async (backend: string) => backend === 'claude' + ? { backend, ready: true, detail: 'Signed in with Claude Max. Quips use Claude Haiku.' } + : { backend, ready: false, detail: 'Sign in to Codex with ChatGPT to enable AI quips.' }); + vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), backendStatus } }); + settings = { ...settings!, aiComments: true, aiBackend: 'codex' }; + await render(); + const status = () => container.querySelector('.pip-settings-status')!; + expect(backendStatus).toHaveBeenLastCalledWith('codex'); + expect(status().textContent).toContain('Sign in to Codex'); + expect(status().dataset.ready).toBe('false'); + expect(container.textContent).toContain('to OpenAI'); + await choose('Backend', 'claude'); + expect(update).toHaveBeenLastCalledWith({ aiComments: true, aiBackend: 'claude' }); + settings = { ...settings, aiBackend: 'claude' }; + await render(); + expect(backendStatus).toHaveBeenLastCalledWith('claude'); + expect(status().textContent).toBe('Signed in with Claude Max. Quips use Claude Haiku.'); + expect(container.textContent).toContain('to Anthropic'); + await toggle('Share submitted prompts'); + expect(update).toHaveBeenLastCalledWith({ sharePrompts: true }); + await choose('Backend', 'off'); + expect(update).toHaveBeenLastCalledWith({ aiComments: false }); + }); + + it('saves the hourly limit and gap, and lists a saved value that is not a preset', async () => { + vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), backendStatus: vi.fn(() => new Promise(() => {})) } }); + settings = { ...settings!, aiComments: true, aiHourlyLimit: 9, aiCooldownSeconds: 90 }; + await render(); + const hourly = control('Quips per hour'); + expect(hourly.value).toBe('9'); + expect(Array.from(hourly.options).map(option => option.value)).toEqual(['2', '4', '6', '9', '12', '20', '30']); + expect(control('Shortest gap between quips').selectedOptions[0].textContent).toBe('1.5 minutes'); + await choose('Quips per hour', '20'); + expect(update).toHaveBeenLastCalledWith({ aiHourlyLimit: 20 }); + await choose('Shortest gap between quips', '300'); + expect(update).toHaveBeenLastCalledWith({ aiCooldownSeconds: 300 }); + }); + + it('asks for one quip on demand and shows the line or the reason', async () => { + const comment = vi.fn() + .mockResolvedValueOnce({ status: 'ready', line: 'Testing, testing.', model: 'claude-haiku-5-5', reason: null }) + .mockResolvedValueOnce({ status: 'paused', line: null, model: null, reason: 'Hourly limit reached. Local quips for now.' }) + .mockRejectedValueOnce(new Error('ipc down')); + vi.stubGlobal('electronAPI', { pip: { comment, backendStatus: vi.fn(() => new Promise(() => {})) } }); + settings = { ...settings!, aiComments: true, aiBackend: 'claude' }; + await render(); + expect(container.querySelector('.pip-settings-status')?.textContent).toBe('Checking sign-in…'); + await act(async () => tryButton().click()); + expect(comment).toHaveBeenCalledWith({ event: 'hello', sessionId: null }); + expect(container.textContent).toContain('Pip: “Testing, testing.” (claude-haiku-5-5)'); + await act(async () => tryButton().click()); + expect(container.textContent).toContain('Hourly limit reached'); + await act(async () => tryButton().click()); + expect(container.textContent).toContain('Could not ask for a quip.'); + }); + + it.each([ + [{ enabled: false }, 'Turn Pip on to try a quip.'], + [{ collapsed: true }, 'Expand Pip in the sidebar to try a quip.'], + [{ quiet: true }, 'Turn Quiet off to try a quip.'], + ] as const)('explains why Try a quip is unavailable: %j', async (patch, reason) => { + vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), backendStatus: vi.fn(() => new Promise(() => {})) } }); + settings = { ...settings!, aiComments: true, ...patch }; + await render(); + expect(tryButton().disabled).toBe(true); + expect(container.textContent).toContain(reason); + }); + + it('locks every control while a save is in flight', async () => { + vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), backendStatus: vi.fn(() => new Promise(() => {})) } }); + settings = { ...settings!, aiComments: true }; + await render(true); + const controls = [...container.querySelectorAll('input, select, button')]; + expect(controls.length).toBeGreaterThan(8); + expect(controls.every(item => item.disabled)).toBe(true); + }); +}); diff --git a/src/renderer/components/PipSettingsSection.tsx b/src/renderer/components/PipSettingsSection.tsx new file mode 100644 index 0000000..37e48fb --- /dev/null +++ b/src/renderer/components/PipSettingsSection.tsx @@ -0,0 +1,187 @@ +import { useId, useState } from 'react'; +import { CLI_TOOL_REGISTRY } from '../../shared/cli-tools'; +import type { PipAiBackend, PipCommentResult, PipSettings } from '../../shared/pip'; +import { usePipBackendStatus } from '../hooks/usePipBackendStatus'; + +export interface PipSettingsControl { + settings: PipSettings | null; + busy: boolean; + update: (patch: Partial) => Promise; +} + +const HOURLY_LIMITS = [2, 4, 6, 12, 20, 30]; +const COOLDOWNS = [30, 60, 120, 300, 600, 900, 1800]; + +const BACKEND_HELP: Readonly> = { + codex: 'Uses your local Codex ChatGPT sign-in and subscription allowance. Luna only.', + claude: 'Uses your local Claude Code subscription sign-in and allowance. Haiku only.', +}; + +function cooldownLabel(seconds: number): string { + if (seconds < 60) return `${seconds} seconds`; + const minutes = seconds / 60; + const rounded = Number.isInteger(minutes) ? String(minutes) : minutes.toFixed(1); + return `${rounded} ${minutes === 1 ? 'minute' : 'minutes'}`; +} + +/** The preset list, plus the saved value when it is not one of the presets. */ +function withSaved(presets: readonly number[], saved: number): number[] { + return presets.includes(saved) ? [...presets] : [...presets, saved].sort((a, b) => a - b); +} + +function tryQuipBlocker(settings: PipSettings): string | null { + if (!settings.enabled) return 'Turn Pip on to try a quip.'; + if (settings.collapsed) return 'Expand Pip in the sidebar to try a quip.'; + if (settings.quiet) return 'Turn Quiet off to try a quip.'; + return null; +} + +function quipOutcome(result: PipCommentResult): string { + if (!result.line) return result.reason ?? 'No quip came back.'; + const model = result.model ? ` (${result.model})` : ''; + return `Pip: “${result.line}”${model}`; +} + +/** + * Settings → Pip. Every control saves as it changes, like the panel's own Quiet switch, because + * Pip is live in the sidebar while this dialog is open. + */ +export function PipSettingsSection({ settings, busy, update }: Readonly) { + const id = useId(); + const [trying, setTrying] = useState(false); + const [outcome, setOutcome] = useState(null); + const aiOn = settings?.aiComments ?? false; + const backend = usePipBackendStatus(settings?.aiBackend ?? 'codex', aiOn); + + if (!settings) return

Loading Pip preferences…

; + + const change = (patch: Partial) => { void update(patch); }; + const recipient = CLI_TOOL_REGISTRY[settings.aiBackend].pipQuips?.recipient ?? 'the AI provider'; + const blocker = tryQuipBlocker(settings); + const tryQuip = async () => { + setTrying(true); + setOutcome(null); + try { + setOutcome(quipOutcome(await window.electronAPI.pip.comment({ event: 'hello', sessionId: null }))); + } catch { + setOutcome('Could not ask for a quip.'); + } finally { + setTrying(false); + } + }; + + return ( + <> +
+ +

+ A small cable gremlin that follows your focused session and reacts to its status. Same switch as + {' '}View → Pip Sidebar Pet. Changes in this section save as you make them. +

+
+ +
+
Behavior
+ + + + +

Keeps the expressions and silences every comment, local and AI.

+ + +

Idle animation and cursor tracking. Your system’s reduced-motion preference also turns these off.

+ + +

+ One comment when Vault sign-in is about to expire, a quota passes 90%, a usage budget is crossed, or an + update is available. Local only; never sent to an AI backend. +

+
+ +
+
AI quips
+ + +

+ {aiOn ? BACKEND_HELP[settings.aiBackend] : 'Choose Codex or Claude for occasional generated comments. Off makes no model or network requests.'} +

+ {aiOn && ( + + {backend.checking ? 'Checking sign-in…' : backend.status?.detail ?? ''} + + )} + +
+
+ + +
+
+ + +
+
+

+ Each quip is one small request against your subscription allowance. The hourly limit counts every request, + including failed ones and Try a quip; the gap applies to automatic quips. Both are enforced + outside the window, so they survive reloads. +

+ + +

+ Sends up to 400 characters from the latest local Claude, Codex or OpenCode prompt to {recipient} for specific + jokes. Common secrets are scrubbed; private text can remain. Draft typing and terminal output stay local. + Choosing another backend turns this off. +

+ +
+ + {outcome ?? (aiOn ? blocker : null) ?? ''} +
+

Asks for one quip now and shows it here. It counts toward the hourly limit.

+
+ + ); +} diff --git a/src/renderer/components/SettingsDialog.tsx b/src/renderer/components/SettingsDialog.tsx index 3418da4..3f2449e 100644 --- a/src/renderer/components/SettingsDialog.tsx +++ b/src/renderer/components/SettingsDialog.tsx @@ -15,6 +15,7 @@ import type { GitProviderInfo, GitProviderType, LaunchProfileInfo, VaultConfig, import { DEFAULT_NOTIFICATION_PREFS } from '../../shared/types'; import { CLI_TOOL_REGISTRY } from '../../shared/cli-tools'; import { KeybindingsEditor } from './KeybindingsEditor'; +import { PipSettingsSection, type PipSettingsControl } from './PipSettingsSection'; import { HelpAnchor } from './HelpAnchor'; import { CodexLaunchControls, CodexSettingsSection } from './CodexSettingsSection'; import { CliLaunchControls } from './CliLaunchControls'; @@ -99,7 +100,7 @@ const UI_FONT_PRESETS: ReadonlyArray<{ label: string; value: string }> = [ }, ]; -type SettingsSection = 'appearance' | 'general' | 'terminal' | 'sessions' | 'cli-tools' | 'notifications' | 'shortcuts' | 'integrations' | 'usage'; +type SettingsSection = 'appearance' | 'general' | 'terminal' | 'sessions' | 'cli-tools' | 'notifications' | 'shortcuts' | 'integrations' | 'usage' | 'pip'; const SECTIONS: ReadonlyArray<{ id: SettingsSection; label: string }> = [ { id: 'general', label: 'General' }, @@ -111,6 +112,7 @@ const SECTIONS: ReadonlyArray<{ id: SettingsSection; label: string }> = [ { id: 'shortcuts', label: 'Shortcuts' }, { id: 'integrations', label: 'Integrations' }, { id: 'usage', label: 'Usage' }, + { id: 'pip', label: 'Pip' }, ]; /** Per-section docs deep-link target, used by the (?) help icon. */ @@ -124,6 +126,7 @@ const SECTION_HELP: Record = shortcuts: { title: 'Shortcuts', anchor: 'shortcuts' }, integrations: { title: 'Integrations', anchor: 'integrations' }, usage: { title: 'Usage', anchor: 'usage' }, + pip: { title: 'Pip', anchor: 'pip-sidebar-pet' }, }; function SectionHeader({ section }: Readonly<{ section: SettingsSection }>) { @@ -150,9 +153,11 @@ interface SettingsDialogProps { onKeybindingChange: (action: KeybindingAction, chord: Chord | null) => void; onKeybindingsResetAll: () => void; onOpenCliMaintenance?: () => void; + /** Pip's live preferences. They save as they change, not with the dialog's Save button. */ + pip?: PipSettingsControl; } -export function SettingsDialog({ isOpen, initialSection, onClose, currentTheme, onThemeChange, availableThemes = themeList, localThemeCatalog, onReloadThemes, onResetSessionFontSizes, keybindings, onKeybindingChange, onKeybindingsResetAll, onOpenCliMaintenance }: Readonly) { +export function SettingsDialog({ isOpen, initialSection, onClose, currentTheme, onThemeChange, availableThemes = themeList, localThemeCatalog, onReloadThemes, onResetSessionFontSizes, keybindings, onKeybindingChange, onKeybindingsResetAll, onOpenCliMaintenance, pip }: Readonly) { const settingsId = useId(); const [envVars, setEnvVars] = useState>({}); const [cliFlagsPerTool, setCliFlagsPerTool] = useState>>({}); @@ -613,6 +618,7 @@ export function SettingsDialog({ isOpen, initialSection, onClose, currentTheme, shortcuts: 'shortcuts keyboard keybindings remap', integrations: 'integrations git github ado gitea vault ssh known hosts jobs office', usage: 'usage quota tokens cost budget export', + pip: 'pip sidebar pet companion quips ai personality quiet nudges limit hourly', }; const matchingSections = SECTIONS.filter(section => `${section.label} ${sectionTerms[section.id]}`.toLowerCase().includes(sectionQuery.trim().toLowerCase())); @@ -1385,6 +1391,13 @@ export function SettingsDialog({ isOpen, initialSection, onClose, currentTheme, )} + {activeSection === 'pip' && matchingSections.length > 0 && ( + <> + + {})} /> + + )} + {activeSection === 'notifications' && matchingSections.length > 0 && ( <> diff --git a/src/renderer/components/sidebar/PipPanel.test.ts b/src/renderer/components/sidebar/PipPanel.test.ts index 0ead03f..bcf4443 100644 --- a/src/renderer/components/sidebar/PipPanel.test.ts +++ b/src/renderer/components/sidebar/PipPanel.test.ts @@ -31,10 +31,11 @@ let reduced: boolean; let mediaChange: () => void; const save = vi.fn(); const activate = vi.fn(); +const openSettings = vi.fn(); async function render() { await act(async () => root.render(createElement(PipPanel, { - settings, sessions, activeSessionId: focused, childCounts, busy: false, onSettingsChange: save, onActivateSession: activate, + settings, sessions, activeSessionId: focused, childCounts, busy: false, onSettingsChange: save, onOpenSettings: openSettings, onActivateSession: activate, }))); } async function nudge(...nudges: PipNudge[]) { await act(async () => feed.onChange?.(nudges)); } @@ -42,15 +43,6 @@ async function click(selector: string) { await act(async () => (container.queryS async function advance(ms: number) { await act(async () => vi.advanceTimersByTime(ms)); } function panel() { return container.querySelector('.pip-panel')!; } function line() { return container.querySelector('.pip-speech')?.textContent; } -function aiSelect() { - return Array.from(container.querySelectorAll('label')).find(label => label.textContent?.startsWith('AI quips'))!.querySelector('select')!; -} -async function choose(select: HTMLSelectElement, value: string) { - await act(async () => { - select.value = value; - select.dispatchEvent(new Event('change', { bubbles: true })); - }); -} async function state(state: PipSession['state'], waitingReason?: PipSession['waitingReason']) { sessions = sessions.map(session => session.id === focused ? { ...session, state, waitingReason } : session); await render(); @@ -199,14 +191,13 @@ describe('Pip sidebar interactions', () => { expect(cancelComment).not.toHaveBeenCalled(); }); - it('leaves the AI cooldown to main and shows the reason it gives back', async () => { + it('leaves the AI cooldown to main and keeps the local line when it declines', async () => { const comment = vi.fn() .mockResolvedValueOnce({ status: 'ready', line: 'First quip.', model: 'gpt-6-luna', reason: null }) .mockResolvedValueOnce({ status: 'paused', line: null, model: null, reason: 'Taking a breather between AI comments.' }); vi.stubGlobal('electronAPI', { pip: { comment, cancelComment: vi.fn().mockResolvedValue(undefined) } }); settings = { ...settings, aiComments: true }; await render(); - await click('.pip-options-toggle'); await state('waiting', 'permission'); await advance(600); expect(line()).toBe('First quip.'); @@ -214,7 +205,6 @@ describe('Pip sidebar interactions', () => { await state('waiting', 'permission'); await advance(600); expect(comment).toHaveBeenCalledTimes(2); - expect(container.querySelector('.pip-ai-status')?.textContent).toBe('Taking a breather between AI comments.'); expect(line()).not.toBe('First quip.'); }); @@ -233,67 +223,20 @@ describe('Pip sidebar interactions', () => { expect(line()).toBe('Marathon done.'); }); - it('keeps AI requests off by default and exposes separate prompt consent', async () => { + it('keeps AI requests off by default and sends configuration to Settings', async () => { const comment = vi.fn(); vi.stubGlobal('electronAPI', { pip: { comment } }); await render(); await state('waiting', 'permission'); await advance(600); expect(comment).not.toHaveBeenCalled(); - await click('.pip-options-toggle'); - expect(container.querySelector('.pip-options-toggle')?.textContent).toBe('Pip options'); - expect(aiSelect().value).toBe('off'); - await choose(aiSelect(), 'codex'); - expect(save).toHaveBeenLastCalledWith({ aiComments: true, aiBackend: 'codex' }); - expect(container.textContent).not.toContain('Share submitted prompts'); - settings = { ...settings, aiComments: true }; - await render(); - expect(container.textContent).toContain('Share submitted prompts'); - expect(container.textContent).toContain('to OpenAI'); - await choose(aiSelect(), 'off'); - expect(save).toHaveBeenLastCalledWith({ aiComments: false }); - }); - - it('checks the chosen backend when it is picked and names its recipient', async () => { - const backendStatus = vi.fn(async (backend: string) => backend === 'claude' - ? { backend, ready: true, detail: 'Signed in with Claude Max. Quips use Claude Haiku.' } - : { backend, ready: false, detail: 'Sign in to Codex with ChatGPT to enable AI quips.' }); - vi.stubGlobal('electronAPI', { pip: { comment: vi.fn(), cancelComment: vi.fn(), backendStatus } }); - settings = { ...settings, aiComments: true, aiBackend: 'codex' }; - await render(); - expect(backendStatus).not.toHaveBeenCalled(); - await click('.pip-options-toggle'); - expect(backendStatus).toHaveBeenLastCalledWith('codex'); - expect(container.querySelector('.pip-ai-backend')?.textContent).toContain('Sign in to Codex'); - expect(container.querySelector('.pip-ai-backend')?.dataset.ready).toBe('false'); - await choose(aiSelect(), 'claude'); - expect(save).toHaveBeenLastCalledWith({ aiComments: true, aiBackend: 'claude' }); - settings = { ...settings, aiBackend: 'claude' }; - await render(); - expect(backendStatus).toHaveBeenLastCalledWith('claude'); - expect(container.querySelector('.pip-ai-backend')?.textContent).toBe('Signed in with Claude Max. Quips use Claude Haiku.'); - expect(container.textContent).toContain('to Anthropic'); - expect(container.textContent).toContain('Haiku only'); - }); - - it('asks for a quip on demand with Try a quip', async () => { - const comment = vi.fn().mockResolvedValue({ status: 'ready', line: 'Testing, testing.', model: 'claude-haiku-5-5', reason: null }); - vi.stubGlobal('electronAPI', { pip: { comment, cancelComment: vi.fn().mockResolvedValue(undefined), backendStatus: vi.fn(() => new Promise(() => {})) } }); - settings = { ...settings, aiComments: true, aiBackend: 'claude' }; - await render(); - await click('.pip-options-toggle'); - expect(container.querySelector('.pip-ai-backend')?.textContent).toBe('Checking sign-in…'); - await click('.pip-try-quip'); - const local = line(); - expect(local).not.toBe('Testing, testing.'); - await advance(600); - expect(comment).toHaveBeenCalledWith({ event: 'hello', sessionId: 'a' }); - expect(line()).toBe('Testing, testing.'); - expect(container.querySelector('.pip-ai-status')?.textContent).toBe('Quip via claude-haiku-5-5'); - settings = { ...settings, quiet: true }; - await render(); - expect(container.querySelector('.pip-try-quip')?.disabled).toBe(true); + expect(container.querySelector('select')).toBeNull(); + expect(container.textContent).not.toContain('Pip options'); + await click('[aria-label="Pip settings"]'); + expect(openSettings).toHaveBeenCalledTimes(1); + expect(save).not.toHaveBeenCalled(); }); + it('follows real focus and lets keyboard-compatible petting respond immediately', async () => { await render(); expect(panel().dataset.mood).toBe('busy'); @@ -374,19 +317,10 @@ describe('Pip sidebar interactions', () => { expect(line()).toBe('Finally. My performance review.'); }); - it('saves presentation controls, collapse, and hide through the parent', async () => { + it('saves quiet, collapse, and hide through the parent', async () => { await render(); await click('.pip-quiet input'); expect(save).toHaveBeenLastCalledWith({ quiet: true }); - await click('.pip-options-toggle'); - await act(async () => { - const select = container.querySelector('select')!; - select.value = 'sweet'; - select.dispatchEvent(new Event('change', { bubbles: true })); - }); - expect(save).toHaveBeenLastCalledWith({ personality: 'sweet' }); - await click('.pip-options input'); - expect(save).toHaveBeenLastCalledWith({ motion: false }); await click('.pip-heading'); expect(save).toHaveBeenLastCalledWith({ collapsed: true }); await click('[aria-label="Hide Pip"]'); @@ -640,10 +574,6 @@ describe('Pip sidebar interactions', () => { const update: PipNudge = { key: 'update:0.8.0', kind: 'updateAvailable', detail: 'v0.8.0' }; await render(); expect(feed.onChange).toBeNull(); - await click('.pip-options-toggle'); - const toggle = Array.from(container.querySelectorAll('label')).find(label => label.textContent?.includes('Operational nudges'))!.querySelector('input')!; - await act(async () => toggle.click()); - expect(save).toHaveBeenLastCalledWith({ nudges: true }); settings = { ...settings, nudges: true }; await render(); expect(feed.onChange).not.toBeNull(); @@ -681,7 +611,7 @@ describe('Pip sidebar interactions', () => { it('shows a nudge as posture only in quiet mode, and passes the update version to the feed', async () => { settings = { ...settings, nudges: true, quiet: true }; await act(async () => root.render(createElement(PipPanel, { - settings, sessions, activeSessionId: focused, updateVersion: '0.8.0', busy: false, onSettingsChange: save, onActivateSession: activate, + settings, sessions, activeSessionId: focused, updateVersion: '0.8.0', busy: false, onSettingsChange: save, onOpenSettings: openSettings, onActivateSession: activate, }))); expect(feed.updateVersion).toBe('0.8.0'); await nudge({ key: 'vault:soon', kind: 'vaultExpiring', detail: '5 minutes' }); diff --git a/src/renderer/components/sidebar/PipPanel.tsx b/src/renderer/components/sidebar/PipPanel.tsx index dfff363..a9a95a9 100644 --- a/src/renderer/components/sidebar/PipPanel.tsx +++ b/src/renderer/components/sidebar/PipPanel.tsx @@ -5,9 +5,6 @@ import { PIP_MOOD_LABELS, pipSessionLabel, type PipSession } from '../../lib/pip import type { PipSettings } from '../../lib/pip-settings'; import type { PipNudge } from '../../lib/pip-nudges'; import { PipNudgeFeed } from './PipNudgeFeed'; -import { usePipBackendStatus } from '../../hooks/usePipBackendStatus'; -import { CLI_TOOL_REGISTRY } from '../../../shared/cli-tools'; -import type { PipAiBackend } from '../../../shared/pip'; import './pip-panel.css'; interface PipPanelProps { @@ -20,6 +17,8 @@ interface PipPanelProps { updateVersion?: string | null; busy: boolean; onSettingsChange: (patch: Partial) => Promise; + /** Opens Settings → Pip, where personality, nudges and AI quips are configured. */ + onOpenSettings: () => void; onActivateSession: (sessionId: string) => void; } @@ -41,27 +40,11 @@ function PipArtwork() { const NO_NUDGES: readonly PipNudge[] = []; -const BACKEND_HELP: Readonly> = { - codex: 'Uses your local Codex ChatGPT sign-in and subscription allowance. Luna only; up to 12 quips/hour.', - claude: 'Uses your local Claude Code subscription sign-in and allowance. Haiku only; up to 12 quips/hour.', -}; - -function pipActivityStatus(quiet: boolean, comments: ReturnType['comments']): string { - if (quiet) return 'AI paused while Quiet is on.'; - if (comments.pending) return 'Thinking of a quip…'; - if (comments.result?.reason) return comments.result.reason; - return comments.result?.model ? `Quip via ${comments.result.model}` : 'AI on. Waiting for a session moment.'; -} - -export function PipPanel({ settings, sessions, activeSessionId, childCounts, updateVersion = null, busy, onSettingsChange, onActivateSession }: Readonly) { +export function PipPanel({ settings, sessions, activeSessionId, childCounts, updateVersion = null, busy, onSettingsChange, onOpenSettings, onActivateSession }: Readonly) { const [nudges, setNudges] = useState(NO_NUDGES); const receiveNudges = useCallback((next: readonly PipNudge[]) => setNudges(next), []); const pip = usePip(sessions, activeSessionId, settings, childCounts, nudges); const contentId = useId(); - const optionsId = useId(); - const [optionsOpen, setOptionsOpen] = useState(false); - const backend = usePipBackendStatus(settings.aiBackend, pip.active && optionsOpen && settings.aiComments); - const recipient = CLI_TOOL_REGISTRY[settings.aiBackend].pipQuips?.recipient ?? 'the AI provider'; const waiting = sessions.filter(session => session.id !== activeSessionId && session.state === 'waiting'); const nextWaiting = waiting.find(session => session.waitingReason === 'permission') ?? waiting[0]; const update = (patch: Partial) => { void onSettingsChange(patch); }; @@ -82,6 +65,8 @@ export function PipPanel({ settings, sessions, activeSessionId, childCounts, upd {settings.collapsed && waitingButton} + @@ -99,41 +84,6 @@ export function PipPanel({ settings, sessions, activeSessionId, childCounts, upd {pip.following} {waitingButton ?? {PIP_MOOD_LABELS[pip.mood]}} - - {optionsOpen &&
- - - -

One comment when Vault sign-in is about to expire, a quota passes 90%, a usage budget is crossed, or an update is available. Local only.

- -

{settings.aiComments ? BACKEND_HELP[settings.aiBackend] : 'Local quips only. Choose Codex or Claude for occasional generated comments.'}

- {settings.aiComments && <> - - {backend.checking ? 'Checking sign-in…' : backend.status?.detail ?? ''} - - -

Asks for one quip now. It counts toward the hourly limit.

- -

Sends up to 400 characters from the latest local Claude, Codex or OpenCode prompt to {recipient} for specific jokes. Common secrets are scrubbed; private text can remain. Draft typing and terminal output stay local. Choosing another AI backend turns this off.

- {pipActivityStatus(settings.quiet, pip.comments)} - } -
} } ; } diff --git a/src/renderer/components/sidebar/pip-panel.css b/src/renderer/components/sidebar/pip-panel.css index 02bc59e..0637c2d 100644 --- a/src/renderer/components/sidebar/pip-panel.css +++ b/src/renderer/components/sidebar/pip-panel.css @@ -11,7 +11,7 @@ .pip-header { display: flex; flex-wrap: wrap; align-items: center; gap: 0 6px; padding: 3px 8px; } .pip-heading { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 44px; padding: 6px 0; color: var(--text-secondary); background: transparent; border: 0; font: inherit; font-weight: 600; text-align: left; cursor: pointer; } .pip-quiet { display: flex; align-items: center; gap: 4px; color: var(--text-secondary); cursor: pointer; } -.pip-quiet input, .pip-options input { accent-color: var(--accent); } +.pip-quiet input { accent-color: var(--accent); } .pip-panel button:disabled, .pip-panel input:disabled, .pip-panel select:disabled { opacity: .5; cursor: default; } .pip-panel :is(button, input, select):focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } .pip-content { padding: 0 10px 8px; } @@ -70,19 +70,6 @@ .pip-mood { text-align: right; flex: 0 1 auto; } .pip-waiting { display: flex; align-items: center; gap: 4px; flex-shrink: 0; padding: 3px 5px; border: 1px solid var(--border-color); border-radius: var(--control-radius); background: transparent; color: var(--text-primary); font: inherit; cursor: pointer; } .pip-waiting:hover { background: var(--bg-hover); } -.pip-options-toggle { margin-top: 4px; padding: 4px 0; border: 0; background: transparent; color: var(--text-secondary); font: inherit; cursor: pointer; text-align: left; } -.pip-options-toggle:hover { color: var(--text-primary); } -.pip-options { display: flex; flex-direction: column; gap: 8px; margin-top: 6px; padding-top: 8px; border-top: 1px solid var(--border-color); } -.pip-options label { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; color: var(--text-secondary); } -.pip-options select { flex: 1; min-width: 0; max-width: 100%; padding: 3px; color: var(--text-primary); background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: var(--control-radius); font: inherit; } -.pip-options-help { margin: -2px 0 2px; color: var(--text-secondary); line-height: 1.5; } -.pip-ai-status { display: block; color: var(--text-secondary); line-height: 1.5; } -.pip-ai-backend { display: block; color: var(--text-secondary); line-height: 1.5; } -.pip-ai-backend:empty { display: none; } -.pip-ai-backend[data-ready="false"] { color: var(--status-waiting); } -.pip-try-quip { align-self: flex-start; padding: 3px 8px; border: 1px solid var(--border-color); border-radius: var(--control-radius); background: transparent; color: var(--text-primary); font: inherit; cursor: pointer; } -.pip-try-quip:hover:not(:disabled) { background: var(--bg-hover); } -.pip-try-quip:disabled { opacity: .5; cursor: default; } .pip-panel[data-motion="false"] :is(.pip-creature, .pip-tail, .pip-eye, .pip-paw) { animation: none; } .pip-panel[data-motion="false"] :is(.pip-head, .pip-eye, .pip-pupil, .pip-keyboard) { transition: none; } @keyframes pip-breathe { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-2px); } } diff --git a/src/renderer/hooks/usePip.ts b/src/renderer/hooks/usePip.ts index c708d32..803cd7f 100644 --- a/src/renderer/hooks/usePip.ts +++ b/src/renderer/hooks/usePip.ts @@ -261,7 +261,5 @@ export function usePip( emote, following: session ? `Following ${pipSessionLabel(session)}` : 'Keeping you company', pet: () => { sleeping.current = false; setNapping(false); showEvent({ kind: 'pet', label: '' }, true); }, - /** Ask for an AI quip now, so sign-in can be confirmed without waiting for a session moment. */ - tryQuip: () => { rouse.current(); showEvent({ kind: 'hello', label: '' }, true); }, }; } diff --git a/src/renderer/lib/pip-behavior.test.ts b/src/renderer/lib/pip-behavior.test.ts index 76b6ab5..1d97cb7 100644 --- a/src/renderer/lib/pip-behavior.test.ts +++ b/src/renderer/lib/pip-behavior.test.ts @@ -237,6 +237,14 @@ describe('Pip presentation preferences and reactions', () => { expect(readPipSettings('{"enabled":"true","collapsed":0,"quiet":{},"motion":null,"personality":"unknown"}')).toEqual(DEFAULT_PIP_SETTINGS); }); + it('keeps the AI limits inside their bounds and falls back for anything that is not a number', () => { + expect(readPipSettings('{"aiHourlyLimit":20,"aiCooldownSeconds":300}')).toMatchObject({ aiHourlyLimit: 20, aiCooldownSeconds: 300 }); + expect(readPipSettings('{"aiHourlyLimit":9999,"aiCooldownSeconds":1}')).toMatchObject({ aiHourlyLimit: 30, aiCooldownSeconds: 30 }); + expect(readPipSettings('{"aiHourlyLimit":0,"aiCooldownSeconds":99999}')).toMatchObject({ aiHourlyLimit: 1, aiCooldownSeconds: 1800 }); + expect(readPipSettings('{"aiHourlyLimit":4.6,"aiCooldownSeconds":"60"}')).toMatchObject({ aiHourlyLimit: 5, aiCooldownSeconds: 120 }); + expect(readPipSettings('{"aiHourlyLimit":null}')).toMatchObject({ aiHourlyLimit: 12, aiCooldownSeconds: 120 }); + }); + it('uses labels and platform-neutral directory fallbacks', () => { expect(pipSessionLabel()).toBe('your sessions'); expect(pipSessionLabel({ ...session('a'), label: '', workingDir: 'C:\\repo\\tether\\' })).toBe('tether'); diff --git a/src/renderer/styles/global.css b/src/renderer/styles/global.css index 6d65981..498002e 100644 --- a/src/renderer/styles/global.css +++ b/src/renderer/styles/global.css @@ -2067,6 +2067,10 @@ summary.form-label, .settings-advanced > summary { } summary.form-label::marker, .settings-advanced > summary::marker { color: var(--accent); } .settings-advanced { border-top: 1px solid var(--border-color); margin-top: var(--space-5); } +.pip-settings-limits { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--space-3); margin-top: 12px; } +.pip-settings-status { display: block; } +.pip-settings-status:empty { display: none; } +.pip-settings-status[data-ready="false"] { color: var(--status-waiting); } .settings-advanced[open] > summary { margin-bottom: var(--space-3); } .settings-section-label { diff --git a/src/shared/pip.ts b/src/shared/pip.ts index c289600..e45d71f 100644 --- a/src/shared/pip.ts +++ b/src/shared/pip.ts @@ -14,11 +14,25 @@ export interface PipSettings { sharePrompts: boolean; /** Mention Vault expiry, quota, budget and updates that the sidebar already shows. */ nudges: boolean; + /** Most AI quip requests in any rolling hour, including Try a quip. */ + aiHourlyLimit: number; + /** Shortest wait between two automatic AI quips. */ + aiCooldownSeconds: number; +} + +/** Bounds for the two AI limits. Main reads the saved value through `readPipSettings`, so these hold there too. */ +export const PIP_AI_HOURLY_LIMIT_RANGE = { min: 1, max: 30, fallback: 12 } as const; +export const PIP_AI_COOLDOWN_SECONDS_RANGE = { min: 30, max: 1800, fallback: 120 } as const; + +function boundedInteger(value: unknown, range: { min: number; max: number; fallback: number }): number { + if (typeof value !== 'number' || !Number.isFinite(value)) return range.fallback; + return Math.min(range.max, Math.max(range.min, Math.round(value))); } export const PIP_SETTINGS_KEY = 'sidebarPet'; export const DEFAULT_PIP_SETTINGS: PipSettings = { enabled: false, collapsed: false, quiet: false, motion: true, personality: 'dry', aiComments: false, aiBackend: 'codex', sharePrompts: false, nudges: false, + aiHourlyLimit: PIP_AI_HOURLY_LIMIT_RANGE.fallback, aiCooldownSeconds: PIP_AI_COOLDOWN_SECONDS_RANGE.fallback, }; export function readPipSettings(raw: string | null): PipSettings { @@ -36,14 +50,14 @@ export function readPipSettings(raw: string | null): PipSettings { aiBackend: saved.aiBackend === 'claude' ? 'claude' : 'codex', sharePrompts: saved.sharePrompts === true, nudges: saved.nudges === true, + aiHourlyLimit: boundedInteger(saved.aiHourlyLimit, PIP_AI_HOURLY_LIMIT_RANGE), + aiCooldownSeconds: boundedInteger(saved.aiCooldownSeconds, PIP_AI_COOLDOWN_SECONDS_RANGE), }; } catch { return { ...DEFAULT_PIP_SETTINGS }; } } -export const PIP_AI_COOLDOWN_MS = 120_000; -export const PIP_AI_HOURLY_LIMIT = 12; /** * Events that may ask for an AI quip. `longTurn` is the only PR 3 reaction here: crashes are not * joke material, helpers joining is frequent, and nudges stay local by design. `hello` comes only