feat(ui): context panel 2.0 - surface rail, changes-first git view, live PR surface (#2418)
* feat(ui): add context surface registry and rail switcher * feat(ui): move git and project notes into context surfaces, embed editor file tree * feat(ui): replace right sidebar with context surfaces, per-surface panel widths * refactor(ui): retire legacy main-tab overlays and right-sidebar state * feat(ui): rail polish, right-docked file tree, terminal surface * feat(ui): move terminal into context surface, per-surface tab closing, editor empty state * feat(ui): tune default rail order and activity dot * fix(ui): keep context panel controls anchored during width animations * feat(ui): lazy-follow context panel resize with window-level drag tracking * feat(ui): panel dividers, right-dock tree icon, muted outline folder icons * feat(ui): restructure git view into changes-first surface with standalone PR surface - Remove commit/update/pr tabs; git view is always changes + commit - Promote pull request to its own rail surface with shared repo context - Move update-branch and re-integrate flows into separate dialogs - Add PR status chip and repo actions menu to the git header row - Seed new PR-status entries from resolved sibling remotes to avoid a false "checking status" state when the PR is already known - History/graph dialog refresh button, fingerprint global identity icon, muted outline folder icons follow-ups * feat(ui): progressive-disclosure PR surface with live checks and pinned chat context - Segment the PR surface into Overview / Checks / Comments pill tabs with live badges; merge controls move to the status row - Live checks segment: progress bar, per-run rows with workflow names, elapsed timers, expandable failures, auto-refresh while pending - PR comments and failed checks pin as chat-context drafts (like terminal selections) instead of sending an immediate message; works on new-session drafts too - Shared prContext cache client+server, ETag conditional requests in the octokit wrapper (304s bypass rate limits), extended checks aggregate (inProgress/queued/startedAt) - Resolve gh-CLI auth login for merge-permission checks - Full-width description editor with matched control heights * fix(ui): single source of truth for PR checks and status readers - Derive the checks aggregate from the visible run list and sync it into the PR-status store so bar, badges, header, and git-view chip agree - Route PR body hydration through the shared context cache - Git-view PR chip reads the freshest entry across remote keys * fix(github): freshness stamps prevent stale cache responses from regressing PR state - pr/status and pulls/context responses carry a server-side fetchedAt that survives cache serves - The status store rejects responses older than the held snapshot (only clearing the loading flag), and the checks sync adopts the context's stamp so stale status polls cannot flip fresher derived checks - Regression test for the stale-response guard * perf(github): repo-level pull-list cache collapses per-branch PR resolution - One pulls.list per repo per state per 45s answers every branch (10 worktrees = 1 call, not 10 query fans); in-flight fetches coalesce - A complete repo list makes a no-PR miss authoritative, skipping the per-owner head queries AND the Search API fallback (the 30/min killer) - force refresh bypasses the repo list cache; PR create/merge/ready invalidate it * perf(github): back off Search API misses per repo+branch A branch without a PR re-searched on every poll; with >100 closed PRs the list miss is never authoritative, so the search fallback still ran and burned the 30/min search quota. Remember misses for 10 minutes; PR creation clears remembered misses for the repo. * fix(github): dedupe re-run check runs to the latest per (app, name) listForRef returns the superseded completed run alongside its re-run; GitHub's UI shows only the latest per name. Mirror that in both pr/status and pulls/context so counts and run lists match github.com. * fix(ui): address review findings on registry test, surface docs, and PR-context keys - Rail-order test asserts against the registry itself (was stale after the 'pr' surface landed and failed) - surfaces DOCUMENTATION.md describes actual behavior: has-content surfaces hide until content exists; only multi-instance/terminal panes are keep-alive, singleton surfaces remount and restore from stores - PR-context cache keys are runtime-scoped JSON tuples; invalidation compares the directory exactly instead of by string prefix (+ test) * fix(ui): wrap long unbreakable tokens in check-run details Annotation messages with long SHAs/URLs overflowed the panel; break-words on annotation title/message/rawDetails and output summary/text, and the expanded run body clips instead of widening the panel. * fix(ui): busy state for context-attach buttons and honest attach labels - 'Attach failed checks' / 'Attach all to chat' show a spinner and disable while the context request runs (previously nothing happened for seconds) - Action labels/tooltips reworded from send-to-agent to attach-to-chat semantics across all locales * fix(i18n): Ukrainian attach wording uses 'прикріпити' with proper cases * fix(ui): runtime-scope PR-view remote caches, correct surfaces doc on preview - Remote/remote-url caches in PullRequestView are keyed by runtime + directory so a backend switch never serves another runtime's remotes - surfaces DOCUMENTATION.md: preview is not keep-alive; preview tabs remount on switch like singleton surfaces * fix(ui): rail active color, clearer collapse icon, remove dead bottom-terminal dock Design-review feedback on the context panel: - Context rail: icons enlarged 16px -> 18px; the active surface is now highlighted with the primary color only (no background, no scale animation), replacing the previous scale-up effect that read as a resize rather than a selected state. - Files tree: the icon-only 'collapse all folders' toolbar button now uses collapse-vertical instead of contract-up-down, which was easily mistaken for a close button. The labelled 'Collapse all' dropdown item in the session sidebar keeps its icon since text removes the ambiguity. - Terminal: removed the leftover bottom-dock expand/close buttons that rendered in the context-panel terminal but controlled a dock that no longer exists (nothing toggles it anymore), so the expand button appeared to do nothing and duplicated the panel-header fullscreen control. Cleaned up the entire inert layer with it: four useUIStore fields (isBottomTerminalOpen/Expanded, bottomTerminalHeight, hasManuallyResizedBottomTerminal), five actions, their persistence, the MainLayout resize listener that only served the dock height, the dock-driven refit effect in TerminalView, and the terminalView.bottomDock.* keys across all 10 locale dictionaries. Validated: ui type-check and lint clean; messages parity test (2 pass) and useUIStore contextPanel test (13 pass) green; icon sprite regenerated via icons:generate. * refactor: use PR visual state for git header icon Derives the pull request icon color from a single visual state Covers merged, closed, draft, blocked, and open PR states Removes conditional class handling from the git header icon
This commit is contained in:
committed by
GitHub
parent
005b2e61b0
commit
e2fa7dbad2
@@ -147,7 +147,7 @@ These rules are important. Breaking them tends to reintroduce idle CPU churn, st
|
||||
4. Prefer store `ensure*` methods over direct runtime API calls from views.
|
||||
5. Visible consumers should drive refresh. Hidden consumers should not.
|
||||
6. Header should not depend on PR store.
|
||||
7. Closed sidebar should not create live PR work.
|
||||
7. A closed context panel (or hidden git surface) should not create live PR work.
|
||||
8. File tree Git status should update only when the file tree is visible.
|
||||
9. Global session refresh must remain bounded and failure-isolated per directory.
|
||||
10. Global session cache must not drive live activity indicators or message-loading state.
|
||||
|
||||
@@ -25,6 +25,7 @@ type FilesViewTabsActions = {
|
||||
setSelectedPath: (root: string, path: string | null, options?: { allowOutsideRoot?: boolean }) => void;
|
||||
ensureSelectedPath: (root: string) => void;
|
||||
toggleExpandedPath: (root: string, path: string) => void;
|
||||
collapseAllExpandedPaths: (root: string) => void;
|
||||
expandPath: (root: string, path: string) => void;
|
||||
expandPaths: (root: string, paths: string[]) => void;
|
||||
resetForRuntimeSwitch: (runtimeKey: string) => void;
|
||||
@@ -417,6 +418,29 @@ export const useFilesViewTabsStore = create<FilesViewTabsStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
collapseAllExpandedPaths: (root) => {
|
||||
const normalizedRoot = normalizePath((root || '').trim());
|
||||
if (!normalizedRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
set((state) => {
|
||||
const prev = state.byRoot[normalizedRoot];
|
||||
if (!prev || prev.expandedPaths.length === 0) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const byRoot = {
|
||||
...state.byRoot,
|
||||
[normalizedRoot]: {
|
||||
...touchRoot(prev),
|
||||
expandedPaths: [],
|
||||
},
|
||||
};
|
||||
return { byRoot: clampRoots(byRoot, MAX_ROOTS) };
|
||||
});
|
||||
},
|
||||
|
||||
expandPath: (root, path) => {
|
||||
const normalizedRoot = normalizePath((root || '').trim());
|
||||
const normalizedPath = normalizePath((path || '').trim());
|
||||
|
||||
@@ -136,4 +136,33 @@ describe("GitHub PR status cache ownership", () => {
|
||||
expect(staleRequestCount).toBe(0)
|
||||
expect(replacementRequestCount).toBe(1)
|
||||
})
|
||||
|
||||
test("rejects a server-cached response older than the held status", async () => {
|
||||
const newer: GitHubPullRequestStatus = {
|
||||
connected: true,
|
||||
fetchedAt: 2_000,
|
||||
pr: { number: 7, title: "t", url: "u", state: "open", draft: false, base: "main", head: "f" },
|
||||
checks: { state: "pending", total: 3, success: 2, failure: 0, pending: 1 },
|
||||
}
|
||||
const older: GitHubPullRequestStatus = {
|
||||
...newer,
|
||||
fetchedAt: 1_000,
|
||||
checks: { state: "success", total: 3, success: 3, failure: 0, pending: 0 },
|
||||
}
|
||||
|
||||
const responses = [newer, older]
|
||||
const github = { prStatus: async () => responses.shift()! } as unknown as RuntimeAPIs["github"]
|
||||
const key = getGitHubPrStatusKey("/repo", "main", "origin")
|
||||
useGitHubPrStatusStore.getState().ensureEntry(key)
|
||||
useGitHubPrStatusStore.getState().setParams(key, params(github))
|
||||
|
||||
await useGitHubPrStatusStore.getState().refresh(key, { force: true })
|
||||
expect(useGitHubPrStatusStore.getState().entries[key]?.status?.checks?.pending).toBe(1)
|
||||
|
||||
await useGitHubPrStatusStore.getState().refresh(key, { force: true })
|
||||
const held = useGitHubPrStatusStore.getState().entries[key]?.status
|
||||
expect(held?.fetchedAt).toBe(2_000)
|
||||
expect(held?.checks?.pending).toBe(1)
|
||||
expect(useGitHubPrStatusStore.getState().entries[key]?.isLoading).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -179,6 +179,90 @@ const getSignatureFromEntry = (entry: PrStatusEntry | null | undefined): string
|
||||
return JSON.stringify([identity.runtimeKey, identity.directory, identity.branch, identity.remoteName ?? 'auto']);
|
||||
};
|
||||
|
||||
const parseStatusKey = (key: string): { runtimeKey: string; directory: string; branch: string; remote: string } | null => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(key);
|
||||
if (!Array.isArray(parsed) || parsed.length !== 4 || parsed.some((part) => typeof part !== 'string')) {
|
||||
return null;
|
||||
}
|
||||
const [runtimeKey, directory, branch, remote] = parsed as [string, string, string, string];
|
||||
return { runtimeKey, directory, branch, remote };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Best already-resolved entry for the same directory+branch under a different
|
||||
* remote key. Used to seed a freshly created entry so switching remote keys
|
||||
* (e.g. 'auto' -> 'origin') shows the known PR immediately instead of a
|
||||
* "checking status" flash; the entry's own refresh remains authoritative.
|
||||
*/
|
||||
const findResolvedSiblingEntry = (
|
||||
entries: Record<string, PrStatusEntry>,
|
||||
key: string,
|
||||
): PrStatusEntry | null => {
|
||||
const target = parseStatusKey(key);
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let fallback: PrStatusEntry | null = null;
|
||||
for (const [entryKey, entry] of Object.entries(entries)) {
|
||||
if (entryKey === key || !entry.isInitialStatusResolved || !entry.status) {
|
||||
continue;
|
||||
}
|
||||
const parsed = parseStatusKey(entryKey);
|
||||
if (!parsed
|
||||
|| parsed.runtimeKey !== target.runtimeKey
|
||||
|| parsed.directory !== target.directory
|
||||
|| parsed.branch !== target.branch) {
|
||||
continue;
|
||||
}
|
||||
const resolvedRemote = entry.resolvedRemoteName ?? entry.status.resolvedRemoteName ?? null;
|
||||
if (target.remote !== 'auto' && resolvedRemote && resolvedRemote !== target.remote) {
|
||||
continue;
|
||||
}
|
||||
if (parsed.remote === 'auto') {
|
||||
return entry;
|
||||
}
|
||||
fallback = fallback ?? entry;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
};
|
||||
|
||||
/**
|
||||
* Freshest known status for a directory+branch across ALL remote-keyed
|
||||
* entries. Passive readers (e.g. the git-view PR chip) should use this
|
||||
* instead of a single key: the entry being actively watched/refreshed may be
|
||||
* keyed by a concrete remote while the 'auto' entry goes stale.
|
||||
*/
|
||||
export const getFreshestPrStatusForBranch = (
|
||||
entries: Record<string, PrStatusEntry>,
|
||||
directory: string,
|
||||
branch: string,
|
||||
): GitHubPullRequestStatus | null => {
|
||||
const runtimeKey = getRuntimeKey();
|
||||
let best: PrStatusEntry | null = null;
|
||||
for (const [key, entry] of Object.entries(entries)) {
|
||||
if (!entry.status) {
|
||||
continue;
|
||||
}
|
||||
const parsed = parseStatusKey(key);
|
||||
if (!parsed
|
||||
|| parsed.runtimeKey !== runtimeKey
|
||||
|| parsed.directory !== directory
|
||||
|| parsed.branch !== branch) {
|
||||
continue;
|
||||
}
|
||||
if (!best || entry.lastRefreshAt > best.lastRefreshAt) {
|
||||
best = entry;
|
||||
}
|
||||
}
|
||||
return best?.status ?? null;
|
||||
};
|
||||
|
||||
const getKeysBySignature = (entries: Record<string, PrStatusEntry>, signature: string): string[] => {
|
||||
return Object.entries(entries)
|
||||
.filter(([, entry]) => getSignatureFromEntry(entry) === signature)
|
||||
@@ -331,10 +415,19 @@ export const useGitHubPrStatusStore = create<GitHubPrStatusStore>()(
|
||||
if (state.entries[key]) {
|
||||
return state;
|
||||
}
|
||||
const sibling = findResolvedSiblingEntry(state.entries, key);
|
||||
const seeded: PrStatusEntry = sibling
|
||||
? {
|
||||
...createEntry(),
|
||||
status: sibling.status,
|
||||
isInitialStatusResolved: true,
|
||||
resolvedRemoteName: sibling.resolvedRemoteName ?? sibling.status?.resolvedRemoteName ?? null,
|
||||
}
|
||||
: createEntry();
|
||||
return {
|
||||
entries: boundEntries({
|
||||
...state.entries,
|
||||
[key]: createEntry(),
|
||||
[key]: seeded,
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -615,6 +708,25 @@ export const useGitHubPrStatusStore = create<GitHubPrStatusStore>()(
|
||||
return;
|
||||
}
|
||||
|
||||
// Freshness guard: the server may serve this response from its
|
||||
// cache. If we already hold newer data (e.g. checks derived
|
||||
// from a fresher pulls/context fetch), keep it and only clear
|
||||
// the loading flag — never regress to an older snapshot.
|
||||
const currentFetchedAt = current.status?.fetchedAt;
|
||||
const nextFetchedAt = next.fetchedAt;
|
||||
if (typeof currentFetchedAt === 'number'
|
||||
&& typeof nextFetchedAt === 'number'
|
||||
&& nextFetchedAt < currentFetchedAt) {
|
||||
nextEntries[signatureKey] = {
|
||||
...current,
|
||||
error: null,
|
||||
isLoading: options?.silent ? current.isLoading : false,
|
||||
isInitialStatusResolved: options?.markInitialResolved === false ? current.isInitialStatusResolved : true,
|
||||
lastRefreshAt: Date.now(),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const prevPr = current.status?.pr;
|
||||
const nextPr = next.pr;
|
||||
const shouldCarryBody = Boolean(
|
||||
|
||||
@@ -108,7 +108,7 @@ export const useGitIdentitiesStore = create<GitIdentitiesStore>()(
|
||||
authType: data.sshCommand ? 'ssh' : undefined,
|
||||
sshKey: data.sshCommand ? data.sshCommand.replace('ssh -i ', '') : null,
|
||||
color: 'info',
|
||||
icon: 'house'
|
||||
icon: 'fingerprint'
|
||||
};
|
||||
set({ globalIdentity: globalProfile });
|
||||
} else {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { getRuntimeKey } from '@/lib/runtime-switch';
|
||||
import { normalizePath } from '@/lib/pathNormalization';
|
||||
import { createDeferredSafeJSONStorage } from './utils/safeStorage';
|
||||
|
||||
export type InlineCommentSource = 'diff' | 'plan' | 'file' | 'preview-console' | 'preview-annotation' | 'terminal';
|
||||
export type InlineCommentSource = 'diff' | 'plan' | 'file' | 'preview-console' | 'preview-annotation' | 'terminal' | 'pr-comment' | 'pr-check';
|
||||
|
||||
export type InlineCommentDraftTarget = {
|
||||
directory: string;
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { usePrContextStore, getPrContextKey } from './usePrContextStore';
|
||||
import type { GitHubAPI, GitHubPullRequestContextResult } from '@/lib/api/types';
|
||||
|
||||
const makeGithub = (result: GitHubPullRequestContextResult) => {
|
||||
let calls = 0;
|
||||
const prContext = async () => {
|
||||
calls += 1;
|
||||
return result;
|
||||
};
|
||||
return { github: { prContext } as unknown as GitHubAPI, callCount: () => calls };
|
||||
};
|
||||
|
||||
const RESULT: GitHubPullRequestContextResult = {
|
||||
connected: true,
|
||||
pr: null,
|
||||
issueComments: [],
|
||||
reviewComments: [],
|
||||
};
|
||||
|
||||
describe('usePrContextStore', () => {
|
||||
test('caches within TTL and dedupes plain requests after a detailed one', async () => {
|
||||
const { github, callCount } = makeGithub(RESULT);
|
||||
const { ensure } = usePrContextStore.getState();
|
||||
|
||||
const first = await ensure(github, '/repo-a', 1, { includeCheckDetails: true });
|
||||
expect(first).toEqual(RESULT);
|
||||
expect(callCount()).toBe(1);
|
||||
|
||||
// Fresh cache satisfies both detailed and plain requests.
|
||||
await ensure(github, '/repo-a', 1, { includeCheckDetails: true });
|
||||
await ensure(github, '/repo-a', 1);
|
||||
expect(callCount()).toBe(1);
|
||||
|
||||
// force bypasses the cache.
|
||||
await ensure(github, '/repo-a', 1, { includeCheckDetails: true, force: true });
|
||||
expect(callCount()).toBe(2);
|
||||
});
|
||||
|
||||
test('a plain cached result does not satisfy a detailed request', async () => {
|
||||
const { github, callCount } = makeGithub(RESULT);
|
||||
const { ensure } = usePrContextStore.getState();
|
||||
|
||||
await ensure(github, '/repo-b', 2);
|
||||
await ensure(github, '/repo-b', 2, { includeCheckDetails: true });
|
||||
expect(callCount()).toBe(2);
|
||||
});
|
||||
|
||||
test('concurrent callers share one in-flight request', async () => {
|
||||
const { github, callCount } = makeGithub(RESULT);
|
||||
const { ensure } = usePrContextStore.getState();
|
||||
|
||||
const [a, b] = await Promise.all([
|
||||
ensure(github, '/repo-c', 3, { includeCheckDetails: true }),
|
||||
ensure(github, '/repo-c', 3, { includeCheckDetails: true }),
|
||||
]);
|
||||
expect(a).toEqual(RESULT);
|
||||
expect(b).toEqual(RESULT);
|
||||
expect(callCount()).toBe(1);
|
||||
});
|
||||
|
||||
test('invalidate clears the entry so the next ensure refetches', async () => {
|
||||
const { github, callCount } = makeGithub(RESULT);
|
||||
const { ensure, invalidate } = usePrContextStore.getState();
|
||||
|
||||
await ensure(github, '/repo-d', 4);
|
||||
invalidate('/repo-d', 4);
|
||||
expect(usePrContextStore.getState().entries[getPrContextKey('/repo-d', 4)] ?? null).toBe(null);
|
||||
await ensure(github, '/repo-d', 4);
|
||||
expect(callCount()).toBe(2);
|
||||
});
|
||||
|
||||
test('invalidate matches the directory exactly, not by prefix', async () => {
|
||||
const { github } = makeGithub(RESULT);
|
||||
const { ensure, invalidate } = usePrContextStore.getState();
|
||||
|
||||
await ensure(github, '/repo', 1);
|
||||
await ensure(github, '/repo-beta', 1);
|
||||
invalidate('/repo');
|
||||
|
||||
expect(usePrContextStore.getState().entries[getPrContextKey('/repo', 1)] ?? null).toBe(null);
|
||||
expect(usePrContextStore.getState().entries[getPrContextKey('/repo-beta', 1)]?.result).toEqual(RESULT);
|
||||
});
|
||||
|
||||
test('failed fetch records the error and returns null', async () => {
|
||||
const github = { prContext: async () => { throw new Error('boom'); } } as unknown as GitHubAPI;
|
||||
const { ensure } = usePrContextStore.getState();
|
||||
|
||||
const result = await ensure(github, '/repo-e', 5);
|
||||
expect(result).toBeNull();
|
||||
const entry = usePrContextStore.getState().entries[getPrContextKey('/repo-e', 5)];
|
||||
expect(entry?.error).toBe('boom');
|
||||
expect(entry?.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import { create } from 'zustand';
|
||||
import { getRuntimeKey } from '@/lib/runtime-switch';
|
||||
import type {
|
||||
GitHubAPI,
|
||||
GitHubPullRequestContextResult,
|
||||
GitHubRepoSelector,
|
||||
} from '@/lib/api/types';
|
||||
|
||||
const PR_CONTEXT_TTL_MS = 30_000;
|
||||
const PR_CONTEXT_MAX_ENTRIES = 20;
|
||||
|
||||
// JSON tuple key: runtime-scoped (a runtime switch must never serve another
|
||||
// backend's data) and parseable, so invalidation can compare the directory
|
||||
// exactly instead of by string prefix.
|
||||
export const getPrContextKey = (directory: string, number: number): string =>
|
||||
JSON.stringify([getRuntimeKey(), directory, number]);
|
||||
|
||||
const parsePrContextKey = (key: string): { runtimeKey: string; directory: string; number: number } | null => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(key);
|
||||
if (!Array.isArray(parsed) || parsed.length !== 3) {
|
||||
return null;
|
||||
}
|
||||
const [runtimeKey, directory, number] = parsed;
|
||||
if (typeof runtimeKey !== 'string' || typeof directory !== 'string' || typeof number !== 'number') {
|
||||
return null;
|
||||
}
|
||||
return { runtimeKey, directory, number };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
type PrContextEntry = {
|
||||
result: GitHubPullRequestContextResult | null;
|
||||
/** Whether `result` was fetched with check details included. */
|
||||
hasCheckDetails: boolean;
|
||||
fetchedAt: number;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
type EnsureOptions = {
|
||||
includeCheckDetails?: boolean;
|
||||
sourceRepo?: GitHubRepoSelector | null;
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
interface PrContextStoreState {
|
||||
entries: Record<string, PrContextEntry>;
|
||||
/**
|
||||
* Fetch (or reuse) the PR context for directory#number. Deduplicates
|
||||
* concurrent callers and serves a fresh-enough cached result; a
|
||||
* details-inclusive result satisfies detail-free requests.
|
||||
*/
|
||||
ensure: (
|
||||
github: GitHubAPI,
|
||||
directory: string,
|
||||
number: number,
|
||||
options?: EnsureOptions,
|
||||
) => Promise<GitHubPullRequestContextResult | null>;
|
||||
invalidate: (directory: string, number?: number) => void;
|
||||
}
|
||||
|
||||
const createEntry = (): PrContextEntry => ({
|
||||
result: null,
|
||||
hasCheckDetails: false,
|
||||
fetchedAt: 0,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const inFlight = new Map<string, Promise<GitHubPullRequestContextResult | null>>();
|
||||
|
||||
const boundEntries = (entries: Record<string, PrContextEntry>): Record<string, PrContextEntry> => {
|
||||
const all = Object.entries(entries);
|
||||
if (all.length <= PR_CONTEXT_MAX_ENTRIES) return entries;
|
||||
return Object.fromEntries(all
|
||||
.sort(([, left], [, right]) => right.fetchedAt - left.fetchedAt)
|
||||
.slice(0, PR_CONTEXT_MAX_ENTRIES));
|
||||
};
|
||||
|
||||
export const usePrContextStore = create<PrContextStoreState>()((set, get) => ({
|
||||
entries: {},
|
||||
|
||||
ensure: async (github, directory, number, options) => {
|
||||
const key = getPrContextKey(directory, number);
|
||||
const includeCheckDetails = options?.includeCheckDetails ?? false;
|
||||
|
||||
const existing = get().entries[key];
|
||||
const isFresh = existing
|
||||
&& existing.result
|
||||
&& Date.now() - existing.fetchedAt < PR_CONTEXT_TTL_MS
|
||||
&& (existing.hasCheckDetails || !includeCheckDetails);
|
||||
if (!options?.force && isFresh) {
|
||||
return existing.result;
|
||||
}
|
||||
|
||||
// A detail-inclusive request in flight satisfies everyone; a detail-free
|
||||
// one only satisfies detail-free callers.
|
||||
const inFlightKey = `${key}::${includeCheckDetails ? 'details' : 'plain'}`;
|
||||
const detailedInFlight = inFlight.get(`${key}::details`);
|
||||
const pending = detailedInFlight ?? (includeCheckDetails ? null : inFlight.get(inFlightKey));
|
||||
if (pending && !options?.force) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
const request = (async (): Promise<GitHubPullRequestContextResult | null> => {
|
||||
set((state) => ({
|
||||
entries: {
|
||||
...state.entries,
|
||||
[key]: { ...(state.entries[key] ?? createEntry()), isLoading: true, error: null },
|
||||
},
|
||||
}));
|
||||
try {
|
||||
const result = await github.prContext(directory, number, {
|
||||
includeDiff: false,
|
||||
includeCheckDetails,
|
||||
sourceRepo: options?.sourceRepo ?? null,
|
||||
});
|
||||
set((state) => ({
|
||||
entries: boundEntries({
|
||||
...state.entries,
|
||||
[key]: {
|
||||
result,
|
||||
hasCheckDetails: includeCheckDetails,
|
||||
fetchedAt: Date.now(),
|
||||
isLoading: false,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
return result;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to load pull request context';
|
||||
set((state) => ({
|
||||
entries: {
|
||||
...state.entries,
|
||||
[key]: { ...(state.entries[key] ?? createEntry()), isLoading: false, error: message },
|
||||
},
|
||||
}));
|
||||
return null;
|
||||
} finally {
|
||||
inFlight.delete(inFlightKey);
|
||||
}
|
||||
})();
|
||||
|
||||
inFlight.set(inFlightKey, request);
|
||||
return request;
|
||||
},
|
||||
|
||||
invalidate: (directory, number) => {
|
||||
set((state) => {
|
||||
const next: Record<string, PrContextEntry> = {};
|
||||
for (const [key, entry] of Object.entries(state.entries)) {
|
||||
const parsed = parsePrContextKey(key);
|
||||
const matches = Boolean(
|
||||
parsed
|
||||
&& parsed.directory === directory
|
||||
&& (number == null || parsed.number === number),
|
||||
);
|
||||
if (!matches) {
|
||||
next[key] = entry;
|
||||
}
|
||||
}
|
||||
return { entries: next };
|
||||
});
|
||||
},
|
||||
}));
|
||||
@@ -1,8 +1,9 @@
|
||||
import { beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { CONTEXT_SURFACES, sortContextSurfaces } from '../lib/surfaces/registry';
|
||||
import { useUIStore } from './useUIStore';
|
||||
|
||||
beforeEach(() => {
|
||||
useUIStore.setState({ contextPanelByDirectory: {} });
|
||||
useUIStore.setState({ contextPanelByDirectory: {}, contextRailOrder: [] });
|
||||
});
|
||||
|
||||
describe('useUIStore context panel tabs', () => {
|
||||
@@ -28,3 +29,149 @@ describe('useUIStore context panel tabs', () => {
|
||||
expect(tabs[0]?.readOnly).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUIStore openContextSurface', () => {
|
||||
const directory = '/repo';
|
||||
|
||||
test('opens a fresh singleton tab when none of that mode exists', () => {
|
||||
useUIStore.getState().openContextSurface(directory, 'diff');
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.isOpen).toBe(true);
|
||||
expect(state?.tabs.map((tab) => tab.mode)).toEqual(['diff']);
|
||||
});
|
||||
|
||||
test('activates the existing tab of the requested mode instead of duplicating it', () => {
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'diff' });
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'file', targetPath: '/repo/a.ts' });
|
||||
|
||||
useUIStore.getState().openContextSurface(directory, 'diff');
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.tabs.filter((tab) => tab.mode === 'diff')).toHaveLength(1);
|
||||
expect(state?.activeTabId).toBe('diff');
|
||||
expect(state?.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
test('toggles the panel closed when the requested mode is already active and open', () => {
|
||||
useUIStore.getState().openContextSurface(directory, 'diff');
|
||||
useUIStore.getState().openContextSurface(directory, 'diff');
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.isOpen).toBe(false);
|
||||
expect(state?.tabs.map((tab) => tab.mode)).toEqual(['diff']);
|
||||
});
|
||||
|
||||
test('does nothing for content-driven modes without existing content', () => {
|
||||
useUIStore.getState().openContextSurface(directory, 'preview');
|
||||
useUIStore.getState().openContextSurface(directory, 'chat');
|
||||
|
||||
expect(useUIStore.getState().contextPanelByDirectory[directory]).toBe(undefined);
|
||||
});
|
||||
|
||||
test('opens an empty editor tab that a real file later replaces', () => {
|
||||
useUIStore.getState().openContextSurface(directory, 'file');
|
||||
|
||||
let state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.isOpen).toBe(true);
|
||||
expect(state?.tabs.map((tab) => tab.mode)).toEqual(['file']);
|
||||
expect(state?.tabs[0]?.targetPath).toBe(null);
|
||||
|
||||
useUIStore.getState().openContextFile(directory, '/repo/a.ts');
|
||||
|
||||
state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.tabs.filter((tab) => tab.mode === 'file')).toHaveLength(1);
|
||||
expect(state?.tabs.find((tab) => tab.mode === 'file')?.targetPath).toBe('/repo/a.ts');
|
||||
});
|
||||
|
||||
test('activates the most recently touched tab of a content-driven mode', () => {
|
||||
useUIStore.getState().openContextFile(directory, '/repo/a.ts');
|
||||
useUIStore.getState().openContextFile(directory, '/repo/b.ts');
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'diff' });
|
||||
|
||||
useUIStore.getState().openContextSurface(directory, 'file');
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
const activeTab = state?.tabs.find((tab) => tab.id === state.activeTabId);
|
||||
expect(activeTab?.mode).toBe('file');
|
||||
expect(activeTab?.targetPath).toBe('/repo/b.ts');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUIStore closeContextPanelTab surface stability', () => {
|
||||
const directory = '/repo';
|
||||
|
||||
test('closing an active file tab activates another file tab, not another surface', () => {
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'terminal' });
|
||||
useUIStore.getState().openContextFile(directory, '/repo/a.ts');
|
||||
useUIStore.getState().openContextFile(directory, '/repo/b.ts');
|
||||
|
||||
const stateBefore = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
const activeTabId = stateBefore?.activeTabId as string;
|
||||
useUIStore.getState().closeContextPanelTab(directory, activeTabId);
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
const activeTab = state?.tabs.find((tab) => tab.id === state.activeTabId);
|
||||
expect(activeTab?.mode).toBe('file');
|
||||
expect(activeTab?.targetPath).toBe('/repo/a.ts');
|
||||
expect(state?.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
test('closing the last tab of the active surface closes the panel', () => {
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'terminal' });
|
||||
useUIStore.getState().openContextFile(directory, '/repo/a.ts');
|
||||
|
||||
const stateBefore = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
useUIStore.getState().closeContextPanelTab(directory, stateBefore?.activeTabId as string);
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.isOpen).toBe(false);
|
||||
expect(state?.tabs.map((tab) => tab.mode)).toEqual(['terminal']);
|
||||
});
|
||||
|
||||
test('closing an inactive tab keeps the active tab untouched', () => {
|
||||
useUIStore.getState().openContextFile(directory, '/repo/a.ts');
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'terminal' });
|
||||
|
||||
const state0 = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
const fileTab = state0?.tabs.find((tab) => tab.mode === 'file');
|
||||
useUIStore.getState().closeContextPanelTab(directory, fileTab?.id as string);
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.activeTabId).toBe('terminal');
|
||||
expect(state?.isOpen).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUIStore per-surface panel widths', () => {
|
||||
const directory = '/repo';
|
||||
|
||||
test('setContextPanelWidth stores a clamped manual width for one mode only', () => {
|
||||
useUIStore.getState().openContextPanelTab(directory, { mode: 'diff' });
|
||||
useUIStore.getState().setContextPanelWidth(directory, 'diff', 700);
|
||||
useUIStore.getState().setContextPanelWidth(directory, 'git', 100);
|
||||
|
||||
const state = useUIStore.getState().contextPanelByDirectory[directory];
|
||||
expect(state?.widthByMode.diff).toBe(700);
|
||||
expect(state?.widthByMode.git).toBe(380);
|
||||
expect(state?.widthByMode.browser).toBe(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUIStore contextRailOrder', () => {
|
||||
test('setContextRailOrder drops empty and duplicate ids', () => {
|
||||
useUIStore.getState().setContextRailOrder(['diff', 'diff', '', 'editor']);
|
||||
expect(useUIStore.getState().contextRailOrder).toEqual(['diff', 'editor']);
|
||||
});
|
||||
|
||||
test('sortContextSurfaces applies persisted order and appends missing surfaces', () => {
|
||||
const ordered = sortContextSurfaces(['browser', 'unknown-id', 'diff']);
|
||||
const ids = ordered.map((surface) => surface.id);
|
||||
|
||||
expect(ids.slice(0, 2)).toEqual(['browser', 'diff']);
|
||||
// Assert against the registry itself so this test cannot go stale when a
|
||||
// surface is added or removed.
|
||||
expect(new Set(ids)).toEqual(new Set(CONTEXT_SURFACES.map((surface) => surface.id)));
|
||||
expect(ids).toHaveLength(CONTEXT_SURFACES.length);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,11 +9,11 @@ import { DEFAULT_MONO_FONT, DEFAULT_UI_FONT, type MonoFontOption, type UiFontOpt
|
||||
import { getStoredMobileKeyboardMode, type MobileKeyboardMode } from '@/lib/mobileKeyboardMode';
|
||||
import { getRuntimeKey } from '@/lib/runtime-switch';
|
||||
import type { TerminalShell } from '@/lib/api/types';
|
||||
import { useFilesViewTabsStore } from './useFilesViewTabsStore';
|
||||
|
||||
export type MainTab = 'chat' | 'plan' | 'git' | 'diff' | 'terminal' | 'files' | 'context' | 'diagram';
|
||||
export type PendingDiffScope = 'working' | 'staged' | 'turn';
|
||||
export type RightSidebarTab = 'git' | 'files' | 'context';
|
||||
export type ContextPanelMode = 'diff' | 'file' | 'context' | 'plan' | 'chat' | 'preview' | 'browser';
|
||||
export type ContextPanelMode = 'diff' | 'file' | 'context' | 'plan' | 'chat' | 'preview' | 'browser' | 'git' | 'pr' | 'notes' | 'terminal';
|
||||
export type MermaidRenderingMode = 'svg' | 'ascii';
|
||||
export type UserMessageRenderingMode = 'markdown' | 'plain';
|
||||
export type ChatRenderMode = 'sorted' | 'live';
|
||||
@@ -57,7 +57,9 @@ type ContextPanelDirectoryState = {
|
||||
expanded: boolean;
|
||||
tabs: ContextPanelTab[];
|
||||
activeTabId: string | null;
|
||||
width: number;
|
||||
// Manual per-surface widths (px), populated only by user resize; surfaces
|
||||
// without an entry fall back to their registry defaultWidthFraction.
|
||||
widthByMode: Partial<Record<ContextPanelMode, number>>;
|
||||
touchedAt: number;
|
||||
};
|
||||
|
||||
@@ -118,8 +120,6 @@ const CONTEXT_PANEL_MAX_WIDTH = 1400;
|
||||
const CONTEXT_PANEL_MAX_TABS = 12;
|
||||
const CONTEXT_PANEL_MAX_LABEL_LENGTH = 120;
|
||||
const LEFT_SIDEBAR_MIN_WIDTH = 280;
|
||||
export const RIGHT_SIDEBAR_MIN_WIDTH = 360;
|
||||
export const RIGHT_SIDEBAR_MAX_WIDTH = 860;
|
||||
const activeMainTabByRuntime = new Map<string, MainTab>();
|
||||
|
||||
const runtimeMemoryKey = (value?: string | null): string => {
|
||||
@@ -127,6 +127,9 @@ const runtimeMemoryKey = (value?: string | null): string => {
|
||||
return key || 'default';
|
||||
};
|
||||
|
||||
// Shared with rail/panel consumers so contextPanelByDirectory lookups agree on keys.
|
||||
export const normalizeContextPanelDirectoryKey = (value: string): string => normalizeDirectoryPath(value);
|
||||
|
||||
const normalizeDirectoryPath = (value: string): string => {
|
||||
if (!value) return '';
|
||||
|
||||
@@ -283,7 +286,7 @@ const sanitizeContextPanelTabs = (tabs: unknown): ContextPanelTab[] => {
|
||||
touchedAt?: unknown;
|
||||
};
|
||||
|
||||
if (candidate.mode !== 'diff' && candidate.mode !== 'file' && candidate.mode !== 'context' && candidate.mode !== 'plan' && candidate.mode !== 'chat' && candidate.mode !== 'preview' && candidate.mode !== 'browser') {
|
||||
if (candidate.mode !== 'diff' && candidate.mode !== 'file' && candidate.mode !== 'context' && candidate.mode !== 'plan' && candidate.mode !== 'chat' && candidate.mode !== 'preview' && candidate.mode !== 'browser' && candidate.mode !== 'git' && candidate.mode !== 'pr' && candidate.mode !== 'notes' && candidate.mode !== 'terminal') {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -347,7 +350,7 @@ const touchContextPanelState = (prev?: ContextPanelDirectoryState): ContextPanel
|
||||
expanded: false,
|
||||
tabs: [],
|
||||
activeTabId: null,
|
||||
width: CONTEXT_PANEL_DEFAULT_WIDTH,
|
||||
widthByMode: {},
|
||||
touchedAt: Date.now(),
|
||||
};
|
||||
};
|
||||
@@ -357,10 +360,15 @@ const upsertContextPanelTab = (
|
||||
descriptor: ContextPanelTabDescriptor,
|
||||
): ContextPanelDirectoryState => {
|
||||
const nextTab = createContextPanelTab(descriptor);
|
||||
const existingIndex = current.tabs.findIndex((tab) => tab.id === nextTab.id);
|
||||
// A real file tab replaces the empty editor placeholder ('file' with no
|
||||
// target) that the rail can open before any file is picked.
|
||||
const baseTabs = nextTab.mode === 'file' && nextTab.targetPath
|
||||
? current.tabs.filter((tab) => !(tab.mode === 'file' && !tab.targetPath))
|
||||
: current.tabs;
|
||||
const existingIndex = baseTabs.findIndex((tab) => tab.id === nextTab.id);
|
||||
const tabs = existingIndex === -1
|
||||
? [...current.tabs, nextTab]
|
||||
: current.tabs.map((tab, index) => (index === existingIndex
|
||||
? [...baseTabs, nextTab]
|
||||
: baseTabs.map((tab, index) => (index === existingIndex
|
||||
? {
|
||||
...tab,
|
||||
mode: nextTab.mode,
|
||||
@@ -391,16 +399,32 @@ const closeContextPanelTab = (
|
||||
current: ContextPanelDirectoryState,
|
||||
tabID: string,
|
||||
): ContextPanelDirectoryState => {
|
||||
const closedTab = current.tabs.find((tab) => tab.id === tabID) ?? null;
|
||||
const nextTabs = current.tabs.filter((tab) => tab.id !== tabID);
|
||||
const nextActiveTabId = current.activeTabId === tabID
|
||||
? (nextTabs[nextTabs.length - 1]?.id ?? null)
|
||||
: resolveActiveContextPanelTabID(nextTabs, current.activeTabId);
|
||||
|
||||
if (current.activeTabId !== tabID) {
|
||||
return {
|
||||
...current,
|
||||
tabs: nextTabs,
|
||||
activeTabId: resolveActiveContextPanelTabID(nextTabs, current.activeTabId),
|
||||
isOpen: nextTabs.length > 0 ? current.isOpen : false,
|
||||
touchedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
// Closing the active tab stays inside the active surface: activate the most
|
||||
// recent remaining tab of the same mode, and when it was the last one just
|
||||
// close the panel instead of jumping to another surface.
|
||||
const sameModeTabs = closedTab ? nextTabs.filter((tab) => tab.mode === closedTab.mode) : [];
|
||||
const nextSameModeTab = sameModeTabs.length > 0
|
||||
? sameModeTabs.reduce((best, tab) => (tab.touchedAt >= best.touchedAt ? tab : best))
|
||||
: null;
|
||||
|
||||
return {
|
||||
...current,
|
||||
tabs: nextTabs,
|
||||
activeTabId: nextActiveTabId,
|
||||
isOpen: nextTabs.length > 0 ? current.isOpen : false,
|
||||
activeTabId: nextSameModeTab?.id ?? resolveActiveContextPanelTabID(nextTabs, null),
|
||||
isOpen: nextSameModeTab ? current.isOpen : false,
|
||||
touchedAt: Date.now(),
|
||||
};
|
||||
};
|
||||
@@ -467,7 +491,7 @@ const sanitizeContextPanelByDirectory = (
|
||||
expanded?: unknown;
|
||||
tabs?: unknown;
|
||||
activeTabId?: unknown;
|
||||
width?: unknown;
|
||||
widthByMode?: unknown;
|
||||
touchedAt?: unknown;
|
||||
mode?: unknown;
|
||||
targetPath?: unknown;
|
||||
@@ -491,12 +515,27 @@ const sanitizeContextPanelByDirectory = (
|
||||
const resolvedActiveTabId = resolveActiveContextPanelTabID(tabs, activeTabId);
|
||||
const clampedTabs = clampContextPanelTabs(tabs, CONTEXT_PANEL_MAX_TABS, resolvedActiveTabId);
|
||||
|
||||
// Legacy single `width` values are intentionally dropped: widths are now
|
||||
// per-surface, seeded from registry defaults until the user resizes.
|
||||
const widthByMode: Partial<Record<ContextPanelMode, number>> = {};
|
||||
if (candidate.widthByMode && typeof candidate.widthByMode === 'object') {
|
||||
for (const [mode, value] of Object.entries(candidate.widthByMode as Record<string, unknown>)) {
|
||||
if (
|
||||
(mode === 'diff' || mode === 'file' || mode === 'context' || mode === 'plan' || mode === 'chat' || mode === 'preview' || mode === 'browser' || mode === 'git' || mode === 'pr' || mode === 'notes' || mode === 'terminal')
|
||||
&& typeof value === 'number'
|
||||
&& Number.isFinite(value)
|
||||
) {
|
||||
widthByMode[mode] = clampContextPanelWidth(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next[directory] = {
|
||||
isOpen: candidate.isOpen === true,
|
||||
expanded: candidate.expanded === true,
|
||||
tabs: clampedTabs,
|
||||
activeTabId: resolveActiveContextPanelTabID(clampedTabs, resolvedActiveTabId),
|
||||
width: clampContextPanelWidth(typeof candidate.width === 'number' ? candidate.width : CONTEXT_PANEL_DEFAULT_WIDTH),
|
||||
widthByMode,
|
||||
touchedAt: typeof candidate.touchedAt === 'number' && Number.isFinite(candidate.touchedAt)
|
||||
? candidate.touchedAt
|
||||
: Date.now(),
|
||||
@@ -531,15 +570,10 @@ interface UIStore {
|
||||
isSidebarOpen: boolean;
|
||||
sidebarWidth: number;
|
||||
hasManuallyResizedLeftSidebar: boolean;
|
||||
isRightSidebarOpen: boolean;
|
||||
rightSidebarWidth: number;
|
||||
hasManuallyResizedRightSidebar: boolean;
|
||||
rightSidebarTab: RightSidebarTab;
|
||||
contextPanelByDirectory: Record<string, ContextPanelDirectoryState>;
|
||||
isBottomTerminalOpen: boolean;
|
||||
isBottomTerminalExpanded: boolean;
|
||||
bottomTerminalHeight: number;
|
||||
hasManuallyResizedBottomTerminal: boolean;
|
||||
contextRailOrder: string[];
|
||||
contextEditorTreeVisible: boolean;
|
||||
contextEditorTreeWidth: number;
|
||||
notesPanelHeight: number;
|
||||
todoPanelHeight: number;
|
||||
isSessionSwitcherOpen: boolean;
|
||||
@@ -677,10 +711,10 @@ interface UIStore {
|
||||
toggleSidebar: () => void;
|
||||
setSidebarOpen: (open: boolean) => void;
|
||||
setSidebarWidth: (width: number) => void;
|
||||
toggleRightSidebar: () => void;
|
||||
setRightSidebarOpen: (open: boolean) => void;
|
||||
setRightSidebarWidth: (width: number) => void;
|
||||
setRightSidebarTab: (tab: RightSidebarTab) => void;
|
||||
setContextRailOrder: (order: string[]) => void;
|
||||
toggleContextEditorTree: () => void;
|
||||
setContextEditorTreeWidth: (width: number) => void;
|
||||
openContextSurface: (directory: string, mode: ContextPanelMode) => void;
|
||||
openContextPanelTab: (directory: string, tab: ContextPanelTabDescriptor) => void;
|
||||
openContextDiff: (directory: string, filePath: string, staged?: boolean, scope?: PendingDiffScope | null) => void;
|
||||
openContextFile: (directory: string, filePath: string) => void;
|
||||
@@ -695,11 +729,7 @@ interface UIStore {
|
||||
closeContextPanelTab: (directory: string, tabID: string) => void;
|
||||
closeContextPanel: (directory: string) => void;
|
||||
toggleContextPanelExpanded: (directory: string) => void;
|
||||
setContextPanelWidth: (directory: string, width: number) => void;
|
||||
toggleBottomTerminal: () => void;
|
||||
setBottomTerminalOpen: (open: boolean) => void;
|
||||
setBottomTerminalExpanded: (expanded: boolean) => void;
|
||||
setBottomTerminalHeight: (height: number) => void;
|
||||
setContextPanelWidth: (directory: string, mode: ContextPanelMode, width: number) => void;
|
||||
setNotesPanelHeight: (height: number) => void;
|
||||
setTodoPanelHeight: (height: number) => void;
|
||||
setSessionSwitcherOpen: (open: boolean) => void;
|
||||
@@ -765,7 +795,6 @@ interface UIStore {
|
||||
setMobileKeyboardMode: (mode: MobileKeyboardMode) => void;
|
||||
applyTypography: () => void;
|
||||
applyPadding: () => void;
|
||||
updateProportionalSidebarWidths: () => void;
|
||||
toggleFavoriteModel: (providerID: string, modelID: string) => void;
|
||||
reorderFavoriteModel: (
|
||||
activeProviderID: string,
|
||||
@@ -855,15 +884,10 @@ export const useUIStore = create<UIStore>()(
|
||||
isSidebarOpen: true,
|
||||
sidebarWidth: LEFT_SIDEBAR_MIN_WIDTH,
|
||||
hasManuallyResizedLeftSidebar: false,
|
||||
isRightSidebarOpen: false,
|
||||
rightSidebarWidth: RIGHT_SIDEBAR_MIN_WIDTH,
|
||||
hasManuallyResizedRightSidebar: false,
|
||||
rightSidebarTab: 'git',
|
||||
contextPanelByDirectory: {},
|
||||
isBottomTerminalOpen: false,
|
||||
isBottomTerminalExpanded: false,
|
||||
bottomTerminalHeight: 300,
|
||||
hasManuallyResizedBottomTerminal: false,
|
||||
contextRailOrder: [],
|
||||
contextEditorTreeVisible: true,
|
||||
contextEditorTreeWidth: 240,
|
||||
notesPanelHeight: 112,
|
||||
todoPanelHeight: 259,
|
||||
isSessionSwitcherOpen: false,
|
||||
@@ -1036,45 +1060,60 @@ export const useUIStore = create<UIStore>()(
|
||||
set({ sidebarWidth: width, hasManuallyResizedLeftSidebar: true });
|
||||
},
|
||||
|
||||
toggleRightSidebar: () => {
|
||||
set((state) => {
|
||||
const newOpen = !state.isRightSidebarOpen;
|
||||
|
||||
if (newOpen && !state.hasManuallyResizedRightSidebar) {
|
||||
return {
|
||||
isRightSidebarOpen: newOpen,
|
||||
rightSidebarWidth: RIGHT_SIDEBAR_MIN_WIDTH,
|
||||
};
|
||||
}
|
||||
return { isRightSidebarOpen: newOpen };
|
||||
});
|
||||
setContextRailOrder: (order) => {
|
||||
const sanitized = Array.isArray(order)
|
||||
? order.filter((id, index) => typeof id === 'string' && id.trim() !== '' && order.indexOf(id) === index)
|
||||
: [];
|
||||
set({ contextRailOrder: sanitized });
|
||||
},
|
||||
|
||||
setRightSidebarOpen: (open) => {
|
||||
set((state) => {
|
||||
if (state.isRightSidebarOpen === open) {
|
||||
return state;
|
||||
}
|
||||
const shouldResetWidth = open
|
||||
&& !state.hasManuallyResizedRightSidebar
|
||||
&& state.rightSidebarWidth !== RIGHT_SIDEBAR_MIN_WIDTH;
|
||||
return {
|
||||
isRightSidebarOpen: open,
|
||||
rightSidebarWidth: shouldResetWidth ? RIGHT_SIDEBAR_MIN_WIDTH : state.rightSidebarWidth,
|
||||
};
|
||||
});
|
||||
toggleContextEditorTree: () => {
|
||||
set((state) => ({ contextEditorTreeVisible: !state.contextEditorTreeVisible }));
|
||||
},
|
||||
|
||||
setRightSidebarWidth: (width) => {
|
||||
const clamped = Math.min(
|
||||
RIGHT_SIDEBAR_MAX_WIDTH,
|
||||
Math.max(RIGHT_SIDEBAR_MIN_WIDTH, width)
|
||||
);
|
||||
set({ rightSidebarWidth: clamped, hasManuallyResizedRightSidebar: true });
|
||||
setContextEditorTreeWidth: (width) => {
|
||||
if (!Number.isFinite(width)) {
|
||||
return;
|
||||
}
|
||||
set({ contextEditorTreeWidth: Math.min(480, Math.max(200, Math.round(width))) });
|
||||
},
|
||||
|
||||
setRightSidebarTab: (tab) => {
|
||||
set({ rightSidebarTab: tab });
|
||||
// Rail entry point: activates the most recent tab of the requested
|
||||
// mode, opens a fresh singleton tab when none exists, and toggles the
|
||||
// panel closed when the requested mode is already active and visible.
|
||||
openContextSurface: (directory, mode) => {
|
||||
const normalizedDirectory = normalizeDirectoryPath((directory || '').trim());
|
||||
if (!normalizedDirectory) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = get();
|
||||
const panelState = state.contextPanelByDirectory[normalizedDirectory];
|
||||
const tabs = panelState?.tabs ?? [];
|
||||
const activeTab = tabs.find((tab) => tab.id === panelState?.activeTabId) ?? null;
|
||||
|
||||
if (panelState?.isOpen && activeTab?.mode === mode) {
|
||||
state.closeContextPanel(normalizedDirectory);
|
||||
return;
|
||||
}
|
||||
|
||||
const tabsOfMode = tabs.filter((tab) => tab.mode === mode);
|
||||
if (tabsOfMode.length > 0) {
|
||||
// `>=` so equal timestamps (same-millisecond opens) resolve to the
|
||||
// later tab in insertion order.
|
||||
const mostRecent = tabsOfMode.reduce((best, tab) => (tab.touchedAt >= best.touchedAt ? tab : best));
|
||||
state.setActiveContextPanelTab(normalizedDirectory, mostRecent.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Content-driven modes need a payload (a preview URL or session);
|
||||
// the rail renders them disabled until content exists. 'file' opens
|
||||
// an empty editor whose embedded tree picks the first file.
|
||||
if (mode === 'preview' || mode === 'chat') {
|
||||
return;
|
||||
}
|
||||
|
||||
state.openContextPanelTab(normalizedDirectory, { mode });
|
||||
},
|
||||
|
||||
openContextPanelTab: (directory, tab) => {
|
||||
@@ -1283,6 +1322,9 @@ export const useUIStore = create<UIStore>()(
|
||||
return;
|
||||
}
|
||||
|
||||
const closingTab = get().contextPanelByDirectory[normalizedDirectory]?.tabs
|
||||
.find((tab) => tab.id === normalizedTabID);
|
||||
|
||||
set((state) => {
|
||||
const prev = state.contextPanelByDirectory[normalizedDirectory];
|
||||
const current = touchContextPanelState(prev);
|
||||
@@ -1297,6 +1339,12 @@ export const useUIStore = create<UIStore>()(
|
||||
|
||||
return { contextPanelByDirectory: clampContextPanelRoots(byDirectory, 20) };
|
||||
});
|
||||
|
||||
// Keep the editor's own open-file state in sync so a reopened
|
||||
// editor surface does not resurrect the closed file.
|
||||
if (closingTab?.mode === 'file' && closingTab.targetPath) {
|
||||
useFilesViewTabsStore.getState().removeOpenPath(normalizedDirectory, closingTab.targetPath);
|
||||
}
|
||||
},
|
||||
|
||||
closeContextPanel: (directory) => {
|
||||
@@ -1344,7 +1392,7 @@ export const useUIStore = create<UIStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
setContextPanelWidth: (directory, width) => {
|
||||
setContextPanelWidth: (directory, mode, width) => {
|
||||
const normalizedDirectory = normalizeDirectoryPath((directory || '').trim());
|
||||
if (!normalizedDirectory) {
|
||||
return;
|
||||
@@ -1357,7 +1405,10 @@ export const useUIStore = create<UIStore>()(
|
||||
...state.contextPanelByDirectory,
|
||||
[normalizedDirectory]: {
|
||||
...current,
|
||||
width: clampContextPanelWidth(width),
|
||||
widthByMode: {
|
||||
...current.widthByMode,
|
||||
[mode]: clampContextPanelWidth(width),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1365,64 +1416,6 @@ export const useUIStore = create<UIStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
toggleBottomTerminal: () => {
|
||||
set((state) => {
|
||||
const newOpen = !state.isBottomTerminalOpen;
|
||||
|
||||
if (newOpen && typeof window !== 'undefined') {
|
||||
const proportionalHeight = Math.floor(window.innerHeight * 0.32);
|
||||
return {
|
||||
isBottomTerminalOpen: newOpen,
|
||||
bottomTerminalHeight: proportionalHeight,
|
||||
hasManuallyResizedBottomTerminal: false,
|
||||
};
|
||||
}
|
||||
|
||||
return { isBottomTerminalOpen: newOpen };
|
||||
});
|
||||
},
|
||||
|
||||
setBottomTerminalOpen: (open) => {
|
||||
set((state) => {
|
||||
if (state.isBottomTerminalOpen === open) {
|
||||
if (!open) {
|
||||
return state;
|
||||
}
|
||||
if (!state.hasManuallyResizedBottomTerminal && typeof window !== 'undefined') {
|
||||
const proportionalHeight = Math.floor(window.innerHeight * 0.32);
|
||||
if (state.bottomTerminalHeight === proportionalHeight && state.hasManuallyResizedBottomTerminal === false) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
isBottomTerminalOpen: open,
|
||||
bottomTerminalHeight: proportionalHeight,
|
||||
hasManuallyResizedBottomTerminal: false,
|
||||
};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
if (open && typeof window !== 'undefined') {
|
||||
const proportionalHeight = Math.floor(window.innerHeight * 0.32);
|
||||
return {
|
||||
isBottomTerminalOpen: open,
|
||||
bottomTerminalHeight: proportionalHeight,
|
||||
hasManuallyResizedBottomTerminal: false,
|
||||
};
|
||||
}
|
||||
|
||||
return { isBottomTerminalOpen: open };
|
||||
});
|
||||
},
|
||||
|
||||
setBottomTerminalExpanded: (expanded) => {
|
||||
set({ isBottomTerminalExpanded: expanded });
|
||||
},
|
||||
|
||||
setBottomTerminalHeight: (height) => {
|
||||
set({ bottomTerminalHeight: height, hasManuallyResizedBottomTerminal: true });
|
||||
},
|
||||
|
||||
setNotesPanelHeight: (height) => {
|
||||
set({ notesPanelHeight: height });
|
||||
},
|
||||
@@ -2009,25 +2002,6 @@ export const useUIStore = create<UIStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
updateProportionalSidebarWidths: () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
set((state) => {
|
||||
const updates: Partial<UIStore> = {};
|
||||
|
||||
if (state.isBottomTerminalOpen && !state.hasManuallyResizedBottomTerminal) {
|
||||
const nextHeight = Math.floor(window.innerHeight * 0.32);
|
||||
if (state.bottomTerminalHeight !== nextHeight) {
|
||||
updates.bottomTerminalHeight = nextHeight;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(updates).length > 0 ? updates : state;
|
||||
});
|
||||
},
|
||||
|
||||
applyTheme: () => {
|
||||
const { theme } = get();
|
||||
const root = document.documentElement;
|
||||
@@ -2189,13 +2163,7 @@ export const useUIStore = create<UIStore>()(
|
||||
viewPagerPage: 'center',
|
||||
setViewPagerPage: (page: 'left' | 'center' | 'right') => {
|
||||
set({ viewPagerPage: page });
|
||||
if (page === 'left') {
|
||||
set({ isSessionSwitcherOpen: true, isRightSidebarOpen: false });
|
||||
} else if (page === 'right') {
|
||||
set({ isRightSidebarOpen: true, isSessionSwitcherOpen: false });
|
||||
} else {
|
||||
set({ isSessionSwitcherOpen: false, isRightSidebarOpen: false });
|
||||
}
|
||||
set({ isSessionSwitcherOpen: page === 'left' });
|
||||
},
|
||||
|
||||
setShortcutOverride: (actionId, combo) => {
|
||||
@@ -2301,12 +2269,11 @@ export const useUIStore = create<UIStore>()(
|
||||
delete state.memoryLimitActiveSession;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof state.rightSidebarTab !== 'string'
|
||||
|| (state.rightSidebarTab !== 'git' && state.rightSidebarTab !== 'files' && state.rightSidebarTab !== 'context')
|
||||
) {
|
||||
state.rightSidebarTab = 'git';
|
||||
}
|
||||
// Right-sidebar state was removed with the sidebar itself; drop
|
||||
// stale persisted fields.
|
||||
delete state.isRightSidebarOpen;
|
||||
delete state.rightSidebarWidth;
|
||||
delete state.rightSidebarTab;
|
||||
|
||||
state.contextPanelByDirectory = sanitizeContextPanelByDirectory(state.contextPanelByDirectory);
|
||||
|
||||
@@ -2341,19 +2308,20 @@ export const useUIStore = create<UIStore>()(
|
||||
|
||||
state.fileEditorKeymap = normalizeFileEditorKeymap(state.fileEditorKeymap);
|
||||
|
||||
state.contextRailOrder = Array.isArray(state.contextRailOrder)
|
||||
? (state.contextRailOrder as unknown[]).filter((id): id is string => typeof id === 'string' && id.trim() !== '')
|
||||
: [];
|
||||
|
||||
return state;
|
||||
},
|
||||
partialize: (state) => ({
|
||||
theme: state.theme,
|
||||
isSidebarOpen: state.isSidebarOpen,
|
||||
sidebarWidth: state.sidebarWidth,
|
||||
isRightSidebarOpen: state.isRightSidebarOpen,
|
||||
rightSidebarWidth: state.rightSidebarWidth,
|
||||
rightSidebarTab: state.rightSidebarTab,
|
||||
contextPanelByDirectory: state.contextPanelByDirectory,
|
||||
isBottomTerminalOpen: state.isBottomTerminalOpen,
|
||||
isBottomTerminalExpanded: state.isBottomTerminalExpanded,
|
||||
bottomTerminalHeight: state.bottomTerminalHeight,
|
||||
contextRailOrder: state.contextRailOrder,
|
||||
contextEditorTreeVisible: state.contextEditorTreeVisible,
|
||||
contextEditorTreeWidth: state.contextEditorTreeWidth,
|
||||
notesPanelHeight: state.notesPanelHeight,
|
||||
todoPanelHeight: state.todoPanelHeight,
|
||||
isSessionSwitcherOpen: state.isSessionSwitcherOpen,
|
||||
|
||||
Reference in New Issue
Block a user