@startsimpli/integrations 0.2.50 → 0.2.52

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.50",
3
+ "version": "0.2.52",
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
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -64,8 +64,8 @@
64
64
  "react-dom": "^19.0.0",
65
65
  "typescript": "^6.0.0",
66
66
  "vitest": "^3.0.0",
67
- "@startsimpli/ui": "0.4.164",
68
- "@startsimpli/llm": "0.4.25"
67
+ "@startsimpli/llm": "0.4.25",
68
+ "@startsimpli/ui": "0.4.164"
69
69
  },
70
70
  "scripts": {
71
71
  "type-check": "tsc --noEmit",
@@ -0,0 +1,103 @@
1
+ // @vitest-environment jsdom
2
+ import { act, 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
+
6
+ import { VoiceNotesPage, formatDuration, pickMimeType } from '../components/pages/VoiceNotesPage';
7
+ import type { VoiceNote, VoiceNotesApi } from '../corpus/voice';
8
+
9
+ afterEach(cleanup);
10
+
11
+ const note = (over: Partial<VoiceNote> = {}): VoiceNote => ({
12
+ id: 'n1', title: 'Checkout bug', summary: '- fix checkout', transcript: 'fix it', status: 'ready',
13
+ occurredAt: '2026-11-02T12:00:00Z', focusId: 'f1', ...over,
14
+ });
15
+
16
+ function api(over: Partial<VoiceNotesApi> = {}): VoiceNotesApi {
17
+ return {
18
+ submit: vi.fn(async () => ({ id: 'n2' })),
19
+ list: vi.fn(async () => [note()]),
20
+ listFocuses: vi.fn(async () => [{ id: 'f1', title: 'Crochets' }, { id: 'f2', title: 'Raise' }]),
21
+ file: vi.fn(async () => undefined),
22
+ ...over,
23
+ };
24
+ }
25
+
26
+ describe('helpers', () => {
27
+ it('picks the first supported recorder type (Safari -> mp4)', () => {
28
+ expect(pickMimeType((t) => t === 'audio/mp4')).toBe('audio/mp4');
29
+ expect(pickMimeType(() => true)).toBe('audio/webm;codecs=opus');
30
+ expect(pickMimeType(() => false)).toBe('');
31
+ });
32
+ it('formats m:ss', () => expect(formatDuration(65_000)).toBe('1:05'));
33
+ });
34
+
35
+ describe('VoiceNotesPage', () => {
36
+ it('shows the note with its project selected, summary, and transcript', async () => {
37
+ render(<VoiceNotesPage api={api()} />);
38
+ expect(await screen.findByText('Checkout bug')).toBeTruthy();
39
+ expect(screen.getByText('- fix checkout')).toBeTruthy();
40
+ const select = await screen.findByLabelText('Project for Checkout bug') as HTMLSelectElement;
41
+ await waitFor(() => expect(select.value).toBe('f1'));
42
+ });
43
+
44
+ it('re-files on change, and rolls back with a message if it fails', async () => {
45
+ const file = vi.fn(async () => { throw new Error('nope'); });
46
+ render(<VoiceNotesPage api={api({ file })} />);
47
+ const select = await screen.findByLabelText('Project for Checkout bug') as HTMLSelectElement;
48
+ await waitFor(() => expect(select.value).toBe('f1'));
49
+ fireEvent.change(select, { target: { value: 'f2' } });
50
+ expect(file).toHaveBeenCalledWith('n1', 'f2');
51
+ expect((await screen.findByRole('alert')).textContent).toMatch(/nope/);
52
+ await waitFor(() => expect(select.value).toBe('f1'));
53
+ });
54
+
55
+ it('polls only while a note is processing, then stops', async () => {
56
+ const list = vi.fn()
57
+ .mockResolvedValueOnce([note({ status: 'processing', summary: '', transcript: '' })])
58
+ .mockResolvedValue([note()]);
59
+ render(<VoiceNotesPage api={api({ list })} pollMs={20} />);
60
+ await screen.findByText('Transcribing…');
61
+ await waitFor(() => expect(screen.queryByText('Transcribing…')).toBeNull());
62
+ const calls = list.mock.calls.length;
63
+ await act(async () => { await new Promise((r) => setTimeout(r, 120)); });
64
+ expect(list.mock.calls.length).toBe(calls);
65
+ });
66
+
67
+ it('records, stops, and uploads the blob with its duration', async () => {
68
+ const submit = vi.fn(async () => ({ id: 'n2' }));
69
+ const stream = { getTracks: () => [{ stop: vi.fn() }] } as unknown as MediaStream;
70
+ let rec: any;
71
+ const recorderFactory = () => {
72
+ rec = {
73
+ mimeType: 'audio/webm',
74
+ start: vi.fn(),
75
+ stop: vi.fn(() => {
76
+ rec.ondataavailable({ data: new Blob(['abc'], { type: 'audio/webm' }) });
77
+ rec.onstop();
78
+ }),
79
+ };
80
+ return rec as MediaRecorder;
81
+ };
82
+ render(
83
+ <VoiceNotesPage
84
+ api={api({ submit })}
85
+ mediaDevices={{ getUserMedia: vi.fn(async () => stream) }}
86
+ recorderFactory={recorderFactory}
87
+ />,
88
+ );
89
+ fireEvent.click(await screen.findByText('Record a voice note'));
90
+ fireEvent.click(await screen.findByText(/^Stop/));
91
+ await waitFor(() => expect(submit).toHaveBeenCalledOnce());
92
+ const [blob, meta] = submit.mock.calls[0] as unknown as [Blob, { durationMs: number }];
93
+ expect(blob.size).toBe(3);
94
+ expect(meta.durationMs).toBeGreaterThanOrEqual(0);
95
+ });
96
+
97
+ it('explains a blocked microphone', async () => {
98
+ const denied = Object.assign(new Error('x'), { name: 'NotAllowedError' });
99
+ render(<VoiceNotesPage api={api()} mediaDevices={{ getUserMedia: vi.fn(async () => { throw denied; }) }} />);
100
+ fireEvent.click(await screen.findByText('Record a voice note'));
101
+ expect((await screen.findByRole('alert')).textContent).toMatch(/Microphone access was blocked/);
102
+ });
103
+ });
@@ -0,0 +1,211 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { createVoiceTranscriber, parseVoiceAnalysis, renderVoicePrompt, stripPlaceholderOwners } from '../corpus/llm';
4
+ import { rulesExtract } from '../corpus/extract';
5
+ import { toSourceDocument } from '../corpus/entities';
6
+ import {
7
+ createVoiceApi,
8
+ toVoiceNote,
9
+ finishVoiceNote,
10
+ startVoiceNote,
11
+ voiceToEntity,
12
+ type VoiceDeps,
13
+ } from '../corpus/voice';
14
+
15
+ const focuses = [
16
+ { id: 'f-crochet', title: 'Crochets' },
17
+ { id: 'f-raise', title: 'Raise' },
18
+ ];
19
+
20
+ function deps(over: Partial<VoiceDeps> = {}) {
21
+ const posts: Array<{ path: string; body: any }> = [];
22
+ const d: VoiceDeps = {
23
+ http: {
24
+ get: vi.fn(),
25
+ post: vi.fn(async (path: string, body: unknown) => {
26
+ posts.push({ path, body });
27
+ return { id: 'doc-1' } as never;
28
+ }),
29
+ } as never,
30
+ transcriber: { transcribe: vi.fn(async () => 'fix the checkout bug on crochets') },
31
+ analyzer: {
32
+ analyze: vi.fn(async () => ({ title: 'Checkout bug', summary: '- fix checkout', focusId: 'f-crochet' })),
33
+ },
34
+ store: { put: vi.fn(async ({ noteId }) => `s3://bucket/${noteId}.webm`) },
35
+ listFocuses: async () => focuses,
36
+ now: () => new Date('2026-11-02T12:00:00Z'),
37
+ ...over,
38
+ };
39
+ return { d, posts };
40
+ }
41
+ const sub = { noteId: 'n1', audio: new Uint8Array([1, 2]), mimeType: 'audio/webm', durationMs: 4000 };
42
+
43
+ describe('parseVoiceAnalysis', () => {
44
+ it('keeps an offered focus id', () => {
45
+ expect(parseVoiceAnalysis('{"title":"T","summary":"- a","focusId":"f-raise"}', focuses)?.focusId).toBe('f-raise');
46
+ });
47
+ it('drops an id the model invented rather than filing under a guess', () => {
48
+ expect(parseVoiceAnalysis('{"title":"T","summary":"- a","focusId":"nope"}', focuses)?.focusId).toBeNull();
49
+ });
50
+ it('rejects output with neither title nor summary', () => {
51
+ expect(parseVoiceAnalysis('{"focusId":"f-raise"}', focuses)).toBeNull();
52
+ expect(parseVoiceAnalysis('not json', focuses)).toBeNull();
53
+ });
54
+ it('tells the model when there are no projects', () => {
55
+ expect(renderVoicePrompt({ transcript: 'x', focuses: [] })).toMatch(/focusId must be null/);
56
+ });
57
+ });
58
+
59
+ describe('voice pipeline', () => {
60
+ it('start: keeps the audio and creates a processing source_document', async () => {
61
+ const { d, posts } = deps();
62
+ const started = await startVoiceNote(sub, d);
63
+ expect(started).toMatchObject({ id: 'doc-1', audioRef: 's3://bucket/n1.webm' });
64
+ expect(d.store.put).toHaveBeenCalledOnce();
65
+ expect(posts[0].body).toMatchObject({
66
+ entity_type: 'source_document',
67
+ external_id: 'voice:n1',
68
+ data: { source: 'voice', voice_status: 'processing', audio_ref: 's3://bucket/n1.webm', duration_ms: 4000 },
69
+ });
70
+ });
71
+
72
+ it('finish: writes transcript + summary and files under the chosen project', async () => {
73
+ const { d, posts } = deps();
74
+ const started = await startVoiceNote(sub, d);
75
+ posts.length = 0;
76
+ const done = await finishVoiceNote(started, sub, d);
77
+ expect(done.focusId).toBe('f-crochet');
78
+ expect(posts[0].body.data).toMatchObject({ voice_status: 'ready', body: 'fix the checkout bug on crochets', summary: '- fix checkout', title: 'Checkout bug' });
79
+ expect(posts[1]).toEqual({ path: 'api/v1/relationships', body: { rel_type: 'about_focus', source: 'doc-1', target: 'f-crochet' } });
80
+ });
81
+
82
+ it('finish: leaves the note unfiled when the model picks no project', async () => {
83
+ const { d, posts } = deps({ analyzer: { analyze: async () => ({ title: 'T', summary: '- s', focusId: null }) } });
84
+ const started = await startVoiceNote(sub, d);
85
+ posts.length = 0;
86
+ await finishVoiceNote(started, sub, d);
87
+ expect(posts.some((p) => p.path === 'api/v1/relationships')).toBe(false);
88
+ });
89
+
90
+ it('finish: records a failure on the row instead of staying "processing"', async () => {
91
+ const { d, posts } = deps({ transcriber: { transcribe: async () => { throw new Error('quota'); } } });
92
+ const started = await startVoiceNote(sub, d);
93
+ posts.length = 0;
94
+ await expect(finishVoiceNote(started, sub, d)).rejects.toThrow('quota');
95
+ expect(posts[0].body.data).toMatchObject({ voice_status: 'failed', voice_error: 'quota' });
96
+ });
97
+
98
+ it('finish: silence is a failure, not an empty ready note', async () => {
99
+ const { d } = deps({ transcriber: { transcribe: async () => ' ' } });
100
+ const started = await startVoiceNote(sub, d);
101
+ await expect(finishVoiceNote(started, sub, d)).rejects.toThrow(/No speech/);
102
+ });
103
+ });
104
+
105
+ describe('createVoiceApi', () => {
106
+ const scope = { orgId: 'o' };
107
+ it('list: joins each note to its project edge and ignores other sources', async () => {
108
+ const get = vi.fn(async (path: string) =>
109
+ path.endsWith('entities')
110
+ ? { results: [
111
+ { id: 'a', name: 'A', data: { source: 'voice', voice_status: 'ready', summary: 's', body: 'b' } },
112
+ { id: 'z', name: 'Z', data: { source: 'fathom' } },
113
+ ] }
114
+ : { results: [{ source: 'a', target: 'f-raise' }] },
115
+ );
116
+ const api = createVoiceApi({ http: { get } as never, scope, upload: vi.fn() });
117
+ const notes = await api.list();
118
+ expect(notes).toHaveLength(1);
119
+ expect(notes[0]).toMatchObject({ id: 'a', status: 'ready', focusId: 'f-raise' });
120
+ });
121
+
122
+ it('file: replaces the existing edge rather than adding a second project', async () => {
123
+ const post = vi.fn(async () => ({}));
124
+ const del = vi.fn(async () => ({}));
125
+ const get = vi.fn(async () => ({ results: [{ id: 'e1', source: 'a', target: 'old' }] }));
126
+ const api = createVoiceApi({ http: { get, post, delete: del } as never, scope, upload: vi.fn() });
127
+ await api.file('a', 'f-raise');
128
+ expect(del).toHaveBeenCalledWith('api/v1/relationships/e1');
129
+ expect(post).toHaveBeenCalledWith('api/v1/relationships', { rel_type: 'about_focus', source: 'a', target: 'f-raise' });
130
+ });
131
+
132
+ it('file(null) unfiles without writing a new edge', async () => {
133
+ const post = vi.fn(); const del = vi.fn(async () => ({}));
134
+ const get = vi.fn(async () => ({ results: [{ id: 'e1' }] }));
135
+ const api = createVoiceApi({ http: { get, post, delete: del } as never, scope, upload: vi.fn() });
136
+ await api.file('a', null);
137
+ expect(del).toHaveBeenCalledOnce();
138
+ expect(post).not.toHaveBeenCalled();
139
+ });
140
+ });
141
+
142
+ describe('voiceToEntity', () => {
143
+ it('omits unset keys so a later merge cannot blank earlier ones', () => {
144
+ const e = voiceToEntity({ noteId: 'n', title: 'T', status: 'ready', occurredAt: 'x' });
145
+ expect(e.data).not.toHaveProperty('body');
146
+ expect(e.data).not.toHaveProperty('audio_ref');
147
+ });
148
+ });
149
+
150
+ describe('stripPlaceholderOwners', () => {
151
+ it('removes a literal "(Owner)" the model copied from the template, keeps real names', () => {
152
+ expect(stripPlaceholderOwners('- **Fix the checkout bug** (Owner)\n- **Send the deck** (Malin)'))
153
+ .toBe('- **Fix the checkout bug**\n- **Send the deck** (Malin)');
154
+ });
155
+ it('is applied by parseVoiceAnalysis', () => {
156
+ const out = parseVoiceAnalysis('{"title":"T","summary":"- **Fix the thing now** (owner)","focusId":null}', focuses);
157
+ expect(out?.summary).toBe('- **Fix the thing now**');
158
+ });
159
+ });
160
+
161
+ describe('createVoiceTranscriber', () => {
162
+ it('delegates to the speech service, passing project names as recognition hints', async () => {
163
+ const service = { transcribe: vi.fn(async () => ({ text: 'hello', model: 'm', provider: 'p', usage: {} })) };
164
+ const out = await createVoiceTranscriber({ service: service as never }).transcribe({
165
+ audio: new Uint8Array([1]), mimeType: 'audio/webm', focusTitles: ['Crochets', 'Raise'],
166
+ });
167
+ expect(out).toBe('hello');
168
+ expect(service.transcribe).toHaveBeenCalledWith(expect.objectContaining({ hints: ['Crochets', 'Raise'], mimeType: 'audio/webm' }));
169
+ });
170
+ });
171
+
172
+ describe('toVoiceNote', () => {
173
+ it('reads the camelCased keys the shared API client produces', () => {
174
+ const note = toVoiceNote({
175
+ id: 'a', name: 'n',
176
+ data: { voiceStatus: 'failed', voiceError: 'bad audio', durationMs: 4000, occurredAt: '2026-11-02T12:00:00Z', audioRef: 's3://x' },
177
+ } as never, null);
178
+ expect(note).toMatchObject({ status: 'failed', error: 'bad audio', durationMs: 4000, occurredAt: '2026-11-02T12:00:00Z', audioRef: 's3://x' });
179
+ });
180
+ it('treats a row with no status as still processing', () => {
181
+ expect(toVoiceNote({ id: 'a', name: 'n', data: {} } as never, null).status).toBe('processing');
182
+ });
183
+ });
184
+
185
+ describe('filing failure', () => {
186
+ it('leaves the note ready and unfiled instead of overwriting it as failed', async () => {
187
+ const posts: any[] = [];
188
+ const { d } = deps({
189
+ http: { get: vi.fn(), post: vi.fn(async (path: string, body: unknown) => {
190
+ posts.push({ path, body });
191
+ if (path === 'api/v1/relationships') throw new Error("source must be a 'commitment'");
192
+ return { id: 'doc-1' };
193
+ }) } as never,
194
+ });
195
+ const started = await startVoiceNote(sub, d);
196
+ const done = await finishVoiceNote(started, sub, d);
197
+ expect(done).toMatchObject({ focusId: null, title: 'Checkout bug' });
198
+ expect(done.filingError).toMatch(/commitment/);
199
+ expect(posts.some((p) => p.body?.data?.voice_status === 'failed')).toBe(false);
200
+ });
201
+ });
202
+
203
+ describe('the summary format the analyzer asks for', () => {
204
+ it('is one the deterministic rules pass turns into commitments', () => {
205
+ const summary = 'Quinn wants two things done.\n\n## Next Steps\n- **Fix the checkout bug on Crochets** (Quinn)\n- **Ask Malin about the Raise deck**';
206
+ const doc = toSourceDocument({ id: 'd', name: 'T', data: { source: 'voice', title: 'T', summary, body: 'transcript text' } } as never, { orgId: 'o' });
207
+ const drafts = rulesExtract(doc);
208
+ expect(drafts.map((x) => x.title)).toEqual(['Fix the checkout bug on Crochets', 'Ask Malin about the Raise deck']);
209
+ expect(drafts[0].ownerName).toBe('Quinn');
210
+ });
211
+ });
@@ -18,6 +18,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
18
18
  import { http, HttpResponse } from 'msw';
19
19
  import { setupServer } from 'msw/node';
20
20
 
21
+ import { DraftItem } from '../components/DraftReview';
21
22
  import { CustomerEmailsPage } from '../components/pages/CustomerEmailsPage';
22
23
  import { createCommsApi, setApiBase } from '../api/index';
23
24
  import type { Draft } from '../types/index';
@@ -45,6 +46,11 @@ const server = setupServer(
45
46
  const results = drafts.filter((d) => d.approval === wanted);
46
47
  return HttpResponse.json({ count: results.length, next: null, previous: null, results });
47
48
  }
49
+ const pv = hit.path.match(/^\/drafts\/([^/]+)\/preview\/$/);
50
+ if (pv) {
51
+ const d = drafts.find((x) => x.id === pv[1])!;
52
+ return HttpResponse.json({ subject: d.subject, preheader: d.preheader, html: d.html, text: d.text });
53
+ }
48
54
  const m = hit.path.match(/^\/drafts\/([^/]+)\/$/);
49
55
  if (m && hit.method === 'GET') {
50
56
  const d = drafts.find((x) => x.id === m[1])!;
@@ -183,4 +189,54 @@ describe('Announcements fold', () => {
183
189
  const { region } = await openFold();
184
190
  expect(await within(region).findByText('Waiting for you')).toBeInTheDocument();
185
191
  });
192
+
193
+ it('opens the viewer on a draft that is already listed when it is asked to', async () => {
194
+ const d = draft({ id: 'f-2', program_key: 'announcement', window: [] as any, item_keys: [] });
195
+ drafts.push(d);
196
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
197
+ const ui = (open: boolean) => (
198
+ <QueryClientProvider client={qc}>
199
+ <DraftItem api={createCommsApi(SLUG)} draft={d} startPreviewing={open} />
200
+ </QueryClientProvider>
201
+ );
202
+ const { rerender } = render(ui(false));
203
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
204
+ rerender(ui(true));
205
+ expect(await screen.findByTitle(/email preview/i)).toBeInTheDocument();
206
+ });
207
+
208
+ describe('loading an email from a file', () => {
209
+ const file = (content: string, name = 'engine.comms-content.json') =>
210
+ new File([content], name, { type: 'application/json' });
211
+ const email = { subject: 'Meet the engine, {{first_name}}', preheader: 'Faster patterns', html: '<h1>Hi</h1><p><img src="https://cdn.test/a.png" alt="A"></p>', text: 'Hi' };
212
+
213
+ it('saves the file as a draft exactly as written (html untouched) and opens it in the inbox viewer, never approving', async () => {
214
+ createReply = () => {
215
+ const d = draft({ id: 'f-1', program_key: 'announcement', ...email, window: [] as any, item_keys: [] });
216
+ drafts.push(d);
217
+ return HttpResponse.json(d, { status: 201 });
218
+ };
219
+ const { user, region } = await openFold();
220
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file(JSON.stringify(email)));
221
+ await waitFor(() => expect(posts()).toHaveLength(1));
222
+ expect(posts()[0].body).toEqual(email);
223
+ expect(await screen.findByTitle(/email preview/i)).toBeInTheDocument();
224
+ expect(screen.getByRole('group', { name: /inbox row/i })).toBeInTheDocument();
225
+ expect(hits.filter((h) => h.path.includes('approve') || h.path.includes('test'))).toEqual([]);
226
+ });
227
+
228
+ it('refuses a file that is not an email, and saves nothing', async () => {
229
+ const { user, region } = await openFold();
230
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file('{"hello":1}'));
231
+ expect(await within(region).findByText(/needs a subject and html/i)).toBeInTheDocument();
232
+ expect(posts()).toHaveLength(0);
233
+ });
234
+
235
+ it('refuses a file that is not JSON', async () => {
236
+ const { user, region } = await openFold();
237
+ await user.upload(within(region).getByLabelText(/load an email from a file/i), file('not json'));
238
+ expect(await within(region).findByText(/not valid JSON/i)).toBeInTheDocument();
239
+ expect(posts()).toHaveLength(0);
240
+ });
241
+ });
186
242
  });
@@ -354,11 +354,11 @@ describe('comeback sequence settings (A2)', () => {
354
354
  const step2 = within(fold).getAllByRole('listitem')[1];
355
355
  await userEvent.click(within(step2).getByRole('button', { name: /^preview$/i }));
356
356
  await waitFor(() => expect(hits.some((h) => h.method === 'GET' && h.path === '/programs/comeback/steps/1/preview/')).toBe(true));
357
- const frame = await within(fold).findByTitle(/email preview/i);
357
+ const frame = await screen.findByTitle(/email preview/i);
358
358
  expect(frame.tagName).toBe('IFRAME');
359
359
  expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, step 1</p>');
360
360
  expect(frame.hasAttribute('sandbox')).toBe(true);
361
- expect(within(fold).getByText('Preview subject 1')).toBeInTheDocument();
361
+ expect(screen.getAllByText('Preview subject 1')).toHaveLength(1);
362
362
  });
363
363
 
364
364
  it('sends a test of a step to the admin only, on click', async () => {
@@ -546,14 +546,58 @@ describe('draft review (A4)', () => {
546
546
  it('previews a draft as the SERVER rendered it (G2), in a sandboxed iframe', async () => {
547
547
  renderPage();
548
548
  const fold = await openFold(/^product updates$/i);
549
- await userEvent.click(await within(fold).findByRole('button', { name: /^preview$/i }));
549
+ await userEvent.click(await within(fold).findByRole('button', { name: /^preview as inbox$/i }));
550
550
  await waitFor(() => expect(hits.some((h) => h.method === 'GET' && h.path === '/drafts/d-1/preview/')).toBe(true));
551
- const frame = await within(fold).findByTitle(/email preview/i);
551
+ const frame = await screen.findByTitle(/email preview/i);
552
552
  expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, New: stitch counter</p>');
553
553
  expect(frame.hasAttribute('sandbox')).toBe(true);
554
554
  expect(writes()).toEqual([]);
555
555
  });
556
556
 
557
+ describe('inbox viewer', () => {
558
+ async function openViewer() {
559
+ renderPage();
560
+ const fold = await openFold(/^product updates$/i);
561
+ await userEvent.click(await within(fold).findByRole('button', { name: /^preview as inbox$/i }));
562
+ const frame = await screen.findByTitle(/email preview/i);
563
+ return { frame };
564
+ }
565
+
566
+ it('shows the inbox row: sender name, subject once, and the preheader snippet', async () => {
567
+ await openViewer();
568
+ const row = screen.getByRole('group', { name: /inbox row/i });
569
+ expect(within(row).getByText('Crochets')).toBeInTheDocument();
570
+ expect(screen.getAllByText('Rendered: New: stitch counter')).toHaveLength(1);
571
+ expect(within(row).getByText(/Count rows hands-free/)).toBeInTheDocument();
572
+ });
573
+
574
+ it('switches the rendered email between desktop (700px) and mobile (375px) width', async () => {
575
+ const { frame } = await openViewer();
576
+ expect(screen.getByRole('button', { name: /^desktop$/i })).toHaveAttribute('aria-pressed', 'true');
577
+ expect(frame.style.width).toBe('700px');
578
+ await userEvent.click(screen.getByRole('button', { name: /^mobile$/i }));
579
+ expect(screen.getByRole('button', { name: /^mobile$/i })).toHaveAttribute('aria-pressed', 'true');
580
+ expect(frame.style.width).toBe('375px');
581
+ expect(frame.getAttribute('srcdoc')).toContain('<p>Hi Quinn, New: stitch counter</p>');
582
+ });
583
+
584
+ it('shows the plain-text version, and goes back to the email', async () => {
585
+ await openViewer();
586
+ await userEvent.click(screen.getByRole('button', { name: /^plain text$/i }));
587
+ expect(screen.queryByTitle(/email preview/i)).toBeNull();
588
+ expect(screen.getByText('Stitch counter', { selector: 'pre' })).toBeInTheDocument();
589
+ await userEvent.click(screen.getByRole('button', { name: /^email$/i }));
590
+ expect(screen.getByTitle(/email preview/i)).toBeInTheDocument();
591
+ });
592
+
593
+ it('never writes: viewing is read-only', async () => {
594
+ await openViewer();
595
+ await userEvent.click(screen.getByRole('button', { name: /^mobile$/i }));
596
+ await userEvent.click(screen.getByRole('button', { name: /^plain text$/i }));
597
+ expect(writes()).toEqual([]);
598
+ });
599
+ });
600
+
557
601
  it('a draft whose writing failed offers only Discard', async () => {
558
602
  db.drafts = [draft({ subject: '', error: 'generation_failed' })];
559
603
  renderPage();