@adminide-stack/clock-tik-mobile 12.0.37-alpha.0 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/jest.config.cjs +3 -0
  3. package/lib/chat/agent.js +40 -1
  4. package/lib/chat/agent.js.map +1 -1
  5. package/lib/chat/connectors.js +3 -0
  6. package/lib/chat/connectors.js.map +1 -1
  7. package/lib/chat/handover.js +196 -0
  8. package/lib/chat/handover.js.map +1 -0
  9. package/lib/chat/protocol.js +16 -2
  10. package/lib/chat/protocol.js.map +1 -1
  11. package/lib/components/HandoverCards.js +179 -0
  12. package/lib/components/HandoverCards.js.map +1 -0
  13. package/lib/components/ResultCards.js +3 -3
  14. package/lib/components/ResultCards.js.map +1 -1
  15. package/lib/config/env-config.js +7 -1
  16. package/lib/config/env-config.js.map +1 -1
  17. package/lib/offer/blackFriday.js.map +1 -1
  18. package/lib/offer/state.js.map +1 -1
  19. package/lib/screens/Chat/index.js +2 -1
  20. package/lib/screens/Chat/index.js.map +1 -1
  21. package/lib/screens/Home/index.js +9 -5
  22. package/lib/screens/Home/index.js.map +1 -1
  23. package/lib/utils/yantraLinks.js +26 -8
  24. package/lib/utils/yantraLinks.js.map +1 -1
  25. package/package.json +4 -4
  26. package/src/__tests__/agent.test.ts +201 -0
  27. package/src/__tests__/chores.test.ts +15 -2
  28. package/src/__tests__/connectLink.test.ts +21 -0
  29. package/src/__tests__/envConfig.test.ts +14 -0
  30. package/src/__tests__/handover.test.ts +149 -0
  31. package/src/__tests__/protocol.test.ts +27 -2
  32. package/src/__tests__/yantraLinks.test.ts +66 -1
  33. package/src/chat/agent.ts +65 -0
  34. package/src/chat/connectors.ts +13 -3
  35. package/src/chat/handover.ts +241 -0
  36. package/src/chat/protocol.ts +23 -7
  37. package/src/components/HandoverCards.tsx +224 -0
  38. package/src/components/ResultCards.tsx +4 -3
  39. package/src/config/env-config.ts +13 -0
  40. package/src/offer/blackFriday.ts +1 -1
  41. package/src/offer/state.ts +1 -1
  42. package/src/screens/Chat/index.tsx +6 -1
  43. package/src/screens/Home/index.tsx +10 -7
  44. package/src/utils/yantraLinks.ts +40 -10
@@ -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')
@@ -3,8 +3,9 @@
3
3
  * the two in step), and where each one is connected.
4
4
  *
5
5
  * Clockbook connects nothing itself: the connection is the person's Yantra account's (Clockbook runs on Yantra), so
6
- * Connect opens the Yantra app's public `/connect/<connector>` page, which signs them in when needed and opens the
7
- * connector's form. Once saved, Lucy can use it here and everywhere else on Yantra.
6
+ * Connect opens the Yantra app signed in (utils/yantraLinks.ts) on the connector's own form: an app's connect form on
7
+ * the Connectors page, a vault entry's form behind Yantra's `/connect/<connector>` page. Once saved, Lucy can use it
8
+ * here and everywhere else on Yantra.
8
9
  */
9
10
  export type ConnectorGroup = 'apps' | 'saved';
10
11
 
@@ -50,11 +51,20 @@ export function connectVerb(connector: Pick<LucyConnector, 'group'>): string {
50
51
 
51
52
  const base = (appUrl: string) => appUrl.trim().replace(/\/+$/, '');
52
53
 
53
- /** Yantra's page that connects `id`: `<app>/connect/<id>?via=surface`. '' without an app or an id. */
54
+ /**
55
+ * Where Yantra connects `id`, '' without an app or an id:
56
+ * - an app (Google Calendar, Gmail): its connect form, opened at once on the Connectors page
57
+ * (`<app>/account/connectors?credentialChain=<id>&autoStart=true`) - no connect page in between, which only
58
+ * redirected there, and no "Open in Connectors" step;
59
+ * - a vault entry (a website login, an address, a card) or anything else: Yantra's connect page for it
60
+ * (`<app>/connect/<id>?via=surface`), which opens the vault form for its kind.
61
+ */
54
62
  export function connectLink(appUrl: string, id: string): string {
55
63
  const app = base(appUrl);
56
64
  const connector = id.trim();
57
65
  if (!app || !connector) return '';
66
+ const isApp = LUCY_CONNECTORS.some((c) => c.id === connector && c.group === 'apps');
67
+ if (isApp) return `${app}/account/connectors?credentialChain=${encodeURIComponent(connector)}&autoStart=true`;
58
68
  return `${app}/connect/${encodeURIComponent(connector)}?via=surface`;
59
69
  }
60
70
 
@@ -0,0 +1,241 @@
1
+ /**
2
+ * What Lucy hands over beside her words: a place to do a step herself can't (her Computer, to sign in to a site or pass
3
+ * a robot check; another of Yantra's surfaces), as a `[[surface:<id>|<what to do there>]]` marker, and something to
4
+ * connect or keep in the vault (a website login, a card, an app), as a `[CONNECTOR_CONNECT]{…}[/CONNECTOR_CONNECT]`
5
+ * card. The web chat draws both (browser surfaces.ts with CallsCard's SurfaceLinks, and the kit's ConnectorConnectCard).
6
+ * This chat used to take them out of the bubble and draw nothing, so "save it below" and "sign in on your Computer"
7
+ * pointed at nothing a phone could tap. components/HandoverCards.tsx draws them; these are the pure parts.
8
+ *
9
+ * The connect marker rules are a copy of the kit's (`@yantra/surface-kit` chat/connectorConnectProtocol.ts, itself a
10
+ * copy of yantra-app common's CONNECTOR_CONNECT_PROTOCOL): the documented shape, and the same shape whose closing tag
11
+ * the model left off. Keep the link in step with the kit's connectorConnectUrl, which Yantra's /connect page reads.
12
+ */
13
+ import { surfaceLink, takeSurfaceMarkers } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';
14
+
15
+ /* ----------------------------------------------------------------------------- surfaces */
16
+
17
+ export interface SurfaceHandover {
18
+ /** The surface's own id, an alias resolved: `computer`. */
19
+ id: string;
20
+ /** "your Computer". */
21
+ title: string;
22
+ /** Its host's first label: `computer-surface`. */
23
+ host: string;
24
+ /** What Lucy said to do there ("Sign in to Flipkart"); may be empty. */
25
+ label: string;
26
+ }
27
+
28
+ /** The surfaces a reply hands over, each once, in order; one this chat cannot open is left out. */
29
+ export function surfaceHandovers(text: string): SurfaceHandover[] {
30
+ const seen = new Set<string>();
31
+ return takeSurfaceMarkers(text).markers.flatMap((marker) => {
32
+ const link = surfaceLink(marker.id);
33
+ if (!link || seen.has(link.id)) return [];
34
+ seen.add(link.id);
35
+ return [{ ...link, label: marker.label }];
36
+ });
37
+ }
38
+
39
+ /** The card's button: "Open your Computer", "Open Phone Calls". */
40
+ export function surfaceButton(surface: Pick<SurfaceHandover, 'title'>): string {
41
+ return `Open ${surface.title}`;
42
+ }
43
+
44
+ /* ----------------------------------------------------------------------------- connect cards */
45
+
46
+ export const SITE_LOGIN = 'site-login';
47
+
48
+ export interface ConnectHandover {
49
+ requestId: string;
50
+ /** A catalog connector's template key, `site-login`, or an autofill kind (`autofill-payment-card`). */
51
+ connector: string;
52
+ /** The card's name for it ("Flipkart login"). */
53
+ title?: string;
54
+ /** Why Lucy asks, one sentence. */
55
+ reason?: string;
56
+ /** For a website login: the site and the sign-in page her Computer is on. */
57
+ site?: string;
58
+ loginUrl?: string;
59
+ /** The saved entry the card updates, when Lucy names one. */
60
+ credentialId?: string;
61
+ }
62
+
63
+ const OPEN_TAG = /\[CONNECTOR_CONNECT\]\s*(?=\{)/g;
64
+ const CLOSE_TAG = /^\s*\[\/CONNECTOR_CONNECT\]/;
65
+ const SAFE_ID = /^[A-Za-z0-9_-]+$/;
66
+
67
+ /** The JSON object that opens at `text[start]`, through its matching `}`; null while it is still coming in. */
68
+ function balancedObject(text: string, start: number): string | null {
69
+ let depth = 0;
70
+ let inString = false;
71
+ for (let i = start; i < text.length; i += 1) {
72
+ const ch = text[i];
73
+ if (inString) {
74
+ if (ch === '\\') i += 1;
75
+ else if (ch === '"') inString = false;
76
+ } else if (ch === '"') inString = true;
77
+ else if (ch === '{') depth += 1;
78
+ else if (ch === '}') {
79
+ depth -= 1;
80
+ if (depth === 0) return text.slice(start, i + 1);
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /**
87
+ * A card's body opening at `text[start]`: the object through its matching `}`, or, for a body copied out of a tool result
88
+ * with its quotes still escaped (`{\"connector\":…}`, whose braces never balance), through the `}` before the closing
89
+ * tag or the end. null while it is still coming in.
90
+ */
91
+ function cardBody(text: string, start: number): string | null {
92
+ const json = balancedObject(text, start);
93
+ if (json) return json;
94
+ const escaped = /^\{\s*\\"[\s\S]*?\}(?=\s*(?:\[\/CONNECTOR_CONNECT\]|$))/.exec(text.slice(start));
95
+ return escaped ? escaped[0] : null;
96
+ }
97
+
98
+ const clean = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
99
+
100
+ function readBody(json: string): Record<string, unknown> | null {
101
+ const parse = (s: string) => {
102
+ try {
103
+ const body = JSON.parse(s) as unknown;
104
+ return body && typeof body === 'object' && !Array.isArray(body) ? (body as Record<string, unknown>) : null;
105
+ } catch {
106
+ return null;
107
+ }
108
+ };
109
+ // A body copied out of a tool result with one level of escaping left on (`{\"connector\":…}`).
110
+ return parse(json) ?? (/^\{\s*\\"/.test(json) ? parse(json.replace(/\\(["\\])/g, '$1')) : null);
111
+ }
112
+
113
+ function toHandover(body: Record<string, unknown>, index: number): ConnectHandover | null {
114
+ // `provider` and `type` are what the model writes in place of `connector`.
115
+ const connector = clean(body.connector) ?? clean(body.provider) ?? clean(body.type);
116
+ if (!connector) return null;
117
+ const card: ConnectHandover = {
118
+ requestId: clean(body.requestId) ?? clean(body.id) ?? `connect-${index}`,
119
+ connector,
120
+ };
121
+ const title = clean(body.title) ?? clean(body.label) ?? clean(body.name);
122
+ const reason = clean(body.reason);
123
+ const credentialId = clean(body.credentialId) ?? clean(body.credential_id);
124
+ if (title) card.title = title;
125
+ if (reason) card.reason = reason;
126
+ if (credentialId && SAFE_ID.test(credentialId)) card.credentialId = credentialId;
127
+ // Only the fields the form reads, only as strings: the marker is model output. Nested under `form`, or flat.
128
+ const form = (body.form && typeof body.form === 'object' ? body.form : body) as Record<string, unknown>;
129
+ const site = clean(form.site);
130
+ const loginUrl = clean(form.loginUrl) ?? clean(form.login_url) ?? clean(form.url);
131
+ if (site) card.site = site;
132
+ if (loginUrl && /^https?:\/\//i.test(loginUrl)) card.loginUrl = loginUrl;
133
+ return card;
134
+ }
135
+
136
+ /** Every finished connect card in a reply, in order; one still streaming in is left for the next read. */
137
+ export function connectHandovers(text: string): ConnectHandover[] {
138
+ const cards: ConnectHandover[] = [];
139
+ for (const m of text.matchAll(OPEN_TAG)) {
140
+ const start = (m.index ?? 0) + m[0].length;
141
+ const json = cardBody(text, start);
142
+ const body = json ? readBody(json) : null;
143
+ const card = body ? toHandover(body, cards.length) : null;
144
+ if (card && !cards.some((c) => c.requestId === card.requestId)) cards.push(card);
145
+ }
146
+ return cards;
147
+ }
148
+
149
+ /** Every connect card's text, gone from the words: finished, missing its closing tag, or still coming in. */
150
+ export function stripConnectCards(text: string): string {
151
+ let out = '';
152
+ let at = 0;
153
+ // A tag inside a card already cut (index < at) went with that card.
154
+ for (const m of text.matchAll(OPEN_TAG)) {
155
+ const index = m.index ?? 0;
156
+ if (index >= at) {
157
+ out += text.slice(at, index);
158
+ const start = index + m[0].length;
159
+ const json = cardBody(text, start);
160
+ if (!json) return out; // still streaming in: nothing after it is the bubble's yet
161
+ const close = CLOSE_TAG.exec(text.slice(start + json.length));
162
+ at = start + json.length + (close ? close[0].length : 0);
163
+ }
164
+ }
165
+ out += text.slice(at);
166
+ // An opening tag the cards above did not take (no body yet, or not JSON) runs to its closing tag or the end, as
167
+ // the bubble always cut it; a closing tag left on its own goes alone.
168
+ return out
169
+ .replace(/\[CONNECTOR_CONNECT\][\s\S]*?(?:\[\/CONNECTOR_CONNECT\]|$)/g, '')
170
+ .replace(/\[\/CONNECTOR_CONNECT\]/g, '');
171
+ }
172
+
173
+ const isSiteLogin = (card: Pick<ConnectHandover, 'connector'>) => card.connector.toLowerCase() === SITE_LOGIN;
174
+
175
+ /** An autofill entry the vault keeps (a card, an address, a passport), as words: "payment card". */
176
+ function autofillNoun(connector: string): string | undefined {
177
+ const raw = connector.trim().toLowerCase();
178
+ if (!/^autofill[-_ ]/.test(raw)) return undefined;
179
+ return (
180
+ raw
181
+ .replace(/^autofill[-_ ]+/, '')
182
+ .replace(/[-_]+/g, ' ')
183
+ .trim() || undefined
184
+ );
185
+ }
186
+
187
+ /** What the card connects, as it names it: "Flipkart login", "Google Calendar". */
188
+ export function connectName(card: ConnectHandover): string {
189
+ if (card.title) return card.title;
190
+ if (isSiteLogin(card)) return card.site ? `${card.site} login` : 'website login';
191
+ const noun = autofillNoun(card.connector);
192
+ if (noun) return noun;
193
+ const words = card.connector
194
+ .replace(/-app-[a-z0-9]+$/i, '')
195
+ .replace(/[_-]+/g, ' ')
196
+ .trim();
197
+ return words ? words.replace(/\b\w/g, (c) => c.toUpperCase()) : card.connector;
198
+ }
199
+
200
+ /** The card's heading (the kit's connectorConnectHeading): "Save your Flipkart login", "Connect Google Calendar". */
201
+ export function connectHeading(card: ConnectHandover): string {
202
+ const noun = autofillNoun(card.connector);
203
+ if (noun && !card.title) return `${card.credentialId ? 'Update' : 'Add'} your ${noun}`;
204
+ if (isSiteLogin(card)) return `${card.credentialId ? 'Update' : 'Save'} your ${connectName(card)}`;
205
+ return `Connect ${connectName(card)}`;
206
+ }
207
+
208
+ /** The button's word. */
209
+ export function connectButton(card: ConnectHandover): string {
210
+ if (card.credentialId) return 'Update';
211
+ if (isSiteLogin(card)) return 'Save';
212
+ return autofillNoun(card.connector) ? 'Add' : 'Connect';
213
+ }
214
+
215
+ /**
216
+ * Yantra's page for the card (the kit's connectorConnectUrl): `/connect/<connector>` with the site, the sign-in page
217
+ * and the entry it updates, `via=surface` because no gateway answers this chat. '' without an app.
218
+ */
219
+ export function connectUrl(appUrl: string, card: ConnectHandover): string {
220
+ const base = appUrl.trim().replace(/\/+$/, '');
221
+ if (!base) return '';
222
+ const params: string[] = [];
223
+ const add = (key: string, value: string) => params.push(`${key}=${encodeURIComponent(value)}`);
224
+ if (SAFE_ID.test(card.requestId)) add('request', card.requestId);
225
+ add('via', 'surface');
226
+ if (card.title) add('title', card.title);
227
+ if (card.credentialId) add('credential', card.credentialId);
228
+ if (isSiteLogin(card)) {
229
+ if (card.site) add('site', card.site);
230
+ if (card.loginUrl) add('loginUrl', card.loginUrl);
231
+ }
232
+ return `${base}/connect/${encodeURIComponent(card.connector)}?${params.join('&')}`;
233
+ }
234
+
235
+ /**
236
+ * What the person says back from a card once they have been there, so Lucy carries on without them typing it: "Done"
237
+ * is the word her Computer hand-over waits for (yantra-computer "When they say done"); a saved login she looks up.
238
+ */
239
+ export function doneWords(kind: 'surface' | 'connect', name: string): string {
240
+ return kind === 'connect' ? `I saved my ${name}.` : 'Done';
241
+ }
@@ -8,6 +8,8 @@ import {
8
8
  RESULT_CARDS_PROMPT,
9
9
  takeResultWidgets,
10
10
  } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/results.js';
11
+ import { surfaceLink } from '@adminide-stack/clock-tik-browser/lib/pages/Home/chat/surfaces.js';
12
+ import { stripConnectCards } from './handover';
11
13
 
12
14
  export const MAX_QUESTIONS = 6;
13
15
 
@@ -152,18 +154,32 @@ export function formatAskAnswers(ask: AskUser, answers: Record<string, AskAnswer
152
154
 
153
155
  /* ----------------------------------------------------------------------------- display */
154
156
 
157
+ /** A surface marker as the gateway reads it (surfaces.ts MARKER): `[[surface:<id>]]` or `[[surface:<id>|<label>]]`. */
158
+ const SURFACE_MARKER = /[ \t]*\[\[\s*surface\s*:\s*([A-Za-z0-9_-]{1,40})\s*(?:\|\s*([^\]\n]{0,200}?))?\s*\]\]/gi;
159
+
160
+ /** The text without a surface marker still streaming in at its end (`[[surface:comp`), as surfaces.ts cuts it. */
161
+ function withoutUnfinishedSurface(text: string): string {
162
+ const at = text.lastIndexOf('[[');
163
+ if (at < 0) return text;
164
+ const tail = text.slice(at + 2);
165
+ if (tail.includes('\n') || tail.includes(']]')) return text;
166
+ const head = tail.trimStart().toLowerCase();
167
+ return head.startsWith('surface') || 'surface'.startsWith(head) ? text.slice(0, at) : text;
168
+ }
169
+
155
170
  /**
156
171
  * A reply's text as the bubble shows it: no question block (it has its own card), no result blocks in any of the forms
157
- * a model writes them (fenced, under a bare marker, or still streaming in: they draw as cards), and the web-only
158
- * markers either dropped (Connect cards, other widgets) or reduced to a plain label (surface links).
172
+ * a model writes them (fenced, under a bare marker, or still streaming in: they draw as cards), no Connect cards and no
173
+ * marker of a surface this chat opens (both drawn under the bubble, components/HandoverCards.tsx), other widgets
174
+ * dropped, and a surface this chat cannot open reduced to its plain label.
159
175
  */
160
176
  export function displayText(text: string): string {
161
- return takeResultWidgets(text)
162
- .content.replace(ASK_RE_ALL, '')
163
- .replace(/\[CONNECTOR_CONNECT\][\s\S]*?(?:\[\/CONNECTOR_CONNECT\]|$)/g, '')
177
+ return withoutUnfinishedSurface(stripConnectCards(takeResultWidgets(text).content.replace(ASK_RE_ALL, '')))
164
178
  .replace(/```yantra:widget[\s\S]*?(?:```|$)/g, '')
165
- .replace(/\[\[surface:[^|\]]+\|([^\]]+)\]\]/g, '$1')
166
- .replace(/\[\[surface:([^\]]+)\]\]/g, '$1')
179
+ .replace(SURFACE_MARKER, (marker: string, id: string, label: string | undefined) =>
180
+ surfaceLink(id) ? '' : `${/^[ \t]*/.exec(marker)?.[0] ?? ''}${(label ?? id).trim()}`,
181
+ )
182
+ .replace(/^[ \t]+$/gm, '')
167
183
  .replace(/\n{3,}/g, '\n\n')
168
184
  .trim();
169
185
  }