Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Wait for connectors before a routine runs at startup (#152)

João Vitor Carvalho5a81c4e770d6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f58156..49f8b0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
## [Unreleased]
> **Em português:**
+> - **Uma rotina que roda ao abrir o app já encontra os conectores.** As perdidas enquanto o app estava fechado rodavam antes de os conectores terminarem de conectar, e o agente achava que eles estavam fora do ar. Agora a rotina espera até 1 minuto por eles.
> - **Conversas longas não pesam mais enquanto um agente responde.** Cada palavra recebida redesenhava todas as mensagens; agora só a que mudou.
> - **O navegador dos agentes abre páginas num servidor Linux que é um PC.** O Chrome esperava o chaveiro bloqueado da área de trabalho e nenhuma página carregava; no servidor ele agora usa o próprio armazenamento.
> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.
@@ -32,6 +33,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Fixed
+- **A routine that runs as the app opens finds its connectors.** Routines missed while the app was closed, and any due right as it opens, ran on the first check, before the connectors had finished connecting: the agent was told its tools were offline and ran without them. A routine now waits for the connectors still connecting, up to a minute, then runs anyway (with a line in the log); with none connecting it starts at once, as before. Thanks [@jvitorcarvalho](https://github.com/jvitorcarvalho)! ([#152](https://github.com/eduwxyz/tucano/pull/152))
- **An agent replies once at a time in the same conversation or thread.** When another agent handed the turn to one already replying there, a second reply of it started next to the first, each working from the conversation as it was when it began. The hand-off is now noted instead, and the caller's step says so ("already replying here, will see this next"); when the current reply ends well, one follow-up reply reads everything that came in meanwhile, in the same Claude Code session. A reply that stopped, failed, hit a limit or waits on you gets no follow-up, since you act there anyway. The same agent elsewhere still runs in parallel, and the hand-off router is told who is already replying, and that waiting for someone's update isn't a request. Thanks [@eialanjones](https://github.com/eialanjones)! ([#151](https://github.com/eduwxyz/tucano/pull/151))
- **A connector tool that fails says why.** The reply's step showed a bare ✗ next to the tool's name, and for some failures the agent got an empty result too. The step now shows the reason under its label (a few lines, all of it on a click), and the agent gets it: a reason only in the structured content or an embedded resource, an MCP error's code and data, a timeout in seconds, a result that doesn't match the tool's schema, or a session that couldn't reconnect. An approved call and a routine's poll say it the same way. Thanks [@rjgdias](https://github.com/rjgdias)! ([#133](https://github.com/eduwxyz/tucano/pull/133))
- **Long conversations stay light while an agent replies.** Each streamed word redrew and re-parsed every message in the list, keeping the window busy on long conversations. Now only the message that changed is drawn again.
diff --git a/src/core/connectors.ts b/src/core/connectors.ts
index 8d115f5..c163e4c 100644
--- a/src/core/connectors.ts
+++ b/src/core/connectors.ts
@@ -189,6 +189,13 @@ export class ConnectorManager {
for (const c of this.deps.db.connectors()) void this.connect(c.id)
}
+ // Settles when every connection attempt under way has finished, whether it worked or not;
+ // undefined when none is, so whoever waits on it can go on at once.
+ settled(): Promise<void> | undefined {
+ const pending = [...this.live.values()].flatMap((l) => (l.connecting ? [l.connecting] : []))
+ return pending.length ? Promise.allSettled(pending).then(() => {}) : undefined
+ }
+
async closeAll(): Promise<void> {
this.closing = true
for (const l of this.live.values()) clearTimeout(l.retry)
diff --git a/src/core/index.ts b/src/core/index.ts
index d018b77..de38353 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -552,6 +552,7 @@ const routines = new Routines({
db,
runner: { runRoutine: (r, when) => runner.runRoutine(r, when), retryRoutine: (r, when, id) => runner.retryRoutine(r, when, id) },
connectors: { call: (id, tool, args) => connectors.call(id, tool, args), list: () => connectors.list() },
+ connectorsReady: () => connectors.settled(),
blocked: () => !!settings().paused || inQuietHours(settings().quietHours),
paused: () => !!settings().paused,
emit,
diff --git a/src/core/routines.ts b/src/core/routines.ts
index a99bc53..cf801bb 100644
--- a/src/core/routines.ts
+++ b/src/core/routines.ts
@@ -17,6 +17,7 @@ export { MAX_AGENT_ROUTINES } // the default; each agent's own is agent.maxRouti
export const TICK_MS = 30_000
export const LATE_GRACE_MS = 12 * 3_600_000 // a run missed by more than this is skipped
const LATE_AFTER_MS = 2 * 60_000 // later than this is "atrasada" in the conversation
+export const CONNECTORS_WAIT_MS = 60_000 // a run waits this long, at most, for connectors still connecting
// A reply that fails is tried again in place, after these waits; then it stays failed.
export const RETRY_WAITS_MS = [60_000, 5 * 60_000]
@@ -85,6 +86,8 @@ export interface RoutineDeps {
retryRoutine?(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, messageId: string): Promise<Message | undefined>
}
connectors?: { call(id: string, tool: string, args: Record<string, unknown>): Promise<CallToolResult>; list(): Connector[] }
+ connectorsReady?: () => Promise<void> | undefined // settles when the connectors connecting have finished (or failed); undefined when none is
+ connectorsWaitMs?: number // how long a run waits for that (tests shorten it)
blocked?: () => boolean // paused, or quiet hours: nothing is due until it ends (then it runs late)
paused?: () => boolean // paused: a call from outside says so instead of starting a run
emit: (e: CoreEvent) => void
@@ -342,13 +345,35 @@ export class Routines {
)
}
+ private connectorsSettled(): Promise<void> | undefined {
+ const pending = this.deps.connectorsReady?.()
+ return pending && this.waitFor(pending)
+ }
+
+ private async waitFor(pending: Promise<void>): Promise<void> {
+ const ms = this.deps.connectorsWaitMs ?? CONNECTORS_WAIT_MS
+ let timer: NodeJS.Timeout | undefined
+ const timedOut = new Promise<'timeout'>((resolve) => (timer = setTimeout(() => resolve('timeout'), ms)))
+ timer?.unref()
+ try {
+ const done = await Promise.race([pending.then(() => 'ready' as const, () => 'ready' as const), timedOut])
+ if (done === 'timeout') console.warn(`[routines] connectors still connecting after ${Math.round(ms / 1000)}s: running the routine without waiting`)
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+
// One run of a routine at a time: if the last one is still going, this one skips.
// `more`: a connector check left new items, so check again when this run ends.
private fire(id: string, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, more = false): void {
const r = this.deps.db.routine(id)
if (!r || this.running.has(id)) return
this.running.add(id)
- const run = this.runWithRetries(r, when)
+ // The first tick comes before the connectors have connected, with what was missed while the
+ // app was closed and what is due right then: a run waits for them (a little), or the agent
+ // starts without its tools. With none connecting, it starts right now, as before.
+ const wait = this.connectorsSettled()
+ const run = (wait ? wait.then(() => this.runWithRetries(r, when)) : this.runWithRetries(r, when))
.then((reply) => {
if (!reply) return
const latest = this.deps.db.routine(id)
diff --git a/test/connector-reconnect.test.ts b/test/connector-reconnect.test.ts
index 8c16ca0..2481170 100644
--- a/test/connector-reconnect.test.ts
+++ b/test/connector-reconnect.test.ts
@@ -122,3 +122,23 @@ describe('which failed calls go again on a new connection', () => {
expect(staleSession(new StreamableHTTPError(500, 'Internal error'))).toBe(false)
})
})
+
+describe('settled()', () => {
+ it('waits for a stdio connector that is still connecting, and is immediate when none is', async () => {
+ await connectors.settled() // nothing connecting
+ const script = join(mkdtempSync(join(tmpdir(), 'tucano-stdio-')), 'server.mjs')
+ writeFileSync(
+ script,
+ `const { Server } = await import('${sdk}/server/index.js')
+const { StdioServerTransport } = await import('${sdk}/server/stdio.js')
+const { ListToolsRequestSchema } = await import('${sdk}/types.js')
+const s = new Server({ name: 't', version: '1' }, { capabilities: { tools: {} } })
+s.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ${JSON.stringify(tools)} }))
+await s.connect(new StdioServerTransport())`
+ )
+ const id = await connectors.add({ name: 'Local', kind: 'stdio', command: process.execPath, args: [script] }, false)
+ connectors.connectAll() // as the app does at startup
+ await connectors.settled()
+ expect(status(id)).toBe('connected')
+ }, 20_000)
+})
diff --git a/test/routines-connectors-ready.test.ts b/test/routines-connectors-ready.test.ts
new file mode 100644
index 0000000..46cde38
--- /dev/null
+++ b/test/routines-connectors-ready.test.ts
@@ -0,0 +1,118 @@
+// Issue #146: a routine missed while the app was closed (or due as it opens) fires on the first
+// tick, which used to be before the stdio connectors finished connecting. The agent then ran
+// without its tools.
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { Agent, Message, Routine } from '../src/shared/types'
+import { Db } from '../src/core/db'
+import { Routines } from '../src/core/routines'
+
+const at = (y: number, mo: number, d: number, h = 0, mi = 0): number => new Date(y, mo - 1, d, h, mi).getTime()
+
+describe('routines and connectors that are still connecting', () => {
+ let db: Db
+ let clock: number
+ let log: string[]
+ let warn: ReturnType<typeof vi.spyOn>
+ let release: () => void
+ let connectorsReady: () => Promise<void> | undefined
+
+ const agent: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false }
+ const build = (extra: { connectorsReady?: () => Promise<void> | undefined; connectorsWaitMs?: number } = {}): Routines =>
+ new Routines({
+ db,
+ runner: {
+ runRoutine: async (_r, when) => {
+ log.push(when.late ? 'ran-late' : 'ran')
+ return undefined as Message | undefined
+ }
+ },
+ emit: () => {},
+ now: () => clock,
+ ...extra
+ })
+ const create = (routines: Routines): Routine =>
+ routines.save({ name: 'Morning', agentId: 'a1', conversationId: 'c1', prompt: 'Summarize what is open.', schedule: { days: [1, 2, 3, 4, 5], time: '09:00' }, enabled: true })
+
+ beforeEach(() => {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-routines-conn-')), 'test.db'))
+ db.saveAgent(agent)
+ db.createConversation({ id: 'c1', kind: 'channel', name: 'eng', members: ['a1'] })
+ clock = at(2026, 10, 19, 8, 0) // a Monday
+ log = []
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const gate = new Promise<void>((resolve) => (release = resolve))
+ connectorsReady = async () => {
+ log.push('waiting-for-connectors')
+ await gate
+ log.push('connectors-ready')
+ }
+ })
+ afterEach(() => warn.mockRestore())
+
+ it('a late routine waits for the connectors, then runs with them connected', async () => {
+ const routines = build({ connectorsReady })
+ create(routines)
+ clock = at(2026, 10, 19, 9, 40) // the app was closed at 9:00
+ routines.tick()
+ await new Promise((r) => setTimeout(r, 20))
+ expect(log).not.toContain('ran-late') // still connecting: nothing ran yet
+ release()
+ await routines.idle()
+ expect(log).toEqual(['waiting-for-connectors', 'connectors-ready', 'ran-late'])
+ })
+
+ it('a connector that never connects does not hold the routine back: it runs after the timeout, with a warning', async () => {
+ const never = (): Promise<void> => new Promise(() => {})
+ const routines = build({ connectorsReady: never, connectorsWaitMs: 30 })
+ create(routines)
+ clock = at(2026, 10, 19, 9, 40)
+ routines.tick()
+ await routines.idle()
+ expect(log).toEqual(['ran-late'])
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0]![0])).toContain('[routines]')
+ })
+
+ it('a routine due right as the app opens waits too, not only a late one', async () => {
+ const routines = build({ connectorsReady })
+ create(routines)
+ clock = at(2026, 10, 19, 9, 0) + 10_000 // on time (under two minutes)
+ routines.tick()
+ await new Promise((r) => setTimeout(r, 20))
+ expect(log).not.toContain('ran')
+ release()
+ await routines.idle()
+ expect(log).toEqual(['waiting-for-connectors', 'connectors-ready', 'ran'])
+ })
+
+ it('with every connector connected, a routine runs at once', async () => {
+ const routines = build({ connectorsReady: () => undefined }) // none connecting
+ create(routines)
+ clock = at(2026, 10, 19, 9, 0) + 10_000
+ routines.tick()
+ await routines.idle()
+ expect(log).toEqual(['ran'])
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('a late routine with no connector manager wired runs at once, without a warning', async () => {
+ const routines = build()
+ create(routines)
+ clock = at(2026, 10, 19, 9, 40)
+ routines.tick()
+ await routines.idle()
+ expect(log).toEqual(['ran-late'])
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('with nothing missed, a tick runs nothing and waits for nothing', async () => {
+ const routines = build({ connectorsReady })
+ create(routines)
+ routines.tick() // 8:00, due at 9:00
+ await routines.idle()
+ expect(log).toEqual([])
+ })
+})