@startsimpli/integrations 0.2.172 → 0.2.174

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.172",
3
+ "version": "0.2.174",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -51,7 +51,7 @@
51
51
  "@startsimpli/ui-native": ">=0.1.12",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
53
  "@startsimpli/auth": "^0.4.53",
54
- "@startsimpli/ui": "^0.4.183",
54
+ "@startsimpli/ui": "^0.4.184",
55
55
  "@startsimpli/utils": "^0.4.19"
56
56
  },
57
57
  "peerDependenciesMeta": {
@@ -99,8 +99,8 @@
99
99
  "react-native": "0.85.3",
100
100
  "react-native-safe-area-context": "~5.7.0",
101
101
  "@startsimpli/llm": "0.4.31",
102
- "@startsimpli/ui": "0.4.183",
103
- "@startsimpli/ui-native": "0.1.14",
102
+ "@startsimpli/ui": "0.4.184",
103
+ "@startsimpli/ui-native": "0.1.15",
104
104
  "@startsimpli/auth": "0.4.53",
105
105
  "@startsimpli/utils": "0.4.19"
106
106
  },
@@ -0,0 +1,48 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import * as React from 'react';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { ConnectorPage } from '../components/pages/ConnectorPage';
6
+ import type { OAuthConnectionsApi } from '../api/oauth-connections';
7
+
8
+ afterEach(cleanup);
9
+ const row = { id: 'fam1', workspace: { slug: 'tandem', name: 'Tandem' }, client: { claimed_name: 'Claude', host: 'claude.ai', operator_registered: false }, connected_since: '2026-11-13T10:00:00Z', last_active: '2026-11-13T11:00:00Z', access_expires: null };
10
+ const api = (over: Partial<OAuthConnectionsApi> = {}): OAuthConnectionsApi => ({
11
+ list: vi.fn(async () => ({ connections: [row], revocation_takes_effect_within_seconds: 900 })),
12
+ revoke: vi.fn(async () => ({ revoked: true, renewal_stopped: true, revoked_effective_at: 't', notice: 'Disconnected; access ends within 15 minutes.' })),
13
+ ...over,
14
+ });
15
+
16
+ describe('ConnectorPage', () => {
17
+ it('shows the workspace address from its own document, with steps, and no token to paste', async () => {
18
+ render(<ConnectorPage connections={api()} fetchWellKnown={async () => ({ resource: 'https://tandem.example.com/api/v1/mcp/' })} />);
19
+ expect(await screen.findByText('https://tandem.example.com/api/v1/mcp/')).toBeTruthy();
20
+ expect(screen.getByText(/Add custom connector/)).toBeTruthy();
21
+ expect(screen.queryByText(/Create connection token/)).toBeNull();
22
+ });
23
+ it('lists connections and disconnects one, saying what is true', async () => {
24
+ const a = api();
25
+ render(<ConnectorPage connections={a} mcpUrl="https://x/api/v1/mcp/" />);
26
+ await screen.findByTestId('connection-fam1');
27
+ fireEvent.click(screen.getByText('Disconnect'));
28
+ await waitFor(() => expect(a.revoke).toHaveBeenCalledWith('fam1'));
29
+ expect(await screen.findByText(/access ends within 15 minutes/)).toBeTruthy();
30
+ expect(a.list).toHaveBeenCalledTimes(2);
31
+ });
32
+ it('says nothing is connected, and a failing list does not hide the address', async () => {
33
+ const a = api({ list: vi.fn(async () => { throw new Error('boom'); }) });
34
+ render(<ConnectorPage connections={a} mcpUrl="https://x/api/v1/mcp/" />);
35
+ expect(await screen.findByRole('alert')).toBeTruthy();
36
+ expect(screen.getByText('https://x/api/v1/mcp/')).toBeTruthy();
37
+ });
38
+ it('loads the token flow only when Advanced is opened', async () => {
39
+ const tokens = { list: vi.fn(async () => ({ foundries: [], max_ttl_days: 30, default_ttl_days: 7 })), mint: vi.fn(), listTokens: vi.fn(), revokeToken: vi.fn() };
40
+ render(<ConnectorPage connections={api()} tokens={tokens as never} mcpUrl="https://x/api/v1/mcp/" />);
41
+ await screen.findByText('Advanced: use a token instead');
42
+ expect(tokens.list).not.toHaveBeenCalled();
43
+ const details = document.querySelector('details') as HTMLDetailsElement;
44
+ details.open = true;
45
+ fireEvent(details, new Event('toggle'));
46
+ await waitFor(() => expect(tokens.list).toHaveBeenCalled());
47
+ });
48
+ });
@@ -29,6 +29,24 @@ function rig() {
29
29
  return { io, advance, recorders, audio };
30
30
  }
31
31
 
32
+ describe('reply speed', () => {
33
+ it('plays at the chosen speed with pitch kept, and falls back to 1.25x', async () => {
34
+ for (const [speed, want] of [[1.5, 1.5], [undefined, 1.25]] as const) {
35
+ const audio: any = { src: '', play: vi.fn(async () => undefined), pause: vi.fn(), onended: null, onerror: null };
36
+ const io = createBrowserMeetingIO({ createAudio: () => audio, getSpeed: speed ? () => speed : undefined,
37
+ mediaDevices: { getUserMedia: vi.fn(async () => ({ getTracks: () => [] }) as unknown as MediaStream) },
38
+ levelMeter: () => ({ read: () => 0, close: vi.fn() }), recorderFactory: () => ({ state: 'inactive', start: vi.fn(), stop: vi.fn() }) as any,
39
+ wakeLock: null });
40
+ await io.open();
41
+ const p = io.speak({ audioUrl: 'u' } as any, new AbortController().signal, config);
42
+ await Promise.resolve(); await Promise.resolve();
43
+ expect(audio.playbackRate).toBe(want);
44
+ expect(audio.preservesPitch).toBe(true);
45
+ audio.onended(); await p;
46
+ }
47
+ });
48
+ });
49
+
32
50
  describe('browser meeting io', () => {
33
51
  it('records an utterance and resolves when the speaker goes quiet', async () => {
34
52
  const { io, advance, recorders } = rig();
@@ -31,6 +31,7 @@ function setup(over: { turn?: ConverseClient['turn']; openError?: Error; utteran
31
31
  const io: BrowserMeetingIO = {
32
32
  open: vi.fn(async () => { if (over.openError) throw over.openError; }),
33
33
  close: vi.fn(),
34
+ setSpeed: vi.fn(),
34
35
  listen: vi.fn((signal: AbortSignal) => new Promise<{ audio: Blob | null; cancelled?: boolean }>((resolve) => {
35
36
  if (left > 0) { left -= 1; resolve({ audio: new Blob([new Uint8Array([1])], { type: 'audio/mp4' }) }); return; }
36
37
  signal.addEventListener('abort', () => resolve({ audio: null, cancelled: true }));
@@ -43,6 +44,20 @@ function setup(over: { turn?: ConverseClient['turn']; openError?: Error; utteran
43
44
  const status = () => screen.getByTestId('converse-status').textContent ?? '';
44
45
 
45
46
  describe('ConversePage (meeting)', () => {
47
+ it('speech speed defaults to 1.25x, is remembered, and applies to the open conversation', async () => {
48
+ const store = new Map<string, string>();
49
+ vi.stubGlobal('localStorage', { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); } });
50
+ const { io } = setup();
51
+ const sel = screen.getByTestId('converse-speed') as HTMLSelectElement;
52
+ expect(sel.value).toBe('1.25');
53
+ fireEvent.click(screen.getByTestId('converse-start'));
54
+ await waitFor(() => expect(io.open).toHaveBeenCalled());
55
+ fireEvent.change(sel, { target: { value: '2' } });
56
+ expect(io.setSpeed).toHaveBeenCalledWith(2);
57
+ expect(store.get('tandem.converse.speed')).toBe('2');
58
+ vi.unstubAllGlobals();
59
+ });
60
+
46
61
  it('one Start tap, then it listens, answers, speaks and listens again by itself', async () => {
47
62
  const { client, io, speak } = setup({ utterances: 2 });
48
63
  fireEvent.click(screen.getByTestId('converse-start'));
package/src/api/index.ts CHANGED
@@ -6,4 +6,5 @@ export * from './connections';
6
6
  // The MCP bearer mint (bd startsim-hj5zh / startsim-62dca). Central, not the
7
7
  // tenant — it rides the tenant's own /api/v1/auth/ proxy, see the module.
8
8
  export * from './mcp-tokens';
9
+ export * from './oauth-connections';
9
10
  export { setApiBase, getApiBase, setAuthTokenProvider } from './_fetch';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `/api/v1/auth/oauth-connections/` — the OAuth connections (Claude, the relay, any MCP client that signed in through the
3
+ * consent screen) the signed-in person holds, and cutting one (bd startsim-ym54h, central: oauth_connections_view.py).
4
+ * Revoking stops RENEWAL at once; the access token already in the client's hands lives until its own short expiry, and the
5
+ * response says when, so a screen never has to claim more than is true.
6
+ */
7
+ import { createRequester, request, type ClientDeps, type Requester } from './_fetch';
8
+
9
+ export interface OAuthConnection {
10
+ id: string;
11
+ workspace: { slug: string; name: string };
12
+ client: { claimed_name: string; host: string; operator_registered: boolean };
13
+ connected_since: string;
14
+ last_active: string;
15
+ access_expires: string | null;
16
+ }
17
+ export interface OAuthConnectionList { connections: OAuthConnection[]; revocation_takes_effect_within_seconds: number }
18
+ export interface OAuthRevokeResult { revoked: boolean; renewal_stopped: boolean; revoked_effective_at: string; notice: string }
19
+
20
+ export interface OAuthConnectionsApi {
21
+ list(): Promise<OAuthConnectionList>;
22
+ revoke(id: string): Promise<OAuthRevokeResult>;
23
+ }
24
+
25
+ const BASE = '/auth/oauth-connections';
26
+
27
+ function build(req: Requester): OAuthConnectionsApi {
28
+ return {
29
+ list: () => req<OAuthConnectionList>(`${BASE}/`),
30
+ revoke: (id) => req<OAuthRevokeResult>(`${BASE}/${encodeURIComponent(id)}/`, { method: 'DELETE' }),
31
+ };
32
+ }
33
+
34
+ /** The web client: global base, token provider and fetch. */
35
+ export const oauthConnections: OAuthConnectionsApi = build(request);
36
+ /** The same client over an injected fetch (a phone's `authorizedFetch`). */
37
+ export const createOauthConnectionsApi = (deps: ClientDeps): OAuthConnectionsApi => build(createRequester(deps));
@@ -72,6 +72,8 @@ export * from './pages/VoiceNotesPage';
72
72
  export { VoiceRecordButton, VOICE_MIME_CANDIDATES } from './pages/VoiceRecordButton';
73
73
  export { ConversePage } from './pages/ConversePage';
74
74
  export type { ConversePageProps, ConverseClassNames } from './pages/ConversePage';
75
+ export { ConnectorPage } from './pages/ConnectorPage';
76
+ export type { ConnectorPageProps, ConnectorClassNames } from './pages/ConnectorPage';
75
77
  export { DecisionsPage } from './pages/DecisionsPage';
76
78
  export type { DecisionsPageProps, DecisionsClassNames } from './pages/DecisionsPage';
77
79
  export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
@@ -0,0 +1,105 @@
1
+ /**
2
+ * CONNECT CLAUDE, the normal way (bd startsim-ym54h): the workspace is an MCP server with OAuth, so connecting is adding
3
+ * its ADDRESS in Claude and approving a sign-in screen. Nothing is copied or pasted back; access renews by itself and is
4
+ * withdrawn here. The old token form is still available, folded away under Advanced, and is only loaded when opened so a
5
+ * session that cannot mint tokens never sees an error on the main path.
6
+ *
7
+ * The address comes from the workspace's own RFC 9728 document (same origin), not from a pattern this file guessed.
8
+ */
9
+ import * as React from 'react';
10
+
11
+ import type { OAuthConnection, OAuthConnectionsApi } from '../../api/oauth-connections';
12
+ import type { McpTokensApi } from '../../api/mcp-tokens';
13
+ import { ConnectClaudePage } from './ConnectClaudePage';
14
+
15
+ type Slot = 'root' | 'section' | 'heading' | 'card' | 'button' | 'muted' | 'error' | 'code';
16
+ export type ConnectorClassNames = Partial<Record<Slot, string>>;
17
+ const FALLBACK: Record<Slot, string> = {
18
+ root: 'space-y-6', section: 'space-y-3', heading: 'text-lg font-semibold', card: 'rounded-lg border p-4',
19
+ button: 'rounded-md border px-3 py-2 text-sm font-medium', muted: 'text-sm opacity-70', error: 'rounded-md border p-3 text-sm',
20
+ code: 'block w-full overflow-x-auto rounded p-3 font-mono text-xs',
21
+ };
22
+
23
+ export interface ConnectorPageProps {
24
+ connections: OAuthConnectionsApi;
25
+ /** The token flow, kept under Advanced. */
26
+ tokens?: McpTokensApi;
27
+ classNames?: ConnectorClassNames;
28
+ /** Skip the lookup when the app already knows the address. */
29
+ mcpUrl?: string | null;
30
+ fetchWellKnown?: () => Promise<{ resource?: string }>;
31
+ }
32
+
33
+ const readable = (iso: string) => { const d = new Date(iso); return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(); };
34
+
35
+ export function ConnectorPage({ connections, tokens, classNames, mcpUrl, fetchWellKnown }: ConnectorPageProps) {
36
+ const cx = (k: Slot) => classNames?.[k] ?? FALLBACK[k];
37
+ const [url, setUrl] = React.useState<string | null>(mcpUrl ?? null);
38
+ const [rows, setRows] = React.useState<OAuthConnection[] | null>(null);
39
+ const [error, setError] = React.useState('');
40
+ const [notice, setNotice] = React.useState('');
41
+ const [copied, setCopied] = React.useState(false);
42
+ const [advanced, setAdvanced] = React.useState(false);
43
+
44
+ React.useEffect(() => {
45
+ if (url) return;
46
+ const look = fetchWellKnown ?? (() => fetch('/.well-known/oauth-protected-resource').then((r) => (r.ok ? (r.json() as Promise<{ resource?: string }>) : ({} as { resource?: string }))));
47
+ // The spec's resource is `<origin>/api/v1/mcp/`: used only when the workspace's own document cannot be read.
48
+ const fallback = typeof window !== 'undefined' ? `${window.location.origin}/api/v1/mcp/` : null;
49
+ look().then((d) => setUrl(d.resource ?? fallback), () => setUrl(fallback));
50
+ }, [url, fetchWellKnown]);
51
+
52
+ const load = React.useCallback(() => {
53
+ connections.list().then((r) => setRows(r.connections), (e: unknown) => { setRows([]); setError(e instanceof Error ? e.message : String(e)); });
54
+ }, [connections]);
55
+ React.useEffect(load, [load]);
56
+
57
+ async function copy() {
58
+ if (!url) return;
59
+ try { await navigator.clipboard.writeText(url); setCopied(true); window.setTimeout(() => setCopied(false), 2000); } catch { setCopied(false); }
60
+ }
61
+ async function disconnect(id: string) {
62
+ setError('');
63
+ try { const r = await connections.revoke(id); setNotice(r.notice); load(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
64
+ }
65
+
66
+ return (
67
+ <div className={cx('root')}>
68
+ <section className={cx('section')} data-testid="connector-address">
69
+ <h2 className={cx('heading')}>Add it to Claude</h2>
70
+ <p className={cx('muted')}>
71
+ In Claude, open Settings, then Connectors, then Add custom connector, and enter this address. Claude opens a sign-in
72
+ screen here; approve it. There is nothing to copy back, and it stays connected until you disconnect it below.
73
+ </p>
74
+ {url ? (
75
+ <>
76
+ <code className={cx('code')}>{url}</code>
77
+ <button type="button" className={cx('button')} onClick={copy}>{copied ? 'Copied' : 'Copy address'}</button>
78
+ </>
79
+ ) : <p className={cx('muted')}>Looking up this workspace&rsquo;s address…</p>}
80
+ </section>
81
+
82
+ <section className={cx('section')}>
83
+ <h2 className={cx('heading')}>Your connections</h2>
84
+ {rows === null ? <p className={cx('muted')}>Loading…</p> : null}
85
+ {rows && !rows.length ? <p className={cx('muted')} data-testid="no-connections">Nothing is connected yet.</p> : null}
86
+ {(rows ?? []).map((c) => (
87
+ <div key={c.id} className={cx('card')} data-testid={`connection-${c.id}`}>
88
+ <p><strong>{c.client.claimed_name || c.client.host}</strong>{c.client.operator_registered ? '' : ` (${c.client.host}, not verified)`}</p>
89
+ <p className={cx('muted')}>{c.workspace.name} · connected {readable(c.connected_since)} · last used {readable(c.last_active)}</p>
90
+ <button type="button" className={cx('button')} onClick={() => void disconnect(c.id)}>Disconnect</button>
91
+ </div>
92
+ ))}
93
+ {notice ? <p className={cx('muted')} role="status">{notice}</p> : null}
94
+ {error ? <div className={cx('error')} role="alert">{error}</div> : null}
95
+ </section>
96
+
97
+ {tokens ? (
98
+ <details onToggle={(e) => setAdvanced((e.currentTarget as HTMLDetailsElement).open)}>
99
+ <summary className={cx('muted')}>Advanced: use a token instead</summary>
100
+ {advanced ? <ConnectClaudePage api={tokens} classNames={classNames} /> : null}
101
+ </details>
102
+ ) : null}
103
+ </div>
104
+ );
105
+ }
@@ -15,6 +15,7 @@ import { createMeetingController, type MeetingController, type MeetingState } fr
15
15
  import type { MeetingConfig } from '../../corpus/converse/meeting-config';
16
16
  import type { ConverseEndResult } from '../../corpus/converse/types';
17
17
  import { createBrowserMeetingIO, type BrowserMeetingIO } from './converse/browserIO';
18
+ import { DEFAULT_SPEED, SPEEDS, loadSpeed, normalizeSpeed, saveSpeed } from './converse/speed';
18
19
 
19
20
  export type ConverseSlot = 'root' | 'talk' | 'talking' | 'secondary' | 'bubbleUser' | 'bubbleReply' | 'muted' | 'error' | 'input';
20
21
  export type ConverseClassNames = Partial<Record<ConverseSlot, string>>;
@@ -56,6 +57,12 @@ export function ConversePage({ client, classNames, meeting, createIO, savedLink
56
57
  const ctl = React.useRef<MeetingController | null>(null);
57
58
  const io = React.useRef<BrowserMeetingIO | null>(null);
58
59
  const endRef = React.useRef<HTMLDivElement | null>(null);
60
+ const [speed, setSpeedState] = React.useState<number>(DEFAULT_SPEED);
61
+ const speedRef = React.useRef(speed);
62
+ React.useEffect(() => { const v = loadSpeed(); speedRef.current = v; setSpeedState(v); }, []);
63
+ function onSpeed(v: number) {
64
+ speedRef.current = v; setSpeedState(v); saveSpeed(v); io.current?.setSpeed?.(v);
65
+ }
59
66
 
60
67
  React.useEffect(() => { endRef.current?.scrollIntoView?.({ block: 'end' }); }, [state.lines, state.phase]);
61
68
  React.useEffect(() => () => { void ctl.current?.end(); io.current?.close(); }, []);
@@ -65,7 +72,7 @@ export function ConversePage({ client, classNames, meeting, createIO, savedLink
65
72
  /** `typing`: carry on without the microphone (the reason stays on screen) instead of refusing to start. */
66
73
  async function onStart(typing = false) {
67
74
  setStartError(null);
68
- const browserIO = createIO ? createIO() : createBrowserMeetingIO({ resolveAudio: (u) => client.audioUrl(u) });
75
+ const browserIO = createIO ? createIO() : createBrowserMeetingIO({ resolveAudio: (u) => client.audioUrl(u), getSpeed: () => speedRef.current });
69
76
  try {
70
77
  await browserIO.open(); // inside the tap
71
78
  } catch (e) {
@@ -117,7 +124,11 @@ export function ConversePage({ client, classNames, meeting, createIO, savedLink
117
124
  </div>
118
125
  ) : null}
119
126
  {live ? <p className={cx('muted')}>Keep this screen on: a web page cannot listen once the phone locks or you switch apps.</p> : null}
120
- <div className="flex gap-2">
127
+ <div className="flex flex-wrap items-center gap-2">
128
+ <label className={cx('muted')} htmlFor="converse-speed">Speech speed</label>
129
+ <select id="converse-speed" className={cx('secondary')} value={speed} onChange={(e) => onSpeed(normalizeSpeed(e.target.value))} data-testid="converse-speed">
130
+ {SPEEDS.map((v) => <option key={v} value={v}>{v}x</option>)}
131
+ </select>
121
132
  <button type="button" className={cx('secondary')} onClick={() => void ctl.current?.replay()} disabled={!hasReply || !live || state.phase === 'thinking'}>Play reply</button>
122
133
  </div>
123
134
  <ol className="space-y-2" aria-label="Conversation">
@@ -11,6 +11,7 @@ import type { MeetingConfig } from '../../../corpus/converse/meeting-config';
11
11
  import type { MeetingIO, MeetingReply } from '../../../corpus/converse/meeting';
12
12
  import { pickMimeType } from '../VoiceRecordButton';
13
13
  import { SILENCE_WAV } from './silence';
14
+ import { applySpeed, DEFAULT_SPEED } from './speed';
14
15
 
15
16
  export interface LevelMeter { read(): number; close(): void }
16
17
  const TICK_MS = 50;
@@ -25,6 +26,8 @@ export interface BrowserIOOptions {
25
26
  /** Screen Wake Lock (default: the browser's). Best effort: a refusal never blocks the meeting. */
26
27
  wakeLock?: { request(type: 'screen'): Promise<{ release(): Promise<void> }> } | null;
27
28
  resolveAudio?: (audioUrl: string) => Promise<string>;
29
+ /** Playback speed, read at each reply (default 1.25). */
30
+ getSpeed?: () => number;
28
31
  now?: () => number;
29
32
  setTimer?: (fn: () => void, ms: number) => ReturnType<typeof setInterval>;
30
33
  clearTimer?: (id: ReturnType<typeof setInterval>) => void;
@@ -34,6 +37,8 @@ export interface BrowserMeetingIO extends MeetingIO {
34
37
  /** Call inside the Start tap: opens the mic, resumes audio, unlocks playback. Throws a readable Error. */
35
38
  open(): Promise<void>;
36
39
  close(): void;
40
+ /** Changes the speed of the reply that is playing now, too. */
41
+ setSpeed(speed: number): void;
37
42
  }
38
43
 
39
44
  function webAudioMeter(stream: MediaStream): LevelMeter {
@@ -92,6 +97,8 @@ export function createBrowserMeetingIO(options: BrowserIOOptions = {}): BrowserM
92
97
  if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible);
93
98
  },
94
99
 
100
+ setSpeed(speed: number) { if (audio) applySpeed(audio, speed); },
101
+
95
102
  close() {
96
103
  meter?.close();
97
104
  if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible);
@@ -156,6 +163,7 @@ export function createBrowserMeetingIO(options: BrowserIOOptions = {}): BrowserM
156
163
  el.onended = done;
157
164
  el.onerror = () => done();
158
165
  el.src = url;
166
+ applySpeed(el, options.getSpeed?.() ?? DEFAULT_SPEED);
159
167
  void el.play().catch(() => done());
160
168
  if (config.interruptOnSpeech && meter) {
161
169
  const detector = createUtteranceDetector(config);
@@ -0,0 +1,23 @@
1
+ /** Spoken-reply speed: the same choices and default as the iOS Converse tab. Remembered in the browser. */
2
+ export const SPEEDS = [1, 1.25, 1.5, 2] as const;
3
+ export const DEFAULT_SPEED = 1.25;
4
+ const KEY = 'tandem.converse.speed';
5
+
6
+ export function normalizeSpeed(v: unknown): number {
7
+ const n = typeof v === 'string' ? Number(v) : v;
8
+ return typeof n === 'number' && (SPEEDS as readonly number[]).includes(n) ? n : DEFAULT_SPEED;
9
+ }
10
+ export function loadSpeed(): number {
11
+ try { return normalizeSpeed(globalThis.localStorage?.getItem(KEY)); } catch { return DEFAULT_SPEED; }
12
+ }
13
+ export function saveSpeed(speed: number): void {
14
+ try { globalThis.localStorage?.setItem(KEY, String(speed)); } catch { /* private mode: the choice just is not remembered */ }
15
+ }
16
+ /** Applies a speed to an audio element, keeping the voice's pitch. Setting `src` resets the rate, so call this after it. */
17
+ export function applySpeed(el: HTMLAudioElement, speed: number): void {
18
+ el.defaultPlaybackRate = speed;
19
+ el.playbackRate = speed;
20
+ const p = el as HTMLAudioElement & { preservesPitch?: boolean; webkitPreservesPitch?: boolean };
21
+ p.preservesPitch = true;
22
+ p.webkitPreservesPitch = true;
23
+ }
@@ -150,7 +150,7 @@ function Root({ config, device, registry }: { config: FoundryAppConfig; device:
150
150
  const recordRef = useRef<ReactNode>(record);
151
151
  recordRef.current = record;
152
152
  const tabs = useMemo(
153
- () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, converse: services.converse?.controller ?? null, notify: services.notify, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
153
+ () => buildFoundryTabs({ config: appConfig, corpus: data.corpus, notes: data.notes, record: () => recordRef.current, member: data.member, itemsChanged: services.briefing?.itemsChanged, converse: services.converse?.controller ?? null, converseSpeed: services.converse?.speed ?? null, notify: services.notify, openUrl: data.openUrl ?? ((url) => Linking.openURL(url)) }, registry),
154
154
  [appConfig, data, registry],
155
155
  );
156
156
 
@@ -4,6 +4,7 @@ import type { MeetingConfig } from '../../corpus/converse/meeting-config';
4
4
  import { createNativeMeetingApi } from '../converse/api';
5
5
  import { createFakeMeeting } from '../converse/fake';
6
6
  import { createMeetingIO } from '../converse/io';
7
+ import { createSpeedStore } from '../converse/speed';
7
8
  import { createDiagnostics } from '../recording/diagnostics';
8
9
  import { createPermissionFlow } from '../recording/permissions';
9
10
  import { createRecorderAudio } from '../recording/recorderAudio';
@@ -37,6 +38,10 @@ export function createConverse(deps: {
37
38
  if (!dev) throw new Error('features.converse needs a playback driver (device.briefing.driver)');
38
39
  const inspector = dev.session ?? rec.session;
39
40
  const player = createAudioPlayer({ driver: dev.driver, session: inspector, diag, poll: tick, sleep: wait });
41
+ const speed = createSpeedStore({ path: device.documentUri('converse-speed.json'), files: device.files });
42
+ player.setRate(speed.get());
43
+ speed.subscribe((r) => player.setRate(r));
44
+ void speed.load();
40
45
  let broken: (() => void) | null = null;
41
46
  const audio = createRecorderAudio({
42
47
  driver: rec.driver, session: rec.session, fs: { size: rec.fileSize }, poll: tick, sleep: wait, diag,
@@ -58,5 +63,5 @@ export function createConverse(deps: {
58
63
  client: api, io, config: deps.meeting,
59
64
  onChange: (s) => diag.log('meeting.state', { phase: s.phase, error: s.error, noAudio: s.noAudio }),
60
65
  });
61
- return { controller, player };
66
+ return { controller, player, speed };
62
67
  }
@@ -13,6 +13,7 @@ import { askTab, libraryTab } from '../screens/tabs';
13
13
  import { trackerTab } from '../tracker/tab';
14
14
  import type { MeetingController } from '../../corpus/converse/meeting';
15
15
  import { converseTab } from '../converse/tab';
16
+ import type { SpeedStore } from '../converse/speed';
16
17
  import { decisionsTab } from '../push/tab';
17
18
  import type { DecisionsController } from '../push/decisions';
18
19
  import type { PushController } from '../push/controller';
@@ -38,6 +39,8 @@ export interface ScreenDeps {
38
39
  /** Fires when something outside a list changed its items (a spoken reply to the briefing): lists re-read. */
39
40
  /** The Converse conversation; null when `features.converse` is off. */
40
41
  converse?: MeetingController | null;
42
+ /** How fast Converse replies are spoken; null/absent hides the control. */
43
+ converseSpeed?: SpeedStore | null;
41
44
  /** Decisions and push; null when `features.notifications` is off. */
42
45
  notify?: { decisions: DecisionsController; push: PushController } | null;
43
46
  itemsChanged?: { subscribe(listener: () => void): () => void };
@@ -78,9 +81,9 @@ export const BUILTIN_FACTORIES: Record<string, ScreenFactory> = {
78
81
  planning: ({ config, corpus }, tab) => createPlanningTab({ api: corpus, key: tab.key, label: tabLabel(tab), documentTab: firstKey(config, 'library') }),
79
82
  connections: ({ config, member, openUrl }, tab) => createConnectionsTab({ api: member.connections, key: tab.key, label: tabLabel(tab), openUrl, returnTo: `${config.app.scheme}://${tab.key}` }),
80
83
  'connect-claude': ({ member }, tab) => createConnectClaudeTab({ api: member.mcpTokens, key: tab.key, label: tab.label ?? `Claude` }),
81
- converse: ({ converse }, tab) => {
84
+ converse: ({ converse, converseSpeed }, tab) => {
82
85
  if (!converse) throw new Error(`tab "${tab.key}": the converse screen needs features.converse on`);
83
- return converseTab(converse, { key: tab.key, label: tabLabel(tab) });
86
+ return converseTab(converse, { key: tab.key, label: tabLabel(tab), speed: converseSpeed });
84
87
  },
85
88
  decisions: ({ notify }, tab) => {
86
89
  if (!notify) throw new Error(`tab "${tab.key}": the decisions screen needs features.notifications on`);
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createAudioPlayer, type AudioPlayerDriver } from '../audioPlayer';
3
+
4
+ describe('player speed', () => {
5
+ it('sets the rate before the player is built and changes it while playing', async () => {
6
+ const calls: string[] = [];
7
+ let n = 0;
8
+ const driver: AudioPlayerDriver = {
9
+ configureSession: async () => undefined,
10
+ load: () => { calls.push('load'); },
11
+ play: () => { calls.push('play'); },
12
+ pause: () => undefined,
13
+ release: async () => undefined,
14
+ setRate: (r) => { calls.push(`rate ${r}`); },
15
+ status: () => ({ playing: true, loaded: true, positionMillis: (n += 100), durationMillis: 5000, ended: false }),
16
+ };
17
+ const player = createAudioPlayer({
18
+ driver, session: { info: async () => null, onInterruption: () => () => undefined, onRouteChange: () => () => undefined } as never,
19
+ poll: () => () => undefined, sleep: async () => undefined, diag: { log: () => undefined },
20
+ });
21
+ player.setRate(1.5);
22
+ await player.play({ uri: 'x' });
23
+ expect(calls.slice(0, 4)).toEqual(['rate 1.5', 'rate 1.5', 'load', 'play']);
24
+ player.setRate(2);
25
+ expect(calls.at(-1)).toBe('rate 2');
26
+ });
27
+ });
@@ -28,6 +28,8 @@ export interface AudioPlayerDriver {
28
28
  play(): void;
29
29
  /** Jump to a position (ms) in the loaded source. Optional: without it a player can only start from the beginning. */
30
30
  seekTo?(millis: number): Promise<void> | void;
31
+ /** Playback speed (1 = normal), pitch preserved. Applies to the current player and to ones built later. Optional. */
32
+ setRate?(rate: number): void;
31
33
  pause(): void;
32
34
  /** Removes the player so the session is free for the recorder. */
33
35
  release(): Promise<void>;
@@ -65,6 +67,8 @@ export function createAudioPlayer(deps: {
65
67
  let step = '';
66
68
  /** A player was built and not yet released. */
67
69
  let live = false;
70
+ /** Speed for the next and the current playback. */
71
+ let rate = 1;
68
72
 
69
73
  const set = (patch: Partial<PlayerState>) => {
70
74
  state = { ...state, ...patch };
@@ -117,6 +121,7 @@ export function createAudioPlayer(deps: {
117
121
  await guarded('configureSession', deps.driver.configureSession());
118
122
  step = 'load';
119
123
  live = true;
124
+ deps.driver.setRate?.(rate);
120
125
  deps.driver.load(source);
121
126
  if (options.startAtMillis && options.startAtMillis > 0) {
122
127
  step = 'seek';
@@ -168,6 +173,12 @@ export function createAudioPlayer(deps: {
168
173
  }, POLL_MS));
169
174
  },
170
175
 
176
+ /** Speak faster or slower from now on, including the reply that is playing. */
177
+ setRate(next: number): void {
178
+ rate = next;
179
+ deps.driver.setRate?.(next);
180
+ },
181
+
171
182
  /** Stop and free the session. */
172
183
  async stop(): Promise<void> {
173
184
  await release();
@@ -4,6 +4,7 @@ import { Alert, Button, EmptyState, Header, MessageBubble, Spinner, useHaptics,
4
4
  import { useControllerState } from '../components/useControllerState';
5
5
  import type { MeetingController } from '../../corpus/converse/meeting';
6
6
  import { indicatorLabel, statusLine } from './format';
7
+ import { SPEEDS, speedLabel, type SpeedStore } from './speed';
7
8
 
8
9
  const BIG = 176;
9
10
 
@@ -23,10 +24,11 @@ function useElapsed(on: boolean): number {
23
24
  * Converse is a live meeting. One tap on Start; from then on it listens, notices when you stop talking, sends, speaks the
24
25
  * reply and listens again until End. The reply text stays on screen and Replay says it again.
25
26
  */
26
- export function ConverseScreen({ controller }: { controller: MeetingController }) {
27
+ export function ConverseScreen({ controller, speed }: { controller: MeetingController; speed?: SpeedStore }) {
27
28
  const theme = useTheme();
28
29
  const haptic = useHaptics();
29
30
  const s = useControllerState({ getState: controller.getState, subscribe: (l: () => void) => controller.subscribe(l) });
31
+ const rate = useControllerState({ getState: speed ? speed.get : () => 1, subscribe: (l: () => void) => (speed ? speed.subscribe(l) : () => undefined) });
30
32
  const list = useRef<FlatList<{ role: string; text: string }>>(null);
31
33
  const active = s.phase === 'listening' || s.phase === 'thinking' || s.phase === 'speaking';
32
34
  const busy = s.phase === 'ending';
@@ -74,6 +76,24 @@ export function ConverseScreen({ controller }: { controller: MeetingController }
74
76
  <RNText testID="converse-status" style={{ color: theme.colors.foreground, fontSize: theme.fontSizes.lg, fontWeight: '600', textAlign: 'center' }}>
75
77
  {statusLine(s.phase, sec)}
76
78
  </RNText>
79
+ {speed ? (
80
+ <View testID="converse-speed" accessibilityLabel="Reply speed" style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
81
+ <RNText style={{ color: theme.colors.mutedForeground, fontSize: theme.fontSizes.sm }}>Speed</RNText>
82
+ {SPEEDS.map((r) => (
83
+ <Pressable
84
+ key={r}
85
+ testID={`converse-speed-${r}`}
86
+ accessibilityRole="button"
87
+ accessibilityState={{ selected: rate === r }}
88
+ accessibilityLabel={`Speak at ${speedLabel(r)}`}
89
+ onPress={() => { haptic('light', 'converse.speed'); speed.set(r); }}
90
+ style={{ paddingHorizontal: theme.spacing.md, paddingVertical: theme.spacing.sm, borderRadius: 999, backgroundColor: rate === r ? theme.colors.primary : theme.colors.muted }}
91
+ >
92
+ <RNText style={{ color: rate === r ? theme.colors.primaryForeground : theme.colors.foreground, fontWeight: '600' }}>{speedLabel(r)}</RNText>
93
+ </Pressable>
94
+ ))}
95
+ </View>
96
+ ) : null}
77
97
  <View style={{ flexDirection: 'row', gap: theme.spacing.md }}>
78
98
  <Button testID="converse-repeat" title="Replay" variant="outline" size="lg" disabled={!s.lines.length || busy || s.phase === 'thinking'} onPress={() => { haptic('light', 'converse.replay'); void controller.replay(); }} />
79
99
  <Button testID="converse-end" title="End" variant="outline" size="lg" disabled={busy || (!active && s.phase !== 'stopped')} onPress={() => { haptic('warning', 'converse.end'); void controller.end(); }} />
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createSpeedStore, DEFAULT_SPEED, SPEEDS } from '../speed';
3
+
4
+ const memory = (init?: Record<string, string>) => {
5
+ const data = new Map(Object.entries(init ?? {}));
6
+ return {
7
+ data,
8
+ exists: async (p: string) => data.has(p),
9
+ read: async (p: string) => data.get(p) as string,
10
+ write: async (p: string, v: string) => { data.set(p, v); },
11
+ };
12
+ };
13
+
14
+ describe('speed store', () => {
15
+ it('defaults to 1.25x and offers 1, 1.25, 1.5, 2', () => {
16
+ expect(DEFAULT_SPEED).toBe(1.25);
17
+ expect([...SPEEDS]).toEqual([1, 1.25, 1.5, 2]);
18
+ expect(createSpeedStore({ path: 'p', files: memory() }).get()).toBe(1.25);
19
+ });
20
+ it('remembers a choice across launches', async () => {
21
+ const files = memory();
22
+ const a = createSpeedStore({ path: 'p', files });
23
+ const seen: number[] = [];
24
+ a.subscribe((r) => seen.push(r));
25
+ a.set(2);
26
+ expect(a.get()).toBe(2);
27
+ expect(seen).toEqual([2]);
28
+ const b = createSpeedStore({ path: 'p', files });
29
+ await b.load();
30
+ expect(b.get()).toBe(2);
31
+ });
32
+ it('ignores junk and unreadable files', async () => {
33
+ const s = createSpeedStore({ path: 'p', files: memory({ p: 'not json' }) });
34
+ await s.load();
35
+ expect(s.get()).toBe(1.25);
36
+ s.set(Number.NaN);
37
+ s.set(-1);
38
+ expect(s.get()).toBe(1.25);
39
+ });
40
+ });
@@ -0,0 +1,30 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('react-native', async () => ({ ...(await import('../../../../../ui-native/test/rn-stub')) }));
4
+
5
+ import { act, hostById, maybeById, render } from '../../../../../ui-native/test/render';
6
+ import type { MeetingController } from '../../../corpus/converse/meeting';
7
+ import { ConverseScreen } from '../ConverseScreen';
8
+ import { createSpeedStore } from '../speed';
9
+
10
+ const idle = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null, relayNotice: null };
11
+ const controller = {
12
+ start() {}, end: async () => null, replay: async () => {}, sendText: async () => {}, dismissNotice() {},
13
+ getState: () => idle,
14
+ state: () => idle, subscribe: () => () => undefined,
15
+ } as unknown as MeetingController;
16
+
17
+ describe('Converse speed control', () => {
18
+ it('shows 1x 1.25x 1.5x 2x, marks the current one and changes it on tap', async () => {
19
+ const speed = createSpeedStore({ path: 'p', files: { exists: async () => false, read: async () => '', write: async () => undefined } });
20
+ const r = render(<ConverseScreen controller={controller} speed={speed} />);
21
+ expect(hostById(r, 'converse-speed-1.25').props.accessibilityState).toEqual({ selected: true });
22
+ await act(async () => { hostById(r, 'converse-speed-2').props.onPress(); });
23
+ expect(speed.get()).toBe(2);
24
+ expect(hostById(r, 'converse-speed-2').props.accessibilityState).toEqual({ selected: true });
25
+ expect(hostById(r, 'converse-speed-1.25').props.accessibilityState).toEqual({ selected: false });
26
+ });
27
+ it('has no control when there is no speed store', () => {
28
+ expect(maybeById(render(<ConverseScreen controller={controller} />), 'converse-speed')).toHaveLength(0);
29
+ });
30
+ });
@@ -4,5 +4,7 @@ export { createMeetingIO, dbToLevel } from './io';
4
4
  export type { MeetingSpeaker } from './io';
5
5
  export { createFakeMeeting } from './fake';
6
6
  export { ConverseScreen } from './ConverseScreen';
7
+ export { SPEEDS, DEFAULT_SPEED, createSpeedStore } from './speed';
8
+ export type { SpeedStore } from './speed';
7
9
  export { converseTab } from './tab';
8
10
  export { statusLine } from './format';
@@ -20,6 +20,7 @@ export interface MeetingSpeaker {
20
20
  subscribe(cb: (s: PlayerState) => void): () => void;
21
21
  play(source: PlaybackSource): Promise<void>;
22
22
  stop(): Promise<void>;
23
+ setRate?(rate: number): void;
23
24
  handoffToRecording(): Promise<void>;
24
25
  }
25
26
 
@@ -0,0 +1,42 @@
1
+ /**
2
+ * How fast replies are spoken. A setting, remembered across launches in a small file; the default is 1.25x. The player
3
+ * applies it to the next reply and to the one playing now (pitch is preserved by the platform player).
4
+ */
5
+ export const SPEEDS = [1, 1.25, 1.5, 2] as const;
6
+ export const DEFAULT_SPEED = 1.25;
7
+
8
+ export const speedLabel = (rate: number) => `${rate}x`;
9
+
10
+ export interface SpeedStore {
11
+ get(): number;
12
+ set(rate: number): void;
13
+ subscribe(cb: (rate: number) => void): () => void;
14
+ /** Reads the saved value; call once at start. */
15
+ load(): Promise<void>;
16
+ }
17
+
18
+ export function createSpeedStore(deps: {
19
+ path: string;
20
+ files: { exists(p: string): Promise<boolean>; read(p: string): Promise<string>; write(p: string, v: string): Promise<void> };
21
+ initial?: number;
22
+ }): SpeedStore {
23
+ let rate = deps.initial ?? DEFAULT_SPEED;
24
+ const listeners = new Set<(r: number) => void>();
25
+ const apply = (r: number) => { rate = r; listeners.forEach((l) => l(r)); };
26
+ return {
27
+ get: () => rate,
28
+ set(r) {
29
+ if (!Number.isFinite(r) || r <= 0 || r === rate) return;
30
+ apply(r);
31
+ void deps.files.write(deps.path, JSON.stringify({ rate: r })).catch(() => undefined);
32
+ },
33
+ subscribe(cb) { listeners.add(cb); return () => { listeners.delete(cb); }; },
34
+ async load() {
35
+ try {
36
+ if (!(await deps.files.exists(deps.path))) return;
37
+ const saved = (JSON.parse(await deps.files.read(deps.path)) as { rate?: unknown }).rate;
38
+ if (typeof saved === 'number' && Number.isFinite(saved) && saved > 0 && saved !== rate) apply(saved);
39
+ } catch { /* unreadable: keep the default */ }
40
+ },
41
+ };
42
+ }
@@ -1,8 +1,10 @@
1
1
  import type { FoundryTab } from '../components/FoundryTabsShell';
2
2
  import type { MeetingController } from '../../corpus/converse/meeting';
3
3
  import { ConverseScreen } from './ConverseScreen';
4
+ import type { SpeedStore } from './speed';
4
5
 
5
6
  /** The Converse tab. Leaving it does not end the meeting: a drive may well include a glance at another tab. */
6
- export function converseTab(controller: MeetingController, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
7
- return { key: 'converse', label: 'Converse', ...over, render: () => <ConverseScreen controller={controller} /> };
7
+ export function converseTab(controller: MeetingController, over: Partial<Pick<FoundryTab, 'key' | 'label'>> & { speed?: SpeedStore | null } = {}): FoundryTab {
8
+ const { speed, ...tab } = over;
9
+ return { key: 'converse', label: 'Converse', ...tab, render: () => <ConverseScreen controller={controller} speed={speed ?? undefined} /> };
8
10
  }