From 1323edf58c77aa488457ce1ef7cfd2337140e603 Mon Sep 17 00:00:00 2001 From: Max Thomas Date: Thu, 12 Nov 2026 15:53:49 -0600 Subject: [PATCH 1/2] feat(pip): share prompt excerpts from local OpenCode sessions With Share submitted prompts on, Pip could only quote local Claude and Codex prompts. OpenCode sessions were quip subjects with activity only. Local OpenCode sessions now contribute the same bounded excerpt, so all three first-class CLIs get the same outcome. The excerpt comes from OpenCode's own database, which native usage has already attributed to the session, opened read-only. It takes two bounded, indexed queries: the newest user message from the past five minutes, then that message's text parts. Synthetic parts (OpenCode's reminders and attachments) and non-text parts are skipped, and only typed scalars leave SQLite. The same 400-character limit and scrubbing apply, now shared as scrubPromptExcerpt. `opencode export` was considered and rejected: it serialises the whole session (1.5 MB for a 101-message session here) and runs CLI middleware first, just to read one prompt. SSH and Coder sessions, Copilot and Custom still share activity only. The prompt routing moves into readSessionPrompt, and readRecentPrompt loses its existing Sonar warnings along the way. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- src/docs/settings.md | 2 +- src/main/ipc/pip-handlers.test.ts | 37 ++++++++- src/main/ipc/pip-handlers.ts | 37 ++++++--- src/main/pip/prompt-context.test.ts | 76 +++++++++++++++++- src/main/pip/prompt-context.ts | 81 +++++++++++++++++--- src/main/usage/native-opencode-usage.test.ts | 2 + src/main/usage/usage-service.ts | 7 ++ src/renderer/components/sidebar/PipPanel.tsx | 2 +- 9 files changed, 219 insertions(+), 27 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 167627a2..650c7e0a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -175,7 +175,7 @@ When sharing is enabled, remote SSH/Coder session metadata is narrated through J The GIF panel reads only selected local image folders and ships no media. Pip's local reactions use session/focus metadata and a text-free typing signal. Both are off by default and pause hidden work/reduce motion as documented in [Settings](../src/docs/settings.md#appearance). -Pip AI comments are another opt-in. The user picks a backend behind `PipCommentBackend` (`src/main/pip/backends/`): a bounded temporary Codex conversation with ChatGPT sign-in, or a one-shot Claude Code Haiku prompt with subscription sign-in, no tools, no settings sources (so no hooks), and no saved session. Main owns the cooldown and hourly cap. Activity-only context excludes paths, labels, draft text, and terminal output. Separate prompt-sharing consent permits a scrubbed, bounded excerpt from an attributed recent local Claude/Codex transcript. Tether saves neither excerpts nor generated comments. Failure or unavailable models fall back to local quips. +Pip AI comments are another opt-in. The user picks a backend behind `PipCommentBackend` (`src/main/pip/backends/`): a bounded temporary Codex conversation with ChatGPT sign-in, or a one-shot Claude Code Haiku prompt with subscription sign-in, no tools, no settings sources (so no hooks), and no saved session. Main owns the cooldown and hourly cap. Activity-only context excludes paths, labels, draft text, and terminal output. Separate prompt-sharing consent permits a scrubbed, bounded excerpt from an attributed recent local Claude/Codex transcript, or from the newest user message in a local OpenCode session's database (read-only, two bounded indexed queries, synthetic and non-text parts skipped). Tether saves neither excerpts nor generated comments. Failure or unavailable models fall back to local quips. ## Desktop Security and Packaging diff --git a/src/docs/settings.md b/src/docs/settings.md index 9794d5d4..11efb817 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -198,7 +198,7 @@ Local reactions use session labels, focus, status metadata, and a text-free typi - 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. - 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**. Remote sessions and other 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. +- 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. ## Terminal diff --git a/src/main/ipc/pip-handlers.test.ts b/src/main/ipc/pip-handlers.test.ts index 2b87d438..e51c1a64 100644 --- a/src/main/ipc/pip-handlers.test.ts +++ b/src/main/ipc/pip-handlers.test.ts @@ -3,7 +3,7 @@ import type { BrowserWindow } from 'electron'; const mocks = vi.hoisted(() => ({ handlers: new Map unknown>(), - config: {} as Record, generate: vi.fn(), claude: vi.fn(), status: vi.fn(), prompt: vi.fn(), session: vi.fn(), environment: vi.fn(), transcript: vi.fn(), + config: {} as Record, generate: vi.fn(), claude: vi.fn(), status: vi.fn(), prompt: vi.fn(), opencodePrompt: vi.fn(), opencodeDb: vi.fn(), session: vi.fn(), environment: vi.fn(), transcript: vi.fn(), visible: true, minimized: false, })); vi.mock('electron', () => ({ app: { getPath: () => '/neutral' }, ipcMain: { handle: (key: string, fn: never) => mocks.handlers.set(key, fn) } })); @@ -12,10 +12,10 @@ vi.mock('../db/database', () => ({ getDb: () => ({ config: mocks.config }) })); vi.mock('../pip/backends', () => ({ pipBackend: (id: string) => ({ id, generate: id === 'claude' ? mocks.claude : mocks.generate, status: (cwd: string, signal: AbortSignal) => mocks.status(id, cwd, signal) }), })); -vi.mock('../pip/prompt-context', () => ({ readRecentPrompt: mocks.prompt })); +vi.mock('../pip/prompt-context', () => ({ readRecentPrompt: mocks.prompt, readRecentOpenCodePrompt: mocks.opencodePrompt })); vi.mock('../session/session-manager', () => ({ sessionManager: { getSession: mocks.session } })); vi.mock('../db/environment-repo', () => ({ getEnvironment: mocks.environment })); -vi.mock('../usage/usage-service', () => ({ usageService: { getLocalTranscriptPath: mocks.transcript } })); +vi.mock('../usage/usage-service', () => ({ usageService: { getLocalTranscriptPath: mocks.transcript, getLocalOpenCodeDatabase: mocks.opencodeDb } })); import { registerPipHandlers, validatePipBackend, validatePipRequest } from './pip-handlers'; import { DEFAULT_PIP_SETTINGS, PIP_SETTINGS_KEY } from '../../shared/pip'; import { IPC } from '../../shared/constants'; @@ -35,6 +35,8 @@ beforeEach(() => { mocks.environment.mockReturnValue({ type: 'local' }); mocks.transcript.mockReturnValue('/attributed/rollout.jsonl'); mocks.prompt.mockResolvedValue('Submitted idea'); + mocks.opencodeDb.mockReturnValue('/data/opencode/opencode.db'); + mocks.opencodePrompt.mockReturnValue('OpenCode idea'); registerPipHandlers({ mainWindow: win, send: vi.fn() }); }); @@ -106,4 +108,33 @@ describe('Pip consent and IPC boundary', () => { await handler(trusted, 'claude'); expect(signals[0].aborted).toBe(true); }); + it('reads a local OpenCode prompt from its attributed database', async () => { + prefs({ sharePrompts: true }); + mocks.session.mockReturnValue({ environmentId: 'local', cliTool: 'opencode', toolSessionId: 'ses_1' }); + await mocks.handlers.get(IPC.PIP_COMMENT)!(trusted, request); + expect(mocks.opencodeDb).toHaveBeenCalledWith('ses_1'); + expect(mocks.opencodePrompt).toHaveBeenCalledWith('/data/opencode/opencode.db', 'ses_1'); + expect(mocks.transcript).not.toHaveBeenCalled(); + expect(mocks.generate).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'OpenCode idea' }), expect.any(AbortSignal)); + }); + it('shares no prompt for remote OpenCode, Copilot or Custom sessions, or OpenCode without a database', async () => { + prefs({ sharePrompts: true }); + mocks.session.mockReturnValue({ environmentId: 'coder', cliTool: 'opencode', toolSessionId: 'ses_1' }); + mocks.environment.mockReturnValue({ type: 'coder' }); + // Try a quip skips the cooldown, so every call below reaches the backend. + const hello = { event: 'hello', sessionId: 'a' }; + await mocks.handlers.get(IPC.PIP_COMMENT)!(trusted, hello); + mocks.environment.mockReturnValue({ type: 'local' }); + for (const cliTool of ['copilot', 'custom']) { + mocks.session.mockReturnValue({ environmentId: 'local', cliTool, toolSessionId: 'native-id' }); + await mocks.handlers.get(IPC.PIP_COMMENT)!(trusted, hello); + } + mocks.opencodeDb.mockReturnValue(null); + mocks.session.mockReturnValue({ environmentId: 'local', cliTool: 'opencode', toolSessionId: 'ses_1' }); + await mocks.handlers.get(IPC.PIP_COMMENT)!(trusted, hello); + expect(mocks.generate).toHaveBeenCalledTimes(4); + expect(mocks.opencodePrompt).not.toHaveBeenCalled(); + expect(mocks.prompt).not.toHaveBeenCalled(); + for (const call of mocks.generate.mock.calls) expect(call[0]).toMatchObject({ prompt: null }); + }); }); diff --git a/src/main/ipc/pip-handlers.ts b/src/main/ipc/pip-handlers.ts index 956f7864..c48b6a0a 100644 --- a/src/main/ipc/pip-handlers.ts +++ b/src/main/ipc/pip-handlers.ts @@ -8,7 +8,7 @@ import type { HandlerContext } from './helpers'; import { getDb } from '../db/database'; import { pipBackend } from '../pip/backends'; import { PipCommentService, setPipCommentService } from '../pip/comment-service'; -import { readRecentPrompt } from '../pip/prompt-context'; +import { readRecentOpenCodePrompt, readRecentPrompt } from '../pip/prompt-context'; import { sessionManager } from '../session/session-manager'; import { getEnvironment } from '../db/environment-repo'; import { usageService } from '../usage/usage-service'; @@ -35,22 +35,37 @@ async function pipWorkspace(): Promise { return cwd; } +/** + * The latest prompt submitted in a local session, from the source usage already attributed to it. + * Remote sessions, and CLIs without a supported local source (Copilot, Custom), share activity only. + */ +async function readSessionPrompt(sessionId: string): Promise { + const session = sessionManager.getSession(sessionId); + const env = session?.environmentId ? getEnvironment(session.environmentId) : null; + if (!session || (session.environmentId && env?.type !== 'local')) return null; + const id = session.usageSessionId ?? session.toolSessionId ?? session.claudeSessionId; + if (!id) return null; + const tool = session.cliTool ?? 'claude'; + if (tool === 'claude' || tool === 'codex') { + const file = usageService.getLocalTranscriptPath(id); + return file ? readRecentPrompt(file).catch(() => null) : null; + } + if (tool === 'opencode') { + const db = usageService.getLocalOpenCodeDatabase(id); + return db ? readRecentOpenCodePrompt(db, id) : null; + } + return null; +} + export function registerPipHandlers(ctx: HandlerContext): void { const ipc = createTrustedIpc(ctx.mainWindow); const service = new PipCommentService({ settings: () => readPipSettings(getDb().config[PIP_SETTINGS_KEY] ?? null), async generate(request, settings, signal) { const cwd = await pipWorkspace(); - let prompt: string | null = null; - if (settings.sharePrompts && request.sessionId && request.event !== 'attention') { - const session = sessionManager.getSession(request.sessionId); - const env = session?.environmentId ? getEnvironment(session.environmentId) : null; - if (session && (!session.environmentId || env?.type === 'local') && ['claude', 'codex'].includes(session.cliTool ?? 'claude')) { - const id = session.usageSessionId ?? session.toolSessionId ?? session.claudeSessionId; - const file = id ? usageService.getLocalTranscriptPath(id) : null; - if (file) prompt = await readRecentPrompt(file).catch(() => null); - } - } + // Attention is about another session, so it never carries this one's prompt. + const prompt = settings.sharePrompts && request.sessionId && request.event !== 'attention' + ? await readSessionPrompt(request.sessionId) : null; return pipBackend(settings.aiBackend).generate({ cwd, event: request.event, personality: settings.personality, prompt }, signal); }, }); diff --git a/src/main/pip/prompt-context.test.ts b/src/main/pip/prompt-context.test.ts index d95c432a..7d3d56ca 100644 --- a/src/main/pip/prompt-context.test.ts +++ b/src/main/pip/prompt-context.test.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, it, expect, vi } from 'vitest'; vi.mock('../diagnostics/scrub', () => ({ scrubLogText: (text: string) => text })); -import { readRecentPrompt } from './prompt-context'; +import { readRecentOpenCodePrompt, readRecentPrompt } from './prompt-context'; const roots: string[] = []; afterEach(async () => { for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); }); async function transcript(rows: unknown[]) { @@ -40,3 +40,77 @@ describe('Pip submitted prompt context', () => { expect((await readRecentPrompt(file, now))?.length).toBe(400); }); }); + +async function opencodeDb(rows: { messages: [string, string, number, unknown][]; parts: [string, string, string, unknown][] }) { + const { DatabaseSync } = await import('node:sqlite'); + const root = await mkdtemp(path.join(os.tmpdir(), 'tether-pip-oc-')); + roots.push(root); + const file = path.join(root, 'opencode.db'); + const db = new DatabaseSync(file); + db.exec('CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT)'); + db.exec('CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT)'); + for (const [id, session, time, data] of rows.messages) { + db.prepare('INSERT INTO message VALUES (?, ?, ?, ?, ?)').run(id, session, time, time, typeof data === 'string' ? data : JSON.stringify(data)); + } + for (const [id, message, session, data] of rows.parts) { + db.prepare('INSERT INTO part VALUES (?, ?, ?, 0, 0, ?)').run(id, message, session, typeof data === 'string' ? data : JSON.stringify(data)); + } + db.close(); + return file; +} + +describe('Pip submitted prompt context from OpenCode', () => { + it('uses the newest recent user message in this session, without synthetic or non-text parts', async () => { + const now = Date.now(); + const file = await opencodeDb({ + messages: [ + ['msg_1', 'ses_a', now - 60_000, { role: 'user' }], + ['msg_2', 'ses_a', now - 30_000, { role: 'user' }], + ['msg_3', 'ses_a', now - 10_000, { role: 'assistant' }], + ['msg_4', 'ses_b', now - 5_000, { role: 'user' }], + ], + parts: [ + ['prt_1', 'msg_1', 'ses_a', { type: 'text', text: 'Older prompt' }], + ['prt_2', 'msg_2', 'ses_a', { type: 'text', text: 'DO NOT SHARE', synthetic: true }], + ['prt_3', 'msg_2', 'ses_a', { type: 'text', text: 'Tidy the cables. api_key=private-value' }], + ['prt_4', 'msg_2', 'ses_a', { type: 'file', text: 'FILE CONTENTS' }], + ['prt_5', 'msg_3', 'ses_a', { type: 'text', text: 'ASSISTANT REPLY' }], + ['prt_6', 'msg_4', 'ses_b', { type: 'text', text: 'Other session' }], + ], + }); + expect(readRecentOpenCodePrompt(file, 'ses_a', now)).toBe('Tidy the cables. [REDACTED]'); + expect(readRecentOpenCodePrompt(file, 'ses_b', now)).toBe('Other session'); + }); + + it('ignores stale prompts, malformed rows, unknown sessions and unusable paths, and bounds the excerpt', async () => { + const now = Date.now(); + const file = await opencodeDb({ + messages: [ + ['msg_1', 'ses_old', now - 400_000, { role: 'user' }], + ['msg_2', 'ses_bad', now, 'not json'], + ['msg_3', 'ses_obj', now, { role: { nested: 'user' } }], + ['msg_4', 'ses_long', now, { role: 'user' }], + ], + parts: [ + ['prt_1', 'msg_1', 'ses_old', { type: 'text', text: 'OLD' }], + ['prt_2', 'msg_2', 'ses_bad', { type: 'text', text: 'BAD' }], + ['prt_3', 'msg_3', 'ses_obj', { type: 'text', text: 'OBJECT ROLE' }], + ['prt_4', 'msg_4', 'ses_long', { type: 'text', text: 'x'.repeat(5000) }], + ], + }); + for (const id of ['ses_old', 'ses_bad', 'ses_obj', 'ses_missing', '']) expect(readRecentOpenCodePrompt(file, id, now)).toBeNull(); + expect(readRecentOpenCodePrompt(file, 'ses_long', now)?.length).toBe(400); + expect(readRecentOpenCodePrompt('relative/opencode.db', 'ses_long', now)).toBeNull(); + expect(readRecentOpenCodePrompt(path.join(path.dirname(file), 'missing.db'), 'ses_long', now)).toBeNull(); + }); + + it('never writes to the database', async () => { + const now = Date.now(); + const file = await opencodeDb({ messages: [['msg_1', 'ses_a', now, { role: 'user' }]], parts: [['prt_1', 'msg_1', 'ses_a', { type: 'text', text: 'Hi' }]] }); + const { statSync } = await import('node:fs'); + const before = statSync(file).mtimeMs; + expect(readRecentOpenCodePrompt(file, 'ses_a', now)).toBe('Hi'); + expect(statSync(file).mtimeMs).toBe(before); + expect(require('node:fs').existsSync(`${file}-wal`)).toBe(false); + }); +}); diff --git a/src/main/pip/prompt-context.ts b/src/main/pip/prompt-context.ts index 9b8b58c6..8c9b9747 100644 --- a/src/main/pip/prompt-context.ts +++ b/src/main/pip/prompt-context.ts @@ -1,6 +1,27 @@ import { open } from 'node:fs/promises'; +import path from 'node:path'; import { scrubLogText } from '../diagnostics/scrub'; +/** How far back a submitted prompt may be, and how much of it may be shared. */ +export const PIP_PROMPT_MAX_AGE_MS = 5 * 60_000; +export const PIP_PROMPT_MAX_CHARS = 400; + +/** Scrubbing is best effort, not a promise that arbitrary secrets can be detected. */ +export function scrubPromptExcerpt(text: string): string { + return scrubLogText(text).replace(/\b(sk-[a-z0-9_-]{16,}|(?:password|token|api[_-]?key)\s*[:=]\s*\S+)/gi, '[REDACTED]') + .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '').slice(0, PIP_PROMPT_MAX_CHARS); +} + +/** A typed prompt from one Claude or Codex transcript row, or null for anything else (assistant, tool or meta rows). */ +function transcriptPrompt(row: Record | null): unknown { + if (row?.type === 'event_msg') { + const payload = row.payload as Record | undefined; + return payload?.type === 'user_message' ? payload.message : null; + } + if (row?.type === 'user' && !row.isMeta) return (row.message as Record | undefined)?.content; + return null; +} + /** Read only a bounded tail of an already-attributed local transcript. Never parse PTY output. */ export async function readRecentPrompt(filePath: string, now = Date.now()): Promise { const file = await open(filePath, 'r'); @@ -12,20 +33,62 @@ export async function readRecentPrompt(filePath: string, now = Date.now()): Prom const { bytesRead } = await file.read(buffer, 0, buffer.length, start); const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); if (start > 0) lines.shift(); - for (const line of lines.reverse()) { + // Newest first. + for (let index = lines.length - 1; index >= 0; index--) { let row; - try { row = JSON.parse(line); } catch { continue; } + try { row = JSON.parse(lines[index]); } catch { continue; } const time = Date.parse(row?.timestamp); - if (!Number.isFinite(time) || now - time > 5 * 60_000 || time > now + 1000) continue; - const text = row?.type === 'event_msg' && row?.payload?.type === 'user_message' - ? row.payload.message : row?.type === 'user' && !row.isMeta ? row.message?.content : null; - if (typeof text !== 'string' || !text.trim()) continue; - // Scrubbing is best effort, not a promise that arbitrary secrets can be detected. - return scrubLogText(text).replace(/\b(sk-[A-Za-z0-9_-]{16,}|(?:password|token|api[_-]?key)\s*[:=]\s*\S+)/gi, '[REDACTED]') - .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '').slice(0, 400); + if (!Number.isFinite(time) || now - time > PIP_PROMPT_MAX_AGE_MS || time > now + 1000) continue; + const text = transcriptPrompt(row); + if (typeof text === 'string' && text.trim()) return scrubPromptExcerpt(text); } return null; } finally { await file.close(); } } + +type Row = Record; +// Only typed scalars leave SQLite: the role of a message, and the type, text and synthetic flag of its parts. +const LATEST_USER_MESSAGE = `SELECT id FROM message + WHERE session_id = ? AND time_created >= ? AND time_created <= ? + AND json_valid(data) AND json_type(data, '$.role') = 'text' AND json_extract(data, '$.role') = 'user' + ORDER BY time_created DESC, id DESC LIMIT 1`; +const PROMPT_PARTS = `SELECT + CASE WHEN json_valid(data) AND json_type(data, '$.type') = 'text' THEN json_extract(data, '$.type') END AS type, + CASE WHEN json_valid(data) AND json_type(data, '$.text') = 'text' THEN substr(json_extract(data, '$.text'), 1, 4000) END AS text, + CASE WHEN json_valid(data) THEN json_type(data, '$.synthetic') END AS synthetic + FROM part WHERE session_id = ? AND message_id = ? ORDER BY id LIMIT 50`; + +/** + * The latest prompt typed into a local OpenCode session, from OpenCode's own database opened read-only. + * Two bounded, indexed queries: the newest user message from the past five minutes, then its text parts. + * Synthetic parts (OpenCode's own reminders and attachments) and every other part type are skipped. + */ +export function readRecentOpenCodePrompt(dbPath: string, sessionId: string, now = Date.now()): string | null { + if (!path.isAbsolute(dbPath) || !sessionId || sessionId.length > 200) return null; + let DatabaseSync: typeof import('node:sqlite').DatabaseSync; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + ({ DatabaseSync } = require('node:sqlite')); + } catch { + return null; + } + let db: import('node:sqlite').DatabaseSync | undefined; + try { + db = new DatabaseSync(dbPath, { readOnly: true, allowExtension: false, timeout: 1_000 }); + const message = db.prepare(LATEST_USER_MESSAGE).get(sessionId, now - PIP_PROMPT_MAX_AGE_MS, now + 1000) as Row | undefined; + if (!message || typeof message.id !== 'string') return null; + const parts = db.prepare(PROMPT_PARTS).all(sessionId, message.id) as Row[]; + const text = parts + .filter(part => part.type === 'text' && part.synthetic !== 'true' && typeof part.text === 'string') + .map(part => (part.text as string).trim()) + .filter(Boolean) + .join('\n'); + return text ? scrubPromptExcerpt(text) : null; + } catch { + return null; + } finally { + try { db?.close(); } catch { /* nothing was written */ } + } +} diff --git a/src/main/usage/native-opencode-usage.test.ts b/src/main/usage/native-opencode-usage.test.ts index bd78d08a..9a71f828 100644 --- a/src/main/usage/native-opencode-usage.test.ts +++ b/src/main/usage/native-opencode-usage.test.ts @@ -66,6 +66,8 @@ describe('native OpenCode service integration', () => { expect(service.getAll().daily).toContainEqual(expect.objectContaining({ date: '2026-10-14', totalCost: 0, inputTokens: 20 })); expect(mocks.db.usageSummaries[0]).toMatchObject({ usageSource: 'native-opencode', costSource: 'reported', filePath: dbPath }); expect(service.getLocalTranscriptPath('ses_native')).toBeNull(); + expect(service.getLocalOpenCodeDatabase('ses_native')).toBe(dbPath); + expect(service.getLocalOpenCodeDatabase('ses_unknown')).toBeNull(); }); it('refreshes a preloaded native session on track and preserves environment attribution', async () => { diff --git a/src/main/usage/usage-service.ts b/src/main/usage/usage-service.ts index 22caa6a3..b276634f 100644 --- a/src/main/usage/usage-service.ts +++ b/src/main/usage/usage-service.ts @@ -732,6 +732,13 @@ export class UsageService { return tracked && !tracked.remote && (tracked.cliTool === 'claude' || tracked.cliTool === 'codex') && tracked.filePath ? tracked.filePath : null; } + /** The local native OpenCode database that usage already attributed to this session, if any. */ + getLocalOpenCodeDatabase(sessionId: string): string | null { + const tracked = this.tracked.get(sessionId); + return tracked && !tracked.remote && tracked.cliTool === 'opencode' && tracked.usage.usageSource === 'native-opencode' && tracked.filePath + ? tracked.filePath : null; + } + getAll(): UsageInfo { const sessions: Record = {}; const allUsage: SessionUsage[] = []; diff --git a/src/renderer/components/sidebar/PipPanel.tsx b/src/renderer/components/sidebar/PipPanel.tsx index 807fea7e..bea3bc2f 100644 --- a/src/renderer/components/sidebar/PipPanel.tsx +++ b/src/renderer/components/sidebar/PipPanel.tsx @@ -130,7 +130,7 @@ export function PipPanel({ settings, sessions, activeSessionId, childCounts, upd

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

-

Sends up to 400 characters from the latest local Claude/Codex 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.

+

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)} } } From 60f998d7a8d154705774ec1a5a328c66c7767246 Mon Sep 17 00:00:00 2001 From: Max Thomas Date: Thu, 12 Nov 2026 15:53:35 -0600 Subject: [PATCH 2/2] fix(pip): use output elements for live status and Array.at for the last attempt Co-Authored-By: Claude Opus 5.5 --- src/main/pip/comment-service.ts | 2 +- src/renderer/components/sidebar/PipPanel.tsx | 6 +++--- src/renderer/components/sidebar/pip-panel.css | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/pip/comment-service.ts b/src/main/pip/comment-service.ts index 95f1bc10..52f43f96 100644 --- a/src/main/pip/comment-service.ts +++ b/src/main/pip/comment-service.ts @@ -23,7 +23,7 @@ export class PipCommentService { 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.'); // 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[this.attempts.length - 1] < PIP_AI_COOLDOWN_MS) { + if (request.event !== 'hello' && this.attempts.length && now - this.attempts.at(-1)! < PIP_AI_COOLDOWN_MS) { return paused('Taking a breather between AI comments.'); } this.attempts.push(now); diff --git a/src/renderer/components/sidebar/PipPanel.tsx b/src/renderer/components/sidebar/PipPanel.tsx index bea3bc2f..dfff363d 100644 --- a/src/renderer/components/sidebar/PipPanel.tsx +++ b/src/renderer/components/sidebar/PipPanel.tsx @@ -122,16 +122,16 @@ export function PipPanel({ settings, sessions, activeSessionId, childCounts, upd

{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)} + {pipActivityStatus(settings.quiet, pip.comments)} } } } diff --git a/src/renderer/components/sidebar/pip-panel.css b/src/renderer/components/sidebar/pip-panel.css index 9ef9ead4..02bc59ec 100644 --- a/src/renderer/components/sidebar/pip-panel.css +++ b/src/renderer/components/sidebar/pip-panel.css @@ -76,8 +76,8 @@ .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 { color: var(--text-secondary); line-height: 1.5; } -.pip-ai-backend { 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; }