taskwindow 0.2.4 → 0.2.6

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
@@ -77,13 +77,24 @@ agents. For another MCP client, connect to `http://127.0.0.1:9377/mcp` with
77
77
  ## How the isolation works
78
78
 
79
79
  - **Task groups & sessions**: every tab the agent creates goes into a blue tab
80
- group named after its task (`tabs_create` requires the task name — it says
81
- what the group is about). Sessions are isolated from each other:
80
+ group named after its task (the first `tabs_create` names it — it says what
81
+ the group is about; later tabs join the session's current group unless a new
82
+ task name starts another). Sessions are isolated from each other:
82
83
  `tabs_create` returns a secret sessionToken and every browser tool call is
83
84
  scoped to that session's groups, so concurrent agents never share tabs —
84
85
  even when they pick the same task name. By default the agent can only see
85
86
  and act on tabs in its own groups — never yours. You can click a group in
86
87
  the toolbar popover to watch, and widen access in settings.
88
+ - **Your focus is never taken**: nothing the agent does brings a tab or window
89
+ forward on you. Chrome's `tabs.create` makes a new tab active by default and
90
+ `windows.create` focuses the new window by default; TaskWindow always opens
91
+ tabs in the background (a background tab still renders, so screenshots and
92
+ page reads work), creates the agent window unfocused, and hands focus back if
93
+ Chrome raises a window anyway. Mouse input is the one thing that needs a
94
+ visible tab, and the agent brings a tab forward for it only in a window you
95
+ are not looking at; if the tab is behind yours in your focused window, the
96
+ call fails instead of switching. Clicking a group in the popover is the only
97
+ thing that focuses the agent's window — and that is you asking for it.
87
98
  - **Pairing**: the daemon listens on 127.0.0.1 only. During setup, the CLI gives
88
99
  the extension a short-lived, single-use code; the long-lived bearer token is
89
100
  returned only after the code is claimed. Manual codes are available with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskwindow",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "TaskWindow local daemon: bridges the TaskWindow Chrome extension to any MCP client over Streamable HTTP",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "start": "node src/index.js",
12
- "test": "node --test test/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-tabs.test.mjs test/tool-contract.test.mjs test/updates.test.mjs && node test/run.mjs"
12
+ "test": "node --test test/pairing.test.mjs test/extension-bootstrap.test.mjs test/extension-tabs.test.mjs test/bridge.test.mjs test/tool-contract.test.mjs test/updates.test.mjs && node test/run.mjs"
13
13
  },
14
14
  "engines": {
15
15
  "node": ">=18"
package/src/bridge.js CHANGED
@@ -10,14 +10,27 @@ const PROTOCOL_VERSION = 1;
10
10
  * tool calls go out as {type:"tool_call", id, tool, params} and come back as
11
11
  * {type:"tool_result", id, ok, ...}. Token is checked at handshake time.
12
12
  */
13
+ const SLOW_ANSWER_MS = 5_000; // log tool calls the extension took longer than this
14
+ const EXPIRED_TTL_MS = 10 * 60_000; // how long a timed-out call is remembered, to name a late answer
15
+
13
16
  export class Bridge {
14
- constructor({ token, logger = console }) {
17
+ /**
18
+ * `pingIntervalMs` / `silenceMs`: the extension sends an application-level
19
+ * ping every 20s, so 65s without any message from it means its end of the
20
+ * socket is dead (a laptop sleep can leave it half-open, readyState still
21
+ * OPEN) — tests shrink both.
22
+ */
23
+ constructor({ token, logger = console, pingIntervalMs = 25_000, silenceMs = 65_000 }) {
15
24
  this.token = token;
16
25
  this.logger = logger;
17
26
  this.ext = null; // active extension WebSocket
18
- this.pending = new Map(); // tool_call id -> {resolve, reject, timer}
27
+ this.pending = new Map(); // tool_call id -> {resolve, reject, timer, tool, sentAt}
28
+ this.expired = new Map(); // tool_call id -> {tool, sentAt, timeoutMs}: timed out, answer may still come
19
29
  this.lastHello = null;
30
+ this.lastExtMessage = 0;
20
31
  this.wss = null;
32
+ this.pingIntervalMs = pingIntervalMs;
33
+ this.silenceMs = silenceMs;
21
34
  }
22
35
 
23
36
  start(httpServer) {
@@ -39,6 +52,7 @@ export class Bridge {
39
52
  } catch {}
40
53
  }
41
54
  this.ext = ws;
55
+ this.lastExtMessage = Date.now();
42
56
 
43
57
  ws.on("message", (raw) => this.#onMessage(ws, raw));
44
58
  ws.on("close", () => {
@@ -52,13 +66,25 @@ export class Bridge {
52
66
  ws.on("error", () => {});
53
67
  });
54
68
 
55
- // Ping to keep the MV3 service worker alive and detect dead peers.
69
+ // Ping to keep the MV3 service worker alive, and drop a socket whose
70
+ // extension has gone silent: otherwise `connected` stays true, every tool
71
+ // call waits out its full timeout, and status reports a healthy extension
72
+ // while the popover says "not connected".
56
73
  this.pingTimer = setInterval(() => {
57
74
  if (this.ext && this.ext.readyState === 0 /* CONNECTING */) return;
75
+ if (this.ext && this.ext.readyState === 1 && Date.now() - this.lastExtMessage > this.silenceMs) {
76
+ this.logger.log(
77
+ `[bridge] extension silent for ${Math.round((Date.now() - this.lastExtMessage) / 1000)}s — dropping the stale connection`
78
+ );
79
+ try {
80
+ this.ext.terminate();
81
+ } catch {}
82
+ return;
83
+ }
58
84
  for (const client of this.wss.clients) {
59
85
  if (client.readyState === 1 /* OPEN */) client.ping();
60
86
  }
61
- }, 25_000);
87
+ }, this.pingIntervalMs);
62
88
  }
63
89
 
64
90
  stop() {
@@ -85,12 +111,17 @@ export class Bridge {
85
111
  );
86
112
  }
87
113
  const id = randomUUID();
114
+ const sentAt = Date.now();
88
115
  return new Promise((resolve, reject) => {
89
116
  const timer = setTimeout(() => {
90
117
  this.pending.delete(id);
91
- reject(new Error(`TaskWindow extension did not answer "${tool}" within ${Math.round(timeoutMs / 1000)}s`));
118
+ for (const [k, v] of this.expired) if (Date.now() - v.sentAt > EXPIRED_TTL_MS) this.expired.delete(k);
119
+ this.expired.set(id, { tool, sentAt, timeoutMs });
120
+ const err = new Error(`TaskWindow extension did not answer "${tool}" within ${Math.round(timeoutMs / 1000)}s`);
121
+ err.code = "TIMEOUT";
122
+ reject(err);
92
123
  }, timeoutMs);
93
- this.pending.set(id, { resolve, reject, timer, tool });
124
+ this.pending.set(id, { resolve, reject, timer, tool, sentAt });
94
125
  this.ext.send(JSON.stringify({ type: "tool_call", id, tool, params }));
95
126
  });
96
127
  }
@@ -102,6 +133,7 @@ export class Bridge {
102
133
  } catch {
103
134
  return;
104
135
  }
136
+ if (ws === this.ext) this.lastExtMessage = Date.now();
105
137
  switch (msg.type) {
106
138
  case "hello":
107
139
  this.lastHello = msg;
@@ -114,9 +146,26 @@ export class Bridge {
114
146
  break;
115
147
  case "tool_result": {
116
148
  const entry = this.pending.get(msg.id);
117
- if (!entry) return;
149
+ if (!entry) {
150
+ // The extension did the work; nobody is waiting any more. Say so —
151
+ // "did not answer" alone reads as a dead extension, and the tab or
152
+ // click this answer describes really happened.
153
+ const late = this.expired.get(msg.id);
154
+ if (late) {
155
+ this.expired.delete(msg.id);
156
+ this.logger.log(
157
+ `[bridge] ${late.tool} answered ${((Date.now() - late.sentAt) / 1000).toFixed(1)}s after it was sent — ` +
158
+ `past its ${Math.round(late.timeoutMs / 1000)}s timeout, so the caller already got an error${this.#timing(msg)}`
159
+ );
160
+ }
161
+ return;
162
+ }
118
163
  clearTimeout(entry.timer);
119
164
  this.pending.delete(msg.id);
165
+ const elapsed = Date.now() - entry.sentAt;
166
+ if (elapsed > SLOW_ANSWER_MS) {
167
+ this.logger.log(`[bridge] ${entry.tool} answered after ${(elapsed / 1000).toFixed(1)}s${this.#timing(msg)}`);
168
+ }
120
169
  if (msg.ok) entry.resolve(msg.result ?? {});
121
170
  else entry.reject(new Error(msg.error || `extension tool "${entry.tool}" failed`));
122
171
  break;
@@ -126,6 +175,14 @@ export class Bridge {
126
175
  }
127
176
  }
128
177
 
178
+ /** Per-phase timing a handler reported (tabs_create does), for the slow/late log lines. */
179
+ #timing(msg) {
180
+ const timing = msg.result?.data?.timing;
181
+ if (!timing || typeof timing !== "object") return "";
182
+ const parts = Object.entries(timing).map(([k, v]) => `${k.replace(/Ms$/, "")} ${(v / 1000).toFixed(1)}s`);
183
+ return parts.length ? ` (${parts.join(", ")})` : "";
184
+ }
185
+
129
186
  #failAllPending(err) {
130
187
  for (const [, entry] of this.pending) {
131
188
  clearTimeout(entry.timer);
package/src/tools.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { mkdir, writeFile } from "node:fs/promises";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
@@ -37,17 +38,21 @@ const rawDefs = [
37
38
  {
38
39
  name: "tabs_create",
39
40
  description:
40
- "Open a new tab in a task-named tab group (in the agent's own window). Requires a \"task\" name saying what the group is about; " +
41
- "same task name in the same session reuses that group. Returns a sessionToken — pass it as \"sessionToken\" in every subsequent " +
42
- "browser tool call; concurrent agents' sessions never share tabs. Don't open a second tab for a page you already have: " +
41
+ "Open a new tab in a task-named tab group (in the agent's own window). The tab opens in the background: it never becomes " +
42
+ "the active tab and never takes focus, so the user's window, tab and app stay as they are. Your first call needs a \"task\" name saying what " +
43
+ "the group is about and returns a sessionToken — pass it as \"sessionToken\" in every subsequent browser tool call; concurrent " +
44
+ "agents' sessions never share tabs. Later calls with the token need no task: the tab joins your session's current task group. " +
45
+ "Pass a new task name to start another group. Don't open a second tab for a page you already have: " +
43
46
  "use reload or navigate on the existing tab (see tabs_list).",
44
47
  inputSchema: {
45
48
  url: z.string().url().describe("URL to open (include the scheme, e.g. https://...)"),
46
49
  task: z
47
50
  .string()
48
51
  .min(1)
49
- .describe('Task name for the tab group — required; says what the group is about, e.g. "Research competitors".'),
50
- active: z.boolean().optional().describe("Make it the active tab of the agent window (default true). Never focuses that window: the user's window and app keep focus."),
52
+ .optional()
53
+ .describe(
54
+ 'Task name for the tab group, e.g. "Research competitors". Required on your first call; afterwards omit it to add the tab to your current task group, or pass a new name to start another.'
55
+ ),
51
56
  sessionToken: z
52
57
  .string()
53
58
  .optional()
@@ -341,7 +346,18 @@ export function registerTools(server, { bridge, version, updates = null, logger
341
346
  // save_to_disk is a daemon-side concern: the extension has no disk
342
347
  // access, so it is stripped here and applied to the returned image.
343
348
  const { save_to_disk, ...forwardedArgs } = args;
344
- const result = await bridge.sendTool(def.name, forwardedArgs, def.timeoutMs);
349
+ // A first tabs_create has no token yet; mint it here rather than in the
350
+ // extension so a call that times out on the way back can still name
351
+ // it. The retry with that token (same task and url) then gets the tab
352
+ // the first call opened, not a second tab in a second group.
353
+ if (def.name === "tabs_create" && !forwardedArgs.sessionToken) forwardedArgs.sessionToken = randomUUID();
354
+ let result;
355
+ try {
356
+ result = await bridge.sendTool(def.name, forwardedArgs, def.timeoutMs);
357
+ } catch (err) {
358
+ if (err.code !== "TIMEOUT") throw err;
359
+ throw new Error(`${err.message}. ${timeoutAdvice(def.name, forwardedArgs)}`);
360
+ }
345
361
  if (save_to_disk && result?.image) {
346
362
  try {
347
363
  const savedPath = await saveImageToDisk(result.image);
@@ -368,6 +384,21 @@ export function registerTools(server, { bridge, version, updates = null, logger
368
384
  }
369
385
  }
370
386
 
387
+ /**
388
+ * What to do after the extension missed a tool's deadline. Chrome is slow to
389
+ * wake, not dead: the call usually completes seconds later (the daemon logs
390
+ * it), so a blind repeat doubles whatever it did.
391
+ */
392
+ function timeoutAdvice(tool, args) {
393
+ if (tool === "tabs_create") {
394
+ return (
395
+ `The tab may still be opening. Retry this exact call with sessionToken "${args.sessionToken}" ` +
396
+ "(same task and url): it returns the tab the first call opened instead of opening another."
397
+ );
398
+ }
399
+ return "Chrome may still complete the action; check the page (screenshot or read_page) before repeating anything that has side effects.";
400
+ }
401
+
371
402
  /**
372
403
  * Write an image result to the session temp dir (OS-cleaned, like Claude's
373
404
  * chrome extension does). Timestamped naming so repeat shots never overwrite.