* refactor: add canonical turn projection pipeline for chat Centralizes turn/activity/summary derivation, migrates render consumers to shared projection sources, and adds projector regression coverage for retries, malformed parent fallbacks, and activity segmentation. * refactor: stream assistant text live in turn-first render path * refactor: complete phase-3 turn timeline history/navigation * refactor: complete phase-4 turn pipeline cutover Remove legacy grouping adapters and lock key edge cases with executable regression tests so turn-centric rendering stays stable across retry/history/navigation flows. * fix: align chat history loading path with opencode parity * fix: stabilize chat streaming and reduce render churn * feat: add blurIn streaming text animation and smooth lerp-based auto-scroll Streaming markdown now uses Streamdown blurIn animation (150ms, ease-out) for per-word reveal Auto-scroll during streaming uses continuous exponential smoothing (lerp) instead of restarting spring animations One-shot scroll-to-bottom (button click) uses motion spring for natural deceleration * fix: respect user scroll-up during streaming and re-pin on scroll back to bottom * fix: stabilize activity stream and tool progress rendering Activity now stays chronologically consistent and avoids duplicate reasoning/justification. Tool rows show running state and duration earlier with smoother pending behavior. Removed legacy trim/timestamp paths to prevent message drops and simplify Activity UI. * fix: reverted regression of revert functionality * fix: stabilize chat activity layout and tool progress behavior Stopped user messages from re-animating when new user messages appear. Made Activity and aggregated tool rows wrap inline consistently without misaligned headers/icons. Fixed tool part matching so duration and shine no longer reset across pending/in-progress status updates. * fix: restore activity mode behavior and stabilize tool rendering Re-enabled Collapsed/Summary/Detailed/Changes defaults for Activity and tool expansion. Fixed tool row wrapping/alignment, removed user fade re-animations, and disabled FadeInOnReveal animations. Improved tool status handling to reduce timer/shine resets and made reasoning bold render as normal text. * refactor: simplify chat tool and message rendering Replace activity-group rendering with flat inline part rendering Remove obsolete tool output and justification activity settings Keep user message animation and improve edit/apply-patch file path headers * style: narrow chat and composer columns equally * fix: Tool status checks and abort flow regression * fix: improve multi-file apply patch header rendering * fix: make timeline message jump scroll to selected chat entry Conversation Timeline clicks now reliably scroll to the selected message in chat Timeline dialog waits for navigation result before closing to avoid silent failures Chat message scrolling now resolves the active chat scroller consistently * chore: remove branch-added chat tests and clean lint leftovers Removes newly added chat and message test files from this branch Fixes lint blockers in ProgressiveGroup, ToolPart, and messageStore Keeps type-check, lint, and build passing after cleanup * fix: keep composer status row closest to the input Status/todo row now renders below queued messages and attachments. Linked GitHub issue/PR chips stay above status so input context order is consistent. Improves chat composer readability while assistant is working. * fix: disable assistant header animations and polish chat status behavior Assistant message header now renders without transition effects Removed a lint issue from the working placeholder props Chat status and message flow updates improve consistency during active turns * feat: increase bottom spacer in mobile chat for better scrolling * feat: add sorted chat mode with progressive activity rendering Adds global chat render mode settings for sorted and live behavior Renders non-stop assistant output in Activity as messages complete Disables streaming text animation in sorted mode and restores classic reasoning/justification blocks * fix: stabilize chat timeline navigation and older history loading Prevents auto-loading older history from scroll and keeps loading behind the button Fixes timeline jump-to-message behavior that snapped back to the bottom Reduces chat list flicker and empty-state glitches on large session pagination * fix: stabilize sorted activity text and hide reasoning timers Prevented sorted justification from appearing before message completion by requiring explicit non-stop finish. Removed duration values for sorted Thinking and Justification blocks. Kept smooth sorted auto-follow behavior tuned to reduce bottom-jump jitter. * refactor: simplify chat tool rendering paths and add parts docs Centralized tool icon mapping into a shared presentation helper used by grouped and expandable rows. Removed static-tool-specific branches from ToolPart to keep it focused on expandable tools. Added a new DOCUMENTATION.md explaining where to change tool descriptions and rendering behavior. * feat: enhance event stream handling for message parts - Refactor event key building functions to improve clarity and reduce redundancy. - Introduce `applyPartDelta` method in message store for handling delta updates to message parts. - Update `useEventStream` to utilize the new `applyPartDelta` method for processing incoming deltas. - Enhance text extraction logic to accommodate new part types and improve merging behavior. - Implement logic to skip delta-driven updates for ongoing text/reasoning parts to prevent overwriting. - Adjust server-side text merging logic to handle trimmed text comparisons and improve consistency. * feat: enhance OpencodeService with delta handling and stale delta management - Introduced globalSseStaleDeltas to track stale deltas. - Added methods to generate keys for delta and updated part events. - Updated global SSE loop to skip processing stale deltas. - Refactored global SSE event handling to improve performance and reliability. refactor: remove unused streaming part handling in messageStore - Eliminated streaming part queue and associated logic. - Simplified message merging logic by removing redundant checks. - Streamlined message handling to improve clarity and maintainability. chore: clean up unused streaming text normalization functions - Removed deprecated functions related to streaming text identity and merging. - Simplified normalizeStreamingTextPayload to focus on current functionality. * refactor: simplify streaming event passthrough Use SDK-native global event streaming in the UI client Remove dead server-side SSE normalization helpers Keep streaming payloads closer to upstream behavior * revert: remove message memory settings UI Drop the restored message memory settings screen Keep session settings focused on current defaults Preserve chat history limits as internal behavior * feat: add compact collapsed Activity preview in sorted mode Collapsed Activity now shows a live preview of the latest 7 entries Older activity rows roll up behind a +N more indicator The +N more indicator is clickable to expand the full Activity * fix: adjusted activity changed files text prominence * fix: make sorted mode snap to bottom when not streaming * perf: show chat scrollbar only on user-driven scrolling Chat scrollbar now stays hidden during automatic follow-to-bottom Scrollbar visibility is gated by real user scroll intent Reduced scroll overhead by removing timer-based intent tracking * refactor: align web and vscode session activity streaming Route VS Code SSE through SDK-based proxy flow Restore controlled web session activity tracking and cooldowns Keep chat activity behavior consistent across runtimes * fix: adjusted muted foreground themes color * fix: stabilize session activity and attention updates Keep streamed chat state in sync as sessions complete Restore reliable attention indicators for inactive sessions Tighten server and UI event handling for chat updates * feat: add chat render previews and file icon visibility setting Added animated chat render mode previews in Chat settings. Added a new toggle to show or hide file icons across tool rows. Persisted chat render, activity, and mermaid modes to shared settings file. * fix: update default GitHub OAuth client ID Use the new OpenChamber org GitHub OAuth app ID by default. Keep web server and VS Code auth defaults in sync. * fix: sync chat settings across VS Code chat views Broadcast settings changes to both sidebar and editor chat webviews. Apply synced settings in each webview via shared settings refresh. Ensures chat render mode updates appear immediately in editor tabs. * fix: stop writing session folders file in VS Code workspaces Disable disk persistence for session folders in VS Code webview runtime Keep session folder state in VS Code/webview storage instead of project files Preserve existing behavior for non-VS Code runtimes * style: polish expanded tool panels and bash output readability Removed extra borders/labels in expanded tool cards for a cleaner UI Added softer scroll shadows and full-height decorative activity line Switched bash command/output to code-style typography with tighter spacing * feat: add default-open tool controls for chat activity Added Chat settings toggles to open Bash and Edit tools by default Default-open behavior now applies across both sorted and live activity rendering Users can still manually collapse default-open tools, plus bash output height was reduced * fix: align chat loading skeleton with message layout Match skeleton width and horizontal alignment to chat message column Add one-line tool-style skeleton rows with subtle circular placeholders Increase top spacing so loading state no longer touches chat header * fix: prevent blank screen when adding inline diff comments Sanitize persisted inline comment drafts to ignore invalid data Harden diff annotations against malformed line numbers Fail safely when annotation updates error instead of crashing the view * fix: streamline VS Code archived sessions sidebar Show archived sessions in VS Code only for the active workspace directory. Render archived sessions as a flat list in VS Code without project-root subfolders. Hide the "Open in Side Panel" session action in VS Code.
308 lines
8.1 KiB
JavaScript
308 lines
8.1 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import os from 'os';
|
|
|
|
const OPENCHAMBER_DATA_DIR = process.env.OPENCHAMBER_DATA_DIR
|
|
? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
|
|
: path.join(os.homedir(), '.config', 'openchamber');
|
|
|
|
const STORAGE_DIR = OPENCHAMBER_DATA_DIR;
|
|
const STORAGE_FILE = path.join(STORAGE_DIR, 'github-auth.json');
|
|
const SETTINGS_FILE = path.join(OPENCHAMBER_DATA_DIR, 'settings.json');
|
|
|
|
const DEFAULT_GITHUB_CLIENT_ID = 'Ov23lizomPOC3eFYo56r';
|
|
const DEFAULT_GITHUB_SCOPES = 'repo read:org workflow read:user user:email';
|
|
|
|
function ensureStorageDir() {
|
|
if (!fs.existsSync(STORAGE_DIR)) {
|
|
fs.mkdirSync(STORAGE_DIR, { recursive: true });
|
|
}
|
|
}
|
|
|
|
function readJsonFile() {
|
|
ensureStorageDir();
|
|
if (!fs.existsSync(STORAGE_FILE)) {
|
|
return null;
|
|
}
|
|
try {
|
|
const raw = fs.readFileSync(STORAGE_FILE, 'utf8');
|
|
const trimmed = raw.trim();
|
|
if (!trimmed) {
|
|
return null;
|
|
}
|
|
const parsed = JSON.parse(trimmed);
|
|
if (!parsed || typeof parsed !== 'object') {
|
|
return null;
|
|
}
|
|
return parsed;
|
|
} catch (error) {
|
|
console.error('Failed to read GitHub auth file:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function writeJsonFile(payload) {
|
|
ensureStorageDir();
|
|
|
|
// Atomic write so multiple OpenChamber instances can safely share the same file.
|
|
const tmpFile = `${STORAGE_FILE}.${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, STORAGE_FILE);
|
|
try {
|
|
fs.chmodSync(STORAGE_FILE, 0o600);
|
|
} catch {
|
|
// best-effort
|
|
}
|
|
}
|
|
|
|
function resolveAccountId({ user, accessToken, accountId }) {
|
|
if (typeof accountId === 'string' && accountId.trim()) {
|
|
return accountId.trim();
|
|
}
|
|
if (user && typeof user.login === 'string' && user.login.trim()) {
|
|
return user.login.trim();
|
|
}
|
|
if (user && typeof user.id === 'number') {
|
|
return String(user.id);
|
|
}
|
|
if (typeof accessToken === 'string' && accessToken.trim()) {
|
|
return `token:${accessToken.slice(0, 8)}`;
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function normalizeAuthEntry(entry) {
|
|
if (!entry || typeof entry !== 'object') return null;
|
|
const accessToken = typeof entry.accessToken === 'string' ? entry.accessToken : '';
|
|
if (!accessToken) return null;
|
|
const user = entry.user && typeof entry.user === 'object'
|
|
? {
|
|
login: typeof entry.user.login === 'string' ? entry.user.login : null,
|
|
avatarUrl: typeof entry.user.avatarUrl === 'string' ? entry.user.avatarUrl : null,
|
|
id: typeof entry.user.id === 'number' ? entry.user.id : null,
|
|
name: typeof entry.user.name === 'string' ? entry.user.name : null,
|
|
email: typeof entry.user.email === 'string' ? entry.user.email : null,
|
|
}
|
|
: null;
|
|
|
|
const accountId = resolveAccountId({
|
|
user,
|
|
accessToken,
|
|
accountId: typeof entry.accountId === 'string' ? entry.accountId : '',
|
|
});
|
|
|
|
return {
|
|
accessToken,
|
|
scope: typeof entry.scope === 'string' ? entry.scope : '',
|
|
tokenType: typeof entry.tokenType === 'string' ? entry.tokenType : 'bearer',
|
|
createdAt: typeof entry.createdAt === 'number' ? entry.createdAt : null,
|
|
user,
|
|
current: Boolean(entry.current),
|
|
accountId,
|
|
};
|
|
}
|
|
|
|
function normalizeAuthList(raw) {
|
|
const list = (Array.isArray(raw) ? raw : [raw])
|
|
.map((entry) => normalizeAuthEntry(entry))
|
|
.filter(Boolean);
|
|
|
|
if (!list.length) {
|
|
return { list: [], changed: false };
|
|
}
|
|
|
|
let changed = false;
|
|
let currentFound = false;
|
|
list.forEach((entry) => {
|
|
if (entry.current && !currentFound) {
|
|
currentFound = true;
|
|
} else if (entry.current && currentFound) {
|
|
entry.current = false;
|
|
changed = true;
|
|
}
|
|
});
|
|
|
|
if (!currentFound && list[0]) {
|
|
list[0].current = true;
|
|
changed = true;
|
|
}
|
|
|
|
list.forEach((entry) => {
|
|
if (!entry.accountId) {
|
|
entry.accountId = resolveAccountId(entry);
|
|
changed = true;
|
|
}
|
|
});
|
|
|
|
return { list, changed };
|
|
}
|
|
|
|
function readAuthList() {
|
|
const data = readJsonFile();
|
|
if (!data) {
|
|
return [];
|
|
}
|
|
const { list, changed } = normalizeAuthList(data);
|
|
if (changed) {
|
|
writeJsonFile(list);
|
|
}
|
|
return list;
|
|
}
|
|
|
|
function writeAuthList(list) {
|
|
writeJsonFile(list);
|
|
}
|
|
|
|
export function getGitHubAuth() {
|
|
const list = readAuthList();
|
|
if (!list.length) {
|
|
return null;
|
|
}
|
|
const current = list.find((entry) => entry.current) || list[0];
|
|
if (!current?.accessToken) {
|
|
return null;
|
|
}
|
|
return current;
|
|
}
|
|
|
|
export function getGitHubAuthAccounts() {
|
|
const list = readAuthList();
|
|
return list
|
|
.filter((entry) => entry?.user && entry.accountId)
|
|
.map((entry) => ({
|
|
id: entry.accountId,
|
|
user: entry.user,
|
|
scope: entry.scope || '',
|
|
current: Boolean(entry.current),
|
|
}));
|
|
}
|
|
|
|
export function setGitHubAuth({ accessToken, scope, tokenType, user, accountId }) {
|
|
if (!accessToken || typeof accessToken !== 'string') {
|
|
throw new Error('accessToken is required');
|
|
}
|
|
const normalizedUser = user && typeof user === 'object'
|
|
? {
|
|
login: typeof user.login === 'string' ? user.login : undefined,
|
|
avatarUrl: typeof user.avatarUrl === 'string' ? user.avatarUrl : undefined,
|
|
id: typeof user.id === 'number' ? user.id : undefined,
|
|
name: typeof user.name === 'string' ? user.name : undefined,
|
|
email: typeof user.email === 'string' ? user.email : undefined,
|
|
}
|
|
: undefined;
|
|
|
|
const resolvedAccountId = resolveAccountId({
|
|
user: normalizedUser,
|
|
accessToken,
|
|
accountId,
|
|
});
|
|
|
|
const list = readAuthList();
|
|
const existingIndex = list.findIndex((entry) => entry.accountId === resolvedAccountId);
|
|
const nextEntry = {
|
|
accessToken,
|
|
scope: typeof scope === 'string' ? scope : '',
|
|
tokenType: typeof tokenType === 'string' ? tokenType : 'bearer',
|
|
createdAt: Date.now(),
|
|
user: normalizedUser || null,
|
|
current: true,
|
|
accountId: resolvedAccountId,
|
|
};
|
|
|
|
if (existingIndex >= 0) {
|
|
list[existingIndex] = nextEntry;
|
|
} else {
|
|
list.push(nextEntry);
|
|
}
|
|
|
|
list.forEach((entry, index) => {
|
|
entry.current = index === (existingIndex >= 0 ? existingIndex : list.length - 1);
|
|
});
|
|
writeAuthList(list);
|
|
return nextEntry;
|
|
}
|
|
|
|
export function activateGitHubAuth(accountId) {
|
|
if (typeof accountId !== 'string' || !accountId.trim()) {
|
|
return false;
|
|
}
|
|
const list = readAuthList();
|
|
const index = list.findIndex((entry) => entry.accountId === accountId.trim());
|
|
if (index === -1) {
|
|
return false;
|
|
}
|
|
list.forEach((entry, idx) => {
|
|
entry.current = idx === index;
|
|
});
|
|
writeAuthList(list);
|
|
return true;
|
|
}
|
|
|
|
export function clearGitHubAuth() {
|
|
try {
|
|
const list = readAuthList();
|
|
if (!list.length) {
|
|
return true;
|
|
}
|
|
const remaining = list.filter((entry) => !entry.current);
|
|
if (!remaining.length) {
|
|
if (fs.existsSync(STORAGE_FILE)) {
|
|
fs.unlinkSync(STORAGE_FILE);
|
|
}
|
|
return true;
|
|
}
|
|
remaining.forEach((entry, index) => {
|
|
entry.current = index === 0;
|
|
});
|
|
writeAuthList(remaining);
|
|
return true;
|
|
} catch (error) {
|
|
console.error('Failed to clear GitHub auth file:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export function getGitHubClientId() {
|
|
const raw = process.env.OPENCHAMBER_GITHUB_CLIENT_ID;
|
|
const clientId = typeof raw === 'string' ? raw.trim() : '';
|
|
if (clientId) return clientId;
|
|
|
|
try {
|
|
if (fs.existsSync(SETTINGS_FILE)) {
|
|
const parsed = JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8'));
|
|
const stored = typeof parsed?.githubClientId === 'string' ? parsed.githubClientId.trim() : '';
|
|
if (stored) return stored;
|
|
}
|
|
} catch {
|
|
// ignore
|
|
}
|
|
|
|
return DEFAULT_GITHUB_CLIENT_ID;
|
|
}
|
|
|
|
export function getGitHubScopes() {
|
|
const raw = process.env.OPENCHAMBER_GITHUB_SCOPES;
|
|
const fromEnv = typeof raw === 'string' ? raw.trim() : '';
|
|
if (fromEnv) return fromEnv;
|
|
|
|
try {
|
|
if (fs.existsSync(SETTINGS_FILE)) {
|
|
const parsed = JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8'));
|
|
const stored = typeof parsed?.githubScopes === 'string' ? parsed.githubScopes.trim() : '';
|
|
if (stored) return stored;
|
|
}
|
|
} catch {
|
|
// ignore
|
|
}
|
|
|
|
return DEFAULT_GITHUB_SCOPES;
|
|
}
|
|
|
|
export const GITHUB_AUTH_FILE = STORAGE_FILE;
|