diff --git a/.gitignore b/.gitignore index db2956ea..5c2c809c 100644 --- a/.gitignore +++ b/.gitignore @@ -95,10 +95,12 @@ tmp .zed/settings.json /.devenv* /.devenv-root +/.envrc.local /.stack/state /devshell /packages/gen/infra/package.json.backup /packages/infra/package.json.backup +/process-compose.yaml /result apps/stackpanel-go/.stack/keys/ build @@ -108,7 +110,6 @@ dist logs node_modules packages/scripts/entrypoints/ -process-compose.yaml temp tmp # ── END stackpanel ── diff --git a/AGENTS.md b/AGENTS.md index 901d7fb1..f0214245 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,7 @@ You are an experienced, pragmatic software engineering AI agent. Do not over-eng ├── .stack/ │ ├── config.nix # Primary user config (apps, services, theme, IDE) │ ├── data/*.nix # Auto-loaded data tables -│ ├── gen/ # Generated files (checked in; regenerated on devshell entry) +│ ├── gen/ # Ephemeral generated files (gitignored; regenerated on devshell entry) │ ├── secrets/ # SOPS config + encrypted YAML secrets │ └── state/ # Runtime state (gitignored: stack.json, keys/, etc.) ├── tests/ # Smoke tests + template tests @@ -213,13 +213,12 @@ config = lib.mkIf cfg.enable { }; ``` -### Adding Generated Files (CLI-based generation) +### Adding Generated Files (`stackpanel.files.entries`) -**Do not** use `devenv.files` for generated files — the Go CLI is the single writer (avoids symlink issues). +Declare generated files via `stackpanel.files.entries.` in the owning Nix module: -1. Add the data to `fullConfig` in the relevant Nix module -2. Add generation logic in `apps/stackpanel-go/internal/generator/` -3. Check generated output into `.stack/gen/` for IDE support without devshell +1. Set `format` (`"text"`, `"json"`, `"yaml"`, `"toml"`, `"lines"`, `"derivation"`, `"symlink"`), `writer` (`"full"`, `"block"`, `"paths"`), and `adopt` (`"none"`, `"backup"`, `"refuse"`). +2. Set `gitignore = true` when the file is ephemeral/machine-local (automatically added to the managed `.gitignore` block and checked by `stack doctor`); defaults to `true` for symlinks and paths under `.stack/{gen,profile,state,keys,bin}/` or `.tasks/`, and `false` (committed) for workspace/repo files like `packages/gen/*`. ### Proto-Nix Schema System diff --git a/apps/stackpanel-go/internal/agent/server/nix_files.go b/apps/stackpanel-go/internal/agent/server/nix_files.go index fce263d2..de37ec1f 100644 --- a/apps/stackpanel-go/internal/agent/server/nix_files.go +++ b/apps/stackpanel-go/internal/agent/server/nix_files.go @@ -24,6 +24,8 @@ import ( type GeneratedFile struct { Path string `json:"path"` Type string `json:"type"` + Writer string `json:"writer,omitempty"` + Gitignore bool `json:"gitignore"` Mode *string `json:"mode,omitempty"` Source *string `json:"source,omitempty"` Description *string `json:"description,omitempty"` @@ -55,6 +57,8 @@ type nixFilesOutput struct { type nixFileEntry struct { Path string `json:"path"` Type string `json:"type"` + Writer string `json:"writer"` + Gitignore bool `json:"gitignore"` Mode *string `json:"mode"` Source *string `json:"source"` Description *string `json:"description"` @@ -129,6 +133,8 @@ let in { inherit path; type = entryType; + writer = entry.writer or "full"; + gitignore = entry.gitignore or false; mode = entry.mode or null; source = entry.source or null; description = entry.description or null; @@ -144,6 +150,8 @@ let } else { inherit path; type = "text"; + writer = "full"; + gitignore = false; mode = null; source = null; description = null; @@ -218,6 +226,8 @@ let in { inherit path; type = entryType; + writer = entry.writer or "full"; + gitignore = entry.gitignore or false; mode = entry.mode or null; source = entry.source or null; description = entry.description or null; @@ -231,6 +241,8 @@ let } else { inherit path; type = "text"; + writer = "full"; + gitignore = false; mode = null; source = null; description = null; @@ -288,6 +300,8 @@ func (s *Server) buildFilesResponse(data *nixFilesOutput) *GeneratedFilesRespons file := GeneratedFile{ Path: path, Type: entry.Type, + Writer: entry.Writer, + Gitignore: entry.Gitignore, Mode: entry.Mode, Source: entry.Source, Description: entry.Description, diff --git a/apps/stackpanel-go/internal/fileops/types.go b/apps/stackpanel-go/internal/fileops/types.go index a79c48a4..c444c04d 100644 --- a/apps/stackpanel-go/internal/fileops/types.go +++ b/apps/stackpanel-go/internal/fileops/types.go @@ -35,8 +35,9 @@ type Entry struct { StorePath string `json:"storePath,omitempty"` BlockLabel string `json:"blockLabel,omitempty"` CommentPrefix string `json:"commentPrefix,omitempty"` - Mode string `json:"mode,omitempty"` // octal string, e.g. "0755" - Adopt string `json:"adopt,omitempty"` // "none" | "backup" | "refuse" + Mode string `json:"mode,omitempty"` // octal string, e.g. "0755" + Adopt string `json:"adopt,omitempty"` // "none" | "backup" | "refuse" + Gitignore bool `json:"gitignore,omitempty"` // true when ephemeral/machine-local Ops []JSONOp `json:"ops,omitempty"` Collisions []Collision `json:"collisions,omitempty"` } diff --git a/apps/stackpanel-go/internal/reconcile/plan.go b/apps/stackpanel-go/internal/reconcile/plan.go index ab8a2913..a5a0e62b 100644 --- a/apps/stackpanel-go/internal/reconcile/plan.go +++ b/apps/stackpanel-go/internal/reconcile/plan.go @@ -21,6 +21,7 @@ type PlanEntry struct { Format string `json:"format"` Writer string `json:"writer"` Adopt string `json:"adopt"` + Gitignore bool `json:"gitignore"` Mode *string `json:"mode"` BlockLabel string `json:"blockLabel"` CommentPrefix string `json:"commentPrefix"` diff --git a/apps/stackpanel-go/internal/reconcile/rc_fileops.go b/apps/stackpanel-go/internal/reconcile/rc_fileops.go index 41918e70..08ca1318 100644 --- a/apps/stackpanel-go/internal/reconcile/rc_fileops.go +++ b/apps/stackpanel-go/internal/reconcile/rc_fileops.go @@ -56,11 +56,16 @@ func (r *FileopsReconciler) Diagnose(ctx *Context) (*Diagnosis, error) { }, nil } diag := &Diagnosis{} + var gitignoredPaths []string for _, entry := range manifest.Files { + if entry.Gitignore { + gitignoredPaths = append(gitignoredPaths, entry.Path) + } for _, c := range entry.Collisions { diag.Findings = append(diag.Findings, collisionFinding(fileopsID, entry.Path, c)) } } + diag.Findings = append(diag.Findings, checkGitignoredNotTracked(ctx, fileopsID, gitignoredPaths)...) summary, err := fileops.PlanManifest(ctx.ProjectRoot, ctx.StateDir, *manifest) if err != nil { return nil, err diff --git a/apps/stackpanel-go/internal/reconcile/rc_files.go b/apps/stackpanel-go/internal/reconcile/rc_files.go index 6b90bb8a..e9ada106 100644 --- a/apps/stackpanel-go/internal/reconcile/rc_files.go +++ b/apps/stackpanel-go/internal/reconcile/rc_files.go @@ -29,9 +29,10 @@ type manifestFile struct { } type manifestEntry struct { - Path string `json:"path"` - Format string `json:"format"` - Writer string `json:"writer"` + Path string `json:"path"` + Format string `json:"format"` + Writer string `json:"writer"` + Gitignore bool `json:"gitignore"` // Managed is only present in manifests written before the writer axis // existed; it is read so a pre-upgrade generation's stale blocks are still // stripped rather than deleted as whole files. @@ -87,11 +88,15 @@ func (r *FilesReconciler) Diagnose(ctx *Context) (*Diagnosis, error) { diag := &Diagnosis{} currentPaths := map[string]bool{} + var gitignoredPaths []string entries := append([]manifestEntry{}, current.Files...) sort.Slice(entries, func(i, j int) bool { return entries[i].Path < entries[j].Path }) for _, e := range entries { currentPaths[e.Path] = true + if e.Gitignore { + gitignoredPaths = append(gitignoredPaths, e.Path) + } abs := filepath.Join(ctx.ProjectRoot, e.Path) summary := "" if e.Source != nil && *e.Source != "" { @@ -204,9 +209,46 @@ func (r *FilesReconciler) Diagnose(ctx *Context) (*Diagnosis, error) { diag.Notes = append(diag.Notes, "previous manifest unreadable: "+err.Error()) } + diag.Findings = append(diag.Findings, checkGitignoredNotTracked(ctx, filesID, gitignoredPaths)...) + return diag, nil } +// checkGitignoredNotTracked warns when a generated file marked gitignore = true +// in the manifest is currently tracked in the git index. +func checkGitignoredNotTracked(ctx *Context, reconcilerID string, paths []string) []Finding { + if len(paths) == 0 || ctx == nil || ctx.ProjectRoot == "" { + return nil + } + if _, err := os.Stat(filepath.Join(ctx.ProjectRoot, ".git")); err != nil { + return nil + } + args := append([]string{"-C", ctx.ProjectRoot, "ls-files", "-z", "--"}, paths...) + cmd := exec.Command("git", args...) + if ctx.Ctx != nil { + cmd = exec.CommandContext(ctx.Ctx, "git", args...) + } + out, err := cmd.Output() + if err != nil || len(out) == 0 { + return nil + } + var findings []Finding + for _, tracked := range strings.Split(strings.TrimRight(string(out), "\x00"), "\x00") { + if tracked == "" { + continue + } + findings = append(findings, Finding{ + Reconciler: reconcilerID, + ID: "gitignore-tracked:" + tracked, + Severity: SeverityWarning, + Title: "ephemeral generated file is tracked by git (gitignore = true)", + Path: tracked, + FixCommand: "git rm --cached " + tracked, + }) + } + return findings +} + // Apply implements Reconciler by running the generation's write-files script. func (r *FilesReconciler) Apply(ctx *Context) (*ApplyResult, error) { if ctx.Getenv("STACKPANEL_FILES_MANIFEST") == "" { diff --git a/apps/stackpanel-go/internal/reconcile/reconcile_test.go b/apps/stackpanel-go/internal/reconcile/reconcile_test.go index 12131225..1446ddfe 100644 --- a/apps/stackpanel-go/internal/reconcile/reconcile_test.go +++ b/apps/stackpanel-go/internal/reconcile/reconcile_test.go @@ -2,7 +2,9 @@ package reconcile import ( "bytes" + "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -440,3 +442,66 @@ func TestScaffoldSkipsExistingProjectWithoutFetching(t *testing.T) { t.Errorf("expected nothing written, got %+v", res.Applied) } } + +func TestFilesReconcilerWarnsWhenGitignoredEntryIsTracked(t *testing.T) { + t.Parallel() + + root := t.TempDir() + storeFile := filepath.Join(t.TempDir(), "store-file") + if err := os.WriteFile(storeFile, []byte("ok\n"), 0o644); err != nil { + t.Fatal(err) + } + for _, rel := range []string{"ephemeral.sh", "committed.json", "untracked-ephemeral.sh"} { + if err := os.WriteFile(filepath.Join(root, rel), []byte("ok\n"), 0o644); err != nil { + t.Fatal(err) + } + } + + gitRun := func(args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", root}, args...)...) + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + gitRun("init", "-q") + gitRun("add", "ephemeral.sh", "committed.json") + + manifestPath := filepath.Join(t.TempDir(), "files.json") + manifestJSON := fmt.Sprintf(`{ + "version": 2, + "files": [ + {"path": "ephemeral.sh", "format": "text", "writer": "full", "gitignore": true, "storePath": %q}, + {"path": "committed.json", "format": "json", "writer": "full", "gitignore": false, "storePath": %q}, + {"path": "untracked-ephemeral.sh", "format": "text", "writer": "full", "gitignore": true, "storePath": %q} + ] +}`, storeFile, storeFile, storeFile) + if err := os.WriteFile(manifestPath, []byte(manifestJSON), 0o644); err != nil { + t.Fatal(err) + } + + ctx := &Context{ + Ctx: t.Context(), + ProjectRoot: root, + StateDir: filepath.Join(root, ".stack", "profile"), + Getenv: func(k string) string { + if k == "STACKPANEL_FILES_MANIFEST" { + return manifestPath + } + return "" + }, + } + rc := &FilesReconciler{} + diag, err := rc.Diagnose(ctx) + if err != nil { + t.Fatal(err) + } + if len(diag.Findings) != 1 { + t.Fatalf("expected 1 finding for tracked gitignore=true file, got %+v", diag.Findings) + } + got := diag.Findings[0] + if got.Path != "ephemeral.sh" || got.FixCommand != "git rm --cached ephemeral.sh" || got.Severity != SeverityWarning { + t.Errorf("unexpected finding: %+v", got) + } +} diff --git a/apps/web/src/components/studio/panels/files/components.tsx b/apps/web/src/components/studio/panels/files/components.tsx index 0f6c6e33..fb52140f 100644 --- a/apps/web/src/components/studio/panels/files/components.tsx +++ b/apps/web/src/components/studio/panels/files/components.tsx @@ -3,15 +3,15 @@ */ import { - AlertTriangle, - Check, - ChevronDown, - ChevronRight, - Eye, - FileCode, - FileText, - FolderOpen, - RefreshCw, + AlertTriangle, + Check, + ChevronDown, + ChevronRight, + Eye, + FileCode, + FileText, + FolderOpen, + RefreshCw, } from "lucide-react"; import { useState } from "react"; import { FileType } from "@stackpanel/proto"; @@ -19,38 +19,44 @@ import { StatusBadge } from "@/components/ui/status-badge"; import { cn } from "@/lib/utils"; // GeneratedFileWithStatus type from @/lib/types used in ./types import type { - FileRowProps, - SourceGroupProps, - SummaryStatsProps, - PreviewModalProps, - FileStatusBadgeProps, - FileTypeIconProps, - EmptyStateProps, + FileRowProps, + SourceGroupProps, + SummaryStatsProps, + PreviewModalProps, + FileStatusBadgeProps, + FileTypeIconProps, + EmptyStateProps, } from "./types"; -import { - formatFileSize, - formatRelativeTime, - getSourceDisplayName, -} from "./constants"; +import { formatFileSize, formatRelativeTime, getSourceDisplayName } from "./constants"; // ============================================================================= // File Status Badge // ============================================================================= export function FileStatusBadge({ file }: FileStatusBadgeProps) { - if (!file.enable) { - return ; - } + if (!file.enable) { + return ; + } + + if (!file.existsOnDisk) { + return ; + } - if (!file.existsOnDisk) { - return ; - } + if (file.isStale) { + return ; + } - if (file.isStale) { - return ; - } + return ; +} - return ; +export function FileVcsBadge({ file }: FileStatusBadgeProps) { + if (file.gitignore) { + return ; + } + if (file.writer === "block" || file.writer === "paths") { + return ; + } + return ; } // ============================================================================= @@ -58,10 +64,10 @@ export function FileStatusBadge({ file }: FileStatusBadgeProps) { // ============================================================================= export function FileTypeIcon({ type }: FileTypeIconProps) { - if (type === FileType.DERIVATION) { - return ; - } - return ; + if (type === FileType.DERIVATION) { + return ; + } + return ; } // ============================================================================= @@ -69,60 +75,57 @@ export function FileTypeIcon({ type }: FileTypeIconProps) { // ============================================================================= export function FileRow({ file, onPreview }: FileRowProps) { - const fileName = file.path.split("/").pop() ?? file.path; - const directory = file.path.includes("/") - ? file.path.substring(0, file.path.lastIndexOf("/")) - : ""; + const fileName = file.path.split("/").pop() ?? file.path; + const directory = file.path.includes("/") + ? file.path.substring(0, file.path.lastIndexOf("/")) + : ""; - return ( -
-
- -
-
- {fileName} - -
- {directory && ( -
- - {directory} -
- )} - {file.description && ( -

- {file.description} -

- )} -
-
+ return ( +
+
+ +
+
+ {fileName} + + +
+ {directory && ( +
+ + {directory} +
+ )} + {file.description && ( +

{file.description}

+ )} +
+
-
- {file.size !== null && ( - - {formatFileSize(file.size)} - - )} - {onPreview && ( - - )} -
-
- ); +
+ {file.size !== null && ( + {formatFileSize(file.size)} + )} + {onPreview && ( + + )} +
+
+ ); } // ============================================================================= @@ -130,48 +133,48 @@ export function FileRow({ file, onPreview }: FileRowProps) { // ============================================================================= export function SourceGroup({ - source, - files, - defaultExpanded = true, - onPreview, + source, + files, + defaultExpanded = true, + onPreview, }: SourceGroupProps) { - const [expanded, setExpanded] = useState(defaultExpanded); + const [expanded, setExpanded] = useState(defaultExpanded); - const staleCount = files.filter((f) => f.isStale && f.enable).length; - const enabledCount = files.filter((f) => f.enable).length; + const staleCount = files.filter((f) => f.isStale && f.enable).length; + const enabledCount = files.filter((f) => f.enable).length; - return ( -
- + return ( +
+ - {expanded && ( -
- {files.map((file) => ( - - ))} -
- )} -
- ); + {expanded && ( +
+ {files.map((file) => ( + + ))} +
+ )} +
+ ); } // ============================================================================= @@ -179,36 +182,34 @@ export function SourceGroup({ // ============================================================================= export function SummaryStats({ - totalCount, - enabledCount, - staleCount, - lastUpdated, + totalCount, + enabledCount, + staleCount, + lastUpdated, }: SummaryStatsProps) { - const upToDateCount = enabledCount - staleCount; + const upToDateCount = enabledCount - staleCount; - return ( -
-
- Total: - {totalCount} files -
-
- - {upToDateCount} up to date -
- {staleCount > 0 && ( -
- - - {staleCount} stale - -
- )} -
- Updated: {formatRelativeTime(lastUpdated)} -
-
- ); + return ( +
+
+ Total: + {totalCount} files +
+
+ + {upToDateCount} up to date +
+ {staleCount > 0 && ( +
+ + {staleCount} stale +
+ )} +
+ Updated: {formatRelativeTime(lastUpdated)} +
+
+ ); } // ============================================================================= @@ -216,64 +217,68 @@ export function SummaryStats({ // ============================================================================= export function PreviewModal({ file, onClose }: PreviewModalProps) { - if (!file) return null; + if (!file) return null; - return ( -
-
-
-
- - {file.path} -
- -
-
-
-
- Type: - {file.type} -
- {file.source && ( -
- Source: - {getSourceDisplayName(file.source)} -
- )} - {file.description && ( -
- Description: - {file.description} -
- )} - {file.mode && ( -
- Mode: - {file.mode} -
- )} - {file.store_path && ( -
- Store path: - - {file.store_path} - -
- )} -
-
- Content preview coming soon -
-
-
-
- ); + return ( +
+
+
+
+ + {file.path} +
+ +
+
+
+
+ Type: + {file.type} +
+
+ Git tracking: + + {file.gitignore + ? "Gitignored (ephemeral)" + : file.writer && file.writer !== "full" + ? `Committed (${file.writer}-managed)` + : "Committed"} + +
+ {file.source && ( +
+ Source: + {getSourceDisplayName(file.source)} +
+ )} + {file.description && ( +
+ Description: + {file.description} +
+ )} + {file.mode && ( +
+ Mode: + {file.mode} +
+ )} + {file.store_path && ( +
+ Store path: + {file.store_path} +
+ )} +
+
+ Content preview coming soon +
+
+
+
+ ); } // ============================================================================= @@ -281,29 +286,27 @@ export function PreviewModal({ file, onClose }: PreviewModalProps) { // ============================================================================= export function EmptyState({ onRefresh }: EmptyStateProps) { - return ( -
- -
-

No Generated Files

-

- Files declared in stackpanel.files.entries will appear here. -

-

- Add file entries in your Nix modules using{" "} - - stackpanel.files.entries - -

-
- -
- ); + return ( +
+ +
+

No Generated Files

+

+ Files declared in stackpanel.files.entries will appear here. +

+

+ Add file entries in your Nix modules using{" "} + stackpanel.files.entries +

+
+ +
+ ); } diff --git a/apps/web/src/components/studio/panels/inspector-panel.tsx b/apps/web/src/components/studio/panels/inspector-panel.tsx index 1009ebf5..4d112014 100644 --- a/apps/web/src/components/studio/panels/inspector-panel.tsx +++ b/apps/web/src/components/studio/panels/inspector-panel.tsx @@ -12,11 +12,7 @@ import { FileType } from "@stackpanel/proto"; import { Badge } from "@ui/badge"; import { Button } from "@ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@ui/card"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@ui/collapsible"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@ui/collapsible"; import { ScrollArea, ScrollBar } from "@ui/scroll-area"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@ui/tabs"; import { Textarea } from "@ui/textarea"; @@ -218,9 +214,7 @@ function FileContentPreview({ file }: { file: InspectorGeneratedFile }) { const maxPreviewLines = 12; const lines = file.text.split("\n"); const truncated = lines.length > maxPreviewLines; - const preview = truncated - ? lines.slice(0, maxPreviewLines).join("\n") + "\n..." - : file.text; + const preview = truncated ? lines.slice(0, maxPreviewLines).join("\n") + "\n..." : file.text; return (
@@ -231,13 +225,7 @@ function FileContentPreview({ file }: { file: InspectorGeneratedFile }) { ); } -function FileLeafNode({ - node, - depth, -}: { - node: FileTreeNode; - depth: number; -}) { +function FileLeafNode({ node, depth }: { node: FileTreeNode; depth: number }) { const file = node.file!; const [expanded, setExpanded] = useState(false); @@ -259,13 +247,14 @@ function FileLeafNode({ {node.name} + + {file.gitignore ? "Gitignored" : "Committed"} + {file.source && ( {file.source} @@ -288,6 +277,10 @@ function FileLeafNode({ Type: {file.type === FileType.DERIVATION ? "Derivation" : "Text"}
+
+ Git: + {file.gitignore ? "Gitignored (ephemeral)" : "Committed"} +
{file.mode && (
Mode: @@ -369,20 +362,13 @@ function FolderTreeNode({ )} {node.name} - - {fileCount} - + {fileCount}
{sortedChildren.map((child) => ( - + ))}
@@ -444,10 +430,7 @@ function GeneratedFilesTab({ const collapsed: FileTreeNode = { ...raw, children: new Map( - [...raw.children.entries()].map(([k, v]) => [ - k, - collapseSingleChildFolders(v), - ]), + [...raw.children.entries()].map(([k, v]) => [k, collapseSingleChildFolders(v)]), ), }; return collapsed; @@ -479,9 +462,7 @@ function GeneratedFilesTab({ {staleCount > 0 && (
- - {staleCount} stale - + {staleCount} stale
)} @@ -502,20 +483,13 @@ function GeneratedFilesTab({ {filteredFiles.length === 0 ? (
-

- No generated files match this filter -

+

No generated files match this filter

) : (
{sortedTopLevel.map((child) => ( - + ))}
@@ -528,11 +502,7 @@ function GeneratedFilesTab({ // Integrations Tab // ============================================================================= -function IntegrationItem({ - integration, -}: { - integration: InspectorIntegration; -}) { +function IntegrationItem({ integration }: { integration: InspectorIntegration }) { return (
@@ -545,9 +515,7 @@ function IntegrationItem({
@@ -577,11 +545,7 @@ function IntegrationItem({ ); } -function IntegrationsTab({ - integrations, -}: { - integrations: InspectorIntegration[]; -}) { +function IntegrationsTab({ integrations }: { integrations: InspectorIntegration[] }) { const enabledCount = integrations.filter((i) => i.enabled).length; return ( @@ -595,9 +559,7 @@ function IntegrationsTab({ {integrations.length === 0 ? (
-

- No integrations configured -

+

No integrations configured

) : (
@@ -637,9 +599,7 @@ function ScriptItem({ script }: { script: InspectorScript }) {
{script.name} {script.description && ( - - — {script.description} - + — {script.description} )}
@@ -654,11 +614,7 @@ function ScriptItem({ script }: { script: InspectorScript }) { handleCopy(); }} > - {copied ? ( - - ) : ( - - )} + {copied ? : }
@@ -668,9 +624,7 @@ function ScriptItem({ script }: { script: InspectorScript }) { {script.scriptPath && (
Path:{" "} - - {script.scriptPath} - + {script.scriptPath}
)} @@ -688,9 +642,7 @@ function ScriptItem({ script }: { script: InspectorScript }) { variant="ghost" size="sm" className="h-5 gap-1 px-1 text-xs" - onClick={() => - navigator.clipboard.writeText(script.scriptSource!) - } + onClick={() => navigator.clipboard.writeText(script.scriptSource!)} > Copy @@ -706,9 +658,7 @@ function ScriptItem({ script }: { script: InspectorScript }) { ) : (
Command:{" "} - - {script.command || script.name} - + {script.command || script.name}
)}
@@ -728,9 +678,7 @@ function ScriptsTab({ scripts }: { scripts: InspectorScript[] }) { return (
-

- No scripts match this filter -

+

No scripts match this filter

); } @@ -814,18 +762,14 @@ function StateFileItem({ file }: { file: InspectorStateFile }) { )} {file.name} - - {file.path} - + {file.path}
-              {isJson
-                ? JSON.stringify(parsedContent, null, 2)
-                : String(parsedContent)}
+              {isJson ? JSON.stringify(parsedContent, null, 2) : String(parsedContent)}
             
@@ -1015,10 +959,7 @@ function ConfigSourceBadge({ source }: { source: string | null }) { * * Returns `undefined` when no match is found. */ -function resolveConfigPath( - obj: Record, - path: string, -): unknown | undefined { +function resolveConfigPath(obj: Record, path: string): unknown | undefined { const segments = path.split("."); let current: unknown = obj; @@ -1029,9 +970,7 @@ function resolveConfigPath( const key = segment in record ? segment - : Object.keys(record).find( - (k) => k.toLowerCase() === segment.toLowerCase(), - ); + : Object.keys(record).find((k) => k.toLowerCase() === segment.toLowerCase()); if (key === undefined) return undefined; current = record[key]; } @@ -1050,10 +989,7 @@ function filterConfigByKeySearch( ): Record | undefined { const lowerQuery = query.toLowerCase(); - function walk( - node: unknown, - currentPath: string, - ): unknown | undefined { + function walk(node: unknown, currentPath: string): unknown | undefined { if (node == null || typeof node !== "object") { // Leaf – keep it only if the path so far matches return currentPath.toLowerCase().includes(lowerQuery) ? node : undefined; @@ -1105,19 +1041,15 @@ function ConfigTab({ const [viewMode, setViewMode] = useState("evaluated"); const [editingTarget, setEditingTarget] = useState(null); const [isSaving, setIsSaving] = useState(false); - const [fileStates, setFileStates] = useState>( - EMPTY_CONFIG_FILE_STATES, - ); + const [fileStates, setFileStates] = + useState>(EMPTY_CONFIG_FILE_STATES); const [configSchema, setConfigSchema] = useState(null); const [schemaStatus, setSchemaStatus] = useState<"idle" | "loading" | "ready" | "error">("idle"); const [schemaError, setSchemaError] = useState(null); const [editorMarkers, setEditorMarkers] = useState([]); const updateFileState = useCallback( - ( - target: ConfigFileTarget, - updater: (state: ConfigFileState) => ConfigFileState, - ) => { + (target: ConfigFileTarget, updater: (state: ConfigFileState) => ConfigFileState) => { setFileStates((prev) => ({ ...prev, [target]: updater(prev[target]), @@ -1126,66 +1058,69 @@ function ConfigTab({ [], ); - const loadConfigFile = useCallback(async (target: ConfigFileTarget) => { - if (!isConnected) { - return; - } - - updateFileState(target, (prev) => ({ - ...prev, - status: "loading", - error: null, - })); - - try { - const projection = await nixEval( - CONFIG_FILE_PROJECTION_EVALS[target], - ); - const path = projection.path || CONFIG_FILE_DEFAULT_PATHS[target]; - const rawFile = (await readFile(path)) as FileReadResult; - const nextConfig = isRecord(projection.config) ? projection.config : {}; - const jsonText = JSON.stringify(nextConfig, null, 2); - const rawContent = rawFile.exists ? rawFile.content ?? "" : ""; + const loadConfigFile = useCallback( + async (target: ConfigFileTarget) => { + if (!isConnected) { + return; + } - setFileStates((prev) => ({ + updateFileState(target, (prev) => ({ ...prev, - [target]: { - status: "ready", - path, - exists: Boolean(projection.exists), - isFunction: Boolean(projection.isFunction), - rawMode: false, - config: nextConfig, - jsonText, - savedJsonText: jsonText, - rawContent, - savedRawContent: rawContent, + status: "loading", error: null, - }, })); - } catch (error) { - const fallback = await readConfigFileFallback(target, readFile); - setFileStates((prev) => ({ - ...prev, - [target]: { - status: "ready", - path: fallback.path, - exists: fallback.exists, - isFunction: detectFunctionWrapper(fallback.content), - rawMode: true, - config: null, - jsonText: EMPTY_JSON_TEXT, - savedJsonText: EMPTY_JSON_TEXT, - rawContent: fallback.content, - savedRawContent: fallback.content, - error: - error instanceof Error - ? error.message - : `Could not render ${getConfigFileName(target)} as JSON`, - }, - })); - } - }, [isConnected, nixEval, readFile, updateFileState]); + + try { + const projection = await nixEval( + CONFIG_FILE_PROJECTION_EVALS[target], + ); + const path = projection.path || CONFIG_FILE_DEFAULT_PATHS[target]; + const rawFile = (await readFile(path)) as FileReadResult; + const nextConfig = isRecord(projection.config) ? projection.config : {}; + const jsonText = JSON.stringify(nextConfig, null, 2); + const rawContent = rawFile.exists ? (rawFile.content ?? "") : ""; + + setFileStates((prev) => ({ + ...prev, + [target]: { + status: "ready", + path, + exists: Boolean(projection.exists), + isFunction: Boolean(projection.isFunction), + rawMode: false, + config: nextConfig, + jsonText, + savedJsonText: jsonText, + rawContent, + savedRawContent: rawContent, + error: null, + }, + })); + } catch (error) { + const fallback = await readConfigFileFallback(target, readFile); + setFileStates((prev) => ({ + ...prev, + [target]: { + status: "ready", + path: fallback.path, + exists: fallback.exists, + isFunction: detectFunctionWrapper(fallback.content), + rawMode: true, + config: null, + jsonText: EMPTY_JSON_TEXT, + savedJsonText: EMPTY_JSON_TEXT, + rawContent: fallback.content, + savedRawContent: fallback.content, + error: + error instanceof Error + ? error.message + : `Could not render ${getConfigFileName(target)} as JSON`, + }, + })); + } + }, + [isConnected, nixEval, readFile, updateFileState], + ); const loadConfigSchema = useCallback(async () => { if (!isConnected || schemaStatus === "loading" || schemaStatus === "ready") { @@ -1203,9 +1138,7 @@ function ConfigTab({ setSchemaStatus("ready"); } catch (error) { setSchemaStatus("error"); - setSchemaError( - error instanceof Error ? error.message : "Failed to load config schema", - ); + setSchemaError(error instanceof Error ? error.message : "Failed to load config schema"); } }, [isConnected, nixEval, schemaStatus]); @@ -1213,12 +1146,8 @@ function ConfigTab({ const currentFileState = currentTarget ? fileStates[currentTarget] : null; const isEditing = currentTarget !== null && editingTarget === currentTarget; const currentFileLabel = currentTarget ? CONFIG_FILE_LABELS[currentTarget] : null; - const currentFileDescription = currentTarget - ? CONFIG_FILE_DESCRIPTIONS[currentTarget] - : null; - const currentFileDefaultPath = currentTarget - ? CONFIG_FILE_DEFAULT_PATHS[currentTarget] - : null; + const currentFileDescription = currentTarget ? CONFIG_FILE_DESCRIPTIONS[currentTarget] : null; + const currentFileDefaultPath = currentTarget ? CONFIG_FILE_DEFAULT_PATHS[currentTarget] : null; const currentModelPath = currentTarget ? `file:///stackpanel/${currentTarget === "config" ? "config" : "config.local"}.json` : "file:///stackpanel/config.json"; @@ -1260,16 +1189,16 @@ function ConfigTab({ : !isCurrentFileReady ? null : currentFileState?.rawMode - ? null - : currentFileState?.config ?? null; + ? null + : (currentFileState?.config ?? null); const activeJsonString = viewMode === "evaluated" ? configString : !isCurrentFileReady ? "" : currentFileState?.rawMode - ? currentFileState.rawContent - : currentFileState?.jsonText ?? EMPTY_JSON_TEXT; + ? currentFileState.rawContent + : (currentFileState?.jsonText ?? EMPTY_JSON_TEXT); const hasJsonFiltering = !isEditing && Boolean(activeJsonObject); const hasValidationErrors = editorMarkers.some((marker) => marker.severity === 8); const hasFileChanges = currentFileState @@ -1295,18 +1224,16 @@ function ConfigTab({ const realKey = segments[j] in rec ? segments[j] - : Object.keys(rec).find( - (key) => key.toLowerCase() === segments[j].toLowerCase(), - ) ?? segments[j]; + : (Object.keys(rec).find((key) => key.toLowerCase() === segments[j].toLowerCase()) ?? + segments[j]); lookupObj = rec[realKey]; } const rec = lookupObj as Record; const realKey = segments[i] in rec ? segments[i] - : Object.keys(rec).find( - (key) => key.toLowerCase() === segments[i].toLowerCase(), - ) ?? segments[i]; + : (Object.keys(rec).find((key) => key.toLowerCase() === segments[i].toLowerCase()) ?? + segments[i]); wrapped = { [realKey]: wrapped }; } filteredConfig = JSON.stringify(wrapped, null, 2); @@ -1396,9 +1323,7 @@ function ConfigTab({
- {viewMode === "evaluated" - ? "Full evaluated Nix configuration" - : currentFileDescription} + {viewMode === "evaluated" ? "Full evaluated Nix configuration" : currentFileDescription} {viewMode === "evaluated" ? ( @@ -1458,12 +1383,7 @@ function ConfigTab({ {currentTarget && isEditing ? ( <> -
@@ -1511,15 +1431,19 @@ function ConfigTab({
-

Editing the JSON projection of {currentFileState?.path}.

- Save converts the edited object back into Nix so {currentFileLabel?.toLowerCase() ?? "this file"} stays in sync. + Editing the JSON projection of {currentFileState?.path}. +

+

+ Save converts the edited object back into Nix so{" "} + {currentFileLabel?.toLowerCase() ?? "this file"} stays in sync.

{schemaStatus === "loading" ?

Loading option hints...

: null} {schemaStatus === "error" && schemaError ?

{schemaError}

: null} {hasValidationErrors ? (

- Fix {editorMarkers.filter((marker) => marker.severity === 8).length} validation error(s) before saving. + Fix {editorMarkers.filter((marker) => marker.severity === 8).length} validation + error(s) before saving.

) : null}
@@ -1546,8 +1470,7 @@ function ConfigTab({

Supports dot-path filtering

- Use dot-separated paths to drill into the config and view full - objects. Examples: + Use dot-separated paths to drill into the config and view full objects. Examples:

services.postgres @@ -1619,8 +1542,7 @@ async function readConfigFileFallback( target: ConfigFileTarget, readFile: (path: string) => Promise, ): Promise<{ path: string; exists: boolean; content: string }> { - const stackPath = - target === "config" ? ".stack/config.nix" : ".stack/config.local.nix"; + const stackPath = target === "config" ? ".stack/config.nix" : ".stack/config.local.nix"; const legacyPath = target === "config" ? ".stackpanel/config.nix" : ".stackpanel/config.local.nix"; const [stackFile, legacyFile] = await Promise.all([ @@ -1668,10 +1590,7 @@ function getConfigFileName(target: ConfigFileTarget): string { return target === "config" ? "config.nix" : "config.local.nix"; } -function getDefaultEmptySource( - target: ConfigFileTarget, - isFunction: boolean, -): string { +function getDefaultEmptySource(target: ConfigFileTarget, isFunction: boolean): string { const defaultHeader = CONFIG_FILE_DEFAULT_HEADERS[target]; if (isFunction && defaultHeader) { return `${defaultHeader}\n{ }\n`; @@ -1700,24 +1619,15 @@ function formatFileSize(bytes: number): string { return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } -function matchesContributor( - value: string | null | undefined, - contributor: string, -): boolean { +function matchesContributor(value: string | null | undefined, contributor: string): boolean { return (value ?? "").toLowerCase() === contributor.toLowerCase(); } -function textContainsContributor( - value: string | null | undefined, - contributor: string, -): boolean { +function textContainsContributor(value: string | null | undefined, contributor: string): boolean { return (value ?? "").toLowerCase().includes(contributor.toLowerCase()); } -function filterInspectorDataByContributor( - data: InspectorData, - contributor: string, -): InspectorData { +function filterInspectorDataByContributor(data: InspectorData, contributor: string): InspectorData { const files = data.generatedFiles.files.filter( (file) => matchesContributor(file.source, contributor) || @@ -1840,27 +1750,21 @@ export function InspectorPanel({ initialContributor }: InspectorPanelProps = {})