HonzysClawdbot commited on
Commit
66bd6b3
·
unverified ·
1 Parent(s): c963447

feat: task assignment session targeting (#399)

Browse files

* feat: add task session targeting - dispatch tasks to specific agent sessions (#395)

When assigning a task to an agent, users can now optionally select an
existing session to dispatch the task to instead of creating a new one.

Changes:
- task-dispatch.ts: When target_session is set in task metadata, use
gateway chat.send to dispatch to that specific session instead of
creating a new one via call agent
- task-board-panel.tsx: Add session selector dropdown in both Create
and Edit task modals that appears when an agent is selected and has
active sessions
- store/index.ts: Add agent and channel fields to Session interface

Closes #395

* fix(gateway): ensure gateways table exists before health probe

The gateways table is created lazily by the gateways API (ensureTable).
The health route was querying it directly without CREATE IF NOT EXISTS,
causing SqliteError: no such table: gateways in fresh databases (E2E tests,
Docker first-boot).

Add ensureGatewaysTable() inline to mirror the pattern in route.ts.

src/app/api/gateways/health/route.ts CHANGED
@@ -2,6 +2,26 @@ import { NextRequest, NextResponse } from "next/server"
2
  import { requireRole } from "@/lib/auth"
3
  import { getDatabase } from "@/lib/db"
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  interface GatewayEntry {
6
  id: number
7
  name: string
@@ -144,6 +164,7 @@ export async function POST(request: NextRequest) {
144
  if ("error" in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
145
 
146
  const db = getDatabase()
 
147
  const gateways = db.prepare("SELECT * FROM gateways ORDER BY is_primary DESC, name ASC").all() as GatewayEntry[]
148
 
149
  // Build set of user-configured gateway hosts so the SSRF filter allows them
 
2
  import { requireRole } from "@/lib/auth"
3
  import { getDatabase } from "@/lib/db"
4
 
5
+ function ensureGatewaysTable(db: ReturnType<typeof getDatabase>) {
6
+ db.exec(`
7
+ CREATE TABLE IF NOT EXISTS gateways (
8
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
9
+ name TEXT NOT NULL UNIQUE,
10
+ host TEXT NOT NULL DEFAULT '127.0.0.1',
11
+ port INTEGER NOT NULL DEFAULT 18789,
12
+ token TEXT NOT NULL DEFAULT '',
13
+ is_primary INTEGER NOT NULL DEFAULT 0,
14
+ status TEXT NOT NULL DEFAULT 'unknown',
15
+ last_seen INTEGER,
16
+ latency INTEGER,
17
+ sessions_count INTEGER NOT NULL DEFAULT 0,
18
+ agents_count INTEGER NOT NULL DEFAULT 0,
19
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
20
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch())
21
+ )
22
+ `)
23
+ }
24
+
25
  interface GatewayEntry {
26
  id: number
27
  name: string
 
164
  if ("error" in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
165
 
166
  const db = getDatabase()
167
+ ensureGatewaysTable(db)
168
  const gateways = db.prepare("SELECT * FROM gateways ORDER BY is_primary DESC, name ASC").all() as GatewayEntry[]
169
 
170
  // Build set of user-configured gateway hosts so the SSRF filter allows them
src/components/panels/task-board-panel.tsx CHANGED
@@ -95,6 +95,29 @@ const STATUS_COLUMN_KEYS = [
95
  { key: 'done', titleKey: 'colDone', color: 'bg-green-500/20 text-green-400' },
96
  ]
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  const priorityColors: Record<string, string> = {
99
  low: 'border-l-green-500',
100
  medium: 'border-l-yellow-500',
@@ -1818,8 +1841,10 @@ function CreateTaskModal({
1818
  project_id: projects[0]?.id ? String(projects[0].id) : '',
1819
  assigned_to: '',
1820
  tags: '',
 
1821
  })
1822
  const t = useTranslations('taskBoard')
 
1823
  const [isRecurring, setIsRecurring] = useState(false)
1824
  const [scheduleInput, setScheduleInput] = useState('')
1825
  const [parsedSchedule, setParsedSchedule] = useState<{ cronExpr: string; humanReadable: string } | null>(null)
@@ -1861,6 +1886,9 @@ function CreateTaskModal({
1861
  parent_task_id: null,
1862
  }
1863
  }
 
 
 
1864
 
1865
  try {
1866
  const response = await fetch('/api/tasks', {
@@ -1960,7 +1988,7 @@ function CreateTaskModal({
1960
  <select
1961
  id="create-assignee"
1962
  value={formData.assigned_to}
1963
- onChange={(e) => setFormData(prev => ({ ...prev, assigned_to: e.target.value }))}
1964
  className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
1965
  >
1966
  <option value="">{t('unassigned')}</option>
@@ -1972,6 +2000,26 @@ function CreateTaskModal({
1972
  </select>
1973
  </div>
1974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1975
  <div>
1976
  <label htmlFor="create-tags" className="block text-sm text-muted-foreground mb-1">{t('fieldTags')}</label>
1977
  <input
@@ -2061,8 +2109,10 @@ function EditTaskModal({
2061
  project_id: task.project_id ? String(task.project_id) : (projects[0]?.id ? String(projects[0].id) : ''),
2062
  assigned_to: task.assigned_to || '',
2063
  tags: task.tags ? task.tags.join(', ') : '',
 
2064
  })
2065
  const mentionTargets = useMentionTargets()
 
2066
 
2067
  const handleSubmit = async (e: React.FormEvent) => {
2068
  e.preventDefault()
@@ -2070,6 +2120,14 @@ function EditTaskModal({
2070
  if (!formData.title.trim()) return
2071
 
2072
  try {
 
 
 
 
 
 
 
 
2073
  const response = await fetch(`/api/tasks/${task.id}`, {
2074
  method: 'PUT',
2075
  headers: { 'Content-Type': 'application/json' },
@@ -2077,7 +2135,8 @@ function EditTaskModal({
2077
  ...formData,
2078
  project_id: formData.project_id ? Number(formData.project_id) : undefined,
2079
  tags: formData.tags ? formData.tags.split(',').map(t => t.trim()) : [],
2080
- assigned_to: formData.assigned_to || undefined
 
2081
  })
2082
  })
2083
 
@@ -2182,7 +2241,7 @@ function EditTaskModal({
2182
  <select
2183
  id="edit-assignee"
2184
  value={formData.assigned_to}
2185
- onChange={(e) => setFormData(prev => ({ ...prev, assigned_to: e.target.value }))}
2186
  className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
2187
  >
2188
  <option value="">{t('unassigned')}</option>
@@ -2194,6 +2253,26 @@ function EditTaskModal({
2194
  </select>
2195
  </div>
2196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2197
  <div>
2198
  <label htmlFor="edit-tags" className="block text-sm text-muted-foreground mb-1">{t('fieldTags')}</label>
2199
  <input
 
95
  { key: 'done', titleKey: 'colDone', color: 'bg-green-500/20 text-green-400' },
96
  ]
97
 
98
+ /** Fetch active gateway sessions for a given agent name. */
99
+ function useAgentSessions(agentName: string | undefined) {
100
+ const [sessions, setSessions] = useState<Array<{ key: string; id: string; channel?: string; label?: string }>>([])
101
+ useEffect(() => {
102
+ if (!agentName) { setSessions([]); return }
103
+ let cancelled = false
104
+ fetch('/api/sessions?include_local=1')
105
+ .then(r => r.json())
106
+ .then(data => {
107
+ if (cancelled) return
108
+ const all = (data.sessions || []) as Array<{ key: string; id: string; agent?: string; channel?: string; label?: string; active?: boolean }>
109
+ const filtered = all.filter(s =>
110
+ s.agent?.toLowerCase() === agentName.toLowerCase() ||
111
+ s.key?.toLowerCase().includes(agentName.toLowerCase())
112
+ )
113
+ setSessions(filtered.map(s => ({ key: s.key, id: s.id, channel: s.channel, label: s.label })))
114
+ })
115
+ .catch(() => { if (!cancelled) setSessions([]) })
116
+ return () => { cancelled = true }
117
+ }, [agentName])
118
+ return sessions
119
+ }
120
+
121
  const priorityColors: Record<string, string> = {
122
  low: 'border-l-green-500',
123
  medium: 'border-l-yellow-500',
 
1841
  project_id: projects[0]?.id ? String(projects[0].id) : '',
1842
  assigned_to: '',
1843
  tags: '',
1844
+ target_session: '',
1845
  })
1846
  const t = useTranslations('taskBoard')
1847
+ const agentSessions = useAgentSessions(formData.assigned_to || undefined)
1848
  const [isRecurring, setIsRecurring] = useState(false)
1849
  const [scheduleInput, setScheduleInput] = useState('')
1850
  const [parsedSchedule, setParsedSchedule] = useState<{ cronExpr: string; humanReadable: string } | null>(null)
 
1886
  parent_task_id: null,
1887
  }
1888
  }
1889
+ if (formData.target_session) {
1890
+ metadata.target_session = formData.target_session
1891
+ }
1892
 
1893
  try {
1894
  const response = await fetch('/api/tasks', {
 
1988
  <select
1989
  id="create-assignee"
1990
  value={formData.assigned_to}
1991
+ onChange={(e) => setFormData(prev => ({ ...prev, assigned_to: e.target.value, target_session: '' }))}
1992
  className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
1993
  >
1994
  <option value="">{t('unassigned')}</option>
 
2000
  </select>
2001
  </div>
2002
 
2003
+ {formData.assigned_to && agentSessions.length > 0 && (
2004
+ <div>
2005
+ <label htmlFor="create-target-session" className="block text-sm text-muted-foreground mb-1">Target Session</label>
2006
+ <select
2007
+ id="create-target-session"
2008
+ value={formData.target_session}
2009
+ onChange={(e) => setFormData(prev => ({ ...prev, target_session: e.target.value }))}
2010
+ className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
2011
+ >
2012
+ <option value="">New session (default)</option>
2013
+ {agentSessions.map(s => (
2014
+ <option key={s.key} value={s.key}>
2015
+ {s.label || s.channel || s.key}
2016
+ </option>
2017
+ ))}
2018
+ </select>
2019
+ <p className="text-[11px] text-muted-foreground mt-1">Send task to an existing agent session instead of creating a new one.</p>
2020
+ </div>
2021
+ )}
2022
+
2023
  <div>
2024
  <label htmlFor="create-tags" className="block text-sm text-muted-foreground mb-1">{t('fieldTags')}</label>
2025
  <input
 
2109
  project_id: task.project_id ? String(task.project_id) : (projects[0]?.id ? String(projects[0].id) : ''),
2110
  assigned_to: task.assigned_to || '',
2111
  tags: task.tags ? task.tags.join(', ') : '',
2112
+ target_session: task.metadata?.target_session || '',
2113
  })
2114
  const mentionTargets = useMentionTargets()
2115
+ const agentSessions = useAgentSessions(formData.assigned_to || undefined)
2116
 
2117
  const handleSubmit = async (e: React.FormEvent) => {
2118
  e.preventDefault()
 
2120
  if (!formData.title.trim()) return
2121
 
2122
  try {
2123
+ const existingMeta = task.metadata || {}
2124
+ const updatedMeta = { ...existingMeta }
2125
+ if (formData.target_session) {
2126
+ updatedMeta.target_session = formData.target_session
2127
+ } else {
2128
+ delete updatedMeta.target_session
2129
+ }
2130
+
2131
  const response = await fetch(`/api/tasks/${task.id}`, {
2132
  method: 'PUT',
2133
  headers: { 'Content-Type': 'application/json' },
 
2135
  ...formData,
2136
  project_id: formData.project_id ? Number(formData.project_id) : undefined,
2137
  tags: formData.tags ? formData.tags.split(',').map(t => t.trim()) : [],
2138
+ assigned_to: formData.assigned_to || undefined,
2139
+ metadata: updatedMeta,
2140
  })
2141
  })
2142
 
 
2241
  <select
2242
  id="edit-assignee"
2243
  value={formData.assigned_to}
2244
+ onChange={(e) => setFormData(prev => ({ ...prev, assigned_to: e.target.value, target_session: '' }))}
2245
  className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
2246
  >
2247
  <option value="">{t('unassigned')}</option>
 
2253
  </select>
2254
  </div>
2255
 
2256
+ {formData.assigned_to && agentSessions.length > 0 && (
2257
+ <div>
2258
+ <label htmlFor="edit-target-session" className="block text-sm text-muted-foreground mb-1">Target Session</label>
2259
+ <select
2260
+ id="edit-target-session"
2261
+ value={formData.target_session}
2262
+ onChange={(e) => setFormData(prev => ({ ...prev, target_session: e.target.value }))}
2263
+ className="w-full bg-surface-1 text-foreground border border-border rounded-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-primary/50"
2264
+ >
2265
+ <option value="">New session (default)</option>
2266
+ {agentSessions.map(s => (
2267
+ <option key={s.key} value={s.key}>
2268
+ {s.label || s.channel || s.key}
2269
+ </option>
2270
+ ))}
2271
+ </select>
2272
+ <p className="text-[11px] text-muted-foreground mt-1">Send task to an existing agent session instead of creating a new one.</p>
2273
+ </div>
2274
+ )}
2275
+
2276
  <div>
2277
  <label htmlFor="edit-tags" className="block text-sm text-muted-foreground mb-1">{t('fieldTags')}</label>
2278
  <input
src/lib/task-dispatch.ts CHANGED
@@ -1,5 +1,6 @@
1
  import { getDatabase, db_helpers } from './db'
2
  import { runOpenClaw } from './command'
 
3
  import { eventBus } from './event-bus'
4
  import { logger } from './logger'
5
 
@@ -425,35 +426,72 @@ export async function dispatchAssignedTasks(): Promise<{ ok: boolean; message: s
425
 
426
  const prompt = buildTaskPrompt(task, rejectionFeedback)
427
 
428
- // Step 1: Invoke via gateway
429
- const gatewayAgentId = resolveGatewayAgentId(task)
430
- const dispatchModel = classifyTaskModel(task)
431
- const invokeParams: Record<string, unknown> = {
432
- message: prompt,
433
- agentId: gatewayAgentId,
434
- idempotencyKey: `task-dispatch-${task.id}-${Date.now()}`,
435
- deliver: false,
436
- }
437
- // Route to appropriate model tier based on task complexity.
438
- // null = no override, agent uses its own configured default model.
439
- if (dispatchModel) invokeParams.model = dispatchModel
440
-
441
- // Use --expect-final to block until the agent completes and returns the full
442
- // response payload (result.payloads[0].text). The two-step agent → agent.wait
443
- // pattern only returns lifecycle metadata and never includes the agent's text.
444
- const finalResult = await runOpenClaw(
445
- ['gateway', 'call', 'agent', '--expect-final', '--timeout', '120000', '--params', JSON.stringify(invokeParams), '--json'],
446
- { timeoutMs: 125_000 }
447
- )
448
- const finalPayload = parseGatewayJson(finalResult.stdout)
449
- ?? parseGatewayJson(String((finalResult as any)?.stderr || ''))
450
-
451
- const agentResponse = parseAgentResponse(
452
- finalPayload?.result ? JSON.stringify(finalPayload.result) : finalResult.stdout
453
- )
454
- if (!agentResponse.sessionId && finalPayload?.result?.meta?.agentMeta?.sessionId) {
455
- agentResponse.sessionId = finalPayload.result.meta.agentMeta.sessionId
456
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457
 
458
  if (!agentResponse.text) {
459
  throw new Error('Agent returned empty response')
 
1
  import { getDatabase, db_helpers } from './db'
2
  import { runOpenClaw } from './command'
3
+ import { callOpenClawGateway } from './openclaw-gateway'
4
  import { eventBus } from './event-bus'
5
  import { logger } from './logger'
6
 
 
426
 
427
  const prompt = buildTaskPrompt(task, rejectionFeedback)
428
 
429
+ // Check if task has a target session specified in metadata
430
+ const taskMeta = (() => {
431
+ try {
432
+ const row = db.prepare('SELECT metadata FROM tasks WHERE id = ?').get(task.id) as { metadata: string } | undefined
433
+ return row?.metadata ? JSON.parse(row.metadata) : {}
434
+ } catch { return {} }
435
+ })()
436
+ const targetSession: string | null = typeof taskMeta?.target_session === 'string' && taskMeta.target_session
437
+ ? taskMeta.target_session
438
+ : null
439
+
440
+ let agentResponse: AgentResponseParsed
441
+
442
+ if (targetSession) {
443
+ // Dispatch to a specific existing session via chat.send
444
+ logger.info({ taskId: task.id, targetSession, agent: task.agent_name }, 'Dispatching task to targeted session')
445
+ const sendResult = await callOpenClawGateway<any>(
446
+ 'chat.send',
447
+ {
448
+ sessionKey: targetSession,
449
+ message: prompt,
450
+ idempotencyKey: `task-dispatch-${task.id}-${Date.now()}`,
451
+ deliver: false,
452
+ },
453
+ 125_000,
454
+ )
455
+ const status = String(sendResult?.status || '').toLowerCase()
456
+ if (status !== 'started' && status !== 'ok' && status !== 'in_flight') {
457
+ throw new Error(`chat.send to session ${targetSession} returned status: ${status}`)
458
+ }
459
+ // chat.send is fire-and-forget; we record the session but won't get inline response text
460
+ agentResponse = {
461
+ text: `Task dispatched to existing session ${targetSession}. The agent will process it within that session context.`,
462
+ sessionId: sendResult?.runId || targetSession,
463
+ }
464
+ } else {
465
+ // Step 1: Invoke via gateway (new session)
466
+ const gatewayAgentId = resolveGatewayAgentId(task)
467
+ const dispatchModel = classifyTaskModel(task)
468
+ const invokeParams: Record<string, unknown> = {
469
+ message: prompt,
470
+ agentId: gatewayAgentId,
471
+ idempotencyKey: `task-dispatch-${task.id}-${Date.now()}`,
472
+ deliver: false,
473
+ }
474
+ // Route to appropriate model tier based on task complexity.
475
+ // null = no override, agent uses its own configured default model.
476
+ if (dispatchModel) invokeParams.model = dispatchModel
477
+
478
+ // Use --expect-final to block until the agent completes and returns the full
479
+ // response payload (result.payloads[0].text). The two-step agent → agent.wait
480
+ // pattern only returns lifecycle metadata and never includes the agent's text.
481
+ const finalResult = await runOpenClaw(
482
+ ['gateway', 'call', 'agent', '--expect-final', '--timeout', '120000', '--params', JSON.stringify(invokeParams), '--json'],
483
+ { timeoutMs: 125_000 }
484
+ )
485
+ const finalPayload = parseGatewayJson(finalResult.stdout)
486
+ ?? parseGatewayJson(String((finalResult as any)?.stderr || ''))
487
+
488
+ agentResponse = parseAgentResponse(
489
+ finalPayload?.result ? JSON.stringify(finalPayload.result) : finalResult.stdout
490
+ )
491
+ if (!agentResponse.sessionId && finalPayload?.result?.meta?.agentMeta?.sessionId) {
492
+ agentResponse.sessionId = finalPayload.result.meta.agentMeta.sessionId
493
+ }
494
+ } // end else (new session dispatch)
495
 
496
  if (!agentResponse.text) {
497
  throw new Error('Agent returned empty response')
src/store/index.ts CHANGED
@@ -12,6 +12,8 @@ type DashboardLayoutUpdater = string[] | null | ((current: string[] | null) => s
12
  export interface Session {
13
  id: string
14
  key: string
 
 
15
  kind: string
16
  age: string
17
  model: string
 
12
  export interface Session {
13
  id: string
14
  key: string
15
+ agent?: string
16
+ channel?: string
17
  kind: string
18
  age: string
19
  model: string