From 19ee1d917382137ea6c65c075022c93d971d2f14 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:45:07 -0500 Subject: [PATCH] refactor: satisfy no-array-filter-map and no-accumulating-spread --- .../migrations/019-drop-opencode-configs.ts | 4 +--- backend/src/services/opencode-import.ts | 11 ++++----- backend/src/services/sandbox/runtime.ts | 13 ++++++----- backend/src/services/schedule-worktree.ts | 14 ++++++----- backend/src/services/skills.ts | 9 ++++---- .../components/repo/WorktreeSessionGroups.tsx | 23 +++++++++---------- .../components/schedules/schedule-utils.ts | 2 +- .../settings/AddMcpServerDialog.tsx | 8 ++++--- frontend/src/contexts/EventContext.tsx | 14 +++++------ frontend/src/lib/modelSections.ts | 18 +++++++-------- frontend/src/lib/utils.ts | 2 +- frontend/src/lib/visibleMessageTexts.ts | 6 ++--- frontend/src/pages/SessionDetail.tsx | 6 ++--- frontend/src/test/browserFakes.ts | 2 +- ocm-cli/src/tui-ocm.ts | 2 +- ocm-cli/test/mirror.test.ts | 2 +- 16 files changed, 68 insertions(+), 68 deletions(-) diff --git a/backend/src/db/migrations/019-drop-opencode-configs.ts b/backend/src/db/migrations/019-drop-opencode-configs.ts index a657d877..e1b91820 100644 --- a/backend/src/db/migrations/019-drop-opencode-configs.ts +++ b/backend/src/db/migrations/019-drop-opencode-configs.ts @@ -18,9 +18,7 @@ function firstExistingConfigSourcePath(): string | null { const candidates = [ process.env.OPENCODE_IMPORT_CONFIG_PATH, path.join(os.homedir(), '.config', 'opencode', 'opencode.json'), - ] - .filter((value): value is string => Boolean(value)) - .map((value) => path.resolve(value)) + ].flatMap((value) => (value ? [path.resolve(value)] : [])) return Array.from(new Set(candidates)).find((candidate) => existsSync(candidate)) ?? null } diff --git a/backend/src/services/opencode-import.ts b/backend/src/services/opencode-import.ts index c0781e5d..da20c657 100644 --- a/backend/src/services/opencode-import.ts +++ b/backend/src/services/opencode-import.ts @@ -77,9 +77,7 @@ export interface ImportedSessionDirectorySummary { } export function getImportPathCandidates(envKey: string, fallbackPath: string): string[] { - const candidates = [process.env[envKey], fallbackPath] - .filter((value): value is string => Boolean(value)) - .map((value) => path.resolve(value)) + const candidates = [process.env[envKey], fallbackPath].flatMap((value) => (value ? [path.resolve(value)] : [])) return Array.from(new Set(candidates)) } @@ -89,9 +87,10 @@ function getExistingConfigSourcePaths(): string[] { if (explicitPath && existsSync(path.resolve(explicitPath))) { return [path.resolve(explicitPath)] } - return [...OPENCODE_CONFIG_SOURCE_NAMES, LEGACY_OPENCODE_CONFIG_SOURCE_NAME] - .map(name => path.join(os.homedir(), '.config', 'opencode', name)) - .filter(candidate => existsSync(candidate)) + return [...OPENCODE_CONFIG_SOURCE_NAMES, LEGACY_OPENCODE_CONFIG_SOURCE_NAME].flatMap(name => { + const candidate = path.join(os.homedir(), '.config', 'opencode', name) + return existsSync(candidate) ? [candidate] : [] + }) } async function getFirstExistingPathWithDatabase(paths: string[]): Promise { diff --git a/backend/src/services/sandbox/runtime.ts b/backend/src/services/sandbox/runtime.ts index 0b0db8db..db9d1b47 100644 --- a/backend/src/services/sandbox/runtime.ts +++ b/backend/src/services/sandbox/runtime.ts @@ -993,9 +993,10 @@ async function admitVmStart(name: string, maxRunningVms: number): Promise if (running.length < maxRunningVms) return const execTimeoutMs = ENV.SANDBOX.EXEC_TIMEOUT_MS - const candidates = running - .map((vmName) => ({ vmName, lastUsedAt: vmStates.get(vmName)?.lastUsedAt ?? 0 })) - .filter((candidate) => Date.now() - candidate.lastUsedAt >= execTimeoutMs) + const candidates = running.flatMap((vmName) => { + const lastUsedAt = vmStates.get(vmName)?.lastUsedAt ?? 0 + return Date.now() - lastUsedAt >= execTimeoutMs ? [{ vmName, lastUsedAt }] : [] + }) if (candidates.length === 0) { throw new Error( `${running.length} sandbox VMs are already running (the limit in Settings → Sandbox is ${maxRunningVms}) and none has been idle for ${execTimeoutMs / 60000} minutes; retry when a sandboxed command finishes or raise the limit`, @@ -1196,9 +1197,9 @@ export class SandboxRuntimeService { private async runManagedSandboxStop(): Promise { for (;;) { - const inFlight = [...vmStates.values()] - .map((state) => state.inFlightBoot) - .filter((boot): boot is Promise => boot !== null) + const inFlight: Promise[] = [...vmStates.values()].flatMap((state) => + state.inFlightBoot === null ? [] : [state.inFlightBoot], + ) if (inFlight.length === 0) break await Promise.all(inFlight.map((boot) => boot.catch(() => undefined))) } diff --git a/backend/src/services/schedule-worktree.ts b/backend/src/services/schedule-worktree.ts index 47257ad8..6fb974a7 100644 --- a/backend/src/services/schedule-worktree.ts +++ b/backend/src/services/schedule-worktree.ts @@ -201,12 +201,14 @@ export class ScheduleWorktreeManager { ): Promise { const sharedPath = getScheduleWorktreePath(job.id, null) const sharedBranch = getScheduleWorktreeBranch(job.id, null) - const runWorktrees = artifacts - .map((artifact) => artifact.worktreePath) - .filter((worktreePath): worktreePath is string => worktreePath !== null && worktreePath !== sharedPath) - const branches = artifacts - .map((artifact) => artifact.runBranch) - .filter((branch): branch is string => branch !== null && branch.length > 0 && branch !== sharedBranch) + const runWorktrees = artifacts.flatMap((artifact) => { + const worktreePath = artifact.worktreePath + return worktreePath !== null && worktreePath !== sharedPath ? [worktreePath] : [] + }) + const branches = artifacts.flatMap((artifact) => { + const branch = artifact.runBranch + return branch !== null && branch.length > 0 && branch !== sharedBranch ? [branch] : [] + }) if (runWorktrees.length === 0 && branches.length === 0) return diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index a7b13834..55c8f025 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -99,12 +99,13 @@ function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles const skillDir = path.dirname(skillMd.relativePath) const { name, description, body } = parseSkillMarkdown(skillMd.content.toString('utf-8')) const prefix = skillDir === '.' ? '' : skillDir + '/' - const strippedFiles = normalized - .filter(f => f.relativePath === skillMd.relativePath || f.relativePath.startsWith(prefix)) - .map(f => ({ + const strippedFiles = normalized.flatMap(f => { + if (f.relativePath !== skillMd.relativePath && !f.relativePath.startsWith(prefix)) return [] + return [{ ...f, relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length), - })) + }] + }) for (const f of strippedFiles) { const checkPath = normalizeUploadRelativePath(f.relativePath) if (checkPath.startsWith('..')) { diff --git a/frontend/src/components/repo/WorktreeSessionGroups.tsx b/frontend/src/components/repo/WorktreeSessionGroups.tsx index 0f48495a..cc89cded 100644 --- a/frontend/src/components/repo/WorktreeSessionGroups.tsx +++ b/frontend/src/components/repo/WorktreeSessionGroups.tsx @@ -441,18 +441,17 @@ function buildGroupEntries( }) }) - const groups = worktrees - .filter((worktree) => ownerFilter === 'all' || worktree.worktreeSource === ownerFilter) - .map((worktree): WorktreeGroup => { - const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? [] - return { - worktree, - directory: worktree.fullPath, - sessions: groupSessions, - lastActive: groupSessions[0]?.time.updated ?? 0, - } - }) - .filter((group) => !hideEmpty || group.sessions.length > 0) + const groups = worktrees.flatMap((worktree): WorktreeGroup[] => { + if (ownerFilter !== 'all' && worktree.worktreeSource !== ownerFilter) return [] + const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? [] + const group: WorktreeGroup = { + worktree, + directory: worktree.fullPath, + sessions: groupSessions, + lastActive: groupSessions[0]?.time.updated ?? 0, + } + return !hideEmpty || groupSessions.length > 0 ? [group] : [] + }) const scheduleEntries = new Map>() const multiRunEntries = new Map>() diff --git a/frontend/src/components/schedules/schedule-utils.ts b/frontend/src/components/schedules/schedule-utils.ts index 843c0a9c..9301f327 100644 --- a/frontend/src/components/schedules/schedule-utils.ts +++ b/frontend/src/components/schedules/schedule-utils.ts @@ -145,7 +145,7 @@ function expandDayOfWeekExpression(expression: string): string[] | null { return null } - return weekdayOptions.filter((option) => days.has(option.value)).map((option) => option.value) + return weekdayOptions.flatMap((option) => (days.has(option.value) ? [option.value] : [])) } function sortWeekdayValues(values: string[]): string[] { diff --git a/frontend/src/components/settings/AddMcpServerDialog.tsx b/frontend/src/components/settings/AddMcpServerDialog.tsx index 031f0227..3b0b69bf 100644 --- a/frontend/src/components/settings/AddMcpServerDialog.tsx +++ b/frontend/src/components/settings/AddMcpServerDialog.tsx @@ -27,9 +27,11 @@ interface KeyValueEntry { function toRecord(entries: KeyValueEntry[]): Record | undefined { const record = Object.fromEntries( - entries - .filter((entry) => entry.key.trim() && entry.value.trim()) - .map((entry) => [entry.key.trim(), entry.value.trim()]), + entries.flatMap((entry): [string, string][] => { + const key = entry.key.trim() + const value = entry.value.trim() + return key && value ? [[key, value]] : [] + }), ) return Object.keys(record).length > 0 ? record : undefined } diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 4af28958..26a73ada 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -99,13 +99,13 @@ function usePendingSessionIDs(bySession: Record): string[] { } function groupBySession(items: T[]): Record { - return items.reduce>((grouped, item) => { - const existing = grouped[item.sessionID] ?? [] - return { - ...grouped, - [item.sessionID]: [...existing, item], - } - }, {}) + const groups = new Map() + for (const item of items) { + const existing = groups.get(item.sessionID) + if (existing) existing.push(item) + else groups.set(item.sessionID, [item]) + } + return Object.fromEntries(groups) } function sortById(items: T[]): T[] { diff --git a/frontend/src/lib/modelSections.ts b/frontend/src/lib/modelSections.ts index 6fd904c4..ea61a1d1 100644 --- a/frontend/src/lib/modelSections.ts +++ b/frontend/src/lib/modelSections.ts @@ -96,16 +96,14 @@ export function buildModelSections( function uniqueModelSections(sections: ModelSection[]): ModelSection[] { const seen = new Set() - return sections - .map((section) => ({ - ...section, - options: section.options.filter((option) => { - if (seen.has(option.value)) return false - seen.add(option.value) - return true - }), - })) - .filter((section) => section.options.length > 0) + return sections.flatMap((section): ModelSection[] => { + const options = section.options.filter((option) => { + if (seen.has(option.value)) return false + seen.add(option.value) + return true + }) + return options.length > 0 ? [{ ...section, options }] : [] + }) } function compareSearchMatches(a: ModelOption, b: ModelOption): number { diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 464e5a0a..53aabce9 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -13,7 +13,7 @@ export function getRepoBranchLabel(repo: Pick) const ORIGIN_REMOTE_PREFIX = 'remotes/origin/' export function getOriginOnlyBranchNames(branches: Pick[]): string[] { - const localNames = new Set(branches.filter((b) => b.type === 'local').map((b) => b.name)) + const localNames = new Set(branches.flatMap((b) => (b.type === 'local' ? [b.name] : []))) const seen = new Set() const result: string[] = [] diff --git a/frontend/src/lib/visibleMessageTexts.ts b/frontend/src/lib/visibleMessageTexts.ts index df251942..7d7fbfec 100644 --- a/frontend/src/lib/visibleMessageTexts.ts +++ b/frontend/src/lib/visibleMessageTexts.ts @@ -8,9 +8,9 @@ export function collectVisibleAssistantTexts( ): string[] { const containerRect = container.getBoundingClientRect() const textById = new Map( - messages - .filter((message) => message.type === 'assistant') - .map((message) => [message.id, getAssistantText(message).trim()]), + messages.flatMap((message): [string, string][] => + message.type === 'assistant' ? [[message.id, getAssistantText(message).trim()]] : [], + ), ) return Array.from(container.querySelectorAll('[data-message-id]')) .filter((element) => { diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 14fe823f..900f8105 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -100,7 +100,7 @@ function applyRevertBoundary( } async function fetchCompleteSessionHistory(sessionID: string, serverId?: string): Promise { - let history: SessionMessageInfo[] = [] + const pagesNewestFirst: SessionMessageInfo[][] = [] const seenIds = new Set() const seenCursors = new Set() let cursor: string | undefined @@ -109,9 +109,9 @@ async function fetchCompleteSessionHistory(sessionID: string, serverId?: string) const page = await listSessionMessages(sessionID, cursor === undefined ? {} : { cursor }, serverId) const older = page.messages.filter((message) => !seenIds.has(message.id)) for (const message of older) seenIds.add(message.id) - history = [...older, ...history] + pagesNewestFirst.push(older) - if (!page.nextCursor || seenCursors.has(page.nextCursor)) return history + if (!page.nextCursor || seenCursors.has(page.nextCursor)) return pagesNewestFirst.reverse().flat() seenCursors.add(page.nextCursor) cursor = page.nextCursor } diff --git a/frontend/src/test/browserFakes.ts b/frontend/src/test/browserFakes.ts index ebd4a179..519efefd 100644 --- a/frontend/src/test/browserFakes.ts +++ b/frontend/src/test/browserFakes.ts @@ -533,7 +533,7 @@ export function installResizeObserver(): ResizeObserverFake { vi.stubGlobal('ResizeObserver', FakeResizeObserver) return { - observedElements: () => observations.filter((entry) => entry.element.isConnected).map((entry) => entry.element), + observedElements: () => observations.flatMap((entry) => (entry.element.isConnected ? [entry.element] : [])), reportHeight: (height) => { act(() => { for (const entry of [...observations]) { diff --git a/ocm-cli/src/tui-ocm.ts b/ocm-cli/src/tui-ocm.ts index 884d52c5..3916aa40 100644 --- a/ocm-cli/src/tui-ocm.ts +++ b/ocm-cli/src/tui-ocm.ts @@ -114,7 +114,7 @@ async function chooseFromLocal( const matchIds = new Set(matches.map((repo) => repo.repoId)) return selectDialog(context, 'Switch to Manager repo', [ ...matches.map((repo) => repoOption(repo, MATCH_CATEGORY)), - ...repos.filter((repo) => !matchIds.has(repo.repoId)).map((repo) => repoOption(repo, REPO_CATEGORY)), + ...repos.flatMap((repo) => (matchIds.has(repo.repoId) ? [] : [repoOption(repo, REPO_CATEGORY)])), ]) } diff --git a/ocm-cli/test/mirror.test.ts b/ocm-cli/test/mirror.test.ts index 2339c23d..b5f235e0 100644 --- a/ocm-cli/test/mirror.test.ts +++ b/ocm-cli/test/mirror.test.ts @@ -1216,7 +1216,7 @@ describe('mirrorUpFast targets the selected repo', () => { await mirrorUpFast(plan, { api, force: false, onPhase: (p) => phases.push(p) }) expect(phases.map((p) => p.kind)).toEqual(['bundling', 'uploading', 'uploading', 'uploading', 'processing', 'patching']) - const sent = phases.filter((p): p is Extract => p.kind === 'uploading').map((p) => p.bytesSent) + const sent = phases.flatMap((p): number[] => (p.kind === 'uploading' ? [p.bytesSent] : [])) expect(sent[0]).toBe(0) expect(sent[1]!).toBeGreaterThan(0) expect(sent[2]!).toBeGreaterThan(sent[1]!)