⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: log on the issue when an agent picks up its run and when it ends (#169)
Croff046cc4947caf
diff --git a/apps/api/src/modules/agents/core/internal-routes.ts b/apps/api/src/modules/agents/core/internal-routes.tsindex e1461615..f2a26bbe 100644--- a/apps/api/src/modules/agents/core/internal-routes.ts+++ b/apps/api/src/modules/agents/core/internal-routes.ts@@ -3,6 +3,8 @@ import { runAgent } from './runtime';import { deleteThreadsWhere } from './runtime/memory';import { runThreadId } from './runtime/thread-ids';import { framePrompt, runModePreamble, peopleContext } from './prompt/framing';+import { recordAgentRunFinished, recordAgentRunStarted } from './run-activity';+import { agentRunConfig } from './run-queue';const runBody = t.Object({id: t.Number(),@@ -11,6 +13,7 @@ const runBody = t.Object({scheduleId: t.Nullable(t.Number()),trigger: t.UnionEnum(['mention', 'delegation', 'schedule', 'manual']),prompt: t.String(),+ attempts: t.Number(),projectId: t.Number(),agentUserId: t.String(),issueIdentifier: t.Nullable(t.String()),@@ -37,14 +40,25 @@ export const internalAgentRunRoutes = new Elysia({set.status = 401;return { error: 'Unauthorized' };}- const result = await runAgent(body.agentId, body.projectId, framePrompt(body), {- callerUserId: body.agentUserId,- threadId: runThreadId(body),- issueId: body.issueId,- scheduleId: body.scheduleId,- contextPreamble: runModePreamble(body.trigger) + peopleContext(body),- });- return { output: result.text };+ // The worker writes the run's own status; the issue's timeline entries are+ // written here, where the agent's work actually starts and ends. A failure the+ // worker will retry is not the end of the run, so only the last attempt logs one.+ await recordAgentRunStarted(body);+ try {+ const result = await runAgent(body.agentId, body.projectId, framePrompt(body), {+ callerUserId: body.agentUserId,+ threadId: runThreadId(body),+ issueId: body.issueId,+ scheduleId: body.scheduleId,+ contextPreamble: runModePreamble(body.trigger) + peopleContext(body),+ });+ await recordAgentRunFinished(body, 'success');+ return { output: result.text };+ } catch (error) {+ if (body.attempts >= agentRunConfig.maxAttempts())+ await recordAgentRunFinished(body, 'failed');+ throw error;+ }},{body: runBody,diff --git a/apps/api/src/modules/agents/core/run-activity.ts b/apps/api/src/modules/agents/core/run-activity.tsnew file mode 100644index 00000000..d44ba247--- /dev/null+++ b/apps/api/src/modules/agents/core/run-activity.ts@@ -0,0 +1,25 @@+import { recordActivity } from '../../../issues/activity';++// Records that an agent took a queued run of the issue. Only the first claim is+// logged: a re-claim after an expired lease is the same task handed out again.+export async function recordAgentRunStarted(run: {+ issueId: number | null;+ attempts: number;+ agentUserId: string;+}): Promise<void> {+ if (run.issueId == null || run.attempts > 1) return;+ await recordActivity(run.issueId, [{ action: 'agent_started' }], run.agentUserId);+}++// Records how the agent's run of the issue ended.+export async function recordAgentRunFinished(+ run: { issueId: number | null; agentUserId: string },+ status: 'success' | 'failed',+): Promise<void> {+ if (run.issueId == null) return;+ await recordActivity(+ run.issueId,+ [{ action: 'agent_finished', subject: status }],+ run.agentUserId,+ );+}diff --git a/apps/api/src/modules/agents/runner/__tests__/integration/agent-runner.test.ts b/apps/api/src/modules/agents/runner/__tests__/integration/agent-runner.test.tsindex c06f831c..cf014176 100644--- a/apps/api/src/modules/agents/runner/__tests__/integration/agent-runner.test.ts+++ b/apps/api/src/modules/agents/runner/__tests__/integration/agent-runner.test.ts@@ -65,6 +65,29 @@ describe('agent runner queue', () => {expect(res.data!.run!.systemPrompt).toContain('Run mode');});+ it('logs on the issue that the agent picked the run up and how it ended', async () => {+ const { asOwner, asRunner, agent, columnId } = await setup();+ const issue = await queueRun(asOwner, columnId, agent.userId);+ const run = (await asRunner['agent-runs'].claim.post()).data!.run!;++ await asRunner['agent-runs']({ runId: run.id }).result.post({+ status: 'failed',+ error: 'claude exited with 1',+ });++ const feed = await asOwner.issues({ issueId: issue.id }).feed.get({ query: {} });+ expect(feed.data!.items).toContainEqual(+ expect.objectContaining({ action: 'agent_started', actorUserId: agent.userId }),+ );+ expect(feed.data!.items).toContainEqual(+ expect.objectContaining({+ action: 'agent_finished',+ subject: 'failed',+ actorUserId: agent.userId,+ }),+ );+ });+it("mixes the agent's own instructions into the system prompt", async () => {const { asOwner, asRunner, agent, columnId } = await setup();await asOwnerdiff --git a/apps/api/src/modules/agents/runner/index.ts b/apps/api/src/modules/agents/runner/index.tsindex 0b81e545..36738fa7 100644--- a/apps/api/src/modules/agents/runner/index.ts+++ b/apps/api/src/modules/agents/runner/index.ts@@ -46,7 +46,7 @@ export const agentRunnerRoutes = new Elysia({.post('/agent-runs/:runId/result',async ({ agent, params, body }) => {- const ok = await finishRun(agent.id, params.runId, body);+ const ok = await finishRun(agent, params.runId, body);if (!ok) throw new HttpError(404, 'Run not found');return noContent();},diff --git a/apps/api/src/modules/agents/runner/service.ts b/apps/api/src/modules/agents/runner/service.tsindex 81d4094c..f9d9cc67 100644--- a/apps/api/src/modules/agents/runner/service.ts+++ b/apps/api/src/modules/agents/runner/service.ts@@ -1,6 +1,7 @@import { db, aiAgent, agentRun, project } from '@repo/db';import { and, eq, sql } from 'drizzle-orm';import { agentRunConfig } from '../core/run-queue';+import { recordAgentRunFinished, recordAgentRunStarted } from '../core/run-activity';import type { AgentKind } from '../core/service';import type { AgentRunTrigger } from '../model';import {@@ -88,26 +89,31 @@ export async function touchRunner(agentId: number): Promise<void> {}// Fails runs that were handed out too many times without a result, so a run whose-// runner keeps dying ends in a visible state instead of being served forever.-async function expireExhaustedRuns(agentId: number): Promise<void> {- await db+// runner keeps dying ends in a visible state instead of being served forever. That is+// the end of the run, so the issue's timeline gets the same entry a reported failure+// writes.+async function expireExhaustedRuns(agent: RunnerAgent): Promise<void> {+ const rows = await db.update(agentRun).set({ status: 'failed', lastError: 'Runner did not report a result', finishedAt: new Date() }).where(and(- eq(agentRun.agentId, agentId),+ eq(agentRun.agentId, agent.id),eq(agentRun.status, 'pending'),sql`${agentRun.attempts} >= ${agentRunConfig.maxAttempts()}`,sql`${agentRun.nextAttemptAt} <= now()`,),- );+ )+ .returning({ issueId: agentRun.issueId });+ for (const row of rows)+ await recordAgentRunFinished({ ...row, agentUserId: agent.userId }, 'failed');}// Claims the agent's next due run, or null when it has none. FOR UPDATE SKIP LOCKED// keeps two runners on the same key from taking the same run.export async function claimRunnerRun(agent: RunnerAgent): Promise<RunnerRun | null> {const agentId = agent.id;- await expireExhaustedRuns(agentId);+ await expireExhaustedRuns(agent);await touchRunner(agentId);const rows = await db.execute(sql`UPDATE agent_run r@@ -140,6 +146,7 @@ export async function claimRunnerRun(agent: RunnerAgent): Promise<RunnerRun | nuconst row = (rows as unknown as ClaimedRow[])[0];if (!row) return null;const forPrompt = { ...row, agentUserId: agent.userId };+ await recordAgentRunStarted(forPrompt);return {id: row.id,trigger: row.trigger,@@ -185,11 +192,11 @@ export async function heartbeatRun(agentId: number, runId: number): Promise<bool// command and it failed, so re-serving the same run would just repeat it. False when// the run is not this agent's, or was already finished.export async function finishRun(- agentId: number,+ agent: RunnerAgent,runId: number,result: { status: 'success' | 'failed'; output?: string | null; error?: string | null },): Promise<boolean> {- await touchRunner(agentId);+ await touchRunner(agent.id);const rows = await db.update(agentRun).set({@@ -199,8 +206,11 @@ export async function finishRun(finishedAt: new Date(),}).where(- and(eq(agentRun.id, runId), eq(agentRun.agentId, agentId), eq(agentRun.status, 'pending')),+ and(eq(agentRun.id, runId), eq(agentRun.agentId, agent.id), eq(agentRun.status, 'pending')),)- .returning({ id: agentRun.id });- return rows.length > 0;+ .returning({ issueId: agentRun.issueId });+ const row = rows[0];+ if (!row) return false;+ await recordAgentRunFinished({ ...row, agentUserId: agent.userId }, result.status);+ return true;}diff --git a/apps/web/messages/ar/issue.json b/apps/web/messages/ar/issue.jsonindex 702f171c..01c7dbc1 100644--- a/apps/web/messages/ar/issue.json+++ b/apps/web/messages/ar/issue.json@@ -275,6 +275,9 @@"fieldCleared": "مسح <v>{field}</v>","archived": "أرشف المهمة","restored": "استعاد المهمة",+ "agentStarted": "استلم المهمة",+ "agentFinished": "أنهى العمل على المهمة",+ "agentFailed": "لم يتمكن من إنهاء المهمة","pullRequestMerged": "دمج طلب السحب <v>{pr}</v>","pullRequestOpened": "فتح طلب السحب <v>{pr}</v>"},diff --git a/apps/web/messages/en/issue.json b/apps/web/messages/en/issue.jsonindex a2210dfd..f259f57d 100644--- a/apps/web/messages/en/issue.json+++ b/apps/web/messages/en/issue.json@@ -275,6 +275,9 @@"fieldCleared": "cleared <v>{field}</v>","archived": "archived the issue","restored": "restored the issue",+ "agentStarted": "picked up the issue",+ "agentFinished": "finished working on the issue",+ "agentFailed": "could not finish the issue","pullRequestMerged": "merged pull request <v>{pr}</v>","pullRequestOpened": "opened pull request <v>{pr}</v>"},diff --git a/apps/web/messages/ru/issue.json b/apps/web/messages/ru/issue.jsonindex e58fe4ef..890f0c66 100644--- a/apps/web/messages/ru/issue.json+++ b/apps/web/messages/ru/issue.json@@ -275,6 +275,9 @@"fieldCleared": "очистил(а) <v>{field}</v>","archived": "архивировал(а) задачу","restored": "восстановил(а) задачу",+ "agentStarted": "взял(а) задачу в работу",+ "agentFinished": "завершил(а) работу над задачей",+ "agentFailed": "не смог(ла) завершить работу над задачей","pullRequestMerged": "смержил(а) пул-реквест <v>{pr}</v>","pullRequestOpened": "открыл(а) пул-реквест <v>{pr}</v>"},diff --git a/apps/web/messages/uk/issue.json b/apps/web/messages/uk/issue.jsonindex 15bb6745..b0872910 100644--- a/apps/web/messages/uk/issue.json+++ b/apps/web/messages/uk/issue.json@@ -275,6 +275,9 @@"fieldCleared": "очистив(-ла) <v>{field}</v>","archived": "архівував(-ла) задачу","restored": "відновив(-ла) задачу",+ "agentStarted": "взяв(-ла) задачу в роботу",+ "agentFinished": "завершив(-ла) роботу над задачею",+ "agentFailed": "не зміг(-ла) завершити роботу над задачею","pullRequestMerged": "змержив(-ла) пул-реквест <v>{pr}</v>","pullRequestOpened": "відкрив(-ла) пул-реквест <v>{pr}</v>"},diff --git a/apps/web/messages/zh-CN/issue.json b/apps/web/messages/zh-CN/issue.jsonindex 3242567d..6ea4a784 100644--- a/apps/web/messages/zh-CN/issue.json+++ b/apps/web/messages/zh-CN/issue.json@@ -275,6 +275,9 @@"fieldCleared": "清除了 <v>{field}</v>","archived": "归档了工作项","restored": "恢复了工作项",+ "agentStarted": "接手了该工作项",+ "agentFinished": "完成了该工作项的处理",+ "agentFailed": "未能完成该工作项","pullRequestMerged": "合并了拉取请求 <v>{pr}</v>","pullRequestOpened": "打开了拉取请求 <v>{pr}</v>"},diff --git a/apps/web/src/features/issue/hooks/useActivityText.tsx b/apps/web/src/features/issue/hooks/useActivityText.tsxindex 48e2693b..8281d47d 100644--- a/apps/web/src/features/issue/hooks/useActivityText.tsx+++ b/apps/web/src/features/issue/hooks/useActivityText.tsx@@ -137,6 +137,10 @@ export function useActivityText() {return { line: line('archived') };case 'restored':return { line: line('restored') };+ case 'agent_started':+ return { line: line('agentStarted') };+ case 'agent_finished':+ return { line: line(a.subject === 'failed' ? 'agentFailed' : 'agentFinished') };case 'github_pr': {// fromText is "owner/repo#42", toText the PR's URL on GitHub.const key = a.subject === 'merged' ? 'pullRequestMerged' : 'pullRequestOpened';diff --git a/apps/web/src/features/issue/utils/activityIcons.ts b/apps/web/src/features/issue/utils/activityIcons.tsindex 3f1873f6..d9f80de6 100644--- a/apps/web/src/features/issue/utils/activityIcons.ts+++ b/apps/web/src/features/issue/utils/activityIcons.ts@@ -51,4 +51,6 @@ export const ACTION_ICON: Record<ActivityAction, LucideIcon> = {archived: Archive,restored: ArchiveRestore,github_pr: GitPullRequest,+ agent_started: Bot,+ agent_finished: Bot,};diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex b302621c..4bfcd2ea 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1522,7 +1522,9 @@ export type ActivityAction =| 'field'| 'archived'| 'restored'- | 'github_pr';+ | 'github_pr'+ | 'agent_started'+ | 'agent_finished';// One entry in an issue's timeline. kind selects which payload fields are set:// a 'comment' carries body; an 'activity' carries action/subject/fromText/toText.