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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
37 changes: 34 additions & 3 deletions src/main/ipc/pip-handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { BrowserWindow } from 'electron';

const mocks = vi.hoisted(() => ({
handlers: new Map<string, (event: unknown, ...args: unknown[]) => unknown>(),
config: {} as Record<string, string>, generate: vi.fn(), claude: vi.fn(), status: vi.fn(), prompt: vi.fn(), session: vi.fn(), environment: vi.fn(), transcript: vi.fn(),
config: {} as Record<string, string>, 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) } }));
Expand All @@ -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';
Expand All @@ -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() });
});

Expand Down Expand Up @@ -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 });
});
});
37 changes: 26 additions & 11 deletions src/main/ipc/pip-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -35,22 +35,37 @@ async function pipWorkspace(): Promise<string> {
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<string | null> {
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);
},
});
Expand Down
2 changes: 1 addition & 1 deletion src/main/pip/comment-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
76 changes: 75 additions & 1 deletion src/main/pip/prompt-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]) {
Expand Down Expand Up @@ -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: '<system-reminder>DO NOT SHARE</system-reminder>', 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);
});
});
Loading
Loading