@adminide-stack/clock-tik-mobile 12.0.37-alpha.1 → 12.0.37-alpha.2

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.
@@ -0,0 +1,201 @@
1
+ import { describe, expect, it, jest } from '@jest/globals';
2
+
3
+ // agent.ts streams with expo/fetch, signs in through native storage and watches the app state: stub them for node.
4
+ jest.mock<{ fetch: jest.Mock }>('expo/fetch', () => ({ fetch: jest.fn() }), { virtual: true });
5
+ jest.mock<
6
+ Pick<
7
+ typeof import('../chat/auth'),
8
+ 'agentBackendUrl' | 'agentUrl' | 'getChatToken' | 'clearChatToken' | 'isLockedOut'
9
+ >
10
+ >('../chat/auth', () => ({
11
+ agentBackendUrl: async () => 'https://backend.test/graphql',
12
+ agentUrl: () => 'https://agent.test',
13
+ getChatToken: async () => 'tok',
14
+ clearChatToken: async () => undefined,
15
+ isLockedOut: () => false,
16
+ }));
17
+ jest.mock<Pick<typeof import('../chat/appFront'), 'inFront' | 'onFront' | 'whenInFront'>>('../chat/appFront', () => ({
18
+ inFront: () => true,
19
+ onFront: () => () => undefined,
20
+ whenInFront: async () => undefined,
21
+ }));
22
+
23
+ // eslint-disable-next-line import/first
24
+ import { fetch as streamFetch } from 'expo/fetch';
25
+ // eslint-disable-next-line import/first
26
+ import { BUSY_GIVE_UP_MS, sendTurn, WAITING_FOR_LAST } from '../chat/agent';
27
+
28
+ const stream = jest.mocked(
29
+ streamFetch as (url: string, init: { body: string; signal: AbortSignal }) => Promise<unknown>,
30
+ );
31
+
32
+ /** A streamed reply: the SSE blocks as the agent writes them. */
33
+ function sse(...events: [string, unknown][]) {
34
+ const text = events.map(([e, d]) => `event: ${e}\ndata: ${JSON.stringify(d)}\n\n`).join('');
35
+ let sent = false;
36
+ return {
37
+ status: 200,
38
+ ok: true,
39
+ body: {
40
+ getReader: () => ({
41
+ read: async () => {
42
+ if (sent) return { done: true, value: undefined };
43
+ sent = true;
44
+ return { done: false, value: new TextEncoder().encode(text) };
45
+ },
46
+ }),
47
+ },
48
+ };
49
+ }
50
+ const json = (body: unknown, status = 200) => ({ status, ok: status < 300, json: async () => body });
51
+ const busySse = () => sse(['error', { class: 'session_busy', error: 'still working on your previous message' }]);
52
+ const busy409 = () => ({ status: 409, ok: false, body: null });
53
+
54
+ /** The agent's plain GETs (agent.ts authed) go through the global fetch. */
55
+ function agentReads() {
56
+ const get = jest.fn<(url: string, init?: unknown) => Promise<unknown>>();
57
+ globalThis.fetch = get as unknown as typeof fetch;
58
+ stream.mockReset();
59
+ return get;
60
+ }
61
+
62
+ const handlers = () => ({ onText: jest.fn(), onStatus: jest.fn(), onSession: jest.fn() });
63
+ const sentTurnIds = () => stream.mock.calls.map(([, init]) => JSON.parse(init.body).turn_id as string);
64
+
65
+ /** Runs a turn on a fake clock, moving it on a second at a time until it settles. */
66
+ async function onFakeClock<T>(start: () => Promise<T>, ms = 40 * 60_000): Promise<T> {
67
+ jest.useFakeTimers();
68
+ try {
69
+ let out: { v: T } | { e: unknown } | undefined;
70
+ start().then(
71
+ (v) => {
72
+ out = { v };
73
+ },
74
+ (e: unknown) => {
75
+ out = { e };
76
+ },
77
+ );
78
+ for (let t = 0; t < ms && !out; t += 1000) await jest.advanceTimersByTimeAsync(1000);
79
+ if (!out) throw new Error('still waiting');
80
+ if ('e' in out) throw out.e;
81
+ return out.v;
82
+ } finally {
83
+ jest.useRealTimers();
84
+ }
85
+ }
86
+
87
+ describe('sendTurn when the agent is still on an earlier turn', () => {
88
+ // "Update me?" in the 2026-11-17 report: refused as busy while the agent was still on earlier turns.
89
+ it('waits until the session has room, then sends the same turn instead of failing', async () => {
90
+ const get = agentReads();
91
+ stream
92
+ .mockResolvedValueOnce(busySse())
93
+ .mockResolvedValueOnce(sse(['delta', { text: 'Here is where it stands.' }], ['done', {}]));
94
+ get.mockResolvedValueOnce(json({ in_flight: true })).mockResolvedValueOnce(json({ in_flight: false }));
95
+ const h = handlers();
96
+
97
+ await expect(onFakeClock(() => sendTurn('Update me?', 'srv_1', h, new AbortController().signal))).resolves.toBe(
98
+ 'Here is where it stands.',
99
+ );
100
+
101
+ const ids = sentTurnIds();
102
+
103
+ expect(ids).toHaveLength(2);
104
+ expect(ids[1]).toBe(ids[0]);
105
+ expect(get.mock.calls.map(([url]) => url)).toStrictEqual([
106
+ 'https://agent.test/v1/agent/session?id=srv_1',
107
+ 'https://agent.test/v1/agent/session?id=srv_1',
108
+ ]);
109
+ expect(h.onStatus).toHaveBeenCalledWith(WAITING_FOR_LAST);
110
+ });
111
+
112
+ it('treats an HTTP 409 refusal the same way', async () => {
113
+ const get = agentReads();
114
+ stream.mockResolvedValueOnce(busy409()).mockResolvedValueOnce(sse(['delta', { text: 'Done.' }], ['done', {}]));
115
+ get.mockResolvedValue(json({ in_flight: false }));
116
+
117
+ await expect(
118
+ onFakeClock(() => sendTurn('hello', 'srv_1', handlers(), new AbortController().signal)),
119
+ ).resolves.toBe('Done.');
120
+ expect(new Set(sentTurnIds()).size).toBe(1);
121
+ });
122
+
123
+ // cdecli#838: `queued` says whether another message would be refused; mid-turn there can still be room.
124
+ it('goes as soon as the agent says there is room, even while it is mid-turn', async () => {
125
+ const get = agentReads();
126
+ stream.mockResolvedValueOnce(busySse()).mockResolvedValueOnce(sse(['delta', { text: 'Next.' }], ['done', {}]));
127
+ get.mockResolvedValueOnce(json({ in_flight: true, queued: true })).mockResolvedValueOnce(
128
+ json({ in_flight: true, queued: false }),
129
+ );
130
+
131
+ await expect(
132
+ onFakeClock(() => sendTurn('and this', 'srv_1', handlers(), new AbortController().signal)),
133
+ ).resolves.toBe('Next.');
134
+ expect(get).toHaveBeenCalledTimes(2);
135
+ });
136
+
137
+ // Seen live on dev (cdecli 2.20.120): GET /v1/agent/session said idle while the agent kept refusing.
138
+ it('keeps waiting, longer each time, when the agent reports room but still refuses', async () => {
139
+ const get = agentReads();
140
+ const replies = [busySse(), busySse(), busySse(), busySse(), sse(['delta', { text: 'Ok.' }], ['done', {}])];
141
+ const sentAt: number[] = [];
142
+ stream.mockImplementation(async () => {
143
+ sentAt.push(Date.now());
144
+ return replies.shift();
145
+ });
146
+ get.mockResolvedValue(json({ in_flight: false }));
147
+
148
+ await expect(
149
+ onFakeClock(() => sendTurn('Update me?', 'srv_1', handlers(), new AbortController().signal)),
150
+ ).resolves.toBe('Ok.');
151
+
152
+ const gaps = sentAt.slice(1).map((t, i) => t - sentAt[i]);
153
+
154
+ expect(new Set(sentTurnIds()).size).toBe(1);
155
+ expect(gaps).toHaveLength(4);
156
+ expect(gaps[3]).toBeGreaterThan(gaps[0]);
157
+ });
158
+
159
+ it('keeps waiting through a moment the agent cannot be reached', async () => {
160
+ const get = agentReads();
161
+ stream.mockResolvedValueOnce(busySse()).mockResolvedValueOnce(sse(['delta', { text: 'Back.' }], ['done', {}]));
162
+ get.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(json({ in_flight: false }));
163
+
164
+ await expect(
165
+ onFakeClock(() => sendTurn('hi', 'srv_1', handlers(), new AbortController().signal)),
166
+ ).resolves.toBe('Back.');
167
+ });
168
+
169
+ it('gives up as busy past the agent’s own turn limit', async () => {
170
+ const get = agentReads();
171
+ stream.mockImplementation(async () => busySse());
172
+ get.mockResolvedValue(json({ in_flight: true, queued: true }));
173
+ const started = Date.now();
174
+ let endedAt = 0;
175
+
176
+ await expect(
177
+ onFakeClock(() =>
178
+ sendTurn('hi', 'srv_1', handlers(), new AbortController().signal).finally(() => {
179
+ endedAt = Date.now();
180
+ }),
181
+ ),
182
+ ).rejects.toMatchObject({ kind: 'busy' });
183
+ expect(endedAt - started).toBeGreaterThanOrEqual(BUSY_GIVE_UP_MS);
184
+ expect(stream).toHaveBeenCalledTimes(1);
185
+ });
186
+
187
+ it('stops waiting when the chat stops the reply', async () => {
188
+ const get = agentReads();
189
+ stream.mockImplementation(async () => busySse());
190
+ get.mockResolvedValue(json({ in_flight: true }));
191
+ const stop = new AbortController();
192
+
193
+ await expect(
194
+ onFakeClock(() => {
195
+ setTimeout(() => stop.abort(), 10_000);
196
+ return sendTurn('hi', 'srv_1', handlers(), stop.signal);
197
+ }),
198
+ ).rejects.toMatchObject({ kind: 'stopped' });
199
+ expect(stream).toHaveBeenCalledTimes(1);
200
+ });
201
+ });
@@ -1,5 +1,9 @@
1
1
  // chores.ts reads through chat/auth.ts (native storage): the record parsing and grouping are what is tested here.
2
2
  jest.mock('../chat/auth', () => ({ agentBackendUrl: jest.fn(), getChatToken: jest.fn() }));
3
+ // chores.ts keeps the phone's last list in AsyncStorage, a native module: stub it for node as the other suites do.
4
+ jest.mock('@react-native-async-storage/async-storage', () => ({ getItem: jest.fn(), setItem: jest.fn() }), {
5
+ virtual: true,
6
+ });
3
7
 
4
8
  // eslint-disable-next-line import/first
5
9
  import { choreFromRow, groupChores, setAskingChore, setChoreProgress, type Chore } from '../chat/chores';
@@ -0,0 +1,149 @@
1
+ import {
2
+ connectButton,
3
+ connectHandovers,
4
+ connectHeading,
5
+ connectName,
6
+ connectUrl,
7
+ doneWords,
8
+ stripConnectCards,
9
+ surfaceButton,
10
+ surfaceHandovers,
11
+ } from '../chat/handover';
12
+
13
+ // What Lucy sent on 2026-11-22 when Flipkart wanted a sign-in (replayed on dev): the words, her computer, a login card.
14
+ const FLIPKART = [
15
+ "I've opened Flipkart's sign-in on my computer. Flipkart signs in with your phone number and a code.",
16
+ '',
17
+ '[[surface:computer|Sign in to Flipkart, then tell me]]',
18
+ '',
19
+ '[CONNECTOR_CONNECT]{"requestId":"fk7q2m9d","connector":"site-login","title":"Flipkart login","reason":"Save your Flipkart sign-in so I can sign in for you next time.","form":{"site":"flipkart.com","loginUrl":"https://www.flipkart.com/login"}}[/CONNECTOR_CONNECT]',
20
+ ].join('\n');
21
+
22
+ describe('surfaceHandovers', () => {
23
+ it("hands over Lucy's computer with what to do there", () => {
24
+ expect(surfaceHandovers(FLIPKART)).toEqual([
25
+ {
26
+ id: 'computer',
27
+ title: "Lucy's computer",
28
+ host: 'computer-surface',
29
+ label: 'Sign in to Flipkart, then tell me',
30
+ },
31
+ ]);
32
+ });
33
+
34
+ it('takes each surface once, resolves aliases, and leaves out one this chat cannot open', () => {
35
+ const text =
36
+ '[[surface:computer]] [[surface:Computer|Again]] [[surface:trips|Your trip]] [[surface:mystery|?]]';
37
+ expect(surfaceHandovers(text).map((s) => [s.id, s.label])).toEqual([
38
+ ['computer', ''],
39
+ ['travel', 'Your trip'],
40
+ ]);
41
+ });
42
+
43
+ it('waits for a marker still streaming in', () => {
44
+ expect(surfaceHandovers('Opened it.\n[[surface:compu')).toEqual([]);
45
+ });
46
+
47
+ it('words the button after the surface', () => {
48
+ expect(surfaceButton({ title: "Lucy's computer" })).toBe("Open Lucy's computer");
49
+ });
50
+ });
51
+
52
+ describe('connectHandovers', () => {
53
+ it('reads a website-login card', () => {
54
+ expect(connectHandovers(FLIPKART)).toEqual([
55
+ {
56
+ requestId: 'fk7q2m9d',
57
+ connector: 'site-login',
58
+ title: 'Flipkart login',
59
+ reason: 'Save your Flipkart sign-in so I can sign in for you next time.',
60
+ site: 'flipkart.com',
61
+ loginUrl: 'https://www.flipkart.com/login',
62
+ },
63
+ ]);
64
+ });
65
+
66
+ it('reads the shapes a model drifts to: no closing tag, flat fields, `provider` for `connector`, escaped JSON', () => {
67
+ expect(connectHandovers('Save it.\n[CONNECTOR_CONNECT]{"requestId":"a1","connector":"google-gmail"}')).toEqual([
68
+ { requestId: 'a1', connector: 'google-gmail' },
69
+ ]);
70
+ expect(
71
+ connectHandovers(
72
+ '[CONNECTOR_CONNECT]{"id":"b2","provider":"site-login","site":"amazon.in"}[/CONNECTOR_CONNECT]',
73
+ ),
74
+ ).toEqual([{ requestId: 'b2', connector: 'site-login', site: 'amazon.in' }]);
75
+ expect(connectHandovers('[CONNECTOR_CONNECT]{\\"requestId\\":\\"c3\\",\\"connector\\":\\"openai\\"}')).toEqual([
76
+ { requestId: 'c3', connector: 'openai' },
77
+ ]);
78
+ });
79
+
80
+ it('keeps only what the form reads, as strings, and a sign-in page only over http(s)', () => {
81
+ const [card] = connectHandovers(
82
+ '[CONNECTOR_CONNECT]{"requestId":"d4","connector":"site-login","credentialId":"bad id!","form":{"site":7,"loginUrl":"javascript:alert(1)"}}[/CONNECTOR_CONNECT]',
83
+ );
84
+ expect(card).toEqual({ requestId: 'd4', connector: 'site-login' });
85
+ });
86
+
87
+ it('skips a card with nothing to connect, one still streaming in, and the same card twice', () => {
88
+ expect(connectHandovers('[CONNECTOR_CONNECT]{"requestId":"e5"}[/CONNECTOR_CONNECT]')).toEqual([]);
89
+ expect(connectHandovers('[CONNECTOR_CONNECT]{"requestId":"e5","connec')).toEqual([]);
90
+ const twice = '[CONNECTOR_CONNECT]{"requestId":"f6","connector":"openai"}[/CONNECTOR_CONNECT]';
91
+ expect(connectHandovers(`${twice}\n${twice}`)).toHaveLength(1);
92
+ });
93
+ });
94
+
95
+ describe('stripConnectCards', () => {
96
+ it('takes every card out of the words and keeps the rest', () => {
97
+ expect(
98
+ stripConnectCards(
99
+ 'Before.\n[CONNECTOR_CONNECT]{"requestId":"a","connector":"x"}[/CONNECTOR_CONNECT]\nAfter.',
100
+ ),
101
+ ).toBe('Before.\n\nAfter.');
102
+ expect(stripConnectCards('Before. [CONNECTOR_CONNECT]{"connector":"x","note":"a } in a string"} After.')).toBe(
103
+ 'Before. After.',
104
+ );
105
+ });
106
+
107
+ it('cuts a card still streaming in, and a stray tag of another shape', () => {
108
+ expect(stripConnectCards('Before.\n[CONNECTOR_CONNECT]{"requestId":"a","conn')).toBe('Before.\n');
109
+ expect(stripConnectCards('Before. [CONNECTOR_CONNECT] whatever')).toBe('Before. ');
110
+ expect(stripConnectCards('Before. [/CONNECTOR_CONNECT] After.')).toBe('Before. After.');
111
+ });
112
+ });
113
+
114
+ describe('what a connect card says', () => {
115
+ const login = connectHandovers(FLIPKART)[0];
116
+
117
+ it('names a website login, an autofill entry and an app', () => {
118
+ expect(connectHeading(login)).toBe('Save your Flipkart login');
119
+ expect(connectButton(login)).toBe('Save');
120
+ expect(connectHeading({ requestId: 'a', connector: 'site-login', site: 'myntra.com' })).toBe(
121
+ 'Save your myntra.com login',
122
+ );
123
+ expect(connectHeading({ requestId: 'a', connector: 'autofill-payment-card' })).toBe('Add your payment card');
124
+ expect(connectButton({ requestId: 'a', connector: 'autofill-payment-card' })).toBe('Add');
125
+ expect(connectHeading({ requestId: 'a', connector: 'google-calendar' })).toBe('Connect Google Calendar');
126
+ expect(connectButton({ requestId: 'a', connector: 'google-calendar' })).toBe('Connect');
127
+ });
128
+
129
+ it('says Update for a saved entry it changes', () => {
130
+ const update = { ...login, credentialId: 'cred_1' };
131
+ expect(connectHeading(update)).toBe('Update your Flipkart login');
132
+ expect(connectButton(update)).toBe('Update');
133
+ });
134
+
135
+ it("opens Yantra's /connect page for it, as the kit's card does", () => {
136
+ expect(connectUrl('https://yantra.app/', login)).toBe(
137
+ 'https://yantra.app/connect/site-login?request=fk7q2m9d&via=surface&title=Flipkart%20login&site=flipkart.com&loginUrl=https%3A%2F%2Fwww.flipkart.com%2Flogin',
138
+ );
139
+ expect(connectUrl('https://yantra.app', { requestId: 'x y', connector: 'google-gmail' })).toBe(
140
+ 'https://yantra.app/connect/google-gmail?via=surface',
141
+ );
142
+ expect(connectUrl('', login)).toBe('');
143
+ });
144
+
145
+ it('answers for the person once they are back', () => {
146
+ expect(doneWords('connect', connectName(login))).toBe('I saved my Flipkart login.');
147
+ expect(doneWords('surface', "Lucy's computer")).toBe('Done');
148
+ });
149
+ });
@@ -69,10 +69,32 @@ describe('question cards', () => {
69
69
  });
70
70
 
71
71
  describe('displayText', () => {
72
- it('drops web-only cards and keeps surface labels', () => {
72
+ it('drops web-only widgets and what is drawn under the bubble, and keeps a surface it cannot open as its label', () => {
73
73
  const t =
74
74
  'On it. [[surface:phone-calls|Phone Calls]]\n\n```yantra:widget {"propsComponent":"travel"}```\n[CONNECTOR_CONNECT]{"id":"gmail"}[/CONNECTOR_CONNECT]';
75
- expect(displayText(t)).toBe('On it. Phone Calls');
75
+ expect(displayText(t)).toBe('On it.');
76
+ expect(displayText('Opened it. [[surface:mystery-board|The board]]')).toBe('Opened it. The board');
77
+ });
78
+
79
+ // The Flipkart sign-in of 2026-11-22: the words said "below" and "on my computer", and nothing was there to tap.
80
+ it('keeps the computer hand-over and a website-login card out of the words, with no line left blank', () => {
81
+ const reply = [
82
+ "I've opened Flipkart's sign-in on my computer.",
83
+ '',
84
+ '[[surface:computer|Sign in to Flipkart, then tell me]]',
85
+ '',
86
+ "Tell me when you're signed in.",
87
+ '',
88
+ '[CONNECTOR_CONNECT]{"requestId":"fk7q2m9d","connector":"site-login","title":"Flipkart login","form":{"site":"flipkart.com"}}[/CONNECTOR_CONNECT]',
89
+ ].join('\n');
90
+ expect(displayText(reply)).toBe(
91
+ "I've opened Flipkart's sign-in on my computer.\n\nTell me when you're signed in.",
92
+ );
93
+ });
94
+
95
+ it('never shows a hand-over still streaming in', () => {
96
+ expect(displayText('Opened it.\n\n[[surface:comp')).toBe('Opened it.');
97
+ expect(displayText('Opened it.\n\n[CONNECTOR_CONNECT]{"requestId":"a1","connec')).toBe('Opened it.');
76
98
  });
77
99
 
78
100
  const envelope = JSON.stringify({
@@ -121,5 +143,8 @@ describe('small lines', () => {
121
143
  it('opens sessions as Lucy, taught to ask with cards', () => {
122
144
  expect(SYSTEM_PROMPT).toContain('You are Lucy');
123
145
  expect(SYSTEM_PROMPT).toContain('[ASK_USER]');
146
+ // Lucy knows her computer without being told, and how this chat shows it.
147
+ expect(SYSTEM_PROMPT).toContain('the Computer of the yantra-computer skill');
148
+ expect(SYSTEM_PROMPT).toContain('[[surface:computer|the step there]]');
124
149
  });
125
150
  });
@@ -13,7 +13,7 @@ jest.mock('react-native', () => ({ Platform: { OS: 'ios' }, Linking: { openURL:
13
13
  });
14
14
 
15
15
  // eslint-disable-next-line import/first
16
- import { signedInYantraLink, type SignInDeps } from '../utils/yantraLinks';
16
+ import { appForSurface, signedInYantraLink, type SignInDeps } from '../utils/yantraLinks';
17
17
 
18
18
  const CONNECT = 'https://yantra.app/connect/google-calendar?via=surface';
19
19
  const SIGNED_IN = 'https://yantra.app/auth/app-sign-in?ticket=t&next=%2Fconnect%2Fgoogle-calendar%3Fvia%3Dsurface';
@@ -94,3 +94,68 @@ describe('signedInYantraLink', () => {
94
94
  await expect(signedInYantraLink(CONNECT, all)).resolves.toBe(CONNECT);
95
95
  });
96
96
  });
97
+
98
+ // The screenshot of 2026-11-22: "More in Travel" opened travel-surface on its own "Sign in to Yantra" card.
99
+ describe('surfaces opened signed in', () => {
100
+ const TRAVEL = 'https://travel-surface.yantra.app/?q=flights';
101
+ const VIA_APP = `https://yantra.app/auth/app-sign-in?ticket=t&next=${encodeURIComponent(TRAVEL)}`;
102
+
103
+ it('asks the Yantra app of the surface\u2019s base for a link that goes on to the surface', async () => {
104
+ const { fetch, all } = deps({ url: VIA_APP });
105
+
106
+ await expect(signedInYantraLink(TRAVEL, all)).resolves.toBe(VIA_APP);
107
+ expect(fetch).toHaveBeenCalledWith(
108
+ 'https://yantra.app/resources/app-sign-in/start',
109
+ expect.objectContaining({ body: JSON.stringify({ returnTo: TRAVEL }) }),
110
+ );
111
+ });
112
+
113
+ it('signs in to a staging surface through staging\u2019s Yantra', async () => {
114
+ const surface = 'https://shopping-surface.yantra-app-v1.cdebase.dev/';
115
+ const { fetch, all } = deps(
116
+ { url: 'https://idefront.yantra-app-v1.cdebase.dev/auth/app-sign-in?ticket=t' },
117
+ { agentApp: async () => 'https://idefront.yantra-app-v1.cdebase.dev' },
118
+ );
119
+
120
+ await expect(signedInYantraLink(surface, all)).resolves.toContain('/auth/app-sign-in');
121
+ expect(fetch).toHaveBeenCalledWith(
122
+ 'https://idefront.yantra-app-v1.cdebase.dev/resources/app-sign-in/start',
123
+ expect.anything(),
124
+ );
125
+ });
126
+
127
+ it.each([
128
+ ['a surface of another site', 'https://travel-surface.evil.example/'],
129
+ ['a Yantra host that is not a surface', 'https://travel.yantra.app/'],
130
+ ['a surface one level down', 'https://a.travel-surface.yantra.app/'],
131
+ ['a surface over http', 'http://travel-surface.yantra.app/'],
132
+ ])('leaves %s as it is, without the token', async (_name, url) => {
133
+ const { fetch, all } = deps();
134
+
135
+ await expect(signedInYantraLink(url, all)).resolves.toBe(url);
136
+ expect(fetch).not.toHaveBeenCalled();
137
+ });
138
+
139
+ it('opens the surface as before when that Yantra does not take surfaces yet', async () => {
140
+ const { all } = deps({ ok: false });
141
+
142
+ await expect(signedInYantraLink(TRAVEL, all)).resolves.toBe(TRAVEL);
143
+ });
144
+
145
+ it('takes only a link on the Yantra app that was asked, never one on the surface or elsewhere', async () => {
146
+ const { all } = deps({ url: 'https://travel-surface.yantra.app/?code=x' });
147
+
148
+ await expect(signedInYantraLink(TRAVEL, all)).resolves.toBe(TRAVEL);
149
+ });
150
+
151
+ it('finds the app of a surface by its base', () => {
152
+ const apps = ['https://yantra.app', 'https://idefront.yantra-app-v1.cdebase.dev'];
153
+
154
+ expect(appForSurface('https://travel-surface.yantra.app', apps)).toBe('https://yantra.app');
155
+ expect(appForSurface('https://travel-surface.yantra-app-v1.cdebase.dev', apps)).toBe(
156
+ 'https://idefront.yantra-app-v1.cdebase.dev',
157
+ );
158
+ expect(appForSurface('https://travel-surface.cdebase.dev', apps)).toBe('');
159
+ expect(appForSurface('https://travel.yantra.app', apps)).toBe('');
160
+ });
161
+ });
package/src/chat/agent.ts CHANGED
@@ -10,6 +10,11 @@
10
10
  * to its end there, never run twice. So when the phone is locked or the app leaves the front mid-reply, the turn is
11
11
  * not failed: it waits for the app to be in front again and sends the same turn once more. A line that has gone
12
12
  * silent (the agent writes at least every 15 seconds) is let go the same way.
13
+ *
14
+ * A message the agent refuses as busy is not failed either: the session is still on an earlier turn (one this phone
15
+ * stopped listening to, or another device's) and took nothing. It waits until the agent says the session has room
16
+ * GET /v1/agent/session?id=<session> -> {in_flight, queued}
17
+ * and then goes, with the same turn id.
13
18
  */
14
19
  import { fetch as streamFetch } from 'expo/fetch';
15
20
  import { inFront, onFront, whenInFront } from './appFront';
@@ -318,12 +323,58 @@ const wait = (ms: number, signal: AbortSignal) =>
318
323
  }, ms);
319
324
  });
320
325
 
326
+ /** What the reply says while its message waits for the session to finish an earlier turn. */
327
+ export const WAITING_FOR_LAST = 'Waiting for the last message to finish';
328
+ /**
329
+ * Before asking again after the n-th refusal: the session's own report can say it has room a moment before the agent
330
+ * lets the earlier turn go (seen live on dev, cdecli 2.20.120), so each refusal waits a little longer.
331
+ */
332
+ export const BUSY_BACKOFF_MS = [2000, 4000, 8000, 15_000, 30_000] as const;
333
+ /** How often to ask while the session is on its turn. */
334
+ const BUSY_POLL_MS = 5000;
335
+ /** Past the agent's own 20-minute turn limit: a session still refusing then is a real refusal. */
336
+ export const BUSY_GIVE_UP_MS = 25 * 60_000;
337
+
338
+ /**
339
+ * Waits until the agent says `sessionId` has room for another message: no turn held behind the one it is on
340
+ * (`queued`), or, from an agent that does not say, not on a turn at all (`in_flight`). False past `deadline`.
341
+ */
342
+ async function waitForRoom(
343
+ sessionId: string,
344
+ refusals: number,
345
+ deadline: number,
346
+ handlers: TurnHandlers,
347
+ signal: AbortSignal,
348
+ ): Promise<boolean> {
349
+ handlers.onStatus(WAITING_FOR_LAST);
350
+ await wait(BUSY_BACKOFF_MS[Math.min(Math.max(refusals, 1), BUSY_BACKOFF_MS.length) - 1], signal);
351
+ for (;;) {
352
+ if (Date.now() > deadline) return false;
353
+ try {
354
+ const res = await authed(`/v1/agent/session?id=${encodeURIComponent(sessionId)}`, { method: 'GET' });
355
+ // Gone from the agent: nothing is in the way any more.
356
+ if (res.status === 404) return true;
357
+ if (res.ok) {
358
+ const s = (await res.json().catch(() => null)) as { in_flight?: boolean; queued?: boolean } | null;
359
+ const full = typeof s?.queued === 'boolean' ? s.queued : !!s?.in_flight;
360
+ if (s && !full) return true;
361
+ }
362
+ } catch {
363
+ if (signal.aborted) throw stoppedError();
364
+ // Unreachable for a moment, or the keychain shut: keep waiting.
365
+ }
366
+ handlers.onStatus(WAITING_FOR_LAST);
367
+ await wait(BUSY_POLL_MS, signal);
368
+ }
369
+ }
370
+
321
371
  /**
322
372
  * Sends `message` on `sessionId` and streams Lucy's reply, retrying the way the web chat does: a resend repeats the same
323
373
  * turn id (so the agent never runs it twice), a continue keeps the partial reply and asks Lucy to carry on.
324
374
  *
325
375
  * A line lost while the app was away (the phone locked, the app in the background), a keychain the lock shut, or a
326
376
  * line gone silent never fails the turn: once the app is in front, the same turn is sent again and followed to its end.
377
+ * Nor does a refusal as busy: the same turn goes once the session has room (waitForRoom), for up to BUSY_GIVE_UP_MS.
327
378
  */
328
379
  export async function sendTurn(
329
380
  message: string,
@@ -338,6 +389,8 @@ export async function sendTurn(
338
389
  let attempt = 0;
339
390
  let pickups = 0;
340
391
  let shutInFront = 0;
392
+ let refusals = 0;
393
+ let busySince = 0;
341
394
  for (;;) {
342
395
  const line = watchLine(signal);
343
396
  try {
@@ -356,6 +409,18 @@ export async function sendTurn(
356
409
  shutInFront += 1;
357
410
  if (shutInFront > SHUT_IN_FRONT_TRIES) throw err;
358
411
  await wait(1000, signal);
412
+ } else if (err instanceof TurnError && err.kind === 'busy') {
413
+ // Refused, not taken: the same turn id goes once there is room.
414
+ refusals += 1;
415
+ if (!busySince) busySince = Date.now();
416
+ const room = await waitForRoom(
417
+ err.sessionId || sessionId,
418
+ refusals,
419
+ busySince + BUSY_GIVE_UP_MS,
420
+ handlers,
421
+ signal,
422
+ );
423
+ if (!room) throw err;
359
424
  } else {
360
425
  const e = err as TurnError & { partial?: string };
361
426
  if (!(e instanceof TurnError) || !e.retry || attempt >= BACKOFF_MS.length || e.kind === 'stopped')