Linear
This page shows how to test an integration or agent built on Linear's APIs: how to point it at the fake, which people, teams and issues a test creates, what those people do, and what you check afterwards. It assumes you have run Getting started once.
import { expect, test } from "vitest";test("delegating an issue opens one session with a first thought", async ({ linear }) => { const ana = await linear.createUser({ name: "Ana" }); const team = await linear.createTeam({ members: [ana] }); const issue = await ana.createIssue({ title: "Checkout fails on Safari" }, { team }); const session = await ana.delegate(linear.app, { issue }); await expect(session).toHaveActivity({ type: "thought" }, { timeout: "10s" }); await expect(issue).toBeDelegatedTo(linear.app); expect(await issue.sessions()).toHaveLength(1);});from channelstack import LinearFixturefrom pytest_channelstack import expectasync def test_delegating_an_issue_opens_one_session_with_a_first_thought(linear: LinearFixture) -> None: ana = await linear.create_user(name="Ana") team = await linear.create_team(members=[ana]) issue = await ana.create_issue({"title": "Checkout fails on Safari"}, team=team) session = await ana.delegate(linear.app, issue=issue) await expect(session).to_have_activity(type="thought", timeout="10s") await expect(issue).to_be_delegated_to(linear.app) assert len(await issue.sessions()) == 1let ana = linear.create_user().name("Ana").await?;let team = linear .create_team() .members(vec![&ana as &dyn Handle]) .await?;let issue = ana .create_issue(json!({ "title": "Checkout fails on Safari" })) .team(&team) .await?;let session = ana.delegate(&linear.app()).issue(&issue).await?;expect(&session) .to_have_activity() .r#type("thought") .timeout("10s") .await?;expect(&issue).to_be_delegated_to(&linear.app()).await?;// The Rust SDK returns the sessions as JSON.let sessions = issue.sessions().await?;assert_eq!(sessions.as_array().map(Vec::len), Some(1));What the fake covers#
The fake Linear is one workspace with one OAuth app installed in it, my-agent, acting as itself (actor=app), and any other app a test adds (several apps). It serves Linear's GraphQL API and sends the app's webhooks. Queries run against Linear's own published schema, so an app on @linear/sdk gets the shapes it gets from Linear, including every scalar the SDK selects.
| Area | What's there |
|---|---|
| Reads | viewer, organization, users, teams, issues, comments, workflow states, labels, agent sessions and activities, with Linear's filters and cursors |
| Agent sessions | agentActivityCreate (thoughts, actions, elicitations, responses, errors), agentSessionUpdate (plan, external URLs) |
| Issues | issueUpdate (state, assignee, delegate, priority, title, description), issueAddLabel, issueRemoveLabel |
| Comments | commentCreate, commentUpdate, commentDelete, reactionCreate |
| Webhooks | AgentSessionEvent (created, prompted), Issue and Comment (create, update, remove) |
Sessions follow Linear's rules: created as pending, active after a thought or action, awaitingInput after an elicitation, complete after a response (or active again with the continue signal), error after an error. A person's prompt starts a new turn, and Stop makes the session stopping until the agent's next response or error.
What a person has to read is also a comment. The agent's response, elicitation and error activities appear as the app's comments in the session's thread: the comment that mentioned it, or for a delegation the thread Linear opens with a comment of its own ("This thread is for an agent session with my-agent."). That comment is no one's: issue.comments(), the comment matchers and the transcript leave it out, in both modes. A reply there prompts the session. Delegating an issue nobody is assigned to makes the person who delegated it its assignee, as in Linear.
Not covered: creating issues as the app (issueCreate), projects, cycles, initiatives, documents, attachments, notifications and the OAuth install flow. A field the fake doesn't model either gets Linear's empty value for its type or, for a required object, an error that names it (The fake has no Issue.sharedAccess), so a gap shows up as a failing call, never as an invented value.
Connecting a Linear app#
Ask the running server for the app's settings:
npx channelstack env
LINEAR_API_URL=https://linear.localhost/graphql
LINEAR_ACCESS_TOKEN=lin_oauth_…
LINEAR_WEBHOOK_SECRET=…
LINEAR_CLIENT_ID=…
LINEAR_CLIENT_SECRET=…
The token and secrets are random, made once for your machine and kept in ~/.channelstack/secrets.json. With --no-portless, the URL is http://127.0.0.1:4500/linear/graphql.
@linear/sdk#
import { LinearClient } from "@linear/sdk";
import { LinearWebhookClient } from "@linear/sdk/webhooks";
const linear = new LinearClient({
accessToken: process.env.LINEAR_ACCESS_TOKEN,
...(process.env.LINEAR_API_URL ? { apiUrl: process.env.LINEAR_API_URL } : {}),
});
const handler = new LinearWebhookClient(process.env.LINEAR_WEBHOOK_SECRET!).createHandler();
handler.on("AgentSessionEvent", async (event) => {
if (event.action === "created") {
await linear.createAgentActivity({
agentSessionId: event.agentSession.id,
content: { type: "thought", body: "Looking into it" },
});
}
});
// Serve handler(request) at /webhooks/linear.
LinearWebhookClient checks the signature and the timestamp for you. Leave LINEAR_API_URL unset in production, where the SDK talks to https://api.linear.app/graphql.
Chat SDK#
The Chat SDK's Linear adapter reads LINEAR_API_URL from the environment by itself. In agent-session mode, a session (a delegation or a mention) arrives as a new mention and a person's prompt as a message in the subscribed thread:
import { createLinearAdapter } from "@chat-adapter/linear";
import { createMemoryState } from "@chat-adapter/state-memory";
import { Chat } from "chat";
const linear = createLinearAdapter({
mode: "agent-sessions",
accessToken: process.env.LINEAR_ACCESS_TOKEN!,
userName: "my-agent",
});
const bot = new Chat({ userName: "my-agent", adapters: { linear }, state: createMemoryState() });
bot.onNewMention(async (thread) => {
await thread.subscribe();
await thread.post("On it.");
});
// Serve bot.webhooks.linear(request) at /api/webhooks/linear.
Where webhooks are delivered#
channelstack sends the app's webhooks to the URL you give it when the server starts:
CHANNELSTACK_LINEAR_WEBHOOK_URL=http://localhost:3000/webhooks/linear npx channelstack start
The @linear/sdk reference agent serves /webhooks/linear, the Chat SDK one /api/webhooks/linear. Without a webhook URL, Issue and Comment events aren't sent. An agent session is announced anyway, because an agent's webhook is part of its app: its delivery is then unreachable, which tells you the URL is missing. See Connecting your agent for TLS trust and the other runtimes, and proxy mode for a client that hard-codes api.linear.app.
People, teams and issues in a test#
A test creates the people, teams and issues it needs. Nothing is declared in a config file.
const ana = await linear.createUser({ name: "Ana" });const ben = await linear.createUser({ name: "Ben", admin: true });ana = await linear.create_user(name="Ana")ben = await linear.create_user(name="Ben", admin=True)let ana = linear.create_user().name("Ana").await?;let ben = linear.create_user().name("Ben").admin(true).await?;| Option | What it does |
|---|---|
name | Required. Mentions (@Ana) and matchers find the person by it |
id | A fixed id (a UUID), for apps that allowlist by id |
displayName, email | Profile fields |
admin, guest | Workspace roles |
token | Live mode only: see Live |
const team = await linear.createTeam({ key: "OPS", members: [ana, ben], labels: ["incident"], states: [ { name: "Triage", type: "triage" }, { name: "Investigating", type: "started" }, { name: "Resolved", type: "completed" }, ],});team = await linear.create_team( key="OPS", members=[ana, ben], labels=["incident"], states=[ {"name": "Triage", "type": "triage"}, {"name": "Investigating", "type": "started"}, {"name": "Resolved", "type": "completed"}, ],)let team = linear .create_team() .key("OPS") .members(vec![&ana as &dyn Handle, &ben]) .labels(vec!["incident"]) .states(json!([ { "name": "Triage", "type": "triage" }, { "name": "Investigating", "type": "started" }, { "name": "Resolved", "type": "completed" }, ])) .await?;| Option | What it does |
|---|---|
key | The issue prefix, e.g. OPS. Generated if omitted, so parallel tests never share one |
name | The team's name |
members | People in the team |
states | Workflow states, each { name, type } with type one of triage, backlog, unstarted, started, completed, canceled. Default: Backlog, Todo, In Progress, In Review, Done, Canceled. Every team also has Linear's own Duplicate state (type: duplicate), which can't be created |
labels | Label names |
Issues are created by a person, so the creation reaches the app as an Issue event:
const issue = await ana.createIssue( { title: "API latency spike", labels: ["incident"], priority: 2, state: "Triage", assignee: ben }, { team },);issue = await ana.create_issue( {"title": "API latency spike", "labels": ["incident"], "priority": 2, "state": "Triage", "assignee": ben}, team=team,)let issue = ana .create_issue(json!({ "title": "API latency spike", "labels": ["incident"], "priority": 2, "state": "Triage", "assignee": ben.data(), })) .team(&team) .await?;createIssue also takes description, parent (a sub-issue) and delegate: linear.app, which delegates right away and opens a session.
Giving the app access#
Nothing to do. On Linear an app is installed workspace-wide, so the fake's app sees every team and issue, and hears about every one. A session starts when a person delegates an issue to it or mentions it in a comment.
What people do#
Every action is a method on the person who takes it, with the content first and the place as an option. An action that sends one webhook resolves to that delivery. The API reference lists every method and option.
Delegation and agent sessions#
const session = await ana.delegate(linear.app, { issue });const issue2 = await ana.createIssue({ title: "Bump the Node version", delegate: linear.app }, { team });const session2 = await issue2.session();const comment = await ana.comment("@my-agent can you take a look?", { issue });await expect(comment.session!).toHaveActivity({ type: "response" });await ana.undelegate({ issue });session = await ana.delegate(linear.app, issue=issue)issue2 = await ana.create_issue({"title": "Bump the Node version", "delegate": linear.app}, team=team)session2 = await issue2.session()comment = await ana.comment("@my-agent can you take a look?", issue=issue)assert comment.sessionawait expect(comment.session).to_have_activity(type="response")await ana.undelegate(issue=issue)let session = ana.delegate(&linear.app()).issue(&issue).await?;let issue2 = ana .create_issue(json!({ "title": "Bump the Node version", "delegate": linear.app().data() })) .team(&team) .await?;let session2 = issue2.session().await?;let comment = ana .comment("@my-agent can you take a look?") .issue(&issue) .await?;let opened = comment.session().expect("the mention opened a session");expect(&opened) .to_have_activity() .r#type("response") .await?;ana.undelegate().issue(&issue).await?;delegate and a mention each open a session and send AgentSessionEvent (created). delegate resolves to the session; a mention's session is on comment.session, and issue.session() waits for the latest one on an issue. undelegate takes the issue back.
Prompts and elicitations#
const question = await session.waitForActivity({ type: "elicitation" });await ana.answer("Only Safari 18", { elicitation: question });await ana.prompt("also update the docs", { session });question = await session.wait_for_activity(type="elicitation")await ana.answer("Only Safari 18", elicitation=question)await ana.prompt("also update the docs", session=session)let question = session.wait_for_activity().r#type("elicitation").await?;ana.answer("Only Safari 18").elicitation(&question).await?;ana.prompt("also update the docs").session(&session).await?;prompt and answer send AgentSessionEvent (prompted), with the person's text as a prompt activity. After a prompt, session.waitForActivity() only looks at what came after it, so you get the answer to that prompt, not to an earlier one.
Stop#
await expect(session).toHaveActivity({ type: "thought" });await ana.stop({ session });await expect(session).toHaveSessionState("complete");await expect(session).to_have_activity(type="thought")await ana.stop(session=session)await expect(session).to_have_session_state("complete")expect(&session) .to_have_activity() .r#type("thought") .await?;ana.stop().session(&session).await?;expect(&session).to_have_session_state("complete").await?;stop presses Stop in Linear. The agent gets prompted with the stop signal on the activity, and the session stays stopping until the agent's response or error ends the turn. Only a person can send stop: the app's own agentActivityCreate with it is refused.
Issues and comments#
await ana.setState("In Progress", { issue });await ana.assign(ben, { issue });await ana.label(["incident"], { issue });await ana.editIssue({ priority: 1 }, { issue });const comment = await ana.comment("Is this still happening?", { issue });await ana.reply("@my-agent can you check the logs?", { comment });await ana.edit("Is this still happening on Safari?", { comment });await ana.set_state("In Progress", issue=issue)await ana.assign(ben, issue=issue)await ana.label(["incident"], issue=issue)await ana.edit_issue({"priority": 1}, issue=issue)comment = await ana.comment("Is this still happening?", issue=issue)await ana.reply("@my-agent can you check the logs?", comment=comment)await ana.edit("Is this still happening on Safari?", comment=comment)ana.set_state("In Progress").issue(&issue).await?;ana.assign(&ben).issue(&issue).await?;ana.label(vec!["incident"]).issue(&issue).await?;ana.edit_issue(json!({ "priority": 1 })) .issue(&issue) .await?;let comment = ana .comment("Is this still happening?") .issue(&issue) .await?;ana.reply("@my-agent can you check the logs?") .comment(&comment) .await?;ana.edit("Is this still happening on Safari?") .comment(&comment) .await?;ana.react(emoji, { comment }) adds a reaction. @name in a body becomes a real Linear mention. These send Issue or Comment webhooks (create, update, remove).
What to check#
The matchers read the session and the issue as a person would see them in Linear. Positive matchers resolve as soon as the condition holds; .not and exact counts wait until the app is quiet first. Waiting and quiet explains how.
| Matcher | Subject | Reads |
|---|---|---|
toHaveSessionState(state) | session, issue (its latest session) | session.state() |
toHaveActivity({ type, from, text }) | session, issue (its latest session) | session.activities(), the agent's only |
toBeDelegatedTo(app) | issue | issue.delegatedTo() |
toBeAssignedTo(user) | issue | issue.assignee() |
toHaveState(name) | issue | issue.state() |
toHaveCommentFrom(author, { text }) | issue | issue.comments() |
toHaveCommentsFrom(author, { count }) | issue | issue.comments(), once quiet |
toContainText(text) | issue, comment, session | transcript() |
toBeAccepted, toBeRejected, toBeRetried | delivery | delivery.attempts |
toHaveReceivedCall(operation, { times, error }) | linear | linear.calls() |
toHaveActivity counts the agent's activities only: a person's prompts, delegation's first among them, don't count. Pass toBeDelegatedTo(undefined) to check an issue was taken back.
The reads behind them: session.state(), session.waitForState(["complete", "error"]), session.activities(), session.waitForActivity({ type }), session.plan(), session.externalUrls(), issue.sessions(), issue.labels(), issue.latestComment({ from }) and comment.replies(). linear.calls() names each call by the root field it asked for, such as agentActivityCreate or issueUpdate.
A full test, an agent that asks a question and continues after the answer, then links its work:
import { expect, test } from "vitest";test("the agent asks a question and continues after the answer", async ({ linear }) => { const ana = await linear.createUser({ name: "Ana" }); const team = await linear.createTeam({ members: [ana] }); const issue = await ana.createIssue({ title: "Fix the login bug" }, { team }); const session = await ana.delegate(linear.app, { issue }); const question = await session.waitForActivity({ type: "elicitation" }); await expect(issue).toHaveSessionState("awaitingInput"); await ana.answer("Only Safari 18", { elicitation: question }); await expect(session).toHaveActivity({ type: "response", text: /safari 18/i }); await expect(linear).toHaveReceivedCall("agentActivityCreate"); expect(await linear.calls({ error: true })).toEqual([]);});import refrom channelstack import LinearFixturefrom pytest_channelstack import expectasync def test_the_agent_asks_a_question_and_continues_after_the_answer(linear: LinearFixture) -> None: ana = await linear.create_user(name="Ana") team = await linear.create_team(members=[ana]) issue = await ana.create_issue({"title": "Fix the login bug"}, team=team) session = await ana.delegate(linear.app, issue=issue) question = await session.wait_for_activity(type="elicitation") await expect(issue).to_have_session_state("awaitingInput") await ana.answer("Only Safari 18", elicitation=question) await expect(session).to_have_activity(type="response", text=re.compile("safari 18", re.I)) await expect(linear).to_have_received_call("agentActivityCreate") assert await linear.calls(error=True) == []let ana = linear.create_user().name("Ana").await?;let team = linear .create_team() .members(vec![&ana as &dyn Handle]) .await?;let issue = ana .create_issue(json!({ "title": "Fix the login bug" })) .team(&team) .await?;let session = ana.delegate(&linear.app()).issue(&issue).await?;let question = session.wait_for_activity().r#type("elicitation").await?;expect(&issue) .to_have_session_state("awaitingInput") .await?;ana.answer("Only Safari 18").elicitation(&question).await?;expect(&session) .to_have_activity() .r#type("response") .text(Regex::new("(?i)safari 18")?) .await?;expect(&linear) .to_have_received_call("agentActivityCreate") .await?;// The Rust SDK returns the calls as JSON.assert_eq!(linear.calls().error(true).await?, json!([]));linearChecks() from channelstack/checks adds the checks every Linear agent should pass: a first activity soon after delegation, the turn always ends, Stop is honoured, redelivery, a stale or badly signed webhook. See Standard checks.
Delivery specifics#
Signatures and headers#
| Header or field | Value |
|---|---|
Linear-Signature | The hex HMAC-SHA256 of the body, keyed with LINEAR_WEBHOOK_SECRET |
Linear-Delivery | The delivery's id |
Linear-Event | The resource type: AgentSessionEvent, Issue, Comment |
Linear-Timestamp | The attempt's time, in milliseconds |
User-Agent | Linear-Webhook |
webhookTimestamp (body) | The attempt's time, in milliseconds. Receivers refuse a delivery more than a minute off |
The body also has type, action, organizationId and webhookId. Because the time is inside the signed body, every attempt (a retry, a redelivery) writes its own webhookTimestamp and is signed again over those bytes.
Acknowledgement and retries#
The app has five seconds to answer with a 2xx. A delivery that wasn't answered in time is retried on Linear's schedule: after a minute, an hour and six hours. In a test you don't wait for those; you send the delivery again yourself:
const session = await ana.delegate(linear.app, { issue });await session.delivery!.redeliver(); // same webhook, new timestamp, signed againawait session.delivery!.resend({ stale: true });await expect(session.delivery!).toBeRejected();session = await ana.delegate(linear.app, issue=issue)assert session.deliveryawait session.delivery.redeliver() # same webhook, new timestamp, signed againawait session.delivery.resend(stale=True)await expect(session.delivery).to_be_rejected()let session = ana.delegate(&linear.app()).issue(&issue).await?;let delivery = session.delivery().expect("the fake delivered the webhook");delivery.redeliver().await?; // same webhook, new timestamp, signed againdelivery.resend().stale(true).await?;expect(&delivery).to_be_rejected().await?;resend({ stale: true }) stamps a webhookTimestamp two minutes back; resend({ badSignature: true }) signs with a secret that isn't the app's. An agent that handles a redelivered created twice shows up as duplicate activities. Delivery and failures covers what each of these proves.
What the fake refuses#
Errors have Linear's shape: errors[].extensions with code, type, statusCode, userError and userPresentableMessage. A missing or wrong token answers HTTP 401, and a query that doesn't parse or validate against the schema answers 400 with GraphQL's own message.
| Code | When |
|---|---|
AUTHENTICATION_ERROR | No token, or a token that isn't the app's |
BAD_REQUEST | A request without a query |
FORBIDDEN | Publishing to another app's session, editing or deleting someone else's comment |
INPUT_ERROR | An id that names nothing (Entity not found), an empty comment body, a priority outside 0 to 4, a stop signal from the app, continue on anything but a response, an ephemeral activity that isn't a thought or action, an activity on a stale session, a plan that isn't 1 to 100 entries, an external URL that isn't HTTP(S), delegating to someone who isn't an agent |
The errors reference lists every code.
Several apps#
A test adds another app to the workspace with linear.createApp({ name }): an OAuth app installed with actor=app, with its own app user (mentionable and assignable), access token, client id and secret, and webhook secret, subscribed to AgentSessionEvent, Issue and Comment unless events says otherwise. Its webhooks go to CHANNELSTACK_LINEAR_APP_<NAME>_WEBHOOK_URL; channelstack env --app coder --channel linear prints its .env lines under my-agent's keys. See several apps.
const coder = await linear.createApp({ name: "coder" });
const ana = await linear.createUser({ name: "Ana" });
const team = await linear.createTeam({ members: [ana] });
const issue = await ana.createIssue({ title: "Checkout fails on Safari" }, { team });
const session = await ana.delegate(coder, { issue });
await expect(session).toHaveActivity({ type: "thought" }, { timeout: "10s" });
await expect(issue).toBeDelegatedTo(coder);
- Agent sessions are per app. Delegating to an app, or a person's
@mentionof it, opens a session for that app, and itsAgentSessionEvents go to it alone. An issue has one delegate: delegating to another app moves it. Another app can't post activities into the session. IssueandCommentwebhooks go to every app, each its own delivery signed with its own secret, with the writing app's user as the actor.- Between apps, an app's mention of another app, and an app delegating to one, are refused for now: whether Linear allows them is still to be confirmed live.
A test can act as an app it made: coder.comment and coder.reply write through the fake's own path, as that app; acting as my-agent is refused. comment.delivery is still the delivery to my-agent; comment.deliveryFor(coder) reads another app's.
Live#
The same tests can run in a real Linear workspace. Set the OAuth app's token (CHANNELSTACK_LINEAR_APP_TOKEN), allowlist the workspace with CHANNELSTACK_LIVE_LINEAR_WORKSPACES, and give each person their personal API key (CHANNELSTACK_LINEAR_USER_ANA_TOKEN for createUser({ name: "Ana" })). A person creates each session's teams, which are deleted when the session closes.
Live, Linear delivers to your app itself, so its webhook must reach a running app: Linear opens no session otherwise, and the live backend says so (no_agent_session) after 15 seconds. Delegation, comments, prompts, answers and every read work with the personal keys. Stop has no API, so it needs the browser actor, which isn't built for Linear yet. Redelivery, resend and session.delivery are fake only. See Live mode and the API reference.