Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(goal): keep draft goals honest after start, and refuse rollout folds that lose work (#20860)

Arvin Xu13d5c0e099e4
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.md
index 769bb237abc..6db8b3ebdd3 100644
--- a/.agents/skills/cli/references/goal.md
+++ b/.agents/skills/cli/references/goal.md
@@ -160,7 +160,11 @@ then launch it with `lh goal start <id>`; the owner can also start it from the
goal page. Many tasks of one recipe start as a batch:
`lh goal start <id> --rollout canary --recipe-file <md> --probes <2-5 node ids>`
moves the probes into a batch and turns every other seed (or only `--units`)
-into roster units released wave by wave behind the gate.
+into roster units released wave by wave behind the gate. Inside a batch a seed
+may depend only on a probe, and every folded seed needs its own title; start
+refuses anything else. Once started with tasks in place, the creating turn is
+settled: `lh goal plan` on its token is refused, and later work comes from the
+next planning turn.
## Decision gates and graph editing
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.ts
index 93078a32f6b..ccf1d587d2d 100644
--- a/apps/cli/src/commands/goal.test.ts
+++ b/apps/cli/src/commands/goal.test.ts
@@ -558,6 +558,8 @@ describe('goal create command', () => {
agentId: 'agent-1',
conversationOperationId: 'op-1',
conversationTopicId: 'tpc-1',
+ // The server opens a draft only for a CLI that can start it.
+ draft: true,
}),
);
},
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index d371e048951..2000209330c 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -236,6 +236,8 @@ const admissionHint: Record<string, string> = {
pending_decision: 'a decision gate is still waiting on an answer',
review_changed: 'task review feedback changed after this turn started',
stale_input: 'the graph moved after this turn started, so the plan would apply to stale input',
+ started_from_draft:
+ 'the Goal was started from its draft, which settled this turn; the next turn plans further work',
turn_owner: 'this Goal has no matching planning turn',
turn_settled: "this turn's run is no longer running",
wait_unsettled: 'unfinished work must be settled before waiting',
@@ -763,11 +765,13 @@ export function registerGoalCommand(program: Command) {
? hasOperationToken()
? await client.goal.createConversationGoal.mutate({
...goalInput,
+ draft: true,
operationId: operationId!,
})
: await client.goal.create.mutate({
...goalInput,
agentId: process.env.LOBEHUB_AGENT_ID,
+ draft: true,
conversationOperationId: operationId,
conversationTopicId: process.env.LOBEHUB_TOPIC_ID,
})
@@ -809,6 +813,10 @@ export function registerGoalCommand(program: Command) {
"kept as that unit's note, and is released wave by wave once the probes ran through without a person.",
'A rejection revises the recipe and re-probes. Tasks that differ only in names, files or details are',
'one recipe; tasks whose steps differ are not, so start those without --rollout.',
+ 'Inside a batch a seed may depend only on a probe, and folded seeds need distinct titles.',
+ '',
+ 'Starting a draft that holds tasks settles the planning turn that created it: submit any plan with',
+ 'lh goal plan before starting, not after.',
].join('\n'),
)
.option('--rollout <mode>', 'Fold the seed tasks into a batch: canary or full')
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 1ffeca5aaf8..1f9f410ea46 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -141,6 +141,11 @@ const conversationGoalInput = z.object({
}),
)
.optional(),
+ /**
+ * Open a conversation goal as a draft that runs only once `start` launches
+ * it. Sent by a CLI that has `lh goal start`; ignored for a standalone goal.
+ */
+ draft: z.boolean().optional(),
problemDescription: z.string().optional(),
projectId: z.string().optional(),
requirement: z.string().optional(),
@@ -789,7 +794,8 @@ export const goalRouter = router({
});
return { data: graph, message: 'Goal created', success: true, turnToken };
}
- const data = await ctx.goalService.create(input);
+ const { draft: _draft, ...standaloneInput } = input;
+ const data = await ctx.goalService.create(standaloneInput);
// A goal is not a document β€” creating one means starting it. The
// coordinator takes it from here without a client holding a loop open.
await scheduleGoalAdvance({
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 97b396d33da..ef22ed5292c 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -153,6 +153,12 @@ const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);
const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;
/** Why a decomposition did or did not become a batch: DEBUG=lobe-server:goal-rollout. */
const log = debug('lobe-server:goal-rollout');
+
+const draftNotStarted = (goalId: string) =>
+ new TRPCError({
+ code: 'CONFLICT',
+ message: `Goal is a draft; start it with lh goal start ${goalId}`,
+ });
/** Who does the goal's Tasks: its dedicated executor, else the goal agent itself. */
export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>
goal.config?.taskAgentId ?? goal.agentId ?? undefined;
@@ -351,14 +357,15 @@ export class GoalService {
'Only a run in a topic with an agent can create a goal it supervises',
);
- // A conversation goal opens as a draft: its agent arranges the graph in
- // this run, and the goal runs only once someone starts it.
+ // A conversation goal opens as a draft when the caller asks for one: its
+ // agent arranges the graph in this run, and the goal runs only once someone
+ // starts it. Opt-in, because a CLI released before `lh goal start` existed
+ // could never start the draft it created.
const created = await this.create({
...input,
agentId,
config: { ...input.config, manager: input.config?.manager ?? {} },
createdByAgentId: agentId,
- draft: true,
topicId,
});
try {
@@ -1255,6 +1262,8 @@ export class GoalService {
pause = async (goalId: string) => {
const graph = await this.requireGraph(goalId);
+ // A draft never ran; pausing it would let a later resume skip `start`.
+ if (graph.goal.status === 'draft') throw draftNotStarted(goalId);
// From here the pause is the person's, so no later measurement lifts it.
// Written even when the goal is already paused β€” that transition is a
// no-op, so this marker is the only record that the person took it over.
@@ -1890,6 +1899,9 @@ export class GoalService {
const model = new GoalModel(tx, this.userId, this.workspaceId);
const current = await model.lockById(goalId);
if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ // Only `start` launches a draft: it settles the creating run's planning
+ // turn and checks who may launch it, which a plain status flip skips.
+ if (current.status === 'draft') throw draftNotStarted(goalId);
if (current.status !== graph.goal.status) {
throw new TRPCError({
code: 'CONFLICT',
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index 10b140b7877..eebf43c380d 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -27,15 +27,20 @@ elsewhere are refused. Like `create --topic`, the topic comes from
the run's operation; an operation-token run (device or gateway) needs the
`goal:manage` capability that `/goal` grants.
-A topic goal (`create --topic`, `/goal`) opens as a `draft`. The coordinator
-leaves a draft alone: its agent arranges the graph β€” seed tasks, `add-node`,
-`add-edge`, even a submitted plan β€” and `lh goal start` (or the goal page's
-Start) moves it to `running` (`start.ts`). Starting a draft that already holds
-work settles the adopted planning turn on the spot, so dispatch does not wait
-for the creating run to exit; an empty draft keeps the turn open for a plan.
-`start --rollout` folds the seed tasks into a batch: the probes are re-created
-inside it and the other seeds leave the graph as roster units, their
-descriptions kept as unit notes (`rollout.unitBriefs`).
+A topic goal (`create --topic`, `/goal`) opens as a `draft` when the CLI asks
+for one (`draft: true`, sent by every CLI that has `lh goal start`; an older CLI
+gets a goal that runs at once). The coordinator leaves a draft alone: its agent
+arranges the graph β€” seed tasks, `add-node`, `add-edge`, even a submitted plan β€”
+and `lh goal start` (or the goal page's Start) moves it to `running`
+(`start.ts`). `pause` and `resume` refuse a draft, so `start` stays the only way
+in. Starting a draft that already holds work settles the adopted planning turn
+on the spot, so dispatch does not wait for the creating run to exit; a plan
+submitted on that turn afterwards is refused (`started_from_draft`). An empty
+draft keeps the turn open for a plan. `start --rollout` folds the seed tasks
+into a batch: the probes are re-created inside it and the other seeds leave the
+graph as roster units, their descriptions kept as unit notes
+(`rollout.unitBriefs`). A folded seed may depend only on a probe, and folded
+seeds need distinct titles; anything else is refused rather than dropped.
The main Agent must have a working shell and an authenticated `lh` CLI in its
execution environment (for example a configured device Kimi/Codex Agent). Its
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index 8691f3f7639..128091bb8f2 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -317,6 +317,7 @@ describe('CLI main Agent planning', () => {
const { graph, turnToken } = await service().createFromConversation(conversationOpId, {
criteria: [{ title: 'Report delivered' }],
+ draft: true,
title: 'Ship the report',
});
@@ -366,6 +367,7 @@ describe('CLI main Agent planning', () => {
it('dispatches nothing from a seeded draft until it is started', async () => {
await startConversationRun();
const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
tasks: seeds,
title: 'Cache the resources',
});
@@ -388,6 +390,7 @@ describe('CLI main Agent planning', () => {
it('folds the seeds into a batch when started with a rollout', async () => {
await startConversationRun();
const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
tasks: seeds,
title: 'Cache the resources',
});
@@ -429,6 +432,7 @@ describe('CLI main Agent planning', () => {
it('keeps a probe prerequisite whatever order the probes are listed in', async () => {
await startConversationRun();
const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
tasks: seeds,
title: 'Cache the resources',
});
@@ -463,6 +467,7 @@ describe('CLI main Agent planning', () => {
it('refuses to fold a seed another kept node depends on, changing nothing', async () => {
await startConversationRun();
const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
tasks: seeds,
title: 'Cache the resources',
});
@@ -488,9 +493,143 @@ describe('CLI main Agent planning', () => {
).toHaveLength(4);
});
+ /**
+ * Regression: a CLI released before `lh goal start` existed created a draft
+ * it could never start, and nothing noticed the goal sat there.
+ */
+ it('opens a running goal when the caller does not ask for a draft', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+
+ expect(graph.goal.status).toBe('running');
+ });
+
+ /**
+ * Regression: a probe's link to a unit or to a node left behind was dropped
+ * without a word, so the probe ran before the work it needed.
+ */
+ it.each([
+ ['a unit', 'Project skills'],
+ ['a seed kept out of the batch', 'Home inbox'],
+ ])('refuses a probe that depends on %s, changing nothing', async (_, prerequisite) => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await new GoalGraphModel(db, userId).createEdge(
+ graph.goal.id,
+ seedId(graph, 'Device list'),
+ seedId(graph, prerequisite),
+ 'depends_on',
+ );
+
+ await expect(
+ starter().start(graph.goal.id, {
+ rollout: {
+ probeNodeIds: [seedId(graph, 'Device list'), seedId(graph, 'Tool payload')],
+ recipe: 'Persist the resource',
+ unitNodeIds: [seedId(graph, 'Project skills')],
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect((await model().findById(graph.goal.id))!.status).toBe('draft');
+ expect(
+ (await service().graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task'),
+ ).toHaveLength(4);
+ });
+
+ it('keeps a unit that depends on a probe, which the gate already orders', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await new GoalGraphModel(db, userId).createEdge(
+ graph.goal.id,
+ seedId(graph, 'Home inbox'),
+ seedId(graph, 'Device list'),
+ 'depends_on',
+ );
+
+ await starter().start(graph.goal.id, {
+ rollout: {
+ probeNodeIds: [seedId(graph, 'Device list'), seedId(graph, 'Tool payload')],
+ recipe: 'Persist the resource',
+ },
+ });
+
+ expect((await model().findById(graph.goal.id))!.status).toBe('running');
+ });
+
+ /** Regression: the roster is keyed by title, so a second seed of one title vanished. */
+ it('refuses to fold two seeds that share a title', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
+ tasks: [...seeds, { title: 'Home inbox', description: 'HomeInbox/index.tsx:12' }],
+ title: 'Cache the resources',
+ });
+
+ await expect(
+ starter().start(graph.goal.id, {
+ rollout: {
+ probeNodeIds: [seedId(graph, 'Device list'), seedId(graph, 'Tool payload')],
+ recipe: 'Persist the resource',
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect((await model().findById(graph.goal.id))!.status).toBe('draft');
+ });
+
+ /**
+ * Regression: after `start` settled the turn, `lh goal plan` on it read as a
+ * duplicate and printed "Plan recorded" while writing nothing.
+ */
+ it('refuses a plan submitted after start settled the turn', async () => {
+ await startConversationRun();
+ const { graph, turnToken } = await service().createFromConversation(conversationOpId, {
+ draft: true,
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await starter().start(graph.goal.id, { operationId: conversationOpId });
+
+ await expect(
+ manager().submit(graph.goal.id, turnToken, conversationOpId, taskPlan),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect((await service().graph(graph.goal.id)).nodes.some((n) => n.title === 'Audit')).toBe(
+ false,
+ );
+ });
+
+ /**
+ * Regression: resume (or pause then resume) moved a draft to running
+ * without `start`, so the creating run's turn stayed open and nothing
+ * dispatched until that run exited.
+ */
+ it('leaves launching a draft to start, refusing pause and resume', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+
+ await expect(service().resume(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });
+ await expect(service().pause(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect((await model().findById(graph.goal.id))!.status).toBe('draft');
+ });
+
it('starts a draft only once', async () => {
await startConversationRun();
const { graph } = await service().createFromConversation(conversationOpId, {
+ draft: true,
tasks: seeds,
title: 'Cache the resources',
});
@@ -562,7 +701,7 @@ describe('CLI main Agent planning', () => {
const { graph, turnToken } = await service().createFromConversation(
'op_client_only_local_run',
- { title: 'Local goal' },
+ { draft: true, title: 'Local goal' },
localRun,
);
expect(graph.goal).toMatchObject({ agentId, subjectId: conversationTopicId });
@@ -818,6 +957,7 @@ describe('CLI main Agent planning', () => {
topicId: shared,
});
const { graph: b } = await service().createFromConversation(sharedRunId, {
+ draft: true,
title: 'Second goal',
});
await starter().start(b.goal.id);
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 677115d388a..d4d8c74f3ab 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -232,6 +232,11 @@ const PLAN_REJECTION = {
trpc: 'CONFLICT',
},
stale_input: { message: 'Stale planning input; no plan applied', trpc: 'CONFLICT' },
+ started_from_draft: {
+ message:
+ 'The Goal was started with the tasks arranged in its draft, which settled this planning turn; no plan applied',
+ trpc: 'CONFLICT',
+ },
turn_owner: { message: 'This planning turn does not own the Goal', trpc: 'FORBIDDEN' },
turn_settled: { message: 'Stale planning input; no plan applied', trpc: 'CONFLICT' },
wait_unsettled: { message: 'Settle existing work before waiting', trpc: 'CONFLICT' },
@@ -560,10 +565,12 @@ export class GoalManagerService {
await this.save(this.db, goal.id, {
...state,
consumed: true,
- submitted: state.submitted ?? {
- action: 'tasks',
- reason: 'Started with the tasks arranged in the draft',
- },
+ ...(state.submitted
+ ? {}
+ : {
+ startedFromDraft: true,
+ submitted: { action: 'tasks', reason: 'Started with the tasks arranged in the draft' },
+ }),
});
};
@@ -1461,6 +1468,9 @@ export class GoalManagerService {
return rejectPlan('inactive', op?.status);
if (graph.decisions.some((d) => d.status === 'pending'))
return rejectPlan('pending_decision', op?.status);
+ // That receipt is start's, not a plan: reporting it as a duplicate would
+ // tell the agent its plan was recorded when nothing was written.
+ if (state.startedFromDraft) return rejectPlan('started_from_draft', op?.status);
if (state.submitted) return { code: 'duplicate', ok: true, submitted: state.submitted };
if (state.consumed) return rejectPlan('consumed', op?.status);
if (op && op.status !== 'running') return rejectPlan('turn_settled', op?.status);
diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.ts
index 0962db9678e..ad8366d6bfd 100644
--- a/apps/server/src/services/goal/start.ts
+++ b/apps/server/src/services/goal/start.ts
@@ -216,18 +216,47 @@ export class GoalStartService {
// The folded seeds leave the graph, and their links go with them. A node
// staying behind that builds on one would silently lose that prerequisite.
const folded = new Set([...probes, ...units].map((node) => node.id));
+ const title = (id: string) => graph.nodes.find((node) => node.id === id)?.title ?? id;
const stranded = graph.edges.find(
(edge) =>
edge.kind === 'depends_on' &&
folded.has(edge.targetNodeId) &&
!folded.has(edge.sourceNodeId),
);
- if (stranded) {
- const title = (id: string) => graph.nodes.find((node) => node.id === id)?.title ?? id;
+ if (stranded)
refuse(
`"${title(stranded.sourceNodeId)}" depends on "${title(stranded.targetNodeId)}", which joins the batch; remove that link or keep it out of the batch`,
);
- }
+ // Inside the batch only a link to a probe still holds: probes run first and
+ // the gate releases units after them. A probe waiting on anything else, or a
+ // unit waiting on another unit or on a node left behind, would lose that
+ // prerequisite and run without it.
+ const probeSet = new Set(probeIds);
+ const resolved = new Set(
+ graph.nodes.filter((node) => node.status === 'resolved').map((node) => node.id),
+ );
+ const dropped = graph.edges.find(
+ (edge) =>
+ edge.kind === 'depends_on' &&
+ folded.has(edge.sourceNodeId) &&
+ !probeSet.has(edge.targetNodeId) &&
+ !resolved.has(edge.targetNodeId),
+ );
+ if (dropped)
+ refuse(
+ `"${title(dropped.sourceNodeId)}" depends on "${title(dropped.targetNodeId)}", which is not a probe of the batch; a batch keeps only links to its probes, so make it a probe or remove that link`,
+ );
+ // The roster and the unit notes are keyed by title, so two seeds sharing a
+ // title would collapse into one unit and the other's work would vanish.
+ const seen = new Set<string>();
+ const duplicate = [...probes, ...units].find((node) => {
+ const key = node.title.trim();
+ if (seen.has(key)) return true;
+ seen.add(key);
+ return false;
+ });
+ if (duplicate)
+ refuse(`Two seeds share the title "${duplicate.title.trim()}"; give each a distinct title`);
const roster = normalizeRolloutRoster(
units.map((unit) => unit.title),
diff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
index 93e19ecf141..3d6006c0df8 100644
--- a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
@@ -17,12 +17,13 @@ export const conversationGoalPrompt = `The user sent this request with LobeHub's
1. Draft the goal from the user's request, in the user's language: a short title, the requirement, and one concrete, checkable acceptance criterion per explicit requirement. Do not add requirements the user did not ask for.
2. Create it bound to this conversation, with its tasks (the LOBEHUB_* environment already identifies you and this conversation). Write the tasks to a JSON file β€” bounded, independent tasks, each [{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}] β€” then:
lh goal create "<title>" --conversation -r "<requirement>" -i "<the user's ask in their words>" --criterion "<criterion>" --criterion "<criterion>" --task-file <tasks.json> --json
- The goal opens as a draft: nothing is dispatched until you start it. The output contains goal.id, the graph with each task's node id, and turnToken. You are now the goal's supervising agent.
+ If lh rejects --task-file, pass the task titles with -t "<title>" "<title>" instead. The goal opens as a draft: nothing is dispatched until you start it. The output contains goal.id, the graph with each task's node id, and turnToken. You are now the goal's supervising agent.
3. Start it from the graph lh goal create printed (do not run lh goal show or other lh goal commands: this run's credentials only allow creating or binding this goal, planning it and starting it):
lh goal start <goalId> --json
If the tasks apply one recipe to many units (migrate N stores to one mechanism, give N resources the same caching, update N callers), start them as a batch instead:
lh goal start <goalId> --rollout canary --recipe-file <recipe.md> --probes <2-5 task node ids> --json
The recipe is the procedure every unit follows; the probes are the most representative units, covering every way the units differ. The probes run first, and the other tasks are released wave by wave only after the probes ran through without a person; a rejection revises the recipe and re-probes. Tasks that differ only in names, files or details are one recipe; tasks whose steps differ are not, so start those without --rollout.
+ If lh has no goal start command, the goal already runs: skip this step.
4. Then end the run with one or two sentences in the user's language: the goal is running, and what runs first.
If the request instead asks to attach an existing goal to this conversation (it names a goal id like goal_xxx, or a /goal/goal_xxx link, to continue, bind or supervise here), do not create a new goal. Bind that one:
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 56a1ef2a79b..161013ea0ae 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -336,6 +336,12 @@ export interface GoalManagerState {
reviewSnapshot?: string;
snapshot: string;
startedAt: string;
+ /**
+ * `start` settled this turn with the draft's arrangement rather than a plan
+ * the agent submitted, so a later `lh goal plan` on it is refused, not
+ * reported as a duplicate of a plan that was never written.
+ */
+ startedFromDraft?: boolean;
submitted?: {
action: 'tasks' | 'verify' | 'retry' | 'escalate' | 'wait';
/**
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index f97cfb8dd86..a76e01a99e5 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -20,6 +20,7 @@ import RightPanel from '@/features/RightPanel';
import { useWorkspaceSidePanel } from '@/features/RightPanel/WorkspaceSidePanel';
import WideScreenContainer from '@/features/WideScreenContainer';
import { usePermission } from '@/hooks/usePermission';
+import { useResourceManageable } from '@/hooks/useResourceManageable';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
@@ -68,6 +69,8 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const pauseGoal = useGoalStore((s) => s.pauseGoal);
const resumeGoal = useGoalStore((s) => s.resumeGoal);
const startGoal = useGoalStore((s) => s.startGoal);
+ // The server lets only a draft's creator or a workspace owner launch it.
+ const canStart = useResourceManageable(snapshot?.goal.userId);
const buildAgentPath = useAgentRoutePath(agentId ?? '');
@@ -243,7 +246,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
and starting it is the one explicit move into running. */}
{goal.status === 'draft' && (
<Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>
- {canEdit && (
+ {canEdit && canStart && (
<Button
icon={PlayIcon}
loading={starting}
diff --git a/src/features/AgentGoals/goalStatusMenu.test.ts b/src/features/AgentGoals/goalStatusMenu.test.ts
index 8fa77c71133..a3c3f86c464 100644
--- a/src/features/AgentGoals/goalStatusMenu.test.ts
+++ b/src/features/AgentGoals/goalStatusMenu.test.ts
@@ -30,6 +30,8 @@ describe('goal status menu', () => {
it('offers only starting a draft goal, unchecked', () => {
expect(toManualStatus('draft')).toBeUndefined();
expect(isStatusChoiceDisabled('running', 'draft', true)).toBe(false);
+ // The server lets only the creator or an owner start a draft.
+ expect(isStatusChoiceDisabled('running', 'draft', false)).toBe(true);
expect(isStatusChoiceDisabled('paused', 'draft', true)).toBe(true);
expect(isStatusChoiceDisabled('canceled', 'draft', true)).toBe(true);
});
diff --git a/src/features/AgentGoals/goalStatusMenu.ts b/src/features/AgentGoals/goalStatusMenu.ts
index f374bbf6278..7fb7b771c94 100644
--- a/src/features/AgentGoals/goalStatusMenu.ts
+++ b/src/features/AgentGoals/goalStatusMenu.ts
@@ -30,8 +30,9 @@ export const isStatusChoiceDisabled = (
canClose: boolean,
): boolean => {
if (next === 'paused') return !PAUSABLE_STATUSES.has(status ?? '');
- // Closing a draft would end a goal that never ran; delete it instead.
- if (status === 'draft' && next !== 'running') return true;
+ // Closing a draft would end a goal that never ran; delete it instead. Starting
+ // it is allowed to the same people as closing: its creator or an owner.
+ if (status === 'draft') return next !== 'running' || !canClose;
if (next === 'achieved' || next === 'canceled') return !canClose;
return false;
};
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 740ca69f162..37844a77fcc 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -82,6 +82,18 @@ describe('GoalAction', () => {
},
);
+ /**
+ * Regression: the agent starts its draft from the conversation a few seconds
+ * after creating it. Unpolled, the card and page kept reading "Not started"
+ * while its tasks ran.
+ */
+ it('keeps re-reading a draft its agent may start at any moment', () => {
+ seedGraph(graphWith('draft'));
+ renderGraph();
+
+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBeGreaterThan(0);
+ });
+
it.each(['review', 'paused', 'achieved', 'failed', 'canceled'])(
'stops polling a %s goal',
(status) => {
@@ -198,6 +210,8 @@ describe('GoalAction', () => {
expect(options.refreshInterval(withStatuses('achieved', 'running'))).toBeGreaterThan(0);
expect(options.refreshInterval(withStatuses('review', 'paused'))).toBe(0);
expect(options.refreshInterval(undefined)).toBe(0);
+ // Regression: the tray read "Not started" after its agent started the draft.
+ expect(options.refreshInterval(withStatuses('draft'))).toBeGreaterThan(0);
});
it('polls while the conversation is generating, before any goal exists', () => {
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 46606ac5943..2d25abe2126 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -65,6 +65,14 @@ const HOME_GOAL_FETCH_LIMIT = 100;
*/
const SERVER_ADVANCING_STATUSES = new Set<GoalStatus>(['planning', 'running', 'verifying']);
+/**
+ * Whether an open view must keep re-reading a goal in this status. A draft is
+ * arranged and usually started by its agent from the conversation, never from
+ * this view, so no local action would refresh its "Not started".
+ */
+const goalStatusPolled = (status: GoalStatus) =>
+ SERVER_ADVANCING_STATUSES.has(status) || status === 'draft';
+
/** Kept coarse on purpose β€” this is liveness, not a progress bar. */
const GOAL_GRAPH_POLL_INTERVAL = 5000;
const PENDING_CLARIFICATIONS_POLL_INTERVAL = 30_000;
@@ -113,7 +121,7 @@ const goalAcceptanceUnsettled = (graph: GoalGraphSnapshot): boolean => {
* for the graph snapshot itself.
*/
const goalGraphShouldPoll = (graph: GoalGraphSnapshot): boolean =>
- SERVER_ADVANCING_STATUSES.has(graph.goal.status) ||
+ goalStatusPolled(graph.goal.status) ||
graph.report?.status === 'running' ||
(graph.goal.status === 'achieved' && goalAcceptanceUnsettled(graph));
@@ -148,7 +156,7 @@ const topicGoalsRefreshInterval = (
result: { goals: { goal: { status: GoalStatus } }[] } | undefined,
generating?: boolean,
) =>
- generating || result?.goals.some(({ goal }) => SERVER_ADVANCING_STATUSES.has(goal.status))
+ generating || result?.goals.some(({ goal }) => goalStatusPolled(goal.status))
? GOAL_GRAPH_POLL_INTERVAL
: 0;