@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9
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/README.i18n.yaml +2 -2
- package/README.md +93 -26
- package/README.zh.md +91 -26
- package/icon.svg +3 -0
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +8891 -2433
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/approvals.d.ts +24 -0
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +124 -5
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/dsh-frames.d.ts +155 -4
- package/lib/types/core/envelope.d.ts +34 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/hub.d.ts +96 -20
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +491 -2
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +109 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/core/wire.d.ts +1 -1
- package/lib/types/core/ws-frames.d.ts +11 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/host/websocket.d.ts +8 -1
- package/lib/types/index.d.ts +34 -3
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +20 -14
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/approvals.ts +32 -1
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +1483 -31
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +221 -3
- package/src/core/dsh-frames.ts +365 -8
- package/src/core/envelope.ts +46 -0
- package/src/core/extension.ts +197 -0
- package/src/core/hub.ts +441 -49
- package/src/core/jobs.ts +372 -0
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +556 -2
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +264 -17
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +13 -1
- package/src/core/ws-frames.ts +14 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/host/websocket.ts +37 -3
- package/src/index.ts +310 -9
- package/src/mount-once.ts +142 -0
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Live Activity half of the push channel (protocol §29).
|
|
3
|
+
*
|
|
4
|
+
* The alert channel in `core/push.ts` tells a phone something happened; a Live
|
|
5
|
+
* Activity is the lock-screen card that keeps being right while the app is
|
|
6
|
+
* suspended, which is why it is a second payload with its own rules rather than
|
|
7
|
+
* a field on the first one:
|
|
8
|
+
*
|
|
9
|
+
* - the request is a `liveactivity` push to a per-card APNs token, under the app
|
|
10
|
+
* bundle's `.push-type.liveactivity` topic, with `apns-expiration: 0` — a card
|
|
11
|
+
* update that arrives late is a lie about the present, so it is never resent;
|
|
12
|
+
* - `content-state` is the App's own `SessionActivityState`, decoded with
|
|
13
|
+
* ActivityKit's default Codable strategy. Timestamps in it are seconds since
|
|
14
|
+
* Apple's reference date (2001-01-01T00:00:00Z), never Unix seconds: a Unix
|
|
15
|
+
* number decodes as a date decades away and the whole card fails to decode;
|
|
16
|
+
* - one card shows one session. A registered card names its session, a card
|
|
17
|
+
* without one is never pushed to, and a state is delivered to the cards whose
|
|
18
|
+
* session it is about — never to "all cards", because that is how one session's
|
|
19
|
+
* question ends up on another session's lock screen (§29.9). `runningCount` is
|
|
20
|
+
* the one bridge-wide number on a card, and it stays the total on purpose;
|
|
21
|
+
* - one card lays out at most three rows (§30). The address is still one session
|
|
22
|
+
* per card — rows say what that card has to tell, not who it is sent to — and
|
|
23
|
+
* every card is given them the same way: the sessions waiting on the user
|
|
24
|
+
* first, in the order their questions arrived, then the sessions running now,
|
|
25
|
+
* most recently updated first. A row's name is the host's own title with its
|
|
26
|
+
* trailing path group taken off, because §29.5 keeps paths off a lock screen;
|
|
27
|
+
* - a card that would say what the card before it already said is not sent, one
|
|
28
|
+
* activity takes at most one update per `LIVE_ACTIVITY_INTERVAL_MS`, and
|
|
29
|
+
* the whole bridge at most `LIVE_ACTIVITY_PER_MINUTE` a minute. What does
|
|
30
|
+
* not fit is dropped, never queued: a card is a snapshot of now, and a backlog
|
|
31
|
+
* of stale snapshots is exactly what this channel must not deliver.
|
|
32
|
+
*
|
|
33
|
+
* Nothing here is awaited by a frame path. Every entry point returns before a
|
|
34
|
+
* delivery starts, and a failure — connection, 401, 410, 5xx, timeout — is one
|
|
35
|
+
* log line and a dropped card, never a delayed or broken follow stream (§28.5).
|
|
36
|
+
* @module dsh-remote-bridge/core/liveactivity
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import type { PushSendResult } from './push.ts'
|
|
40
|
+
import { pushEventOfTurnEnd } from './push.ts'
|
|
41
|
+
|
|
42
|
+
/** The phases a lock-screen card can report. */
|
|
43
|
+
export type SessionActivityPhase = 'running' | 'waitingForAnswer' | 'failed' | 'ended'
|
|
44
|
+
|
|
45
|
+
/** The two events one Live Activity push carries. */
|
|
46
|
+
export type LiveActivityEvent = 'update' | 'end'
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Seconds from 1970-01-01T00:00:00Z to Apple's reference date, 2001-01-01T00:00:00Z.
|
|
50
|
+
*
|
|
51
|
+
* ActivityKit encodes a `Date` as a double relative to that reference date, so a
|
|
52
|
+
* value meant to decode as "now" is Unix seconds minus this offset.
|
|
53
|
+
*/
|
|
54
|
+
export const APPLE_REFERENCE_OFFSET_SECONDS = 978_307_200
|
|
55
|
+
|
|
56
|
+
/** How long after delivery iOS may still treat a card as current. */
|
|
57
|
+
export const LIVE_ACTIVITY_STALE_SECONDS = 90
|
|
58
|
+
|
|
59
|
+
/** Shortest gap between two updates of the same activity. */
|
|
60
|
+
export const LIVE_ACTIVITY_INTERVAL_MS = 5_000
|
|
61
|
+
|
|
62
|
+
/** Most Live Activity pushes this bridge sends in any rolling minute. */
|
|
63
|
+
export const LIVE_ACTIVITY_PER_MINUTE = 30
|
|
64
|
+
|
|
65
|
+
/** Longest option list a card carries; the App shows them as the answer choices. */
|
|
66
|
+
export const LIVE_ACTIVITY_OPTION_LIMIT = 2
|
|
67
|
+
|
|
68
|
+
/** Most rows one card lays out; a fourth is dropped, never wrapped or paged (§30.2). */
|
|
69
|
+
export const LIVE_ACTIVITY_ROW_LIMIT = 3
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Longest row name a card carries, in characters.
|
|
73
|
+
*
|
|
74
|
+
* A row is one line under a status phrase, so a name longer than this is cut
|
|
75
|
+
* rather than allowed to push the rest of the card off the glass.
|
|
76
|
+
*/
|
|
77
|
+
export const LIVE_ACTIVITY_ROW_NAME_MAX = 48
|
|
78
|
+
|
|
79
|
+
/** Activity ids whose last content is remembered before the oldest is forgotten. */
|
|
80
|
+
export const LIVE_ACTIVITY_TRACKED = 64
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The one line a card shows per phase, in the App's own words.
|
|
84
|
+
*
|
|
85
|
+
* Fixed English strings, one per phase, and the same table the App renders
|
|
86
|
+
* (§29.7, §30.2): the words on the glass are the client's, so a bridge that sent
|
|
87
|
+
* its own would put a second language on the same card. Fixed for the second
|
|
88
|
+
* reason the alert channel's bodies are fixed too — a line built out of host text
|
|
89
|
+
* is session content on a lock screen. `core/push.ts` keeps its own localized
|
|
90
|
+
* bodies: a notification is read in the user's language, a card is the App's, and
|
|
91
|
+
* both are the same event said for two different surfaces.
|
|
92
|
+
*/
|
|
93
|
+
export const ACTIVITY_STATUS_LINE = {
|
|
94
|
+
running: 'Running',
|
|
95
|
+
waitingForAnswer: 'Waiting for your answer',
|
|
96
|
+
failed: 'Stopped',
|
|
97
|
+
ended: 'Turn finished',
|
|
98
|
+
} as const
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The fixed line one phase shows.
|
|
102
|
+
*
|
|
103
|
+
* The one accessor the single-session field and a row both go through, so a
|
|
104
|
+
* phase cannot be named two ways on one card.
|
|
105
|
+
* @param phase - the phase whose line is wanted.
|
|
106
|
+
* @returns the App's own English phrase for it.
|
|
107
|
+
*/
|
|
108
|
+
export function statusLineOf(phase: SessionActivityPhase): string {
|
|
109
|
+
return ACTIVITY_STATUS_LINE[phase]
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* How iOS ranks one card against another.
|
|
114
|
+
*
|
|
115
|
+
* A card waiting on the user outranks one reporting work in progress, which in
|
|
116
|
+
* turn outranks a finished one; `ended` is last because it is on its way out.
|
|
117
|
+
*/
|
|
118
|
+
const RELEVANCE_SCORE: Readonly<Record<SessionActivityPhase, number>> = {
|
|
119
|
+
waitingForAnswer: 100,
|
|
120
|
+
failed: 90,
|
|
121
|
+
running: 60,
|
|
122
|
+
ended: 10,
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* One row of the multi-session card (§30.2).
|
|
127
|
+
*
|
|
128
|
+
* Exactly three keys, all non-empty: the host's own name for the session, the
|
|
129
|
+
* same status phrase that session's own card would carry, and its phase. There
|
|
130
|
+
* is no id, no url and no count — a row is a line on a card, not a record.
|
|
131
|
+
*
|
|
132
|
+
* A row only ever carries one of the two live phases: a failed or ended turn is
|
|
133
|
+
* the card's own `phase`, and repeating it as a row would say one thing twice
|
|
134
|
+
* on a card that is already on its way out.
|
|
135
|
+
*/
|
|
136
|
+
export interface ActivityRow {
|
|
137
|
+
readonly name: string
|
|
138
|
+
readonly status: string
|
|
139
|
+
readonly phase: SessionActivityPhase
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* One card's state, as the App's own `SessionActivityState` decodes it.
|
|
144
|
+
*
|
|
145
|
+
* The key set is frozen (§29): no field may be added or renamed, because the
|
|
146
|
+
* App's Codable type is the other half of this contract and a key it does not
|
|
147
|
+
* declare fails the whole decode.
|
|
148
|
+
*/
|
|
149
|
+
export interface SessionActivityState {
|
|
150
|
+
readonly phase: SessionActivityPhase
|
|
151
|
+
readonly statusLine: string
|
|
152
|
+
readonly questionHeader?: string
|
|
153
|
+
readonly optionLabels?: readonly string[]
|
|
154
|
+
/** Apple-reference-date seconds of the moment this bridge delivered the card. */
|
|
155
|
+
readonly asOf: number
|
|
156
|
+
/** Sessions running right now across the whole bridge, never below 1. */
|
|
157
|
+
readonly runningCount: number
|
|
158
|
+
/**
|
|
159
|
+
* The sessions this card lays out, most urgent first, at most
|
|
160
|
+
* {@link LIVE_ACTIVITY_ROW_LIMIT} of them (§30). Absent and empty mean the
|
|
161
|
+
* same thing to the App: it lays out one row out of the single-session keys.
|
|
162
|
+
*/
|
|
163
|
+
readonly rows?: readonly ActivityRow[]
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The request body one Live Activity delivery carries (protocol §29). */
|
|
167
|
+
export interface LiveActivityNotification {
|
|
168
|
+
readonly aps: {
|
|
169
|
+
/** Unix epoch seconds of the delivery. */
|
|
170
|
+
readonly timestamp: number
|
|
171
|
+
readonly event: LiveActivityEvent
|
|
172
|
+
readonly 'content-state': SessionActivityState
|
|
173
|
+
/** Unix epoch seconds after which the card is stale: the delivery plus 90. */
|
|
174
|
+
readonly 'stale-date': number
|
|
175
|
+
readonly 'relevance-score': number
|
|
176
|
+
/** Only an `end` for a card whose session left the roster dismisses at once. */
|
|
177
|
+
readonly 'dismissal-date'?: number
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** What the projection of one delivery says, before it is dated. */
|
|
182
|
+
export interface LiveActivityStateInput {
|
|
183
|
+
readonly event: LiveActivityEvent
|
|
184
|
+
readonly phase: SessionActivityPhase
|
|
185
|
+
readonly statusLine: string
|
|
186
|
+
readonly questionHeader?: string
|
|
187
|
+
readonly optionLabels?: readonly string[]
|
|
188
|
+
readonly runningCount: number
|
|
189
|
+
/** The rows this card lays out, already chosen, ordered and capped by the notifier. */
|
|
190
|
+
readonly rows?: readonly ActivityRow[]
|
|
191
|
+
/** Delivery moment, in milliseconds since the Unix epoch. */
|
|
192
|
+
readonly now: number
|
|
193
|
+
/** Dismiss the card the moment it is delivered, instead of letting it expire. */
|
|
194
|
+
readonly dismiss?: boolean
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @returns the score iOS ranks one card of this phase by. */
|
|
198
|
+
export function relevanceScoreOf(phase: SessionActivityPhase): number {
|
|
199
|
+
return RELEVANCE_SCORE[phase]
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The content state one card carries.
|
|
204
|
+
* @param input - the projection and the delivery moment.
|
|
205
|
+
* @returns the frozen key set, in a fixed order.
|
|
206
|
+
*/
|
|
207
|
+
function contentStateOf(input: LiveActivityStateInput): SessionActivityState {
|
|
208
|
+
const labels = input.optionLabels === undefined
|
|
209
|
+
? undefined
|
|
210
|
+
: input.optionLabels.filter(label => label !== '').slice(0, LIVE_ACTIVITY_OPTION_LIMIT)
|
|
211
|
+
return {
|
|
212
|
+
phase: input.phase,
|
|
213
|
+
statusLine: input.statusLine,
|
|
214
|
+
...(input.questionHeader === undefined || input.questionHeader === '' ? {} : { questionHeader: input.questionHeader }),
|
|
215
|
+
...(labels === undefined || labels.length === 0 ? {} : { optionLabels: labels }),
|
|
216
|
+
// ActivityKit's default strategy decodes a `Date` as a double relative to
|
|
217
|
+
// Apple's reference date, so this is not `now / 1000`.
|
|
218
|
+
asOf: input.now / 1000 - APPLE_REFERENCE_OFFSET_SECONDS,
|
|
219
|
+
runningCount: Math.max(1, Math.trunc(input.runningCount)),
|
|
220
|
+
// Appended last so the six frozen keys keep their names, their order and
|
|
221
|
+
// their meaning (§29.3): a client that never reads `rows` decodes exactly
|
|
222
|
+
// the state it decoded before this key existed.
|
|
223
|
+
...(input.rows === undefined ? {} : { rows: input.rows.slice(0, LIVE_ACTIVITY_ROW_LIMIT) }),
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The push one card gets.
|
|
229
|
+
*
|
|
230
|
+
* Pure, and exported so the shape can be asserted without a sender: the headers
|
|
231
|
+
* and this key set are the contract, and every value derived from the delivery
|
|
232
|
+
* moment is derived here, once.
|
|
233
|
+
* @param input - the projection and the delivery moment.
|
|
234
|
+
* @returns the exact body an APNs Live Activity delivery carries.
|
|
235
|
+
*/
|
|
236
|
+
export function buildLiveActivityNotification(input: LiveActivityStateInput): LiveActivityNotification {
|
|
237
|
+
const timestamp = Math.floor(input.now / 1000)
|
|
238
|
+
return {
|
|
239
|
+
aps: {
|
|
240
|
+
timestamp,
|
|
241
|
+
event: input.event,
|
|
242
|
+
'content-state': contentStateOf(input),
|
|
243
|
+
'stale-date': timestamp + LIVE_ACTIVITY_STALE_SECONDS,
|
|
244
|
+
'relevance-score': relevanceScoreOf(input.phase),
|
|
245
|
+
...(input.event === 'end' && input.dismiss === true ? { 'dismissal-date': timestamp } : {}),
|
|
246
|
+
},
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** One card this bridge may push to. */
|
|
251
|
+
export interface LiveActivityAddress {
|
|
252
|
+
/** The activity the App created; stable for the life of one card. */
|
|
253
|
+
readonly activityId: string
|
|
254
|
+
/** The per-card APNs token, which is not the device's token. */
|
|
255
|
+
readonly token: string
|
|
256
|
+
/**
|
|
257
|
+
* The session this card shows. Absent is a card this bridge never pushes to:
|
|
258
|
+
* it has no state to put on it, and borrowing another session's state is
|
|
259
|
+
* exactly what §29.9 forbids.
|
|
260
|
+
*/
|
|
261
|
+
readonly sessionId?: string
|
|
262
|
+
readonly environment: 'sandbox' | 'production'
|
|
263
|
+
/** The app bundle id; the topic is this bundle plus the Live Activity suffix. */
|
|
264
|
+
readonly bundle: string
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Whatever actually reaches a card; the APNs client implements this. */
|
|
268
|
+
export interface LiveActivitySender {
|
|
269
|
+
sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult>
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** One row of a roster this bridge just served, as the projection reads it. */
|
|
273
|
+
export interface ActivityRosterRow {
|
|
274
|
+
readonly id: string
|
|
275
|
+
readonly agentRunning?: boolean
|
|
276
|
+
/** The host's own title for that session, the name a row carries (§26, §30.2). */
|
|
277
|
+
readonly title?: string
|
|
278
|
+
/** When the host last updated the session, in milliseconds; 0 when it names none. */
|
|
279
|
+
readonly updatedAt?: number
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The question or approval one session's card is waiting on. */
|
|
283
|
+
interface Waiting {
|
|
284
|
+
readonly statusLine: string
|
|
285
|
+
readonly questionHeader?: string
|
|
286
|
+
readonly optionLabels?: readonly string[]
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export interface LiveActivityNotifierOptions {
|
|
290
|
+
/** The cards that are alive right now, read per delivery. */
|
|
291
|
+
readonly targets: () => readonly LiveActivityAddress[]
|
|
292
|
+
/** The sender; absent is a bridge with no signing key, and then nothing happens. */
|
|
293
|
+
readonly sender?: LiveActivitySender
|
|
294
|
+
readonly now?: () => number
|
|
295
|
+
readonly log?: (message: string) => void
|
|
296
|
+
/**
|
|
297
|
+
* Forget a token APNs reported dead. The roster owner removes it from the
|
|
298
|
+
* device row and persists, so a token that can never work again is not retried
|
|
299
|
+
* on every later card (§29 token lifecycle).
|
|
300
|
+
*/
|
|
301
|
+
readonly retire?: (activityId: string, token: string) => Promise<boolean> | boolean | void
|
|
302
|
+
readonly intervalMs?: number
|
|
303
|
+
readonly perMinute?: number
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* The bridge's Live Activity path.
|
|
308
|
+
*
|
|
309
|
+
* Deliberately inert when no sender is configured: `enabled` is false, no
|
|
310
|
+
* card is ever read and no clock is consulted, so a bridge without an Apple key
|
|
311
|
+
* behaves — byte for byte, frame for frame — exactly as it did before this
|
|
312
|
+
* channel existed, and `push.register` still answers the same acknowledgement
|
|
313
|
+
* (§28.3: registering is one thing, sending is another).
|
|
314
|
+
*/
|
|
315
|
+
export class LiveActivityNotifier {
|
|
316
|
+
readonly #options: LiveActivityNotifierOptions
|
|
317
|
+
readonly #now: () => number
|
|
318
|
+
readonly #log: (message: string) => void
|
|
319
|
+
/** Session ids the last roster reported as running. */
|
|
320
|
+
#running = new Set<string>()
|
|
321
|
+
/** Session ids the last roster named. */
|
|
322
|
+
#listed = new Set<string>()
|
|
323
|
+
/** Session ids any roster ever named, so "left the roster" is not "never listed". */
|
|
324
|
+
#known = new Set<string>()
|
|
325
|
+
/** The host's own title of each session the last roster named (§26). */
|
|
326
|
+
#titles = new Map<string, string>()
|
|
327
|
+
/** When the host last updated each session the last roster named, in milliseconds. */
|
|
328
|
+
#sessionUpdatedAt = new Map<string, number>()
|
|
329
|
+
/** The question or approval each session's card is waiting on, one entry per session. */
|
|
330
|
+
readonly #waiting = new Map<string, Waiting>()
|
|
331
|
+
/** Content last admitted per activity id. */
|
|
332
|
+
readonly #content = new Map<string, string>()
|
|
333
|
+
/** When each activity id was last updated, in milliseconds. */
|
|
334
|
+
readonly #updated = new Map<string, number>()
|
|
335
|
+
/** Delivery timestamps inside the rolling minute. */
|
|
336
|
+
#recent: number[] = []
|
|
337
|
+
/** Cards already reported as carrying no session, so the line is logged once each. */
|
|
338
|
+
readonly #unaddressed = new Set<string>()
|
|
339
|
+
|
|
340
|
+
constructor(options: LiveActivityNotifierOptions) {
|
|
341
|
+
this.#options = options
|
|
342
|
+
this.#now = options.now ?? (() => Date.now())
|
|
343
|
+
this.#log = options.log ?? (() => undefined)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** @returns whether this bridge will actually deliver anything. */
|
|
347
|
+
get enabled(): boolean {
|
|
348
|
+
return this.#options.sender !== undefined
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Take the roster this bridge just served as the current picture of what runs.
|
|
353
|
+
*
|
|
354
|
+
* A listing is the only place this bridge learns which sessions are live, so it
|
|
355
|
+
* is where each running session's own card is refreshed: that session's card is
|
|
356
|
+
* told it is running, and the number beside it is how many sessions are running
|
|
357
|
+
* in total. A card waiting on the user keeps that state — listing sessions is
|
|
358
|
+
* not an answer, and downgrading the card would hide the question still owed.
|
|
359
|
+
* @param rows - the roster rows, as this connection built them.
|
|
360
|
+
*/
|
|
361
|
+
noteRoster(rows: readonly ActivityRosterRow[]): void {
|
|
362
|
+
if (!this.enabled) return
|
|
363
|
+
try {
|
|
364
|
+
this.#listed = new Set()
|
|
365
|
+
this.#running = new Set()
|
|
366
|
+
// The roster is the only place a row's name and its recency come from, so
|
|
367
|
+
// both are replaced wholesale with it: a renamed session must not keep
|
|
368
|
+
// describing itself under the name it was listed under before, and a
|
|
369
|
+
// session this roster does not name has no recency to be ordered by.
|
|
370
|
+
this.#titles = new Map()
|
|
371
|
+
this.#sessionUpdatedAt = new Map()
|
|
372
|
+
for (const row of rows) {
|
|
373
|
+
this.#listed.add(row.id)
|
|
374
|
+
this.#known.add(row.id)
|
|
375
|
+
if (row.title !== undefined) this.#titles.set(row.id, row.title)
|
|
376
|
+
this.#sessionUpdatedAt.set(row.id, row.updatedAt ?? 0)
|
|
377
|
+
if (row.agentRunning === true) this.#running.add(row.id)
|
|
378
|
+
}
|
|
379
|
+
const runningCount = this.#running.size
|
|
380
|
+
if (runningCount === 0) return
|
|
381
|
+
for (const sessionId of this.#running) {
|
|
382
|
+
if (this.#waiting.has(sessionId)) continue
|
|
383
|
+
this.#emit(sessionId, {
|
|
384
|
+
event: 'update',
|
|
385
|
+
phase: 'running',
|
|
386
|
+
statusLine: statusLineOf('running'),
|
|
387
|
+
runningCount,
|
|
388
|
+
})
|
|
389
|
+
}
|
|
390
|
+
} catch (error) {
|
|
391
|
+
this.#log(`live activity could not be prepared from a roster: ${String(error)}`)
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Report one turn that ended.
|
|
397
|
+
*
|
|
398
|
+
* Only that session's own card is affected: the session stops running, its
|
|
399
|
+
* pending question is gone with the turn, and its card is ended — not updated —
|
|
400
|
+
* because the turn it was about is over. A session that was listed before and
|
|
401
|
+
* is not in the roster any more has left it, so its card is dismissed on
|
|
402
|
+
* delivery instead of being left on a lock screen to describe a session that no
|
|
403
|
+
* longer exists.
|
|
404
|
+
* @param sessionId - the session whose turn ended.
|
|
405
|
+
* @param reason - the host's own reason, read exactly as the alert channel reads it.
|
|
406
|
+
*/
|
|
407
|
+
noteTurnEnd(sessionId: string, reason: string): void {
|
|
408
|
+
if (!this.enabled) return
|
|
409
|
+
try {
|
|
410
|
+
this.#waiting.delete(sessionId)
|
|
411
|
+
this.#running.delete(sessionId)
|
|
412
|
+
const completed = pushEventOfTurnEnd(reason) === 'turn-end'
|
|
413
|
+
this.#emit(sessionId, {
|
|
414
|
+
event: 'end',
|
|
415
|
+
phase: completed ? 'ended' : 'failed',
|
|
416
|
+
statusLine: statusLineOf(completed ? 'ended' : 'failed'),
|
|
417
|
+
runningCount: this.#running.size,
|
|
418
|
+
...(this.#known.has(sessionId) && !this.#listed.has(sessionId) ? { dismiss: true } : {}),
|
|
419
|
+
})
|
|
420
|
+
} catch (error) {
|
|
421
|
+
this.#log(`live activity end for ${sessionId} could not be prepared: ${String(error)}`)
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Report a question that reached a phone and is now waiting for an answer.
|
|
427
|
+
*
|
|
428
|
+
* Only the header and at most two option labels cross: they are the choices the
|
|
429
|
+
* App can offer. The question itself and its detail stay behind the wire, the
|
|
430
|
+
* same rule the alert channel follows (§28.4), and only this session's card is
|
|
431
|
+
* told — another session's card has no business showing this question (§29.9).
|
|
432
|
+
* @param sessionId - the session that asked.
|
|
433
|
+
* @param question - the first question of the claimed batch.
|
|
434
|
+
*/
|
|
435
|
+
noteQuestion(sessionId: string, question: { readonly header?: string; readonly optionLabels?: readonly string[] }): void {
|
|
436
|
+
if (!this.enabled) return
|
|
437
|
+
try {
|
|
438
|
+
const header = question.header === '' ? undefined : question.header
|
|
439
|
+
const labels = question.optionLabels?.filter(label => label !== '').slice(0, LIVE_ACTIVITY_OPTION_LIMIT)
|
|
440
|
+
// One waiting phrase serves a question and an approval: the App's table has
|
|
441
|
+
// one, and a bridge-only second line would be a word it never renders.
|
|
442
|
+
const waiting: Waiting = {
|
|
443
|
+
statusLine: statusLineOf('waitingForAnswer'),
|
|
444
|
+
...(header === undefined ? {} : { questionHeader: header }),
|
|
445
|
+
...(labels === undefined || labels.length === 0 ? {} : { optionLabels: labels }),
|
|
446
|
+
}
|
|
447
|
+
this.#waiting.set(sessionId, waiting)
|
|
448
|
+
this.#emit(sessionId, { event: 'update', phase: 'waitingForAnswer', runningCount: this.#running.size, ...waiting })
|
|
449
|
+
} catch (error) {
|
|
450
|
+
this.#log(`live activity question for ${sessionId} could not be prepared: ${String(error)}`)
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Report an approval that reached a phone and is blocking the agent.
|
|
456
|
+
*
|
|
457
|
+
* The card says what state that session is in and nothing more: an approval's
|
|
458
|
+
* own summary is a tool's reason text, which is exactly the session content a
|
|
459
|
+
* lock screen must not carry, so it gets the fixed line and no details.
|
|
460
|
+
* @param sessionId - the session whose tool is blocked.
|
|
461
|
+
*/
|
|
462
|
+
noteApproval(sessionId: string): void {
|
|
463
|
+
if (!this.enabled) return
|
|
464
|
+
try {
|
|
465
|
+
const waiting: Waiting = { statusLine: statusLineOf('waitingForAnswer') }
|
|
466
|
+
this.#waiting.set(sessionId, waiting)
|
|
467
|
+
this.#emit(sessionId, { event: 'update', phase: 'waitingForAnswer', runningCount: this.#running.size, ...waiting })
|
|
468
|
+
} catch (error) {
|
|
469
|
+
this.#log(`live activity approval for ${sessionId} could not be prepared: ${String(error)}`)
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Report that the question one card was waiting on is gone — answered here, on
|
|
475
|
+
* the desktop, or expired.
|
|
476
|
+
*
|
|
477
|
+
* A card left saying "waiting for an answer" after the answer landed is the one
|
|
478
|
+
* lie a lock screen cannot afford, so that session's card goes back to whatever
|
|
479
|
+
* is true now. Nothing is sent when that session is not known to run: there is
|
|
480
|
+
* no fact to show, and the ended card already covers that case.
|
|
481
|
+
* @param sessionId - the session whose claim settled.
|
|
482
|
+
*/
|
|
483
|
+
noteSettled(sessionId: string): void {
|
|
484
|
+
if (!this.enabled) return
|
|
485
|
+
if (!this.#waiting.has(sessionId)) return
|
|
486
|
+
try {
|
|
487
|
+
this.#waiting.delete(sessionId)
|
|
488
|
+
if (!this.#running.has(sessionId)) return
|
|
489
|
+
this.#emit(sessionId, {
|
|
490
|
+
event: 'update',
|
|
491
|
+
phase: 'running',
|
|
492
|
+
statusLine: statusLineOf('running'),
|
|
493
|
+
runningCount: this.#running.size,
|
|
494
|
+
})
|
|
495
|
+
} catch (error) {
|
|
496
|
+
this.#log(`live activity resume for ${sessionId} could not be prepared: ${String(error)}`)
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* The cards one session's state is delivered to.
|
|
502
|
+
*
|
|
503
|
+
* A card that names no session is skipped and reported once: §29.9 makes the
|
|
504
|
+
* session the address, and a card this bridge cannot address is a card it must
|
|
505
|
+
* not write to at all.
|
|
506
|
+
* @param sessionId - the session the state is about.
|
|
507
|
+
* @returns that session's cards, possibly none.
|
|
508
|
+
*/
|
|
509
|
+
#targetsFor(sessionId: string): readonly LiveActivityAddress[] {
|
|
510
|
+
const matched: LiveActivityAddress[] = []
|
|
511
|
+
for (const target of this.#options.targets()) {
|
|
512
|
+
if (target.sessionId === undefined) {
|
|
513
|
+
if (this.#unaddressed.has(target.activityId)) continue
|
|
514
|
+
this.#unaddressed.add(target.activityId)
|
|
515
|
+
this.#log(`live activity ${target.activityId} names no session and is never pushed to`)
|
|
516
|
+
while (this.#unaddressed.size > LIVE_ACTIVITY_TRACKED) {
|
|
517
|
+
const oldest = this.#unaddressed.keys().next()
|
|
518
|
+
if (oldest.done === true) break
|
|
519
|
+
this.#unaddressed.delete(oldest.value)
|
|
520
|
+
}
|
|
521
|
+
continue
|
|
522
|
+
}
|
|
523
|
+
if (target.sessionId === sessionId) matched.push(target)
|
|
524
|
+
}
|
|
525
|
+
return matched
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* The rows one card lays out (§30).
|
|
530
|
+
*
|
|
531
|
+
* The order is the whole of the bridge-side priority §30.6 leaves open: a
|
|
532
|
+
* session waiting on the user outranks one that is merely working, so the
|
|
533
|
+
* questions come first in the order they arrived (the waiting map remembers
|
|
534
|
+
* that order), then the running sessions by how recently the host touched
|
|
535
|
+
* them. Which sessions run is read from the same set the single-session state
|
|
536
|
+
* is built from, so a card and its rows can never disagree about that.
|
|
537
|
+
*
|
|
538
|
+
* Only the two live phases ever appear on a row. An ended or failed turn is the
|
|
539
|
+
* card's own `phase` and its own line, said once: adding it here as well would
|
|
540
|
+
* repeat the same sentence and make a card that is already leaving taller.
|
|
541
|
+
* @returns at most {@link LIVE_ACTIVITY_ROW_LIMIT} rows, most urgent first.
|
|
542
|
+
*/
|
|
543
|
+
#rowsFor(): readonly ActivityRow[] {
|
|
544
|
+
const rows: ActivityRow[] = []
|
|
545
|
+
for (const [id, waiting] of this.#waiting) {
|
|
546
|
+
if (rows.length >= LIVE_ACTIVITY_ROW_LIMIT) return rows
|
|
547
|
+
this.#appendRow(rows, id, waiting.statusLine, 'waitingForAnswer')
|
|
548
|
+
}
|
|
549
|
+
for (const id of this.#runningByRecency()) {
|
|
550
|
+
if (rows.length >= LIVE_ACTIVITY_ROW_LIMIT) return rows
|
|
551
|
+
if (this.#waiting.has(id)) continue
|
|
552
|
+
this.#appendRow(rows, id, statusLineOf('running'), 'running')
|
|
553
|
+
}
|
|
554
|
+
return rows
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Add one row, unless that session has no usable name.
|
|
559
|
+
*
|
|
560
|
+
* §30.2 makes all three keys non-empty and §30.4 drops a row it cannot name,
|
|
561
|
+
* so a session the host never titled is left out here instead of on a lock
|
|
562
|
+
* screen — an empty list is the same card as no list at all.
|
|
563
|
+
* @param rows - the row list being built.
|
|
564
|
+
* @param sessionId - the session the row would name.
|
|
565
|
+
* @param status - that session's status line.
|
|
566
|
+
* @param phase - that session's phase.
|
|
567
|
+
*/
|
|
568
|
+
#appendRow(rows: ActivityRow[], sessionId: string, status: string, phase: SessionActivityPhase): void {
|
|
569
|
+
const name = this.#nameOf(sessionId)
|
|
570
|
+
if (name === '') return
|
|
571
|
+
rows.push({ name, status, phase })
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** @returns the running session ids, most recently updated first. */
|
|
575
|
+
#runningByRecency(): readonly string[] {
|
|
576
|
+
return [...this.#running].sort((left, right) => {
|
|
577
|
+
const recency = (this.#sessionUpdatedAt.get(right) ?? 0) - (this.#sessionUpdatedAt.get(left) ?? 0)
|
|
578
|
+
return recency !== 0 ? recency : (left < right ? -1 : left > right ? 1 : 0)
|
|
579
|
+
})
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** @returns the normalized name of one session, or an empty string. */
|
|
583
|
+
#nameOf(sessionId: string): string {
|
|
584
|
+
return normalizeActivityRowName(this.#titles.get(sessionId) ?? '')
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Build one session's delivery and start it, or drop it. */
|
|
588
|
+
#emit(sessionId: string, state: {
|
|
589
|
+
readonly event: LiveActivityEvent
|
|
590
|
+
readonly phase: SessionActivityPhase
|
|
591
|
+
readonly statusLine: string
|
|
592
|
+
readonly questionHeader?: string
|
|
593
|
+
readonly optionLabels?: readonly string[]
|
|
594
|
+
readonly runningCount: number
|
|
595
|
+
readonly dismiss?: boolean
|
|
596
|
+
}): void {
|
|
597
|
+
const sender = this.#options.sender
|
|
598
|
+
if (sender === undefined) return
|
|
599
|
+
const targets = this.#targetsFor(sessionId)
|
|
600
|
+
if (targets.length === 0) return
|
|
601
|
+
const now = this.#now()
|
|
602
|
+
// Every delivery carries the rows, even an `end`: the list is what the card
|
|
603
|
+
// says about the bridge, and a key that appears and disappears would make a
|
|
604
|
+
// client choose between two pictures of the same moment (§30.2).
|
|
605
|
+
const notification = buildLiveActivityNotification({ ...state, rows: this.#rowsFor(), now })
|
|
606
|
+
const content = contentKeyOf(notification.aps['content-state'])
|
|
607
|
+
for (const target of targets) {
|
|
608
|
+
if (!this.#admits(target.activityId, content, state.event, now)) continue
|
|
609
|
+
void Promise.resolve()
|
|
610
|
+
.then(async () => await sender.sendLiveActivity(target, notification))
|
|
611
|
+
.then((result) => { if (!result.ok) this.#failed(target, state.event, result) })
|
|
612
|
+
.catch((error: unknown) => {
|
|
613
|
+
this.#log(`live activity ${state.event} for ${target.activityId} failed: ${String(error)}`)
|
|
614
|
+
})
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* @returns whether this activity may take this content now; records the send
|
|
620
|
+
* when it may. Everything refused here is dropped, never queued.
|
|
621
|
+
*/
|
|
622
|
+
#admits(activityId: string, content: string, event: LiveActivityEvent, now: number): boolean {
|
|
623
|
+
if (this.#content.get(activityId) === content) return false
|
|
624
|
+
if (event === 'update') {
|
|
625
|
+
const interval = this.#options.intervalMs ?? LIVE_ACTIVITY_INTERVAL_MS
|
|
626
|
+
const last = this.#updated.get(activityId)
|
|
627
|
+
if (last !== undefined && now - last < interval) return false
|
|
628
|
+
}
|
|
629
|
+
this.#recent = this.#recent.filter(at => now - at < 60_000)
|
|
630
|
+
if (this.#recent.length >= (this.#options.perMinute ?? LIVE_ACTIVITY_PER_MINUTE)) return false
|
|
631
|
+
this.#recent.push(now)
|
|
632
|
+
// Delete before set so the entry moves to the end: the map is trimmed from its
|
|
633
|
+
// head, and an activity that is still in use must not be the one forgotten.
|
|
634
|
+
this.#content.delete(activityId)
|
|
635
|
+
this.#content.set(activityId, content)
|
|
636
|
+
if (event === 'update') this.#updated.set(activityId, now)
|
|
637
|
+
while (this.#content.size > LIVE_ACTIVITY_TRACKED) {
|
|
638
|
+
const oldest = this.#content.keys().next()
|
|
639
|
+
if (oldest.done === true) break
|
|
640
|
+
this.#content.delete(oldest.value)
|
|
641
|
+
this.#updated.delete(oldest.value)
|
|
642
|
+
}
|
|
643
|
+
return true
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Log one failed delivery and, when the token is dead, forget it. */
|
|
647
|
+
#failed(target: LiveActivityAddress, event: LiveActivityEvent, result: PushSendResult): void {
|
|
648
|
+
const reason = result.reason ?? ''
|
|
649
|
+
this.#log(`live activity ${event} for ${target.activityId} was not delivered (${result.status ?? '-'} ${reason === '' ? 'no reason' : reason})`)
|
|
650
|
+
const dead = result.status === 410 || reason === 'Unregistered' || reason === 'BadDeviceToken'
|
|
651
|
+
if (!dead) return
|
|
652
|
+
const retire = this.#options.retire
|
|
653
|
+
if (retire === undefined) return
|
|
654
|
+
void Promise.resolve()
|
|
655
|
+
.then(async () => await retire(target.activityId, target.token))
|
|
656
|
+
.then((dropped) => {
|
|
657
|
+
if (dropped === false) this.#log(`live activity token for ${target.activityId} was dead but matched no device row`)
|
|
658
|
+
})
|
|
659
|
+
.catch((error: unknown) => {
|
|
660
|
+
this.#log(`live activity token for ${target.activityId} could not be dropped: ${String(error)}`)
|
|
661
|
+
})
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* What identifies a content state for the dedupe.
|
|
667
|
+
*
|
|
668
|
+
* `asOf` is left out on purpose: it is the delivery moment, so it differs on
|
|
669
|
+
* every build, and including it would make "the same content was sent" impossible
|
|
670
|
+
* to observe — a card is a duplicate exactly when everything a user can read on
|
|
671
|
+
* it is unchanged. The rows are part of what a user reads (§30), so a card whose
|
|
672
|
+
* list of sessions reordered, was renamed or lost a row says something new.
|
|
673
|
+
* @param state - the content state of one delivery.
|
|
674
|
+
* @returns a stable key for the readable part of it.
|
|
675
|
+
*/
|
|
676
|
+
export function contentKeyOf(state: SessionActivityState): string {
|
|
677
|
+
return JSON.stringify([
|
|
678
|
+
state.phase,
|
|
679
|
+
state.statusLine,
|
|
680
|
+
state.questionHeader ?? null,
|
|
681
|
+
state.optionLabels ?? null,
|
|
682
|
+
state.runningCount,
|
|
683
|
+
state.rows ?? null,
|
|
684
|
+
])
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** The separators a row name may not end on, and which are never part of its tail (§30.2). */
|
|
688
|
+
const TRAILING_SEPARATOR = /[\s·\-/\\]+$/u
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* A bracket group at the very tail — a host title's `... (/Users/zcl/code/x)` suffix.
|
|
692
|
+
*
|
|
693
|
+
* Anchored at the end and its body may hold no bracket of its own, so a match is
|
|
694
|
+
* always one whole group at the very tail rather than the front half of one.
|
|
695
|
+
*/
|
|
696
|
+
const TRAILING_GROUP = /[((][^()()]*[))]$/u
|
|
697
|
+
|
|
698
|
+
/** Either path separator, however the host wrote it. */
|
|
699
|
+
const PATH_SEPARATOR = /[/\\]/u
|
|
700
|
+
|
|
701
|
+
/** Any closing bracket, ASCII or full-width. */
|
|
702
|
+
const CLOSING_BRACKET = /[))]/u
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* Whether one trailing bracket group names a path.
|
|
706
|
+
*
|
|
707
|
+
* The test §30.2 and the App's own `SessionActivityDisplayName` share: the group
|
|
708
|
+
* is a path when its body holds a separator or holds nothing at all. `Ship (main)`
|
|
709
|
+
* is part of the name and stays — one card may not show two versions of one name.
|
|
710
|
+
* @param group - the whole group, brackets included.
|
|
711
|
+
* @returns whether the group is the path suffix rather than part of the name.
|
|
712
|
+
*/
|
|
713
|
+
function isPathGroup(group: string): boolean {
|
|
714
|
+
const body = group.slice(1, -1).trim()
|
|
715
|
+
return body === '' || PATH_SEPARATOR.test(body)
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* The text with every trailing path group taken off, brackets included.
|
|
720
|
+
* @param text - one name candidate.
|
|
721
|
+
* @returns the same text without a path group hanging on its tail.
|
|
722
|
+
*/
|
|
723
|
+
function stripTrailingPathGroups(text: string): string {
|
|
724
|
+
let next = text
|
|
725
|
+
for (;;) {
|
|
726
|
+
const group = TRAILING_GROUP.exec(next)
|
|
727
|
+
if (group === null || !isPathGroup(group[0])) return next
|
|
728
|
+
next = next.slice(0, group.index).trim()
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* The text without a tail group the host never closed, when that group names a path.
|
|
734
|
+
*
|
|
735
|
+
* A title cut off before its closing bracket — `Deck (/Users/zcl/code/x` — has no
|
|
736
|
+
* group at the tail to strip, and leaving it would put half a path on a lock
|
|
737
|
+
* screen (§29.5). An unclosed group that holds no separator is the name, so
|
|
738
|
+
* `Fix it (beta` keeps its tail.
|
|
739
|
+
* @param text - one name candidate.
|
|
740
|
+
* @returns the same text without a trailing unclosed path group.
|
|
741
|
+
*/
|
|
742
|
+
function cutUnclosedPathTail(text: string): string {
|
|
743
|
+
const opened = Math.max(text.lastIndexOf('('), text.lastIndexOf('('))
|
|
744
|
+
if (opened < 0) return text
|
|
745
|
+
const body = text.slice(opened + 1)
|
|
746
|
+
if (CLOSING_BRACKET.test(body)) return text
|
|
747
|
+
if (!PATH_SEPARATOR.test(body)) return text
|
|
748
|
+
return text.slice(0, opened).trim()
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** @returns how many brackets the text leaves open. */
|
|
752
|
+
function bracketDepth(text: string): number {
|
|
753
|
+
let depth = 0
|
|
754
|
+
for (const character of text) {
|
|
755
|
+
if (character === '(' || character === '(') depth += 1
|
|
756
|
+
else if (character === ')' || character === ')') depth -= 1
|
|
757
|
+
}
|
|
758
|
+
return depth
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* The text without a bracket left dangling on its tail.
|
|
763
|
+
*
|
|
764
|
+
* A closing bracket that still closes a group — `Ship (main)` — is part of the
|
|
765
|
+
* name and stays. What may not end a name (§30.2) is the closing bracket of a
|
|
766
|
+
* group that went away with a path, and a lone opening bracket.
|
|
767
|
+
* @param text - one name candidate.
|
|
768
|
+
* @returns the same text with no dangling bracket on its end.
|
|
769
|
+
*/
|
|
770
|
+
function trimDanglingBracket(text: string): string {
|
|
771
|
+
let next = text
|
|
772
|
+
for (;;) {
|
|
773
|
+
const last = next.slice(-1)
|
|
774
|
+
if (last === '(' || last === '(') {
|
|
775
|
+
next = next.slice(0, -1).trim()
|
|
776
|
+
continue
|
|
777
|
+
}
|
|
778
|
+
if ((last === ')' || last === ')') && bracketDepth(next) < 0) {
|
|
779
|
+
next = next.slice(0, -1).trim()
|
|
780
|
+
continue
|
|
781
|
+
}
|
|
782
|
+
return next
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* One pass of the tail cleanup, in the order that keeps a group whole.
|
|
788
|
+
*
|
|
789
|
+
* The separators come off first, because they are what hides the group at the
|
|
790
|
+
* tail (`Name - (/path)`); only then the path groups; only then a bracket left on
|
|
791
|
+
* its own. Peeling a bracket before its group is reached is how `Name (/path) -`
|
|
792
|
+
* turns into a name still holding half a path.
|
|
793
|
+
* @param text - one name candidate.
|
|
794
|
+
* @returns the same text with no path group, separator or dangling bracket on its tail.
|
|
795
|
+
*/
|
|
796
|
+
function cleanRowNameTail(text: string): string {
|
|
797
|
+
let next = text
|
|
798
|
+
for (let round = 0; round < 8; round += 1) {
|
|
799
|
+
const before = next
|
|
800
|
+
next = stripTrailingPathGroups(cutUnclosedPathTail(next.replace(/\s+/gu, ' ').trim()))
|
|
801
|
+
next = next.replace(TRAILING_SEPARATOR, '').trim()
|
|
802
|
+
next = trimDanglingBracket(next)
|
|
803
|
+
if (next === before) break
|
|
804
|
+
}
|
|
805
|
+
return next
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* The host's own title, as one row may carry it (§30.2).
|
|
810
|
+
*
|
|
811
|
+
* The same rule the App applies to a card's own name
|
|
812
|
+
* (`SessionActivityDisplayName`), so one card cannot show two versions of one
|
|
813
|
+
* name. A roster title is usually the session's first message, and those end on
|
|
814
|
+
* the absolute path the session ran in — `你是本仓 (/Users/zcl/code/x)` — while
|
|
815
|
+
* §29.5 keeps paths off a lock screen. A trailing group whose body is a path or
|
|
816
|
+
* nothing therefore comes off, brackets included, and whatever it exposed is
|
|
817
|
+
* cleaned up after it (the separator in front of it, the bracket of the group
|
|
818
|
+
* before it). A group that is part of the name, `Ship (main)`, stays. What is
|
|
819
|
+
* left is whitespace-collapsed, trimmed of the separators and dangling brackets
|
|
820
|
+
* its tail may hang on, and cut to {@link LIVE_ACTIVITY_ROW_NAME_MAX}.
|
|
821
|
+
*
|
|
822
|
+
* The rule lives here and nowhere else in this bridge, so there is one answer to
|
|
823
|
+
* "which words of a host title may reach a lock screen".
|
|
824
|
+
* @param title - the title the roster carried for that session, possibly empty.
|
|
825
|
+
* @returns a name a row can carry, and an empty string when the title held nothing else.
|
|
826
|
+
*/
|
|
827
|
+
export function normalizeActivityRowName(title: string): string {
|
|
828
|
+
const cleaned = cleanRowNameTail(title)
|
|
829
|
+
const points = Array.from(cleaned)
|
|
830
|
+
if (points.length <= LIVE_ACTIVITY_ROW_NAME_MAX) return cleaned
|
|
831
|
+
// A cut can land inside a group or on a separator, so the tail is cleaned again.
|
|
832
|
+
return cleanRowNameTail(points.slice(0, LIVE_ACTIVITY_ROW_NAME_MAX).join(''))
|
|
833
|
+
}
|