@leg3ndy/otto-bridge 0.6.7 → 0.6.8

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.md CHANGED
@@ -33,10 +33,10 @@ Enquanto o pacote nao estiver publicado, voce pode gerar um tarball local:
33
33
 
34
34
  ```bash
35
35
  npm pack
36
- npm install -g ./leg3ndy-otto-bridge-0.6.7.tgz
36
+ npm install -g ./leg3ndy-otto-bridge-0.6.8.tgz
37
37
  ```
38
38
 
39
- No `0.6.7`, `playwright` deixa de ser opcional no `otto-bridge`. O primeiro `npm install -g @leg3ndy/otto-bridge` pode demorar mais porque instala o browser persistente usado pelo WhatsApp Web e pelos fluxos web em background do bridge.
39
+ No `0.6.8`, `playwright` deixa de ser opcional no `otto-bridge`. O primeiro `npm install -g @leg3ndy/otto-bridge` pode demorar mais porque instala o browser persistente usado pelo WhatsApp Web e pelos fluxos web em background do bridge.
40
40
 
41
41
  ## Publicacao
42
42
 
@@ -106,7 +106,7 @@ otto-bridge run --executor clawd-cursor --clawd-url http://127.0.0.1:3847
106
106
 
107
107
  ### WhatsApp Web em background
108
108
 
109
- Fluxo recomendado no `0.6.7`:
109
+ Fluxo recomendado no `0.6.8`:
110
110
 
111
111
  ```bash
112
112
  otto-bridge extensions --install whatsappweb
@@ -116,7 +116,7 @@ otto-bridge extensions --status whatsappweb
116
116
 
117
117
  O setup agora abre o login do WhatsApp Web em um browser persistente do proprio bridge. Depois do QR code, o Otto usa a sessao local em background, sem depender de aba visivel no Safari.
118
118
 
119
- Contrato do `0.6.7`:
119
+ Contrato do `0.6.8`:
120
120
 
121
121
  - `otto-bridge extensions --setup whatsappweb`: autentica a sessao uma vez
122
122
  - `otto-bridge run`: mantem o browser persistente do WhatsApp vivo em background enquanto o runtime estiver ativo, sem depender de uma aba aberta no Safari
package/dist/types.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export const BRIDGE_CONFIG_VERSION = 1;
2
- export const BRIDGE_VERSION = "0.6.7";
2
+ export const BRIDGE_VERSION = "0.6.8";
3
3
  export const BRIDGE_PACKAGE_NAME = "@leg3ndy/otto-bridge";
4
4
  export const DEFAULT_API_BASE_URL = "http://localhost:8000";
5
5
  export const DEFAULT_POLL_INTERVAL_MS = 3000;
@@ -115,8 +115,7 @@ export class WhatsAppBackgroundBrowser {
115
115
  this.page = pages[0] || await this.context.newPage();
116
116
  await this.ensureWhatsAppPage();
117
117
  if (this.options.background) {
118
- await this.moveWindowOffscreen();
119
- await this.hideAppFromDock();
118
+ await this.ensureBackgroundPlacement();
120
119
  }
121
120
  }
122
121
  async close() {
@@ -131,6 +130,13 @@ export class WhatsAppBackgroundBrowser {
131
130
  async waitForTimeout(timeoutMs) {
132
131
  await this.page?.waitForTimeout(Math.max(0, Number(timeoutMs || 0)));
133
132
  }
133
+ async ensureBackgroundPlacement() {
134
+ if (!this.options.background) {
135
+ return;
136
+ }
137
+ await this.moveWindowOffscreen();
138
+ await this.hideAppFromDock();
139
+ }
134
140
  async moveWindowOffscreen() {
135
141
  const context = this.context;
136
142
  const page = this.page;
@@ -164,15 +170,26 @@ export class WhatsAppBackgroundBrowser {
164
170
  return;
165
171
  }
166
172
  const browserPid = await this.findBrowserProcessId();
167
- if (!browserPid) {
168
- return;
173
+ if (browserPid) {
174
+ const script = [
175
+ 'tell application "System Events"',
176
+ `set visible of (first application process whose unix id is ${browserPid}) to false`,
177
+ "end tell",
178
+ ].join("\n");
179
+ const hidden = await runCommand("osascript", ["-e", script]).then(() => true).catch(() => false);
180
+ if (hidden) {
181
+ return;
182
+ }
169
183
  }
170
- const script = [
184
+ const fallbackScript = [
171
185
  'tell application "System Events"',
172
- `set visible of (first application process whose unix id is ${browserPid}) to false`,
186
+ 'set chromeLikeProcesses to (application processes whose frontmost is true and (name contains "Chrom" or name contains "Chrome"))',
187
+ 'if (count of chromeLikeProcesses) > 0 then',
188
+ 'set visible of item 1 of chromeLikeProcesses to false',
189
+ "end if",
173
190
  "end tell",
174
191
  ].join("\n");
175
- await runCommand("osascript", ["-e", script]).catch(() => undefined);
192
+ await runCommand("osascript", ["-e", fallbackScript]).catch(() => undefined);
176
193
  }
177
194
  async findBrowserProcessId() {
178
195
  if (process.platform !== "darwin") {
@@ -320,18 +337,29 @@ export class WhatsAppBackgroundBrowser {
320
337
  }
321
338
  function focusAndReplaceContent(element, value) {
322
339
  element.focus();
340
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
341
+ element.value = "";
342
+ element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward", data: null }));
343
+ element.value = value;
344
+ element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: value }));
345
+ element.dispatchEvent(new Event("change", { bubbles: true }));
346
+ return;
347
+ }
348
+ element.textContent = "";
349
+ element.innerHTML = "";
350
+ element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward", data: null }));
323
351
  const selection = window.getSelection();
324
352
  const range = document.createRange();
325
353
  range.selectNodeContents(element);
354
+ range.collapse(false);
326
355
  selection?.removeAllRanges();
327
356
  selection?.addRange(range);
328
- document.execCommand("selectAll", false);
329
- document.execCommand("delete", false);
330
357
  document.execCommand("insertText", false, value);
331
- if ((element.innerText || "").trim() !== value.trim()) {
358
+ if (normalize(element.innerText || element.textContent || "") !== normalize(value)) {
332
359
  element.textContent = value;
333
360
  }
334
361
  element.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" }));
362
+ element.dispatchEvent(new Event("change", { bubbles: true }));
335
363
  }
336
364
  const candidates = Array.from(document.querySelectorAll('div[contenteditable="true"][role="textbox"], div[contenteditable="true"][data-tab], [data-testid="chat-list-search"] [contenteditable="true"]'))
337
365
  .filter((node) => node instanceof HTMLElement)
@@ -360,55 +388,61 @@ export class WhatsAppBackgroundBrowser {
360
388
  if (!prepared.ok) {
361
389
  return false;
362
390
  }
363
- await this.page?.waitForTimeout(900);
364
- const result = await this.withPage((page) => page.evaluate((query) => {
365
- const normalize = (value) => String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
366
- const normalizedQuery = normalize(query);
367
- function isVisible(element) {
368
- if (!(element instanceof HTMLElement))
369
- return false;
370
- const rect = element.getBoundingClientRect();
371
- if (rect.width < 6 || rect.height < 6)
372
- return false;
373
- const style = window.getComputedStyle(element);
374
- if (style.visibility === "hidden" || style.display === "none" || Number(style.opacity || "1") === 0)
375
- return false;
376
- return rect.bottom >= 0 && rect.right >= 0 && rect.top <= window.innerHeight && rect.left <= window.innerWidth;
377
- }
378
- const titleNodes = Array.from(document.querySelectorAll('span[title], div[title]'))
379
- .filter((node) => node instanceof HTMLElement)
380
- .filter((node) => isVisible(node))
381
- .map((node) => {
382
- const text = normalize(node.getAttribute("title") || node.textContent || "");
383
- let score = 0;
384
- if (text === normalizedQuery)
385
- score += 160;
386
- if (text.includes(normalizedQuery))
387
- score += 100;
388
- if (normalizedQuery.includes(text) && text.length >= 3)
389
- score += 50;
390
- const container = node.closest('[data-testid="cell-frame-container"], [role="listitem"], [role="gridcell"], div[tabindex]');
391
- if (container instanceof HTMLElement && isVisible(container))
392
- score += 20;
393
- return { node, container, score };
394
- })
395
- .filter((item) => item.score > 0)
396
- .sort((left, right) => right.score - left.score);
397
- if (!titleNodes.length) {
398
- return { clicked: false, reason: "Nao achei uma conversa visivel com esse nome." };
399
- }
400
- const winner = titleNodes[0];
401
- const target = winner.container instanceof HTMLElement ? winner.container : winner.node;
402
- target.scrollIntoView({ block: "center", inline: "center", behavior: "auto" });
403
- target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window }));
404
- target.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window }));
405
- target.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window }));
406
- if (typeof target.click === "function") {
407
- target.click();
391
+ const deadline = Date.now() + 5_000;
392
+ while (Date.now() < deadline) {
393
+ await this.page?.waitForTimeout(650);
394
+ const result = await this.withPage((page) => page.evaluate((query) => {
395
+ const normalize = (value) => String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
396
+ const normalizedQuery = normalize(query);
397
+ function isVisible(element) {
398
+ if (!(element instanceof HTMLElement))
399
+ return false;
400
+ const rect = element.getBoundingClientRect();
401
+ if (rect.width < 6 || rect.height < 6)
402
+ return false;
403
+ const style = window.getComputedStyle(element);
404
+ if (style.visibility === "hidden" || style.display === "none" || Number(style.opacity || "1") === 0)
405
+ return false;
406
+ return rect.bottom >= 0 && rect.right >= 0 && rect.top <= window.innerHeight && rect.left <= window.innerWidth;
407
+ }
408
+ const titleNodes = Array.from(document.querySelectorAll('span[title], div[title]'))
409
+ .filter((node) => node instanceof HTMLElement)
410
+ .filter((node) => isVisible(node))
411
+ .map((node) => {
412
+ const text = normalize(node.getAttribute("title") || node.textContent || "");
413
+ let score = 0;
414
+ if (text === normalizedQuery)
415
+ score += 160;
416
+ if (text.includes(normalizedQuery))
417
+ score += 100;
418
+ if (normalizedQuery.includes(text) && text.length >= 3)
419
+ score += 50;
420
+ const container = node.closest('[data-testid="cell-frame-container"], [role="listitem"], [role="gridcell"], div[tabindex]');
421
+ if (container instanceof HTMLElement && isVisible(container))
422
+ score += 20;
423
+ return { node, container, score };
424
+ })
425
+ .filter((item) => item.score > 0)
426
+ .sort((left, right) => right.score - left.score);
427
+ if (!titleNodes.length) {
428
+ return { clicked: false, reason: "Nao achei uma conversa visivel com esse nome." };
429
+ }
430
+ const winner = titleNodes[0];
431
+ const target = winner.container instanceof HTMLElement ? winner.container : winner.node;
432
+ target.scrollIntoView({ block: "center", inline: "center", behavior: "auto" });
433
+ target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window }));
434
+ target.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window }));
435
+ target.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window }));
436
+ if (typeof target.click === "function") {
437
+ target.click();
438
+ }
439
+ return { clicked: true };
440
+ }, contact));
441
+ if (result.clicked === true) {
442
+ return true;
408
443
  }
409
- return { clicked: true };
410
- }, contact));
411
- return result.clicked === true;
444
+ }
445
+ return false;
412
446
  }
413
447
  async sendMessage(text) {
414
448
  await this.ensureReady();
@@ -568,7 +602,12 @@ export class WhatsAppBackgroundBrowser {
568
602
  if (!this.page) {
569
603
  throw new Error("WhatsApp background browser nao conseguiu abrir a pagina.");
570
604
  }
571
- return handler(this.page);
605
+ try {
606
+ return await handler(this.page);
607
+ }
608
+ finally {
609
+ await this.ensureBackgroundPlacement().catch(() => undefined);
610
+ }
572
611
  }
573
612
  }
574
613
  function clipText(text, maxLength) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leg3ndy/otto-bridge",
3
- "version": "0.6.7",
3
+ "version": "0.6.8",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local companion for Otto Bridge device pairing and WebSocket runtime.",