* feat(linear): start sessions from Linear issues Authorize a Linear workspace on this OpenChamber server, map teams to projects, attach an issue from chat, start a session or worktree from an issue, and post started/completed/failed comments that open the session. Hidden in VS Code. * feat(linear): connect more than one Linear workspace Store each OAuth grant on this OpenChamber server and keep one current, so Settings can add and switch workspaces without dropping the others. Project mapping is per workspace. Remove the Linear button next to New Chat; start-from-issue stays on New Worktree. * feat(linear): add a right-hand issues panel Browse and filter issues in the rail, open a card to change status or start a session, and collapse search plus most filters to icons on a narrow panel. * feat(linear): open issues in the rail and filter by Linear status The rail icon only shows after Linear is connected. Clicking a Linear row on work status opens the panel. Status options match the card, including Done, Canceled, and Duplicate. The Integrations experimental warning sits under Third-party integrations. * fix(linear): use stable OAuth callback broker * fix(chat): preview Linear issue attachments The context switch missed linear-issue, so tsc treated the preview helpers as incomplete. * fix(ui): restore Linear i18n parity and the #2903 sync harness Turkish was missing the Linear dictionaries, and the subagent test still wrapped only SyncContext after reads moved to SyncRuntimeContext. * fix(linear): drop changelog hunks and close review races Keep changelogs out of this PR, restore CodeMirror ranges, ignore stale Linear list pages, and leave a persisted Linear tab open until auth has actually resolved. * fix(linear): tint active issue filters and clear them in one click * fix(markdown): read escaped brackets as text, not display math `\[...\]` is display math in LaTeX and an escaped bracket pair in CommonMark. The block tokenizer claimed every `\[`, so prose like `[title \[Bug\] more](url)` was handed to KaTeX: "Bug" rendered as a centered formula and the block token split the paragraph, tearing the link into three pieces. Linear, GitHub and any other source that escapes brackets the way CommonMark requires hit this. Display math now has to own its line — `\[` starts one and `\]` ends one. A formula on its own line still renders; `\[` mid-sentence stays an escape, which is what CommonMark says it is and what prose almost always means. Inline `\(...\)` keeps the same ambiguity, but inline math is legitimately mid-sentence, so there is no position to judge it by. Covered by regression tests, including the verbatim comment body that surfaced this. * feat(linear): make session status comments opt-in and public-only A status comment lands in a Linear workspace the whole team reads, and the link it carried pointed at whatever origin started the session — usually loopback or a LAN address. Everyone but its author got a dead link, and nobody had agreed to the comments in the first place. Comments are now off until the user turns them on in Settings -> Integrations -> Linear, and the check lives on the server: the event hub posts completed and failure without going through the interface, so a client-side gate would not hold. When the resolved origin is not publicly reachable the server posts nothing at all rather than a link only its author can open; `isPublicSessionOrigin` rejects loopback, private LAN, carrier-grade NAT, link-local and single-label hosts. The desktop deep-link origin is gone with it, since no one else can follow one either. The comment body also dropped the session title. It repeated the issue the comment already sits on, and issue titles routinely carry brackets ("[Bug] ...") that broke the markdown link. The body is now one short link, and `sessionTitle` is gone from the route, client and types. Also caps the dedupe file at the newest 500 sessions; it grew forever. * fix(linear): match the pull request panel and clear review findings Comments in the Linear panel now render as the same avatar timeline the pull request panel uses, with the shared time-format preference instead of a raw locale string. Comment authors carry `avatarUrl`, which the GraphQL selection was not requesting. Review findings from the same pass: - `status-runtime.js` hand-rolled `typeof` narrowing and failed the vendored anti-slop lint; it now parses through `parse.js` like every other file in the module. - `useLinearAuthStore` turned any failed request into `connected: false` with `hasChecked: true`. Since the rail icon, the composer entry and the worktree option all gate on `connected === true`, one network blip hid Linear for the rest of the session, and Settings only re-checked when it had never checked. It now keeps the last known status and leaves `hasChecked` false so the next caller retries. - `LinearIssuesView` (1096 lines) was a static import in `ContextPanel`, shipping in the main bundle although its rail icon stays hidden until a workspace is connected. It is lazy now, like `GitView`. - Dropped dead code: the unused port helpers left over from the loopback callback, two re-exported default values nothing read, and a redundant export in `linkedIssues`. - Integrations is no longer badged beta.
437 lines
12 KiB
JavaScript
437 lines
12 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import os from 'os';
|
|
import { isPlainObject, readEnv, readFiniteNumber, readTrimmedString } from './parse.js';
|
|
|
|
const DEFAULT_LINEAR_CLIENT_ID = '91bbe26a69a2c8568d3683f1e01e776c';
|
|
const DEFAULT_LINEAR_SCOPES = 'read,write,comments:create';
|
|
const DEFAULT_LINEAR_BROKER_URL = 'https://api.openchamber.dev/v1/oauth/linear';
|
|
const ACCESS_TOKEN_REFRESH_SKEW_MS = 2 * 60_000;
|
|
const LEGACY_WORKSPACE_ID = 'legacy';
|
|
const SESSION_COMMENTS_SETTING_KEY = 'linearSessionComments';
|
|
|
|
function resolveDataDir() {
|
|
const fromEnv = readEnv('OPENCHAMBER_DATA_DIR');
|
|
if (fromEnv) {
|
|
return path.resolve(fromEnv);
|
|
}
|
|
return path.join(os.homedir(), '.config', 'openchamber');
|
|
}
|
|
|
|
function storageFile() {
|
|
return path.join(resolveDataDir(), 'linear-auth.json');
|
|
}
|
|
|
|
function settingsFile() {
|
|
return path.join(resolveDataDir(), 'settings.json');
|
|
}
|
|
|
|
function ensureStorageDir() {
|
|
const dir = resolveDataDir();
|
|
if (!fs.existsSync(dir)) {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
}
|
|
}
|
|
|
|
function readJsonFile(filePath) {
|
|
if (!fs.existsSync(filePath)) {
|
|
return null;
|
|
}
|
|
try {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
const trimmed = raw.trim();
|
|
if (!trimmed) {
|
|
return null;
|
|
}
|
|
const parsed = JSON.parse(trimmed);
|
|
if (!isPlainObject(parsed)) {
|
|
return null;
|
|
}
|
|
return parsed;
|
|
} catch (error) {
|
|
console.error('Failed to read Linear auth file:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function writeJsonFile(filePath, payload) {
|
|
ensureStorageDir();
|
|
const tmpFile = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
fs.writeFileSync(tmpFile, JSON.stringify(payload, null, 2), 'utf8');
|
|
try {
|
|
fs.chmodSync(tmpFile, 0o600);
|
|
} catch {
|
|
// best-effort
|
|
}
|
|
fs.renameSync(tmpFile, filePath);
|
|
try {
|
|
fs.chmodSync(filePath, 0o600);
|
|
} catch {
|
|
// best-effort
|
|
}
|
|
}
|
|
|
|
function normalizeUser(user) {
|
|
if (!isPlainObject(user)) {
|
|
return null;
|
|
}
|
|
const id = readTrimmedString(user.id);
|
|
if (!id) {
|
|
return null;
|
|
}
|
|
return {
|
|
id,
|
|
name: readTrimmedString(user.name) || null,
|
|
displayName: readTrimmedString(user.displayName) || null,
|
|
email: readTrimmedString(user.email) || null,
|
|
avatarUrl: readTrimmedString(user.avatarUrl) || null,
|
|
};
|
|
}
|
|
|
|
function normalizeOrganization(organization) {
|
|
if (!isPlainObject(organization)) {
|
|
return null;
|
|
}
|
|
const id = readTrimmedString(organization.id);
|
|
const name = readTrimmedString(organization.name);
|
|
if (!id || !name) {
|
|
return null;
|
|
}
|
|
return {
|
|
id,
|
|
name,
|
|
urlKey: readTrimmedString(organization.urlKey) || null,
|
|
};
|
|
}
|
|
|
|
function resolveLinearWorkspaceId({ organization, user, workspaceId } = {}) {
|
|
const explicit = readTrimmedString(workspaceId);
|
|
if (explicit) return explicit;
|
|
const organizationId = organization ? readTrimmedString(organization.id) : '';
|
|
if (organizationId) return organizationId;
|
|
const userId = user ? readTrimmedString(user.id) : '';
|
|
if (userId) return `user:${userId}`;
|
|
return LEGACY_WORKSPACE_ID;
|
|
}
|
|
|
|
function normalizeAuthEntry(raw) {
|
|
if (!isPlainObject(raw)) {
|
|
return null;
|
|
}
|
|
const accessToken = readTrimmedString(raw.accessToken);
|
|
if (!accessToken) {
|
|
return null;
|
|
}
|
|
const user = normalizeUser(raw.user);
|
|
const organization = normalizeOrganization(raw.organization);
|
|
return {
|
|
accessToken,
|
|
refreshToken: readTrimmedString(raw.refreshToken) || null,
|
|
tokenType: readTrimmedString(raw.tokenType) || 'bearer',
|
|
expiresAt: readFiniteNumber(raw.expiresAt),
|
|
scope: readTrimmedString(raw.scope),
|
|
createdAt: readFiniteNumber(raw.createdAt),
|
|
authorizedAt: readFiniteNumber(raw.authorizedAt) || readFiniteNumber(raw.createdAt),
|
|
user,
|
|
organization,
|
|
current: Boolean(raw.current),
|
|
workspaceId: resolveLinearWorkspaceId({
|
|
organization,
|
|
user,
|
|
workspaceId: raw.workspaceId,
|
|
}),
|
|
};
|
|
}
|
|
|
|
function normalizeAuthList(raw) {
|
|
const source = Array.isArray(raw?.workspaces)
|
|
? raw.workspaces
|
|
: (raw?.accessToken ? [raw] : []);
|
|
const list = source.map((entry) => normalizeAuthEntry(entry)).filter(Boolean);
|
|
|
|
if (!list.length) {
|
|
return { list: [], changed: Boolean(raw && (raw.accessToken || Array.isArray(raw.workspaces))) };
|
|
}
|
|
|
|
let changed = Array.isArray(raw?.workspaces) === false && Boolean(raw?.accessToken);
|
|
const seen = new Set();
|
|
const deduped = [];
|
|
for (const entry of list) {
|
|
if (seen.has(entry.workspaceId)) {
|
|
changed = true;
|
|
continue;
|
|
}
|
|
seen.add(entry.workspaceId);
|
|
deduped.push(entry);
|
|
}
|
|
|
|
let currentFound = false;
|
|
deduped.forEach((entry) => {
|
|
if (entry.current && !currentFound) {
|
|
currentFound = true;
|
|
} else if (entry.current && currentFound) {
|
|
entry.current = false;
|
|
changed = true;
|
|
}
|
|
});
|
|
|
|
if (!currentFound && deduped[0]) {
|
|
deduped[0].current = true;
|
|
changed = true;
|
|
}
|
|
|
|
return { list: deduped, changed };
|
|
}
|
|
|
|
function readAuthList() {
|
|
const data = readJsonFile(storageFile());
|
|
if (!data) {
|
|
return [];
|
|
}
|
|
const { list, changed } = normalizeAuthList(data);
|
|
if (changed) {
|
|
writeAuthList(list);
|
|
}
|
|
return list;
|
|
}
|
|
|
|
function writeAuthList(list) {
|
|
if (!list.length) {
|
|
const filePath = storageFile();
|
|
if (fs.existsSync(filePath)) {
|
|
fs.unlinkSync(filePath);
|
|
}
|
|
return;
|
|
}
|
|
writeJsonFile(storageFile(), { workspaces: list });
|
|
}
|
|
|
|
function readSettings() {
|
|
return readJsonFile(settingsFile()) || {};
|
|
}
|
|
|
|
function writeSettings(settings) {
|
|
writeJsonFile(settingsFile(), settings);
|
|
}
|
|
|
|
function readSettingString(key) {
|
|
const stored = readSettings()[key];
|
|
return readTrimmedString(stored);
|
|
}
|
|
|
|
export function getLinearAuth() {
|
|
const list = readAuthList();
|
|
if (!list.length) {
|
|
return null;
|
|
}
|
|
return list.find((entry) => entry.current) || list[0];
|
|
}
|
|
|
|
export function getLinearAuthByWorkspaceId(workspaceId) {
|
|
const id = readTrimmedString(workspaceId);
|
|
if (!id) {
|
|
return getLinearAuth();
|
|
}
|
|
return readAuthList().find((entry) => entry.workspaceId === id) || null;
|
|
}
|
|
|
|
export function getLinearAuthWorkspaces() {
|
|
return readAuthList().map((entry) => ({
|
|
id: entry.workspaceId,
|
|
name: entry.organization?.name || null,
|
|
urlKey: entry.organization?.urlKey || null,
|
|
current: Boolean(entry.current),
|
|
user: entry.user || null,
|
|
authorizedAt: entry.authorizedAt || entry.createdAt || null,
|
|
}));
|
|
}
|
|
|
|
export function setLinearAuth(input, options = {}) {
|
|
const accessToken = readTrimmedString(input?.accessToken);
|
|
if (!accessToken) {
|
|
throw new Error('accessToken is required');
|
|
}
|
|
const activate = options.activate !== false;
|
|
const list = readAuthList();
|
|
const current = list.find((entry) => entry.current) || list[0] || null;
|
|
|
|
const nextUser = Object.prototype.hasOwnProperty.call(input, 'user')
|
|
? normalizeUser(input.user)
|
|
: current?.user || null;
|
|
const nextOrganization = Object.prototype.hasOwnProperty.call(input, 'organization')
|
|
? normalizeOrganization(input.organization)
|
|
: current?.organization || null;
|
|
const workspaceId = resolveLinearWorkspaceId({
|
|
organization: nextOrganization,
|
|
user: nextUser,
|
|
workspaceId: input?.workspaceId || (nextOrganization || nextUser ? '' : current?.workspaceId),
|
|
});
|
|
|
|
const existingIndex = list.findIndex((entry) => entry.workspaceId === workspaceId);
|
|
const previous = existingIndex >= 0 ? list[existingIndex] : (
|
|
nextOrganization || nextUser ? null : current
|
|
);
|
|
const targetIndex = existingIndex >= 0
|
|
? existingIndex
|
|
: (previous && !nextOrganization && !nextUser ? list.indexOf(previous) : -1);
|
|
const wasCurrent = previous?.current === true;
|
|
|
|
const next = {
|
|
accessToken,
|
|
refreshToken: Object.prototype.hasOwnProperty.call(input, 'refreshToken')
|
|
? (readTrimmedString(input.refreshToken) || null)
|
|
: previous?.refreshToken || null,
|
|
tokenType: readTrimmedString(input?.tokenType) || previous?.tokenType || 'bearer',
|
|
expiresAt: readFiniteNumber(input?.expiresAt) ?? previous?.expiresAt ?? null,
|
|
scope: readTrimmedString(input?.scope) || previous?.scope || '',
|
|
createdAt: previous?.createdAt || Date.now(),
|
|
authorizedAt: Object.prototype.hasOwnProperty.call(input, 'authorizedAt')
|
|
? (readFiniteNumber(input.authorizedAt) || Date.now())
|
|
: (activate ? Date.now() : (previous?.authorizedAt || previous?.createdAt || Date.now())),
|
|
user: nextUser,
|
|
organization: nextOrganization,
|
|
current: false,
|
|
workspaceId,
|
|
};
|
|
|
|
if (targetIndex >= 0) {
|
|
list[targetIndex] = next;
|
|
} else {
|
|
list.push(next);
|
|
}
|
|
|
|
const writtenIndex = targetIndex >= 0 ? targetIndex : list.length - 1;
|
|
if (activate || !list.some((entry) => entry.current)) {
|
|
list.forEach((entry, index) => {
|
|
entry.current = index === writtenIndex;
|
|
});
|
|
} else {
|
|
list[writtenIndex].current = wasCurrent;
|
|
}
|
|
|
|
writeAuthList(list);
|
|
return list[writtenIndex];
|
|
}
|
|
|
|
export function activateLinearAuth(workspaceId) {
|
|
const id = readTrimmedString(workspaceId);
|
|
if (!id) {
|
|
return false;
|
|
}
|
|
const list = readAuthList();
|
|
const index = list.findIndex((entry) => entry.workspaceId === id);
|
|
if (index === -1) {
|
|
return false;
|
|
}
|
|
list.forEach((entry, idx) => {
|
|
entry.current = idx === index;
|
|
});
|
|
writeAuthList(list);
|
|
return true;
|
|
}
|
|
|
|
export function clearLinearAuth(workspaceId) {
|
|
try {
|
|
const list = readAuthList();
|
|
if (!list.length) {
|
|
return true;
|
|
}
|
|
const id = readTrimmedString(workspaceId);
|
|
const remaining = id
|
|
? list.filter((entry) => entry.workspaceId !== id)
|
|
: list.filter((entry) => !entry.current);
|
|
if (!remaining.length) {
|
|
writeAuthList([]);
|
|
return true;
|
|
}
|
|
if (!remaining.some((entry) => entry.current)) {
|
|
remaining[0].current = true;
|
|
}
|
|
writeAuthList(remaining);
|
|
return true;
|
|
} catch (error) {
|
|
console.error('Failed to clear Linear auth file:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export function isLinearAccessTokenStale(expiresAt, now = Date.now()) {
|
|
const expiry = readFiniteNumber(expiresAt);
|
|
if (expiry == null) {
|
|
return true;
|
|
}
|
|
return expiry - ACCESS_TOKEN_REFRESH_SKEW_MS <= now;
|
|
}
|
|
|
|
export function toLinearPublicStatus(auth, workspaces = getLinearAuthWorkspaces()) {
|
|
if (!auth?.accessToken) {
|
|
return { connected: false };
|
|
}
|
|
return {
|
|
connected: true,
|
|
user: auth.user || null,
|
|
organization: auth.organization || null,
|
|
scope: auth.scope || undefined,
|
|
workspaces,
|
|
};
|
|
}
|
|
|
|
export function getLinearClientId() {
|
|
const fromEnv = readEnv('OPENCHAMBER_LINEAR_CLIENT_ID');
|
|
if (fromEnv) return fromEnv;
|
|
const stored = readSettingString('linearClientId');
|
|
if (stored) return stored;
|
|
return DEFAULT_LINEAR_CLIENT_ID;
|
|
}
|
|
|
|
export function getLinearClientSecret() {
|
|
const fromEnv = readEnv('OPENCHAMBER_LINEAR_CLIENT_SECRET');
|
|
if (fromEnv) return fromEnv;
|
|
return readSettingString('linearClientSecret');
|
|
}
|
|
|
|
export function getLinearScopes() {
|
|
const fromEnv = readEnv('OPENCHAMBER_LINEAR_SCOPES');
|
|
if (fromEnv) return fromEnv;
|
|
const stored = readSettingString('linearScopes');
|
|
if (stored) return stored;
|
|
return DEFAULT_LINEAR_SCOPES;
|
|
}
|
|
|
|
export function getLinearBrokerUrl() {
|
|
const fromEnv = readEnv('OPENCHAMBER_LINEAR_BROKER_URL');
|
|
if (fromEnv) return fromEnv.replace(/\/+$/, '');
|
|
const stored = readSettingString('linearBrokerUrl');
|
|
if (stored) return stored.replace(/\/+$/, '');
|
|
return DEFAULT_LINEAR_BROKER_URL;
|
|
}
|
|
|
|
export function getLinearRedirectUri() {
|
|
const fromEnv = readEnv('OPENCHAMBER_LINEAR_REDIRECT_URI');
|
|
if (fromEnv) return fromEnv;
|
|
const stored = readSettingString('linearRedirectUri');
|
|
if (stored) return stored;
|
|
return `${getLinearBrokerUrl()}/callback`;
|
|
}
|
|
|
|
/**
|
|
* Status comments are opt-in: they are written into a Linear workspace other
|
|
* people read, so nothing is posted until the user turns them on.
|
|
*/
|
|
export function getLinearSessionCommentsEnabled() {
|
|
return readSettings()[SESSION_COMMENTS_SETTING_KEY] === true;
|
|
}
|
|
|
|
export function setLinearSessionCommentsEnabled(enabled) {
|
|
const next = enabled === true;
|
|
const settings = readSettings();
|
|
settings[SESSION_COMMENTS_SETTING_KEY] = next;
|
|
writeSettings(settings);
|
|
return next;
|
|
}
|
|
|
|
export function getLinearAuthFilePath() {
|
|
return storageFile();
|
|
}
|
|
export const DEFAULT_LINEAR_CLIENT_ID_VALUE = DEFAULT_LINEAR_CLIENT_ID;
|