Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(scm): Add to / Remove from .gitignore in SCM and Explorer context menus

enes198c4c2a7c30
diff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsx
index 669b5906e..ec128e4ba 100644
--- a/src/renderer/components/ExplorerPanel.tsx
+++ b/src/renderer/components/ExplorerPanel.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import type { DirEntry, FsApi } from '@shared/types'
+import { gitignoreAdd, gitignoreHasExact, gitignoreRemove } from '@shared/gitignore'
import { useProjects } from '../state/projects'
import { useExplorer } from '../state/explorer'
import { sshFs } from '../terminal/ssh-fs'
@@ -20,7 +21,7 @@ interface ExplorerPanelProps {
reveal?: { path: string; nonce: number } | null
}
-type ContextFn = (x: number, y: number, path: string, isDir: boolean) => void
+type ContextFn = (x: number, y: number, path: string, isDir: boolean, ignored?: boolean) => void
type OpenFn = (path: string) => void
type SelectFn = (path: string) => void
type DownloadFn = (path: string, isDir: boolean) => void
@@ -161,7 +162,7 @@ function TreeEntry({
onContextMenu={(e) => {
e.preventDefault()
onSelect(path)
- onContext(e.clientX, e.clientY, path, entry.dir)
+ onContext(e.clientX, e.clientY, path, entry.dir, entry.ignored)
}}
title={entry.name}
>
@@ -239,7 +240,15 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp
const [roots, setRoots] = useState<DirEntry[] | null>(null)
const [version, setVersion] = useState(0)
const [selected, setSelected] = useState<string | null>(null)
- const [menu, setMenu] = useState<{ x: number; y: number; path: string; dir: boolean } | null>(null)
+ const [menu, setMenu] = useState<{
+ x: number
+ y: number
+ path: string
+ dir: boolean
+ ignored?: boolean
+ } | null>(null)
+ /** Whether the ignored menu entry matches an EXACT .gitignore line (null = still resolving). */
+ const [menuExactIgnore, setMenuExactIgnore] = useState<boolean | null>(null)
// Downloading is only meaningful when the tree is NOT this machine's own filesystem, and the
// transport differs per shell — the whole decision is the pure `downloadRoute` (lib/download.ts).
@@ -364,7 +373,35 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reveal?.nonce, cwd])
- const onContext: ContextFn = (x, y, path, isDir) => setMenu({ x, y, path, dir: isDir })
+ const onContext: ContextFn = (x, y, path, isDir, ignored) => {
+ setMenu({ x, y, path, dir: isDir, ignored })
+ // The "Remove from .gitignore" offer needs to know whether the entry is ignored by an EXACT
+ // line (removable) or by a broader pattern like `*.log` (nothing safe to remove — rewriting a
+ // user's pattern is not a menu click's call, so no item is shown). Resolved async while the
+ // menu opens; until then neither gitignore item renders for an ignored entry.
+ setMenuExactIgnore(null)
+ if (ignored && cwd && path !== cwd) {
+ const rel = path.slice(cwd.length + 1)
+ void fs
+ .read(`${cwd}/.gitignore`)
+ .then((content) => setMenuExactIgnore(gitignoreHasExact(content, rel)))
+ .catch(() => setMenuExactIgnore(false))
+ }
+ }
+
+ /** Add (or exact-line-remove) the entry to the project root's .gitignore, then re-list so the
+ * row's dimming reflects the new truth. Read-modify-write via the pure gitignore helpers. */
+ const toggleGitignore = useCallback(
+ async (path: string, remove: boolean): Promise<void> => {
+ if (!cwd) return
+ const rel = path.slice(cwd.length + 1)
+ const gi = `${cwd}/.gitignore`
+ const cur = (await fs.exists(gi)) ? await fs.read(gi) : ''
+ await fs.write(gi, remove ? gitignoreRemove(cur, rel) : gitignoreAdd(cur, rel))
+ setVersion((v) => v + 1)
+ },
+ [cwd, fs]
+ )
// Create a file or folder under the clicked entry (a dir targets itself, a file its
// parent). Multi-segment names create intermediate dirs. Never overwrites: an existing
@@ -490,8 +527,22 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp
{menu &&
createPortal(
<>
- <div className="tab-backdrop" style={{ zIndex: 78 }} onClick={() => setMenu(null)} />
- <div className="ctx-menu" style={{ top: menu.y, left: menu.x, zIndex: 80 }}>
+ {/* stopPropagation everywhere (same as ContextMenu): this portal's React parent is the
+ drawer OVERLAY (not the aside), so a bubbled click lands on the overlay's
+ onClick={onClose} and closes the whole Explorer along with the menu. */}
+ <div
+ className="tab-backdrop"
+ style={{ zIndex: 78 }}
+ onClick={(e) => {
+ e.stopPropagation()
+ setMenu(null)
+ }}
+ />
+ <div
+ className="ctx-menu"
+ style={{ top: menu.y, left: menu.x, zIndex: 80 }}
+ onClick={(e) => e.stopPropagation()}
+ >
<button
className="ctx-item"
onClick={() => {
@@ -560,6 +611,24 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp
>
Copy Relative Path
</button>
+ {/* Root itself (the empty-area menu) is not an ignorable entry. An entry ignored by
+ a broader PATTERN gets neither item: it cannot be "added" (already ignored) and
+ there is no exact line to remove — see onContext. */}
+ {menu.path !== cwd && (!menu.ignored || menuExactIgnore) && (
+ <>
+ <div className="ctx-sep" />
+ <button
+ className="ctx-item"
+ onClick={() => {
+ const m = menu
+ setMenu(null)
+ void toggleGitignore(m.path, !!m.ignored)
+ }}
+ >
+ {menu.ignored ? 'Remove from .gitignore' : 'Add to .gitignore'}
+ </button>
+ </>
+ )}
{/* Only where it can work: revealing an SSH project's REMOTE path in the local file
manager did nothing, and in a browser tab the whole member is an inert stub. */}
{canRevealLocally(dlCtx) && (
diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsx
index 5fd1b1d05..cc0c50134 100644
--- a/src/renderer/components/SourceControlPanel.tsx
+++ b/src/renderer/components/SourceControlPanel.tsx
@@ -1,6 +1,8 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
-import type { GitFileChange, GitResult, GitStatus } from '@shared/types'
+import type { FsApi, GitFileChange, GitResult, GitStatus } from '@shared/types'
+import { gitignoreAdd } from '@shared/gitignore'
+import { sshFs } from '../terminal/ssh-fs'
import type { GitHistoryItem, GitHistoryResult } from '@shared/git-history'
import { promptDialog } from './promptDialog'
import { useProjects } from '../state/projects'
@@ -133,7 +135,29 @@ export function SourceControlPanel({
// This panel's core api (a stable context read — the local session's api IS window.nodeTerminal,
// so `git` keeps its identity and every hook dep array it sits in behaves exactly as before).
- const git = useSession().api.git
+ const { api } = useSession()
+ const git = api.git
+ // The fs the ACTIVE CHECKOUT lives on: an SSH project's repo is on the host, so its .gitignore
+ // must be read/written over the project's ControlMaster fs — the local fs would edit (or invent)
+ // a same-named file on this machine. Same routing the Explorer uses.
+ const fs = useMemo<FsApi>(
+ () => (project?.ssh ? sshFs(project.id) : api.fs),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [project?.id, project?.ssh, api]
+ )
+
+ /**
+ * Append `relPath` (repo-root-relative — porcelain paths already are, and every scope cwd is a
+ * checkout root) to the scope's .gitignore. Read-modify-write through the pure helpers; the
+ * refresh that `act` runs afterwards is what makes the row disappear from CHANGES.
+ */
+ const addToGitignore = (relPath: string) =>
+ act(async () => {
+ const gi = `${cwd}/.gitignore`
+ const cur = (await fs.exists(gi)) ? await fs.read(gi) : ''
+ const ok = await fs.write(gi, gitignoreAdd(cur, relPath))
+ return ok ? { ok: true, message: '' } : { ok: false, message: 'Could not write .gitignore.' }
+ })
const refresh = useCallback(async () => {
setStatus(cwd ? await git.status(cwd) : null)
@@ -693,8 +717,23 @@ export function SourceControlPanel({
{fileMenu &&
createPortal(
<>
- <div className="tab-backdrop" style={{ zIndex: 78 }} onClick={() => setFileMenu(null)} />
- <div className="ctx-menu" style={{ top: fileMenu.y, left: fileMenu.x, zIndex: 80 }}>
+ {/* stopPropagation everywhere (same as ContextMenu): this portal's React parent is the
+ drawer OVERLAY (not the aside), so a bubbled click lands on the overlay's
+ onClick={onClose} and closes the whole panel — dismissing the menu, or running a
+ file action like "Add to .gitignore", must not take the drawer down with it. */}
+ <div
+ className="tab-backdrop"
+ style={{ zIndex: 78 }}
+ onClick={(e) => {
+ e.stopPropagation()
+ setFileMenu(null)
+ }}
+ />
+ <div
+ className="ctx-menu"
+ style={{ top: fileMenu.y, left: fileMenu.x, zIndex: 80 }}
+ onClick={(e) => e.stopPropagation()}
+ >
<button
className="ctx-item"
onClick={() => {
@@ -714,6 +753,19 @@ export function SourceControlPanel({
Copy Relative Path
</button>
<div className="ctx-sep" />
+ {/* Always "Add": a file this panel lists is by definition NOT ignored (git status
+ never shows ignored files), so there is nothing to offer removal for here. */}
+ <button
+ className="ctx-item"
+ onClick={() => {
+ const m = fileMenu
+ setFileMenu(null)
+ void addToGitignore(m.path)
+ }}
+ >
+ Add to .gitignore
+ </button>
+ <div className="ctx-sep" />
<button
className="ctx-item"
onClick={() => {
diff --git a/src/shared/gitignore.test.ts b/src/shared/gitignore.test.ts
new file mode 100644
index 000000000..82ed3e625
--- /dev/null
+++ b/src/shared/gitignore.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import { gitignoreAdd, gitignoreHasExact, gitignoreRemove } from './gitignore'
+
+describe('gitignoreHasExact', () => {
+ it('matches all four line spellings of the same path', () => {
+ for (const line of ['dist', '/dist', 'dist/', '/dist/']) {
+ expect(gitignoreHasExact(`node_modules\n${line}\n`, 'dist')).toBe(true)
+ }
+ })
+ it('matches a dir-form relPath against its file-form line', () => {
+ expect(gitignoreHasExact('/dist\n', 'dist/')).toBe(true)
+ })
+ it('does not treat a broader pattern as an exact line', () => {
+ expect(gitignoreHasExact('*.log\ndist/*\n', 'a.log')).toBe(false)
+ expect(gitignoreHasExact('*.log\ndist/*\n', 'dist')).toBe(false)
+ })
+ it('ignores surrounding whitespace and CRLF', () => {
+ expect(gitignoreHasExact(' /out.txt \r\nfoo\r\n', 'out.txt')).toBe(true)
+ })
+ it('is false for an empty path or empty content', () => {
+ expect(gitignoreHasExact('', 'dist')).toBe(false)
+ expect(gitignoreHasExact('/dist\n', '')).toBe(false)
+ })
+})
+
+describe('gitignoreAdd', () => {
+ it('appends an anchored line with a trailing newline', () => {
+ expect(gitignoreAdd('node_modules\n', 'dist/app.js')).toBe('node_modules\n/dist/app.js\n')
+ })
+ it('starts a missing/empty file cleanly', () => {
+ expect(gitignoreAdd('', 'dist')).toBe('/dist\n')
+ expect(gitignoreAdd('\n\n', 'dist')).toBe('/dist\n')
+ })
+ it('inserts exactly one newline after a file with no trailing newline', () => {
+ expect(gitignoreAdd('node_modules', 'dist')).toBe('node_modules\n/dist\n')
+ })
+ it('is a no-op when an exact line already exists in any spelling', () => {
+ expect(gitignoreAdd('dist/\n', 'dist')).toBe('dist/\n')
+ })
+})
+
+describe('gitignoreRemove', () => {
+ it('removes every exact spelling, keeps everything else', () => {
+ expect(gitignoreRemove('# build\n/dist\ndist/\n*.log\n', 'dist')).toBe('# build\n*.log\n')
+ })
+ it('leaves broader patterns alone', () => {
+ expect(gitignoreRemove('*.log\n', 'a.log')).toBe('*.log\n')
+ })
+ it('returns empty for a file that only held that line', () => {
+ expect(gitignoreRemove('/dist\n', 'dist')).toBe('')
+ })
+})
+
+describe('round trip', () => {
+ it('add then remove restores the original (modulo trailing newline)', () => {
+ const base = '# deps\nnode_modules\n'
+ expect(gitignoreRemove(gitignoreAdd(base, 'out/build'), 'out/build')).toBe(base)
+ })
+})
diff --git a/src/shared/gitignore.ts b/src/shared/gitignore.ts
new file mode 100644
index 000000000..ffcd2c467
--- /dev/null
+++ b/src/shared/gitignore.ts
@@ -0,0 +1,45 @@
+/**
+ * Pure .gitignore line edits for the "Add to / Remove from .gitignore" context-menu actions
+ * (Source Control file rows + Explorer entries). Deliberately line-based, not pattern-aware:
+ * ADD writes one anchored line, and REMOVE only offers itself when one of these exact lines is
+ * present — an entry ignored by a broader pattern (`*.log`, `dist/`) gets no remove action,
+ * because deleting or rewriting a user's pattern on their behalf is not a menu click's call.
+ */
+
+/** Normalize a repo-root-relative path for matching: no leading/trailing slashes. */
+const norm = (relPath: string): string => relPath.replace(/^\/+/, '').replace(/\/+$/, '')
+
+/** The exact .gitignore lines that mean `relPath` and nothing broader (± anchor, ± dir slash). */
+const lineVariants = (relPath: string): Set<string> => {
+ const p = norm(relPath)
+ return new Set([p, `/${p}`, `${p}/`, `/${p}/`])
+}
+
+/** Is `relPath` itself (not a broader pattern) an exact line of this .gitignore? */
+export function gitignoreHasExact(content: string, relPath: string): boolean {
+ if (!norm(relPath)) return false
+ const v = lineVariants(relPath)
+ return content.split(/\r?\n/).some((l) => v.has(l.trim()))
+}
+
+/**
+ * Append an ignore line for `relPath` (no-op when an exact line already exists). The line is
+ * ANCHORED (`/dist`, not `dist`): a bare name is a pattern that matches in every subdirectory,
+ * which is more than "ignore this entry" promised.
+ */
+export function gitignoreAdd(content: string, relPath: string): string {
+ const p = norm(relPath)
+ if (!p || gitignoreHasExact(content, relPath)) return content
+ const line = `/${p}`
+ if (!content.trim()) return `${line}\n`
+ return `${content.replace(/\n+$/, '')}\n${line}\n`
+}
+
+/** Remove every exact line meaning `relPath`; comments, patterns and other lines are untouched. */
+export function gitignoreRemove(content: string, relPath: string): string {
+ if (!norm(relPath)) return content
+ const v = lineVariants(relPath)
+ const kept = content.split(/\r?\n/).filter((l) => !v.has(l.trim()))
+ const out = kept.join('\n').replace(/\n+$/, '')
+ return out ? `${out}\n` : ''
+}