Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 13 additions & 0 deletions .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@
is checked again when it runs) and `get_canvas` (`customAgents`) read it. Work left for an agent
that is deleted or off goes to Doop. Routes: `/api/agents` and `/api/agents/builtin`
(`?workspace=`, members only). Tests: `customAgents.test.ts`, `customAgentsHttp.test.ts`.
- Agent identity (`shared/agentIdentity.ts`): an outside agent is its account and its `agent_name`,
not the name alone, so two people's "Claude" on a shared canvas are two agents with their own
presence and tasks. `mcpAgentKey` hashes the two into the opaque `agentKey` on the `Actor`, the
presence (keyed and `clientId`'d by it) and the task (`tasks.agent_key`, migration 0060);
`set_status`, auto tasks, `endAgentTasks` on presence expiry and the guidelines nudge match on it
(`isAgentsTask`), as do the editor's task and face fly-tos (`taskFrameId`, `locatePresence`).
Not the MCP session: in PostHog's `custom_agent_connected` (one per `initialize`) Codex and the
`openai-mcp` clients start a session every few seconds and Claude Code in bursts, so a session key
would split one agent into many; one person's two agents of one name stay one agent. Resident
roles carry no key and are their name. Feedback on an outside agent's task waits
`OWNER_FIRST_MS` (a minute, the presence lifetime) for that agent before any agent may take it,
and `get_feedback` and delivered feedback say whose work it is about (`whoseWork`). Tests:
`agentIdentity.test.ts`, `agentIdentityHttp.test.ts`, the shared-name cases in `locate.test.ts`.
- Agent feedback (`server/agentFeedback.ts`, `shared/agentFeedback.ts`): agents talk to the Doop
team through two MCP tools, which the resident agent has under the same names. `report_issue`
(kind `issue`: `bug`, `tool_error`, `confusing`, `missing_capability`, `other`) is for where Doop
Expand Down
109 changes: 73 additions & 36 deletions server/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { MAX_PAGES, PageLimitError, store } from './store.ts'
import * as persist from './db/persist.ts'
import * as thumbs from './thumbs.ts'
import { colorFor } from '../shared/types.ts'
import { agentKeyOf, isAgentsTask } from '../shared/agentIdentity.ts'
import type { AgentBrand } from '../shared/agentBrand.ts'
import type { StackWrite } from '../shared/frameStack.ts'
import {
Expand Down Expand Up @@ -92,10 +93,9 @@ import type {
type Broadcast = (canvasId: string, msg: ServerMessage, excludeClientId?: string) => void
type AgentTouch = (
canvasId: string,
agentName: string,
agent: Pick<Actor, 'name' | 'owner' | 'brand' | 'agentKey'>,
frameId?: string | null,
status?: string | null,
identity?: Pick<Actor, 'owner' | 'brand'>,
) => void

let send: Broadcast = () => {}
Expand Down Expand Up @@ -282,15 +282,25 @@ function logActivity(canvasId: string, actor: Actor, message: string, frameId?:
}

export function resolveActor(
raw: { name?: string; kind?: string; clientId?: string; owner?: string; brand?: AgentBrand } | undefined,
raw:
| { name?: string; kind?: string; clientId?: string; owner?: string; brand?: AgentBrand; agentKey?: string }
| undefined,
): Actor {
const kind = raw?.kind === 'agent' ? 'agent' : raw?.kind === 'user' ? 'user' : 'agent'
const name = raw?.name?.trim() || (kind === 'agent' ? 'AI Agent' : 'Anonymous')
return { name, kind, color: colorFor(name), clientId: raw?.clientId, owner: raw?.owner, brand: raw?.brand }
return {
name,
kind,
color: colorFor(name),
clientId: raw?.clientId,
owner: raw?.owner,
brand: raw?.brand,
...(kind === 'agent' && raw?.agentKey ? { agentKey: raw.agentKey } : {}),
}
}

function touch(canvasId: string, actor: Actor, frameId?: string | null) {
if (actor.kind === 'agent') agentTouch(canvasId, actor.name, frameId, undefined, actor)
if (actor.kind === 'agent') agentTouch(canvasId, actor, frameId)
}

/** Refresh an agent's presence without changing its frame or status. A model
Expand All @@ -301,11 +311,6 @@ export function heartbeatAgent(canvasId: string, actor: Actor) {
touch(canvasId, actor)
}

/** Same agent identity = same name. (Owner-scoping deferred until MCP auth.) */
function sameAgent(t: { agentName: string }, actor: Actor): boolean {
return t.agentName === actor.name
}

/* ------------------------------------------------------------------ */
/* Agent routing: a board card carries an ordered pipeline of roles and */
/* is only ever visible to the role at its current stage. Feedback and */
Expand Down Expand Up @@ -468,12 +473,12 @@ export function taskCanvasId(taskId: string): string | undefined {
/** Agent announces what it is working on right now (empty string clears it). */
export function setAgentStatus(canvasId: string, actor: Actor, status: string) {
const clean = status.trim()
agentTouch(canvasId, actor.name, undefined, clean || null, actor)
agentTouch(canvasId, actor, undefined, clean || null)

const list = taskLog.get(canvasId) ?? []
/* board cards stay open until explicitly completed — a status change
narrates work ON a card, it doesn't end it */
const open = list.find((t) => sameAgent(t, actor) && !t.endedAt && !t.queuedBy)
const open = list.find((t) => isAgentsTask(t, actor) && !t.endedAt && !t.queuedBy)
if (open?.status === clean) return // same status re-posted: nothing new
const runStartedAt = open ? (open.runStartedAt ?? open.startedAt) : undefined
if (open) {
Expand All @@ -485,6 +490,7 @@ export function setAgentStatus(canvasId: string, actor: Actor, status: string) {
const task: AgentTask = {
id: nanoid(8),
agentName: actor.name,
...(actor.agentKey ? { agentKey: actor.agentKey } : {}),
owner: actor.owner,
color: actor.color,
status: clean,
Expand Down Expand Up @@ -538,6 +544,7 @@ export function addTaskFeedback(
taskId,
canvasId,
agentName: task.agentName,
...(task.agentKey ? { agentKey: task.agentKey } : {}),
...(target ? { targetAgent: target } : {}),
from,
...(fromUserId ? { fromUserId } : {}),
Expand All @@ -561,26 +568,51 @@ export function addTaskFeedback(
return undefined
}

/** How long feedback on an outside agent's task waits for that agent before
* any agent may take it: the longest an agent's presence outlives its last
* tool call (server/index.ts), so an agent still at work is asked first. */
export const OWNER_FIRST_MS = 60_000

/** Whether an outside agent may take feedback yet: anything once the agent
* whose work it is about has had its minute, and its own feedback at once.
* Resident roles (no key) are routed by `targetAgent` and never wait. */
function ownerFirst(f: TaskFeedback, agent: Pick<Actor, 'name' | 'agentKey'>, now: number): boolean {
if (!f.agentKey || !agent.agentKey || f.agentKey === agent.agentKey) return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Doop skips the feedback wait

ownerFirst lets resident agents skip the new one-minute wait because they have no agentKey. When someone replies to an outside Claude's task, addTaskFeedback immediately wakes the resident runner. If a model is available, Doop can claim the reply before Claude's next call, so Claude never receives the requested change. Apply the wait to feedback carrying another agent's key, including when the caller is a resident.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, fixed in 7a6bd83. The wait now lives in feedbackFor, so it holds for every agent other than the one whose work the feedback is about, residents included. pendingWorkAgents leaves waiting feedback out, so a sweep doesn't run for it early, and addTaskFeedback wakes the residents again once OWNER_FIRST_MS is up. Covered by 'makes the resident agents wait the minute too' in tests/agentIdentity.test.ts.

return now - f.at >= OWNER_FIRST_MS
}

/** The feedback takeFeedbackFor would claim, left unclaimed: what read-only
* tools mention without assigning anything. */
export function openFeedbackFor(canvasId: string, agentName: string, payer?: string, runner?: string): TaskFeedback[] {
export function openFeedbackFor(
canvasId: string,
agent: Pick<Actor, 'name' | 'agentKey'>,
payer?: string,
runner?: string,
): TaskFeedback[] {
const roster = canvasRoster(canvasId)
const now = Date.now()
return (feedbackLog.get(canvasId) ?? []).filter(
(f) =>
!f.deliveredAt &&
!f.failedAt &&
feedbackFor(f, agentName, roster) &&
feedbackFor(f, agent.name, roster) &&
ownerFirst(f, agent, now) &&
(payer === undefined || (f.fromUserId ?? '') === payer) &&
(runner === undefined || runnerKey(feedbackRunner(f)) === runner),
)
}

/** Open feedback this agent may take: everything addressed to it, plus
* untargeted feedback — that part stays a canvas-level queue where the first
* identified agent call wins. `runner` (a `runnerKey`) narrows the claim to
* one connection, since a run calls one model. */
export function takeFeedbackFor(canvasId: string, agentName: string, payer?: string, runner?: string): TaskFeedback[] {
return claimFeedback(canvasId, agentName, false, payer, runner)
/** Open feedback this outside agent may take: everything addressed to it,
* plus untargeted feedback — that part stays a canvas-level queue where the
* first identified agent call wins, after the agent whose work it is about
* has had first pick (OWNER_FIRST_MS). */
export function takeFeedbackFor(
canvasId: string,
agent: Pick<Actor, 'name' | 'agentKey'>,
payer?: string,
runner?: string,
): TaskFeedback[] {
return claimFeedback(canvasId, agent, false, payer, runner)
}

/** takeFeedbackFor for a resident run: the claim is marked in-process, which
Expand All @@ -591,20 +623,22 @@ export function takeResidentFeedbackFor(
payer?: string,
runner?: string,
): TaskFeedback[] {
return claimFeedback(canvasId, agentName, true, payer, runner)
return claimFeedback(canvasId, { name: agentName }, true, payer, runner)
}

/** `runner` (a `runnerKey`) narrows the claim to one connection, since a run
* calls one model. */
function claimFeedback(
canvasId: string,
agentName: string,
agent: Pick<Actor, 'name' | 'agentKey'>,
resident: boolean,
payer?: string,
runner?: string,
): TaskFeedback[] {
const pending = openFeedbackFor(canvasId, agentName, payer, runner)
const pending = openFeedbackFor(canvasId, agent, payer, runner)
for (const f of pending) {
edit(f).deliveredAt = Date.now()
f.claimedBy = agentName
f.claimedBy = agent.name
f.claimedByResident = resident
stored.saveFeedback(f)
broadcast(canvasId, { type: 'feedback', feedback: f }) // clients flip the entry to "picked up"
Expand Down Expand Up @@ -1310,7 +1344,7 @@ export function recordWorkReply(canvasId: string, work: { cardIds: string[]; fee

/** True if the agent has an explicitly announced (non-auto) task open. */
export function hasAnnouncedTask(canvasId: string, actor: Actor): boolean {
return (taskLog.get(canvasId) ?? []).some((t) => sameAgent(t, actor) && !t.endedAt && !t.auto)
return (taskLog.get(canvasId) ?? []).some((t) => isAgentsTask(t, actor) && !t.endedAt && !t.auto)
}

/** How many frames a task remembers — the Agents panel only ever jumps to the
Expand All @@ -1322,7 +1356,7 @@ const TASK_FRAMES_CAP = 20
* card and a set_status task can be open side by side — both are the work. */
function trackTaskFrame(canvasId: string, actor: Actor, frameId: string) {
for (const open of taskLog.get(canvasId) ?? []) {
if (!sameAgent(open, actor) || open.endedAt) continue
if (!isAgentsTask(open, actor) || open.endedAt) continue
if (open.frameIds?.at(-1) === frameId) continue
edit(open).frameIds = [...(open.frameIds ?? []).filter((id) => id !== frameId), frameId].slice(-TASK_FRAMES_CAP)
stored.saveTask(canvasId, open)
Expand All @@ -1334,13 +1368,14 @@ function trackTaskFrame(canvasId: string, actor: Actor, frameId: string) {
they are visibly doing, so the Tasks panel is never silently empty. */
function autoTask(canvasId: string, actor: Actor, status: string, frameId: string) {
const list = taskLog.get(canvasId) ?? []
if (list.some((t) => sameAgent(t, actor) && !t.endedAt)) {
if (list.some((t) => isAgentsTask(t, actor) && !t.endedAt)) {
trackTaskFrame(canvasId, actor, frameId) // any open task wins — it just gains the frame
return
}
const task: AgentTask = {
id: nanoid(8),
agentName: actor.name,
...(actor.agentKey ? { agentKey: actor.agentKey } : {}),
owner: actor.owner,
color: actor.color,
status,
Expand All @@ -1354,18 +1389,20 @@ function autoTask(canvasId: string, actor: Actor, status: string, frameId: strin
}

function endAutoTask(canvasId: string, actor: Actor) {
const open = (taskLog.get(canvasId) ?? []).find((t) => sameAgent(t, actor) && !t.endedAt && t.auto)
const open = (taskLog.get(canvasId) ?? []).find((t) => isAgentsTask(t, actor) && !t.endedAt && t.auto)
if (open) {
edit(open).endedAt = Date.now()
stored.saveTask(canvasId, open)
broadcast(canvasId, { type: 'task', task: open })
}
}

/** Close an agent's open tasks, e.g. when its presence expires. */
export function endAgentTasks(canvasId: string, agentName: string) {
/** Close an agent's open tasks, e.g. when its presence expires. Only that
* agent's: another one sharing its name keeps working. */
export function endAgentTasks(canvasId: string, agent: Pick<Actor, 'name' | 'agentKey'>) {
const agentName = agent.name
for (const t of taskLog.get(canvasId) ?? []) {
if (t.agentName === agentName && !t.endedAt) {
if (isAgentsTask(t, agent) && !t.endedAt) {
if (t.queuedBy && t.failedAt) continue
edit(t)
if (t.queuedBy) {
Expand Down Expand Up @@ -1726,7 +1763,7 @@ function noteHtmlChange(prior: PriorState, actor: Actor, tweak: boolean) {
const joins =
tweak &&
open !== undefined &&
open.actor.name === actor.name &&
agentKeyOf(open.actor) === agentKeyOf(actor) &&
open.actor.kind === actor.kind &&
now - open.lastAt < BURST_IDLE_MS
setKey(bursts, prior.id, { actor, lastAt: now })
Expand Down Expand Up @@ -2858,12 +2895,12 @@ export function patchGuideline(
task log's announce tracking. */
const guidelinesSeen = new Set<string>()

export function markGuidelinesSeen(canvasId: string, agentName: string) {
guidelinesSeen.add(`${canvasId}:${agentName}`)
export function markGuidelinesSeen(canvasId: string, agentKey: string) {
guidelinesSeen.add(`${canvasId}:${agentKey}`)
}

export function hasSeenGuidelines(canvasId: string, agentName: string): boolean {
return guidelinesSeen.has(`${canvasId}:${agentName}`)
export function hasSeenGuidelines(canvasId: string, agentKey: string): boolean {
return guidelinesSeen.has(`${canvasId}:${agentKey}`)
}

/* ------------------------------------------------------------------ */
Expand Down
1 change: 1 addition & 0 deletions server/db/migrations/0060_agent_key.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE "tasks" ADD COLUMN "agent_key" text;
Loading
Loading