@commandgarden/cli 2.3.0 → 2.5.0

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.
@@ -194,7 +194,7 @@ const __deadline = Date.now() + 30000;
194
194
  while (Date.now() < __deadline) {
195
195
  if (exists("button[aria-label='Open Scheduling Assistant']") ||
196
196
  exists("input[aria-label='Start date']")) break;
197
- await sleep(1000);
197
+ await sleep(400);
198
198
  }
199
199
  if (!exists("button[aria-label='Open Scheduling Assistant']") &&
200
200
  !exists("input[aria-label='Start date']")) {
@@ -205,9 +205,9 @@ if (!exists("button[aria-label='Open Scheduling Assistant']") &&
205
205
  }
206
206
 
207
207
  // Open the Scheduling Assistant (free/busy view).
208
- for (let i = 0; i < 12 && !schedulingAssistantOpen(); i++) {
208
+ for (let i = 0; i < 20 && !schedulingAssistantOpen(); i++) {
209
209
  clickByName('Open Scheduling Assistant');
210
- await sleep(1000);
210
+ await sleep(400);
211
211
  }
212
212
  if (!schedulingAssistantOpen()) {
213
213
  throw new Error('Could not open the Scheduling Assistant');
@@ -235,7 +235,7 @@ for (let i = 0; i < 30; i++) {
235
235
  const di = $("input[aria-label='Start date']");
236
236
  if (di) di.click();
237
237
  }
238
- await sleep(1000);
238
+ await sleep(500);
239
239
  }
240
240
  if (!exists(cellSel)) {
241
241
  // If the cell is gone, the click succeeded; otherwise error.
@@ -245,22 +245,23 @@ if (!exists(cellSel)) {
245
245
  // ── Capture pre-existing mailbox IDs (organizer) ─────────────────────
246
246
  const seen = new Set();
247
247
  for (let i = 0; i < 3; i++) {
248
- await sleep(1000);
248
+ await sleep(500);
249
249
  for (const pair of readCapture()) {
250
250
  for (const id of schedulesFromPair(pair).keys()) seen.add(id);
251
251
  }
252
+ if (seen.size > 0) break;
252
253
  }
253
254
 
254
255
  // ── Add the room ─────────────────────────────────────────────────────
255
256
  if (isEmail) {
256
257
  // Email -> attendee picker (resolves SMTP).
257
258
  clickByName('Expand Required attendees');
258
- await sleep(1000);
259
+ await sleep(400);
259
260
 
260
261
  const inputSel = "input[aria-label*='required attendees']";
261
- for (let i = 0; i < 12 && !exists(inputSel); i++) {
262
+ for (let i = 0; i < 20 && !exists(inputSel); i++) {
262
263
  clickByName('Add required attendee');
263
- await sleep(1000);
264
+ await sleep(400);
264
265
  }
265
266
  if (!exists(inputSel)) {
266
267
  throw new Error('Could not open the required-attendee field');
@@ -269,8 +270,8 @@ if (isEmail) {
269
270
 
270
271
  const optionSel = `[role=option][aria-label*='${room}']`;
271
272
  let found = false;
272
- for (let i = 0; i < 12 && !found; i++) {
273
- await sleep(1000);
273
+ for (let i = 0; i < 20 && !found; i++) {
274
+ await sleep(400);
274
275
  found = exists(optionSel);
275
276
  }
276
277
  if (!found) {
@@ -280,18 +281,19 @@ if (isEmail) {
280
281
  } else {
281
282
  // Name -> room finder.
282
283
  const inputSel = "input[aria-label='Add a room']";
283
- for (let i = 0; i < 10 && !exists(inputSel); i++) {
284
+ for (let i = 0; i < 20 && !exists(inputSel); i++) {
284
285
  clickByName('Add a room');
285
- await sleep(1000);
286
+ await sleep(400);
286
287
  }
287
288
  if (!exists(inputSel)) {
288
289
  throw new Error('Could not open the room finder');
289
290
  }
290
291
  typeText(inputSel, room);
292
+ await sleep(1000);
291
293
 
292
294
  let label = null;
293
- for (let i = 0; i < 14 && !label; i++) {
294
- await sleep(1000);
295
+ for (let i = 0; i < 25 && !label; i++) {
296
+ await sleep(400);
295
297
  const opts = Array.from(document.querySelectorAll('[role=option]'));
296
298
  const el = opts.find(o => /capacity/i.test(o.getAttribute('aria-label') || '') && o.offsetParent);
297
299
  if (el) {
@@ -313,8 +315,8 @@ const itemsById = new Map();
313
315
  const isRoomId = id => (isEmail ? id === room.toLowerCase() : !seen.has(id));
314
316
 
315
317
  let stable = 0;
316
- for (let i = 0; i < 30; i++) {
317
- await sleep(1000);
318
+ for (let i = 0; i < 50; i++) {
319
+ await sleep(500);
318
320
  for (const pair of readCapture()) {
319
321
  for (const [id, s] of schedulesFromPair(pair)) {
320
322
  if (!isRoomId(id)) continue;
@@ -327,7 +329,7 @@ for (let i = 0; i < 30; i++) {
327
329
  }
328
330
  }
329
331
  }
330
- if (sawView) { stable += 1; if (stable >= 3) break; }
332
+ if (sawView) { stable += 1; if (stable >= 2) break; }
331
333
  }
332
334
 
333
335
  if (!roomId) {
@@ -3,6 +3,7 @@ name: room-availability
3
3
  version: "1.0"
4
4
  description: "Meeting-room free/busy timeline for one room on a given day (Teams/Outlook calendar)"
5
5
  access: read
6
+ cdp: true
6
7
 
7
8
  domains:
8
9
  - "outlook.cloud.microsoft.mcas.ms"
@@ -0,0 +1,545 @@
1
+ // Runs in page context via js_evaluate step.
2
+ // Drives the Outlook Scheduling Assistant to fetch free/busy timelines for
3
+ // multiple meeting rooms on a single day. Rooms are added sequentially so we
4
+ // can reliably map each scheduleId back to the input room name.
5
+ //
6
+ // Template variables interpolated before execution:
7
+ // ${{ args.rooms }}
8
+ // ${{ args.date | default("") }}
9
+
10
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June',
11
+ 'July', 'August', 'September', 'October', 'November', 'December'];
12
+ const DATE_RE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
13
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
14
+
15
+ function pad2(n) { return String(n).padStart(2, '0'); }
16
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
17
+
18
+ function todayLocalISO() {
19
+ const d = new Date();
20
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
21
+ }
22
+
23
+ /** "2026-06-18" -> "18, June, 2026" (matches the OWA date-cell aria-label). */
24
+ function dateCellLabel(iso) {
25
+ const [y, m, d] = iso.split('-').map(Number);
26
+ return `${d}, ${MONTHS[m - 1]}, ${y}`;
27
+ }
28
+
29
+ /** querySelector shorthand, returns null if not found. */
30
+ function $(sel) { return document.querySelector(sel); }
31
+
32
+ /** True when an element matching the selector exists. */
33
+ function exists(sel) { return !!$(sel); }
34
+
35
+ /**
36
+ * Click a button/link by accessible name (aria-label OR visible text).
37
+ * Returns true if an element was found and clicked.
38
+ */
39
+ function clickByName(name) {
40
+ const els = Array.from(document.querySelectorAll('button,a,[role=button]'));
41
+ const el = els.find(e => {
42
+ if (!e.offsetParent) return false;
43
+ const al = (e.getAttribute('aria-label') || '').trim();
44
+ const tx = (e.textContent || '').replace(/\s+/g, ' ').trim();
45
+ return al === name || al.includes(name) || tx.includes(name);
46
+ });
47
+ if (!el) return false;
48
+ el.scrollIntoView({ block: 'center' });
49
+ el.click();
50
+ return true;
51
+ }
52
+
53
+ /** True when the Scheduling Assistant view (with its Start date picker) is rendered. */
54
+ function schedulingAssistantOpen() {
55
+ return Array.from(document.querySelectorAll('input')).some(
56
+ e => (e.getAttribute('aria-label') || '') === 'Start date'
57
+ );
58
+ }
59
+
60
+ /** Type text into an input by selector (focus, set value, dispatch events). */
61
+ function typeText(sel, text) {
62
+ const el = $(sel);
63
+ if (!el) throw new Error(`Element "${sel}" not found for typing`);
64
+ el.focus();
65
+ const setter = Object.getOwnPropertyDescriptor(
66
+ window.HTMLInputElement.prototype, 'value'
67
+ ).set;
68
+ setter.call(el, text);
69
+ el.dispatchEvent(new Event('input', { bubbles: true }));
70
+ el.dispatchEvent(new Event('change', { bubbles: true }));
71
+ }
72
+
73
+ /** Clear and retype into an input using execCommand, which triggers React's internal events. */
74
+ function reactType(sel, text) {
75
+ const el = $(sel);
76
+ if (!el) throw new Error(`Element "${sel}" not found for typing`);
77
+ el.focus();
78
+ el.select();
79
+ document.execCommand('insertText', false, text);
80
+ }
81
+
82
+ // ── Fetch interceptor ────────────────────────────────────────────────
83
+ // Captures getSchedule GraphQL responses (the page's own authenticated
84
+ // request — the endpoint 401s on replay).
85
+ if (!window.__rfb) {
86
+ window.__rfb = [];
87
+ const origFetch = window.fetch;
88
+ window.fetch = function () {
89
+ const a = arguments;
90
+ const u = (a[0] && a[0].url) || a[0] || '';
91
+ const rb = (a[1] && a[1].body) || '';
92
+ return origFetch.apply(this, a).then(r => {
93
+ try {
94
+ if (String(u).indexOf('graphql') > -1) {
95
+ r.clone().text().then(t => {
96
+ if (t.indexOf('getSchedule') > -1 && t.indexOf('availabilityView') > -1) {
97
+ window.__rfb.push({ req: String(rb || ''), body: t });
98
+ }
99
+ }).catch(() => {});
100
+ }
101
+ } catch (_e) { /* ignore */ }
102
+ return r;
103
+ });
104
+ };
105
+ }
106
+
107
+ /** Read and clear captured {req, body} pairs. */
108
+ function readCapture() {
109
+ const d = window.__rfb || [];
110
+ window.__rfb = [];
111
+ return d;
112
+ }
113
+
114
+ /** Map of scheduleId (lowercased) -> schedule object from a captured response body. */
115
+ function schedulesFromPair(pair) {
116
+ let body;
117
+ try { body = JSON.parse(pair.body); } catch (_e) { return new Map(); }
118
+ const byId = new Map();
119
+ const nodes = Array.isArray(body) ? body : [body];
120
+ for (const node of nodes) {
121
+ const schedules = node?.data?.getSchedule?.schedules;
122
+ if (Array.isArray(schedules)) {
123
+ for (const s of schedules) {
124
+ if (s?.scheduleId) byId.set(String(s.scheduleId).toLowerCase(), s);
125
+ }
126
+ }
127
+ }
128
+ return byId;
129
+ }
130
+
131
+ /**
132
+ * Build a free/busy timeline (busy/tentative/oof/elsewhere blocks + free gaps)
133
+ * for one local day from getSchedule scheduleItems.
134
+ */
135
+ function buildTimeline(items, dateIso) {
136
+ const PRIORITY = { oof: 4, busy: 3, tentative: 2, elsewhere: 1, free: 0 };
137
+ const mapStatus = st => ({
138
+ Busy: 'busy', Tentative: 'tentative', Oof: 'oof', WorkingElsewhere: 'elsewhere', Free: 'free',
139
+ }[st] || 'busy');
140
+
141
+ const dayStart = new Date(`${dateIso}T00:00:00`);
142
+ const dayEnd = new Date(dayStart.getTime() + 86400000);
143
+ const fmt = ms => {
144
+ if (ms >= dayEnd.getTime()) return '24:00';
145
+ const d = new Date(ms);
146
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
147
+ };
148
+
149
+ const blocks = [];
150
+ for (const it of items) {
151
+ if (!it || !it.startTime || !it.endTime) continue;
152
+ const s = new Date(it.startTime.dateTime).getTime();
153
+ const e = new Date(it.endTime.dateTime).getTime();
154
+ const cs = Math.max(s, dayStart.getTime());
155
+ const ce = Math.min(e, dayEnd.getTime());
156
+ if (ce > cs) blocks.push({ state: mapStatus(it.status), s: cs, e: ce });
157
+ }
158
+ blocks.sort((a, b) => a.s - b.s);
159
+
160
+ // Merge overlapping/adjacent busy blocks.
161
+ const merged = [];
162
+ for (const b of blocks) {
163
+ const last = merged[merged.length - 1];
164
+ if (last && b.s <= last.e) {
165
+ last.e = Math.max(last.e, b.e);
166
+ if (PRIORITY[b.state] > PRIORITY[last.state]) last.state = b.state;
167
+ } else {
168
+ merged.push({ ...b });
169
+ }
170
+ }
171
+
172
+ const rows = [];
173
+ let cursor = dayStart.getTime();
174
+ for (const b of merged) {
175
+ if (b.s > cursor) rows.push({ state: 'free', s: cursor, e: b.s });
176
+ rows.push({ state: b.state, s: b.s, e: b.e });
177
+ cursor = b.e;
178
+ }
179
+ if (cursor < dayEnd.getTime()) rows.push({ state: 'free', s: cursor, e: dayEnd.getTime() });
180
+
181
+ return rows.map(r => ({
182
+ date: dateIso,
183
+ state: r.state,
184
+ start: fmt(r.s),
185
+ end: fmt(r.e),
186
+ durationMin: Math.round((r.e - r.s) / 60000),
187
+ }));
188
+ }
189
+
190
+ // ── Parse arguments ──────────────────────────────────────────────────
191
+
192
+ const rawRooms = '${{ args.rooms }}'.trim();
193
+ if (!rawRooms) throw new Error('Missing rooms argument — pass comma-separated room names or emails');
194
+ const roomTokens = rawRooms.split(',').map(r => r.trim()).filter(r => r.length > 0);
195
+ if (roomTokens.length === 0) throw new Error('No rooms provided after parsing');
196
+
197
+ const parsedRooms = roomTokens.map(r => {
198
+ const colonIdx = r.lastIndexOf(':');
199
+ if (colonIdx > 0) {
200
+ const name = r.substring(0, colonIdx).trim();
201
+ const email = r.substring(colonIdx + 1).trim();
202
+ if (EMAIL_RE.test(email)) {
203
+ return { name, email: email.toLowerCase(), mode: 'pair' };
204
+ }
205
+ }
206
+ if (EMAIL_RE.test(r)) {
207
+ return { name: r, email: r.toLowerCase(), mode: 'email' };
208
+ }
209
+ return { name: r, email: null, mode: 'name' };
210
+ });
211
+
212
+ const canBatch = parsedRooms.every(r => r.mode === 'pair');
213
+
214
+ let date = '${{ args.date | default("") }}'.trim();
215
+ if (!date) date = todayLocalISO();
216
+ if (!DATE_RE.test(date)) throw new Error(`Invalid date "${date}" — use YYYY-MM-DD`);
217
+
218
+ // ── Wait for compose form ────────────────────────────────────────────
219
+
220
+ const __deadline = Date.now() + 30000;
221
+ while (Date.now() < __deadline) {
222
+ if (exists("button[aria-label='Open Scheduling Assistant']") ||
223
+ exists("input[aria-label='Start date']")) break;
224
+ await sleep(400);
225
+ }
226
+ if (!exists("button[aria-label='Open Scheduling Assistant']") &&
227
+ !exists("input[aria-label='Start date']")) {
228
+ if (/login\.|\/oauth2\/|signin|sso/i.test(location.href)) {
229
+ throw new Error('Not signed in to Outlook/Teams — log in and retry');
230
+ }
231
+ throw new Error('Calendar compose form did not load');
232
+ }
233
+
234
+ // ── Open the Scheduling Assistant ────────────────────────────────────
235
+
236
+ for (let i = 0; i < 20 && !schedulingAssistantOpen(); i++) {
237
+ clickByName('Open Scheduling Assistant');
238
+ await sleep(400);
239
+ }
240
+ if (!schedulingAssistantOpen()) {
241
+ throw new Error('Could not open the Scheduling Assistant');
242
+ }
243
+
244
+ // ── Set the date ─────────────────────────────────────────────────────
245
+
246
+ const cellSel = `button[aria-label='${dateCellLabel(date)}']`;
247
+ const target = new Date(`${date}T00:00:00`);
248
+ const now = new Date();
249
+ const navSel = target >= new Date(now.getFullYear(), now.getMonth(), now.getDate())
250
+ ? "button[aria-label^='Go to next month']"
251
+ : "button[aria-label^='Go to previous month']";
252
+
253
+ const dateInput = $("input[aria-label='Start date']");
254
+ if (dateInput) dateInput.click();
255
+
256
+ for (let i = 0; i < 30; i++) {
257
+ if (exists(cellSel)) {
258
+ $(cellSel).click();
259
+ break;
260
+ }
261
+ if (exists(navSel)) {
262
+ try { $(navSel).click(); } catch (_e) { /* retry */ }
263
+ } else {
264
+ const di = $("input[aria-label='Start date']");
265
+ if (di) di.click();
266
+ }
267
+ await sleep(500);
268
+ }
269
+
270
+ // ── Capture pre-existing mailbox IDs (organizer) ─────────────────────
271
+
272
+ const seen = new Set();
273
+ for (let i = 0; i < 6; i++) {
274
+ await sleep(300);
275
+ for (const pair of readCapture()) {
276
+ for (const id of schedulesFromPair(pair).keys()) seen.add(id);
277
+ }
278
+ if (seen.size > 0) break;
279
+ }
280
+
281
+ // ── Add room by email (required attendees path) ──────────────────────
282
+
283
+ async function addRoomByEmail(email) {
284
+ clickByName('Expand Required attendees');
285
+ await sleep(200);
286
+
287
+ const inputSel = "input[aria-label*='required attendees']";
288
+ for (let i = 0; i < 20 && !exists(inputSel); i++) {
289
+ clickByName('Add required attendee');
290
+ await sleep(200);
291
+ }
292
+ if (!exists(inputSel)) {
293
+ throw new Error('Could not open the required-attendee field');
294
+ }
295
+ typeText(inputSel, email);
296
+
297
+ const optionSel = `[role=option][aria-label*='${email}']`;
298
+ let found = false;
299
+ for (let i = 0; i < 40 && !found; i++) {
300
+ await sleep(200);
301
+ found = exists(optionSel);
302
+ }
303
+ if (!found) {
304
+ throw new Error(`Room "${email}" was not found in the directory`);
305
+ }
306
+ $(optionSel).click();
307
+ }
308
+
309
+ // ── Add room by name (room finder path) ──────────────────────────────
310
+
311
+ async function addRoomByName(name) {
312
+ const inputSel = "input[aria-label='Add a room']";
313
+
314
+ // If the input is already visible (reuse after dismissRoom), clear and retype.
315
+ // Otherwise, click "Add a room" to open a fresh finder.
316
+ if (exists(inputSel)) {
317
+ reactType(inputSel, name);
318
+ // Wait for OWA to process the search and refresh suggestions.
319
+ await sleep(1000);
320
+ } else {
321
+ for (let i = 0; i < 30 && !exists(inputSel); i++) {
322
+ clickByName('Add a room');
323
+ await sleep(200);
324
+ }
325
+ if (!exists(inputSel)) {
326
+ throw new Error('Could not open the room finder');
327
+ }
328
+ typeText(inputSel, name);
329
+ }
330
+
331
+ let label = null;
332
+ for (let i = 0; i < 40 && !label; i++) {
333
+ await sleep(200);
334
+ const opts = Array.from(document.querySelectorAll('[role=option]'));
335
+ const el = opts.find(o => /capacity/i.test(o.getAttribute('aria-label') || '') && o.offsetParent);
336
+ if (el) {
337
+ el.scrollIntoView({ block: 'center' });
338
+ el.click();
339
+ label = el.getAttribute('aria-label');
340
+ }
341
+ }
342
+ if (!label) {
343
+ throw new Error(`No room matched "${name}"`);
344
+ }
345
+ }
346
+
347
+ // ── Dismiss room: remove the just-added room so "Add a room" reappears ──
348
+
349
+ async function dismissRoom() {
350
+ // Click the "Remove <room>" button on the most recently added room pill.
351
+ // OWA labels these as e.g. "Remove MY_Site_Building_L4_Room Name."
352
+ const removeBtn = Array.from(document.querySelectorAll('button'))
353
+ .filter(el => el.offsetParent)
354
+ .find(el => (el.getAttribute('aria-label') || '').startsWith('Remove '));
355
+ if (removeBtn) {
356
+ removeBtn.scrollIntoView({ block: 'center' });
357
+ removeBtn.click();
358
+ await sleep(200);
359
+ }
360
+
361
+ await sleep(200);
362
+ }
363
+
364
+ // ── Capture schedule for the most recently added room ────────────────
365
+
366
+ async function captureNewSchedule(knownIds) {
367
+ let newId = null;
368
+ let schedule = null;
369
+ let sawView = false;
370
+ let errMsg = null;
371
+ const itemsById = new Map();
372
+
373
+ for (let i = 0; i < 60; i++) {
374
+ await sleep(100);
375
+ for (const pair of readCapture()) {
376
+ for (const [id, s] of schedulesFromPair(pair)) {
377
+ if (knownIds.has(id)) continue;
378
+ if (!newId) newId = id;
379
+ if (id !== newId) continue;
380
+ schedule = s;
381
+ if (s.error) errMsg = s.error.message || s.error.responseCode || 'unknown';
382
+ if (s.availabilityView && s.availabilityView.length) sawView = true;
383
+ for (const it of (s.scheduleItems || [])) {
384
+ const key = it && it.id ? it.id : JSON.stringify(it && [it.startTime, it.endTime, it.subject]);
385
+ if (it) itemsById.set(key, it);
386
+ }
387
+ }
388
+ }
389
+ if (sawView) break;
390
+ }
391
+
392
+ return { newId, schedule, sawView, errMsg, items: [...itemsById.values()] };
393
+ }
394
+
395
+ /**
396
+ * Batch capture: wait for getSchedule responses covering all expected emails.
397
+ * Returns a Map of email (lowercased) -> { schedule, items, sawView, errMsg }.
398
+ */
399
+ async function captureBatchSchedules(expectedEmails, knownIds) {
400
+ const byEmail = new Map();
401
+
402
+ for (let i = 0; i < 80; i++) {
403
+ await sleep(100);
404
+ for (const pair of readCapture()) {
405
+ for (const [id, s] of schedulesFromPair(pair)) {
406
+ if (knownIds.has(id)) continue;
407
+ const idLower = id.toLowerCase();
408
+ if (!expectedEmails.has(idLower)) continue;
409
+ const items = (s.scheduleItems || []).filter(Boolean);
410
+ byEmail.set(idLower, {
411
+ schedule: s,
412
+ items,
413
+ sawView: !!(s.availabilityView && s.availabilityView.length),
414
+ errMsg: s.error ? (s.error.message || s.error.responseCode || 'unknown') : null,
415
+ });
416
+ }
417
+ }
418
+ if (expectedEmails.size > 0 && [...expectedEmails].every(e => byEmail.has(e))) break;
419
+ }
420
+
421
+ return byEmail;
422
+ }
423
+
424
+ // ── Room processing ──────────────────────────────────────────────────
425
+
426
+ const allRows = [];
427
+ const knownIds = new Set(seen);
428
+
429
+ if (canBatch) {
430
+ // ── Batch mode: add all rooms via room finder, single capture ──────
431
+ const emailToName = new Map();
432
+ const expectedEmails = new Set();
433
+ for (const r of parsedRooms) {
434
+ emailToName.set(r.email, r.name);
435
+ expectedEmails.add(r.email);
436
+ }
437
+
438
+ // Clear stale captures, then add all rooms without dismissing.
439
+ readCapture();
440
+
441
+ for (const r of parsedRooms) {
442
+ try {
443
+ await addRoomByName(r.name);
444
+ await sleep(300);
445
+ } catch (addErr) {
446
+ allRows.push({
447
+ roomName: r.name, roomEmail: r.email, date,
448
+ state: 'error', start: addErr.message, end: '', durationMin: 0,
449
+ });
450
+ expectedEmails.delete(r.email);
451
+ }
452
+ }
453
+
454
+ // Single batch capture for all successfully added rooms.
455
+ if (expectedEmails.size > 0) {
456
+ const results = await captureBatchSchedules(expectedEmails, knownIds);
457
+
458
+ for (const [email, data] of results) {
459
+ const name = emailToName.get(email);
460
+ knownIds.add(email);
461
+ if (data.errMsg && !data.sawView) {
462
+ allRows.push({
463
+ roomName: name, roomEmail: email, date,
464
+ state: 'error', start: `Free/busy error: ${data.errMsg}`,
465
+ end: '', durationMin: 0,
466
+ });
467
+ } else {
468
+ const timeline = buildTimeline(data.items, date);
469
+ for (const row of timeline) {
470
+ allRows.push({ roomName: name, roomEmail: email, ...row });
471
+ }
472
+ }
473
+ }
474
+
475
+ // Report rooms not found in any captured response.
476
+ for (const email of expectedEmails) {
477
+ if (!results.has(email)) {
478
+ allRows.push({
479
+ roomName: emailToName.get(email), roomEmail: email, date,
480
+ state: 'error', start: `No free/busy returned for "${emailToName.get(email)}" on ${date}`,
481
+ end: '', durationMin: 0,
482
+ });
483
+ }
484
+ }
485
+ }
486
+ } else {
487
+ // ── Sequential mode (original behavior) ────────────────────────────
488
+ for (const r of parsedRooms) {
489
+ const isEmail = r.mode === 'email';
490
+
491
+ // Clear any pending captures before adding this room.
492
+ readCapture();
493
+
494
+ try {
495
+ if (isEmail) {
496
+ await addRoomByEmail(r.name);
497
+ } else {
498
+ await addRoomByName(r.name);
499
+ }
500
+ } catch (addErr) {
501
+ allRows.push({
502
+ roomName: r.name, roomEmail: r.email || '', date,
503
+ state: 'error', start: addErr.message, end: '', durationMin: 0,
504
+ });
505
+ continue;
506
+ }
507
+
508
+ // Capture the getSchedule response immediately after adding (before dismiss).
509
+ const result = await captureNewSchedule(knownIds);
510
+
511
+ // Remove the room so "Add a room" reappears for the next room.
512
+ await dismissRoom();
513
+
514
+ if (!result.newId) {
515
+ allRows.push({
516
+ roomName: r.name, roomEmail: r.email || '', date,
517
+ state: 'error', start: `No free/busy returned for "${r.name}" on ${date}`,
518
+ end: '', durationMin: 0,
519
+ });
520
+ continue;
521
+ }
522
+
523
+ knownIds.add(result.newId);
524
+
525
+ if (result.errMsg && !result.sawView) {
526
+ allRows.push({
527
+ roomName: r.name, roomEmail: result.newId, date,
528
+ state: 'error', start: `Free/busy error: ${result.errMsg}`,
529
+ end: '', durationMin: 0,
530
+ });
531
+ continue;
532
+ }
533
+
534
+ const timeline = buildTimeline(result.items, date);
535
+ for (const row of timeline) {
536
+ allRows.push({ roomName: r.name, roomEmail: result.newId, ...row });
537
+ }
538
+ }
539
+ }
540
+
541
+ if (allRows.length === 0) {
542
+ throw new Error(`No results for any of the ${parsedRooms.length} room(s) on ${date}`);
543
+ }
544
+
545
+ return allRows;