Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 45 additions & 13 deletions desktop/desktop/channels/adapters/imessage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ export function createIMessageAdapter(deps = {}) {
const launch = deps.launch ?? launchProgram;
const spawnProcess = deps.spawnProcess ?? spawn;
const sendTimeoutMs = deps.sendTimeoutMs ?? 15000;
const pollIntervalMs = deps.pollIntervalMs ?? 1500;
const pollIntervalMs = deps.pollIntervalMs ?? 4000;
const reconnectBaseMs = deps.reconnectBaseMs ?? 1000;
const reconnectMaxMs = deps.reconnectMaxMs ?? 30000;

Expand Down Expand Up @@ -618,18 +618,31 @@ export function createIMessageAdapter(deps = {}) {
* Builds a node-host bridge over the workspace's encrypted same-owner `teamwork-peers` transport
* so iMessage channels can run `channel.imessage.watch` and `channel.imessage.send` on a bound Mac node.
*/
export function createNodeChannelBridge(workspace, { pollMs = 150, timeoutMs = 30000 } = {}) {
const resolvePeer = async (nodeHostId) => {
export function createNodeChannelBridge(
workspace,
{ pollMs = 500, retryBaseMs = 1000, maxRetryMs = 5000, timeoutMs = 30000 } = {},
) {
const resolvePeer = async (nodeHostId, deadline) => {
const peers = workspace?.teamworkPeers;
if (!peers) throw new Error("Teamwork peers transport is unavailable on this host.");
const hosts = await peers.hosts(true);
const host = hosts.find((item) => item.serverId === nodeHostId);
if (!host) throw new Error(`Mac node host "${nodeHostId}" is not linked to this account.`);
return { peers, host };
let retryDelay = 0;
while (true) {
try {
const hosts = await peers.hosts(true);
const host = hosts.find((item) => item.serverId === nodeHostId);
if (!host) throw new Error(`Mac node host "${nodeHostId}" is not linked to this account.`);
return { peers, host };
} catch (err) {
if (err?.code !== "TEAMWORK_OFFLINE" || !deadline || Date.now() >= deadline) throw err;
retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2));
await new Promise((r) => setTimeout(r, Math.min(retryDelay, Math.max(0, deadline - Date.now()))));
}
}
};

const runJob = async (nodeHostId, operation, { botId = "", params = {} } = {}) => {
const { peers, host } = await resolvePeer(nodeHostId);
const deadline = Date.now() + timeoutMs;
const { peers, host } = await resolvePeer(nodeHostId, deadline);
const bot = botId ? workspace.bot?.(botId) : null;
const jobId = randomUUID();
const submit = {
Expand All @@ -642,15 +655,34 @@ export function createNodeChannelBridge(workspace, { pollMs = 150, timeoutMs = 3
params,
createdAt: Date.now(),
};
const deadline = Date.now() + timeoutMs;
let res = await peers.call(host.serverId, "job.submit", submit, host.pin);
while (res && (res.status === "pending" || res.status === "working")) {
let op = "job.submit";
let retryDelay = 0;
let res = null;
while (true) {
if (Date.now() > deadline) {
await peers.call(host.serverId, "job.cancel", { id: jobId }, host.pin).catch(() => {});
throw new Error(`Timed out waiting for ${operation} on node ${host.name || host.serverId}.`);
}
await new Promise((r) => setTimeout(r, pollMs));
res = await peers.call(host.serverId, "job.status", { id: jobId }, host.pin);
try {
res = await peers.call(host.serverId, op, op === "job.submit" ? submit : { id: jobId }, host.pin);
retryDelay = 0;
} catch (err) {
if (err?.code !== "TEAMWORK_OFFLINE") throw err;
retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2));
const remaining = deadline - Date.now();
if (remaining <= 0) {
await peers.call(host.serverId, "job.cancel", { id: jobId }, host.pin).catch(() => {});
throw new Error(`Timed out waiting for ${operation} on node ${host.name || host.serverId}.`);
}
await new Promise((r) => setTimeout(r, Math.min(retryDelay, remaining)));
continue;
}
if (res && (res.status === "pending" || res.status === "working")) {
op = "job.status";
await new Promise((r) => setTimeout(r, pollMs));
continue;
}
break;
}
if (!res || res.status !== "completed") {
throw new Error(res?.error || `Node ${host.name || host.serverId} did not complete ${operation}.`);
Expand Down
75 changes: 63 additions & 12 deletions desktop/desktop/channels/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1506,6 +1506,7 @@ export class ChannelManager {
id: payload.id,
hostHash,
fingerprint,
framedText: framed,
chatId: chat.id,
status: "working",
reply: "",
Expand Down Expand Up @@ -1535,6 +1536,7 @@ export class ChannelManager {
try {
const submitPromise = this.workspace.submit(chat.id, framed, {
title: `${label}: ${senderDisplay}`.slice(0, 100),
clientMessageId: payload.id,
});
if (submitPromise && typeof submitPromise.catch === "function") {
submitPromise.catch(failRow);
Expand All @@ -1558,33 +1560,82 @@ export class ChannelManager {
if (chat.channel.remoteHostId) {
const queue = this.remoteTurnQueue.get(chat.id);
if (!queue?.length) return;
const row = queue.shift();

const runUserMessages = (chat.messages ?? []).filter(
(m) => m.role === "user" && (m.runId === run.id || m.steeredRunId === run.id),
);
const taggedIds = new Set(
runUserMessages
.map((m) => (typeof m.clientMessageId === "string" ? m.clientMessageId : ""))
.filter(Boolean),
);

let matched = [];
if (taggedIds.size > 0) {
matched = queue.filter((r) => taggedIds.has(r.id));
} else if (runUserMessages.length > 0) {
const textMatches = queue.filter((r) =>
runUserMessages.some((m) => typeof m.text === "string" && m.text === r.framedText),
);
if (textMatches.length > 0) {
matched = [textMatches[0]];
} else if (runUserMessages.some((m) => typeof m.text === "string" && m.text.startsWith("[UNTRUSTED_CHANNEL_MESSAGE "))) {
matched = [queue[0]];
}
} else {
matched = [queue[0]];
}

if (!matched.length) return;
for (const item of matched) {
const idx = queue.indexOf(item);
if (idx >= 0) queue.splice(idx, 1);
}
if (queue.length === 0) this.remoteTurnQueue.delete(chat.id);
if (!row || (row.status !== "pending" && row.status !== "working")) return;
row.turnId = run.id || "";
row.updatedAt = this.now();

const activeMatched = matched.filter((r) => r && (r.status === "pending" || r.status === "working"));
if (!activeMatched.length) return;

const now = this.now();
const primary = activeMatched[activeMatched.length - 1];
for (const item of activeMatched.slice(0, -1)) {
item.turnId = run.id || "";
item.updatedAt = now;
if (run.status === "Stopped") {
item.status = "cancelled";
} else if (run.status === "Error" || run.error) {
item.status = "failed";
item.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues());
} else {
item.status = "done";
item.silent = true;
}
}

primary.turnId = run.id || "";
primary.updatedAt = now;
if (run.status === "Stopped") {
row.status = "cancelled";
primary.status = "cancelled";
return;
}
if (run.status === "Error" || run.error) {
row.status = "failed";
row.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues());
primary.status = "failed";
primary.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues());
return;
}
if (run.silent || run.noOutput) {
row.status = "done";
row.silent = true;
primary.status = "done";
primary.silent = true;
return;
}
const replies = (chat.messages ?? []).filter(
(m) => m.role === "assistant" && m.runId === run.id && typeof m.text === "string" && m.text.trim(),
);
const rawText = replies.map((m) => m.text.trim()).join("\n\n").trim();
const safeText = scrubSecrets(rawText, this.allSecretValues());
row.status = "done";
row.reply = safeText;
row.silent = !safeText;
primary.status = "done";
primary.reply = safeText;
primary.silent = !safeText;
return;
}

Expand Down
97 changes: 81 additions & 16 deletions desktop/desktop/channels/remote-bridge.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

import { randomUUID } from "node:crypto";

const DEFAULT_POLL_MS = 350;
const MAX_POLL_MS = 1_000;
const DEFAULT_POLL_MS = 1_000;
const MAX_POLL_MS = 2_500;
const DEFAULT_RETRY_BASE_MS = 1_500;
const MAX_RETRY_MS = 15_000;
const DEFAULT_TIMEOUT_MS = 10 * 60_000;

function sleep(ms, signal) {
Expand Down Expand Up @@ -75,7 +77,16 @@ async function fetchBotsFromHost(peers, host) {
/**
* Builds the remote-turn bridge over `workspace.teamworkPeers`.
*/
export function createRemoteTurnBridge(workspace, { pollMs = DEFAULT_POLL_MS, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
export function createRemoteTurnBridge(
workspace,
{
pollMs = DEFAULT_POLL_MS,
maxPollMs = pollMs === DEFAULT_POLL_MS ? MAX_POLL_MS : Math.max(pollMs, Math.min(MAX_POLL_MS, pollMs * 3)),
retryBaseMs = DEFAULT_RETRY_BASE_MS,
maxRetryMs = MAX_RETRY_MS,
timeoutMs = DEFAULT_TIMEOUT_MS,
} = {},
) {
const getPeers = () => workspace?.teamworkPeers ?? null;

return {
Expand Down Expand Up @@ -133,29 +144,83 @@ export function createRemoteTurnBridge(workspace, { pollMs = DEFAULT_POLL_MS, ti
if (!peers?.available?.()) {
throw new Error("Remote host teamwork transport is unavailable on this computer.");
}
const hosts = await peers.hosts(true);
const host = hosts.find((h) => h.serverId === hostId);
if (!host) {
throw new Error(`Remote computer "${hostId}" is not linked to this account.`);
}

const id = randomUUID();
let state = await peers.call(host.serverId, "channel.submit", { id, ...payload }, host.pin);
const startedAt = Date.now();
const deadline = startedAt + timeoutMs;
let host = null;
let submitted = false;
let operation = "channel.submit";
let retryDelay = 0;

const cancelBestEffort = async () => {
if (!host || !submitted) return;
await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {});
};

const sleepOrCancel = async (ms) => {
const remaining = deadline - Date.now();
if (remaining <= 0) {
await cancelBestEffort();
throw new Error(`Remote agent on ${host?.name || hostId} timed out before replying.`);
}
try {
await sleep(Math.min(ms, remaining), signal);
} catch (err) {
await cancelBestEffort();
throw err;
}
};

while (!host) {
if (Date.now() >= deadline) {
throw new Error(`Remote agent on ${hostId} timed out before replying.`);
}
try {
const hosts = await peers.hosts(true);
host = hosts.find((h) => h.serverId === hostId) ?? null;
if (!host) {
throw new Error(`Remote computer "${hostId}" is not linked to this account.`);
}
retryDelay = 0;
} catch (err) {
if (err?.code !== "TEAMWORK_OFFLINE") throw err;
retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2));
await sleepOrCancel(retryDelay);
}
}

while (state?.status === "pending" || state?.status === "working") {
let state = null;
while (true) {
if (Date.now() >= deadline) {
await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {});
await cancelBestEffort();
throw new Error(`Remote agent on ${host.name || hostId} timed out before replying.`);
}
const waitMs = Date.now() - startedAt > 5_000 ? MAX_POLL_MS : pollMs;
try {
await sleep(waitMs, signal);
if (operation === "channel.submit") {
submitted = true;
state = await peers.call(host.serverId, "channel.submit", { id, ...payload }, host.pin);
} else {
state = await peers.call(host.serverId, "channel.status", { id }, host.pin);
}
retryDelay = 0;
} catch (err) {
await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {});
throw err;
if (err?.code !== "TEAMWORK_OFFLINE") throw err;
// Retry transient relay/profile/network blips with bounded backoff, matching remote-teamwork.mjs.
// Retrying channel.submit with the same id is idempotent on the receiver.
retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2));
await sleepOrCancel(retryDelay);
continue;
}
state = await peers.call(host.serverId, "channel.status", { id }, host.pin);

if (state?.status === "pending" || state?.status === "working") {
operation = "channel.status";
const waitMs = Date.now() - startedAt > 5_000 ? maxPollMs : pollMs;
await sleepOrCancel(waitMs);
continue;
}

break;
}

if (state?.status === "failed") {
Expand Down
Loading
Loading