From 2a0709bb2b4d059adb6090939591083bfc191c8c Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:27:41 +0900 Subject: [PATCH] feat(plugins): browse scripts by package and folder Co-Authored-By: Codex Co-Authored-By: Claude --- Interceptor/Automation/PluginScriptTree.swift | 34 +++++ .../Views/Automation/PluginBrowserView.swift | 123 ++++++++++++---- .../Automation/PluginFileDetailView.swift | 88 ------------ InterceptorTests/PluginScriptTreeTests.swift | 136 ++++++++++++++++++ InterceptorUITests/AutomationUITests.swift | 85 +++++++---- .../plans/2026-10-24-script-tree.md | 67 +++++++++ 6 files changed, 389 insertions(+), 144 deletions(-) create mode 100644 Interceptor/Automation/PluginScriptTree.swift create mode 100644 InterceptorTests/PluginScriptTreeTests.swift create mode 100644 docs/superpowers/plans/2026-10-24-script-tree.md diff --git a/Interceptor/Automation/PluginScriptTree.swift b/Interceptor/Automation/PluginScriptTree.swift new file mode 100644 index 0000000..6ec3061 --- /dev/null +++ b/Interceptor/Automation/PluginScriptTree.swift @@ -0,0 +1,34 @@ +import Foundation + +/// Immediate-child projection of already validated package-relative source paths. +enum PluginScriptTree { + struct Entry: Equatable, Identifiable { + enum Kind: String { case directory, file } + + let name: String + /// Full relative path: the directory prefix, or the exact source file name. + let path: String + let kind: Kind + var id: String { kind.rawValue + ":" + path } + } + + /// Folders first, then files; each sorted exactly by name. Prefixes match whole path components. + static func entries(in files: [String], at directory: [String] = []) -> [Entry] { + var folders = Set() + var leaves = Set() + for file in files { + let components = file.split(separator: "/", omittingEmptySubsequences: false).map(String.init) + guard components.count > directory.count, components.starts(with: directory) else { continue } + if components.count == directory.count + 1 { + leaves.insert(file) + } else { + folders.insert(components[directory.count]) + } + } + let prefix = directory.isEmpty ? "" : directory.joined(separator: "/") + "/" + let directories = folders.sorted().map { Entry(name: $0, path: prefix + $0, kind: .directory) } + let documents = leaves.map { Entry(name: String($0.dropFirst(prefix.count)), path: $0, kind: .file) } + .sorted { $0.name < $1.name } + return directories + documents + } +} diff --git a/Interceptor/Views/Automation/PluginBrowserView.swift b/Interceptor/Views/Automation/PluginBrowserView.swift index 9b99af2..ba6367a 100644 --- a/Interceptor/Views/Automation/PluginBrowserView.swift +++ b/Interceptor/Views/Automation/PluginBrowserView.swift @@ -573,40 +573,109 @@ struct PluginScriptFilesView: View { let model: PluginBrowserModel var package: PluginPackagePresentation? var body: some View { - List { - if let package { - files(package) - } else { - PluginBrowserErrors(controller: model.controller, queryError: model.catalogReadError) - if !model.controller.isLoaded { + if let package { + PluginScriptDirectoryView(package: package, directory: []) + } else { + let controller = model.controller + let hasError = (controller.storeError ?? controller.installationError ?? controller.packageCatalogError + ?? controller.actionError ?? model.catalogReadError) != nil + let installed = model.installedPackages() + let duplicateNames = Set(Dictionary(grouping: installed, by: { $0.package.manifest.name }).filter { $0.value.count > 1 }.keys) + List { + PluginBrowserErrors(controller: controller, queryError: model.catalogReadError) + if !controller.isLoaded { ProgressView("AUTO_BROWSER_LOADING").accessibilityIdentifier("plugins.loading") } - ForEach(model.installedPackages(), id: \.id) { revision in - Section(revision.package.manifest.name) { files(model.presentation(of: revision)) } + ForEach(installed, id: \.id) { revision in + let manifest = revision.package.manifest + let source = PluginBrowserFamilyID(revision).source + let summary = duplicateNames.contains(manifest.name) + ? (source == "local" ? String(localized: "AUTO_BROWSER_LOCAL") : source) : (manifest.summary ?? "") + NavigationLink { + PluginScriptDirectoryView(package: model.presentation(of: revision), directory: []) + } label: { + PluginPackageRow(name: manifest.name, author: manifest.author, version: manifest.version, + summary: summary, iconSource: .bundled(revision.package), isInstalled: true) + } + .accessibilityIdentifier("plugins.scriptPackage." + manifest.id.uuidString + "." + revision.id) + } + if installed.isEmpty && controller.isLoaded && !hasError { + ContentUnavailableView { + Label("AUTO_BROWSER_NO_SCRIPTS", systemImage: "doc.text") + } description: { + Text("AUTO_BROWSER_ADD_TO_SEE_SCRIPTS") + } + .listRowSeparator(.hidden) } } + .listStyle(.plain) + .navigationTitle("AUTO_BROWSER_SCRIPTS") + .navigationBarTitleDisplayMode(.large) + .accessibilityIdentifier("plugins.scripts") } - .listStyle(.plain) - .navigationTitle("AUTO_BROWSER_SCRIPTS") - .navigationBarTitleDisplayMode(package == nil ? .large : .inline) - .accessibilityIdentifier("plugins.scripts") - } - - private func files(_ package: PluginPackagePresentation) -> some View { - ForEach(package.sourceFileNames, id: \.self) { file in - NavigationLink { - PluginFileDetailView(package: package, file: file) - } label: { - Label { - VStack(alignment: .leading, spacing: 3) { - Text(verbatim: (file as NSString).lastPathComponent) - if file.contains("/") { - Text(verbatim: file).font(.footnote).foregroundStyle(.secondary) - } + } +} + +/// One directory level of a package's source tree; folders recurse into the same view. +struct PluginScriptDirectoryView: View { + let package: PluginPackagePresentation + let directory: [String] + @State private var openedFile: OpenedFile? + @State private var selection: String? + + private struct OpenedFile: Identifiable { + let path: String + var id: String { path } + } + + private func source(of file: String) -> String { + package.manifest.schemaVersion == 2 ? package.sourceFiles[file] ?? "" : package.source ?? "" + } + + var body: some View { + let scope = package.manifest.id.uuidString + let entries = PluginScriptTree.entries(in: package.sourceFileNames, at: directory) + List { + if entries.isEmpty { + ContentUnavailableView("AUTO_BROWSER_NO_SCRIPTS", systemImage: "doc.text") + .listRowSeparator(.hidden) + } + Section { + ForEach(entries) { entry in + switch entry.kind { + case .directory: + NavigationLink { + PluginScriptDirectoryView(package: package, directory: directory + [entry.name]) + } label: { + Label { + Text(verbatim: entry.name) + } icon: { Image(systemName: "folder").foregroundStyle(PluginBrowserColor.accent) } + } + .accessibilityIdentifier("plugins.scriptFolder." + scope + "." + entry.path) + case .file: + Button { openedFile = OpenedFile(path: entry.path) } label: { + Label { + Text(verbatim: entry.name).foregroundStyle(.primary) + } icon: { Image(systemName: "doc.text").foregroundStyle(PluginBrowserColor.accent) } + } + .accessibilityIdentifier("plugins.file." + scope + "." + entry.path) } - } icon: { Image(systemName: "doc.text").foregroundStyle(PluginBrowserColor.accent) } + } + } header: { + if !directory.isEmpty { + Text(verbatim: package.manifest.name + "\n" + directory.joined(separator: "/")).textCase(nil) + } } - .accessibilityIdentifier("plugins.file." + package.manifest.id.uuidString + "." + file) + } + .listStyle(.plain) + .navigationTitle(Text(verbatim: directory.last ?? package.manifest.name)) + .navigationBarTitleDisplayMode(.inline) + .accessibilityIdentifier("plugins.scriptDirectory." + scope + "." + directory.joined(separator: "/")) + .fullScreenCover(item: $openedFile) { file in + PluginSourceReader(fileNames: [], selection: $selection, source: { _ in source(of: file.path) }, + sourceIdentifier: "plugins.file.source", pickerIdentifier: "plugins.file.sourcePicker", + closeIdentifier: "plugins.file.closeSource", title: (file.path as NSString).lastPathComponent, + accentColor: PluginBrowserColor.accent) { openedFile = nil } } } } diff --git a/Interceptor/Views/Automation/PluginFileDetailView.swift b/Interceptor/Views/Automation/PluginFileDetailView.swift index e4067af..2edb585 100644 --- a/Interceptor/Views/Automation/PluginFileDetailView.swift +++ b/Interceptor/Views/Automation/PluginFileDetailView.swift @@ -1,94 +1,6 @@ import AutomationCore import SwiftUI -/// File metadata only. The exact file's source remains hidden until Source Code is explicitly opened. -struct PluginFileDetailView: View { - let package: PluginPackagePresentation - let file: String - @State private var showSource = false - @State private var selection: String? - - private var name: String { - (file as NSString).lastPathComponent - } - - private var rules: [PluginBrowserRule] { - package.rulesByFile[file] ?? [] - } - - /// Hooks sharing the same traffic conditions belong to one visible target. - private var groupedRules: [[PluginBrowserRule]] { - rules.reduce(into: []) { groups, rule in - if let index = groups.firstIndex(where: { group in - guard let first = group.first else { return false } - return first.hosts == rule.hosts && first.methods == rule.methods - && first.path == rule.path && first.status == rule.status - }) { - groups[index].append(rule) - } else { - groups.append([rule]) - } - } - } - - private var source: String { - package.manifest.schemaVersion == 2 ? package.sourceFiles[file] ?? "" : package.source ?? "" - } - - var body: some View { - List { - Section { - ForEach(Array(groupedRules.enumerated()), id: \.offset) { index, group in - let rule = group[0] - VStack(alignment: .leading, spacing: 8) { - fact("AUTO_BROWSER_TARGET_HOSTS", rule.hosts.joined(separator: "\n")) - fact("AUTO_TARGET_METHODS", rule.methods?.joined(separator: ", ") ?? String(localized: "AUTO_RULE_ANY_METHOD")) - switch rule.path { - case let .exact(value)?: fact("AUTO_PATH_EXACT", value) - case let .prefix(value)?: fact("AUTO_PATH_PREFIX", value) - case nil: fact("AUTO_TARGET_PATH", String(localized: "AUTO_RULE_ANY_PATH")) - } - fact("AUTO_HOOK", Array(Set(group.map(\.hook))).sorted().joined(separator: "\n")) - if let status = rule.status { - fact("AUTO_TARGET_STATUS", "\(status.lowerBound)–\(status.upperBound)") - } - } - .accessibilityIdentifier("plugins.file.rule.\(index)") - } - } header: { Text("AUTO_TARGETS") } - Section { - Button { showSource = true } label: { - HStack { - Text("AUTO_BROWSER_SOURCE_CODE").foregroundStyle(.primary) - Spacer() - Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary) - } - .contentShape(Rectangle()) - } - .accessibilityAddTraits(.isLink) - .accessibilityIdentifier("plugins.file.openSource") - } - } - .listStyle(.plain) - .navigationTitle(Text(verbatim: name)) - .navigationBarTitleDisplayMode(.inline) - .accessibilityIdentifier("plugins.file.detail") - .fullScreenCover(isPresented: $showSource) { - PluginSourceReader(fileNames: [], selection: $selection, source: { _ in source }, - sourceIdentifier: "plugins.file.source", pickerIdentifier: "plugins.file.sourcePicker", - closeIdentifier: "plugins.file.closeSource", title: name, - accentColor: PluginBrowserColor.accent) { showSource = false } - } - } - - private func fact(_ title: LocalizedStringKey, _ value: String) -> some View { - VStack(alignment: .leading, spacing: 3) { - Text(title).font(.footnote).foregroundStyle(.secondary) - Text(verbatim: value).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) - } - } -} - struct PluginManifestJSONView: View { let package: PluginPackagePresentation let done: () -> Void diff --git a/InterceptorTests/PluginScriptTreeTests.swift b/InterceptorTests/PluginScriptTreeTests.swift new file mode 100644 index 0000000..f1968bf --- /dev/null +++ b/InterceptorTests/PluginScriptTreeTests.swift @@ -0,0 +1,136 @@ +@testable import Interceptor +import XCTest + +final class PluginScriptTreeTests: XCTestCase { + private func summary(_ entries: [PluginScriptTree.Entry]) -> [String] { + entries.map { "\($0.kind == .directory ? "d" : "f"):\($0.name):\($0.path)" } + } + + func testRootMixedFilesAndFoldersListFoldersFirstSorted() { + let entries = PluginScriptTree.entries(in: [ + "z.js", "hooks/POST.js", "a.js", "api/GET.js", "hooks/GET.js", + ]) + XCTAssertEqual(summary(entries), [ + "d:api:api", "d:hooks:hooks", "f:a.js:a.js", "f:z.js:z.js", + ]) + } + + func testRootFileIsLeafWithFullPath() { + let entries = PluginScriptTree.entries(in: ["script.js"]) + XCTAssertEqual(summary(entries), ["f:script.js:script.js"]) + } + + func testLegacyRootScriptJS() { + let entries = PluginScriptTree.entries(in: ["script.js"], at: []) + XCTAssertEqual(entries.count, 1) + XCTAssertEqual(entries.first?.kind, .file) + XCTAssertEqual(entries.first?.path, "script.js") + } + + func testEmptyInputYieldsNoEntries() { + XCTAssertTrue(PluginScriptTree.entries(in: []).isEmpty) + XCTAssertTrue(PluginScriptTree.entries(in: [], at: ["hooks"]).isEmpty) + } + + func testNestedDuplicatePOSTBasenamesStayInSeparateDirectories() { + let files = [ + "hooks/a.example.com/v1/POST.js", + "hooks/b.example.com/v1/POST.js", + "hooks/a.example.com/v2/POST.js", + ] + XCTAssertEqual(summary(PluginScriptTree.entries(in: files)), ["d:hooks:hooks"]) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["hooks"])), + ["d:a.example.com:hooks/a.example.com", "d:b.example.com:hooks/b.example.com"] + ) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["hooks", "a.example.com"])), + ["d:v1:hooks/a.example.com/v1", "d:v2:hooks/a.example.com/v2"] + ) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["hooks", "a.example.com", "v1"])), + ["f:POST.js:hooks/a.example.com/v1/POST.js"] + ) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["hooks", "b.example.com", "v1"])), + ["f:POST.js:hooks/b.example.com/v1/POST.js"] + ) + } + + func testPrefixMatchUsesWholeComponentsSoApiAndApi2AreUnrelated() { + let files = ["api/POST.js", "api2/POST.js", "api2/extra/GET.js"] + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["api"])), + ["f:POST.js:api/POST.js"] + ) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["api2"])), + ["d:extra:api2/extra", "f:POST.js:api2/POST.js"] + ) + XCTAssertEqual(summary(PluginScriptTree.entries(in: files)), ["d:api:api", "d:api2:api2"]) + } + + func testMissingDirectoryYieldsNoEntries() { + XCTAssertTrue(PluginScriptTree.entries(in: ["api/POST.js"], at: ["ap"]).isEmpty) + XCTAssertTrue(PluginScriptTree.entries(in: ["api/POST.js"], at: ["api", "POST.js"]).isEmpty) + } + + func testFileAndFolderWithSameBasenameRetainedWithDistinctIDs() { + let entries = PluginScriptTree.entries(in: ["hooks", "hooks/POST.js"]) + XCTAssertEqual(summary(entries), ["d:hooks:hooks", "f:hooks:hooks"]) + XCTAssertEqual(entries.count, 2) + XCTAssertNotEqual(entries[0].id, entries[1].id) + XCTAssertEqual(Set(entries.map(\.id)).count, 2) + } + + func testIDsAreDistinctForSameBasenameAcrossDirectories() { + let a = PluginScriptTree.entries(in: ["a/POST.js"], at: ["a"]) + let b = PluginScriptTree.entries(in: ["b/POST.js"], at: ["b"]) + XCTAssertEqual(a.first?.name, "POST.js") + XCTAssertEqual(b.first?.name, "POST.js") + XCTAssertNotEqual(a.first?.id, b.first?.id) + } + + func testIDsAreStableAcrossCalls() { + let files = ["x/y/POST.js", "x/z.js", "top.js"] + XCTAssertEqual( + PluginScriptTree.entries(in: files, at: ["x"]).map(\.id), + PluginScriptTree.entries(in: files, at: ["x"]).map(\.id) + ) + } + + func testLeafKeepsExactFullRelativePath() { + let entries = PluginScriptTree.entries( + in: ["hooks/api.example.com/v1/users/POST.js"], + at: ["hooks", "api.example.com", "v1", "users"] + ) + XCTAssertEqual(entries.count, 1) + XCTAssertEqual(entries[0].name, "POST.js") + XCTAssertEqual(entries[0].path, "hooks/api.example.com/v1/users/POST.js") + XCTAssertEqual(entries[0].kind, .file) + } + + func testOutputIsIndependentOfInputOrderAndDeduplicatesFolders() { + let files = [ + "b/POST.js", "a/GET.js", "b/GET.js", "a/POST.js", "root.js", "a/sub/x.js", "a/sub/y.js", + ] + let reversed = Array(files.reversed()) + XCTAssertEqual(PluginScriptTree.entries(in: files), PluginScriptTree.entries(in: reversed)) + XCTAssertEqual(summary(PluginScriptTree.entries(in: files)), ["d:a:a", "d:b:b", "f:root.js:root.js"]) + XCTAssertEqual( + PluginScriptTree.entries(in: files, at: ["a"]), + PluginScriptTree.entries(in: reversed, at: ["a"]) + ) + XCTAssertEqual( + summary(PluginScriptTree.entries(in: files, at: ["a"])), + ["d:sub:a/sub", "f:GET.js:a/GET.js", "f:POST.js:a/POST.js"] + ) + } + + func testSortingIsExactLexicalAndCaseSensitive() { + let entries = PluginScriptTree.entries(in: ["b.js", "B.js", "a.js", "10.js", "2.js", "Z/x.js", "a/x.js"]) + XCTAssertEqual(summary(entries), [ + "d:Z:Z", "d:a:a", "f:10.js:10.js", "f:2.js:2.js", "f:B.js:B.js", "f:a.js:a.js", "f:b.js:b.js", + ]) + } +} diff --git a/InterceptorUITests/AutomationUITests.swift b/InterceptorUITests/AutomationUITests.swift index ae22567..19a8643 100644 --- a/InterceptorUITests/AutomationUITests.swift +++ b/InterceptorUITests/AutomationUITests.swift @@ -164,36 +164,37 @@ final class AutomationUITests: XCTestCase { let app = launch(japanese: japanese, suite: suite) defer { app.terminate() } installMulti(repositoryURL, app: app, japanese: japanese) + XCTAssertFalse(app.buttons.matching(identifier: "plugins.package.test").firstMatch.exists) selectTab("scripts", app: app) if !japanese { attach("Installed script files en") } - for (file, source, path, excluded) in [ - (PluginRepositorySources.primaryFile, PluginRepositorySources.primarySource, "/synthetic", "/other"), - (PluginRepositorySources.secondaryFile, PluginRepositorySources.secondarySource, "/other", "/synthetic"), + for (file, source) in [ + (PluginRepositorySources.primaryFile, PluginRepositorySources.primarySource), + (PluginRepositorySources.secondaryFile, PluginRepositorySources.secondarySource), ] { + XCTAssertGreaterThan(file.split(separator: "/").count, 1, "fixture exercises folder navigation") openFile(file, packageID: Self.multiID, app: app) - let detail = scrollContainer(app, "plugins.file.detail") - XCTAssertTrue(text(path, in: detail).exists) - XCTAssertFalse(text(excluded, in: detail).exists, "file metadata contains only this file's rules") - XCTAssertFalse(app.scrollViews["plugins.file.source"].exists, "source requires an explicit action") - if !japanese && file == PluginRepositorySources.primaryFile { attach("File target metadata en") } - let reader = openFileSource(app) + let parent = file.split(separator: "/").dropLast().joined(separator: "/") + let directory = scrollContainer(app, "plugins.scriptDirectory." + Self.multiID + "." + parent) + XCTAssertFalse(app.scrollViews["plugins.file.source"].exists, "source opens only after the file is tapped") + let reader = openFileSource(file, packageID: Self.multiID, app: app) assertSource(reader, equals: source) assertReadOnly(reader, app: app) if japanese && file == PluginRepositorySources.secondaryFile { attach("Full screen exact file source ja") } app.buttons.matching(identifier: "plugins.file.closeSource").firstMatch.tap() - XCTAssertTrue(detail.waitForExistence(timeout: 5)) - XCTAssertTrue(text(path, in: detail).exists, "Done returns to the same file metadata") - let reopened = openFileSource(app) + XCTAssertTrue(directory.waitForExistence(timeout: 5), "Done returns to the file's parent directory") + let reopened = openFileSource(file, packageID: Self.multiID, app: app) assertSource(reopened, equals: source) app.buttons.matching(identifier: "plugins.file.closeSource").firstMatch.tap() - goBack(app, from: (file as NSString).lastPathComponent) + XCTAssertTrue(directory.waitForExistence(timeout: 5)) + goBackFromScriptDirectories(app, file: file, packageName: "Multi-file hooks") + XCTAssertTrue(scrollContainer(app, "plugins.scripts").waitForExistence(timeout: 5)) } app.terminate() let reopened = launch(japanese: japanese, suite: suite) openPlugins(reopened, japanese: japanese) selectTab("scripts", app: reopened) openFile(PluginRepositorySources.secondaryFile, packageID: Self.multiID, app: reopened) - assertSource(openFileSource(reopened), equals: PluginRepositorySources.secondarySource) + assertSource(openFileSource(PluginRepositorySources.secondaryFile, packageID: Self.multiID, app: reopened), equals: PluginRepositorySources.secondarySource) reopened.buttons.matching(identifier: "plugins.file.closeSource").firstMatch.tap() reopened.terminate() } @@ -326,13 +327,12 @@ final class AutomationUITests: XCTestCase { XCTAssertFalse(app.scrollViews["plugins.file.source"].exists) if japanese { attach("Package aggregate target hosts before GET ja") } reach(app.buttons.matching(identifier: "plugins.package.scripts").firstMatch, in: scrollContainer(app, "plugins.package.detail")).tap() - openFile(PluginRepositorySources.primaryFile, packageID: Self.targetsID, app: app) - let fileDetail = scrollContainer(app, "plugins.file.detail") - XCTAssertTrue(text("api.example.com", in: fileDetail).exists) - XCTAssertFalse(text("example.com", in: fileDetail).exists, "a file shows only its matching rules") - if !japanese { attach("Grouped file target conditions en") } - goBack(app, from: "POST.js") - goBack(app, from: "Scripts") + openFile(PluginRepositorySources.primaryFile, packageID: Self.targetsID, app: app, fromScriptsRoot: false) + assertSource(openFileSource(PluginRepositorySources.primaryFile, packageID: Self.targetsID, app: app), equals: PluginRepositorySources.primarySource) + if !japanese { attach("Direct file source en") } + app.buttons.matching(identifier: "plugins.file.closeSource").firstMatch.tap() + goBackFromScriptDirectories(app, file: PluginRepositorySources.primaryFile, packageName: "Target hosts example") + XCTAssertTrue(scrollContainer(app, "plugins.package.detail").waitForExistence(timeout: 5)) enqueueGet(app) openQueue(app) confirmQueue(app) @@ -488,8 +488,8 @@ final class AutomationUITests: XCTestCase { attach("Persisted manifest JSON") app.buttons["plugins.manifest.close"].tap() reach(app.buttons.matching(identifier: "plugins.package.scripts").firstMatch, in: detail).tap() - openFile(PluginRepositorySources.secondaryFile, packageID: Self.targetsID, app: app) - assertSource(openFileSource(app), equals: PluginRepositorySources.secondarySource) + openFile(PluginRepositorySources.secondaryFile, packageID: Self.targetsID, app: app, fromScriptsRoot: false) + assertSource(openFileSource(PluginRepositorySources.secondaryFile, packageID: Self.targetsID, app: app), equals: PluginRepositorySources.secondarySource) app.buttons["plugins.file.closeSource"].tap() app.terminate() @@ -820,15 +820,42 @@ private extension AutomationUITests { XCTAssertEqual(XCTWaiter.wait(for: [settled], timeout: 5), .completed, file: file, line: line) } + /// Navigates to a file's parent directory by entering its package (unless already at the package's source root) and then each folder. @MainActor - func openFile(_ file: String, packageID: String, app: XCUIApplication) { - reach(app.buttons.matching(identifier: "plugins.file." + packageID + "." + file).firstMatch, in: scrollContainer(app, "plugins.scripts")).tap() - XCTAssertTrue(scrollContainer(app, "plugins.file.detail").waitForExistence(timeout: 5)) + func openFile(_ file: String, packageID: String, app: XCUIApplication, fromScriptsRoot: Bool = true) { + if fromScriptsRoot { + let package = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "plugins.scriptPackage." + packageID + ".")).firstMatch + reach(package, in: scrollContainer(app, "plugins.scripts")).tap() + } + let components = file.split(separator: "/").map(String.init) + XCTAssertTrue(scrollContainer(app, "plugins.scriptDirectory." + packageID + ".").waitForExistence(timeout: 5)) + for count in 1 ..< max(components.count, 1) { + let parent = components[..<(count - 1)].joined(separator: "/") + let folder = components[.. XCUIElement { - reach(app.buttons.matching(identifier: "plugins.file.openSource").firstMatch, in: scrollContainer(app, "plugins.file.detail")).tap() + func openFileSource(_ file: String, packageID: String, app: XCUIApplication) -> XCUIElement { + let parent = file.split(separator: "/").dropLast().joined(separator: "/") + reach(app.buttons.matching(identifier: "plugins.file." + packageID + "." + file).firstMatch, + in: scrollContainer(app, "plugins.scriptDirectory." + packageID + "." + parent)).tap() XCTAssertTrue(app.buttons.matching(identifier: "plugins.file.closeSource").firstMatch.waitForExistence(timeout: 5)) let sourceScrollView = app.scrollViews["plugins.file.source"] XCTAssertTrue(sourceScrollView.waitForExistence(timeout: 5)) @@ -1109,7 +1136,7 @@ extension AutomationUITests { for destination in ["sources", "scripts"] { selectTab(destination, app: app) if destination == "scripts" { - XCTAssertFalse(scrollContainer(app, "plugins.scripts").staticTexts.allElementsBoundByIndex.contains(where: \.isHittable), "empty Scripts has no placeholder copy") + XCTAssertTrue(scrollContainer(app, "plugins.scripts").staticTexts[japanese ? "スクリプトはありません" : "No Scripts"].waitForExistence(timeout: 5)) } guard openSearchTab(app) else { return false } XCTAssertEqual(searchText(app), "Browser fixture author", "Search query retained through \(destination)") diff --git a/docs/superpowers/plans/2026-10-24-script-tree.md b/docs/superpowers/plans/2026-10-24-script-tree.md new file mode 100644 index 0000000..683a3ad --- /dev/null +++ b/docs/superpowers/plans/2026-10-24-script-tree.md @@ -0,0 +1,67 @@ +# Scripts Directory Navigation Implementation Plan + +> **For agentic workers:** Use executing-plans task by task. Codex owns native verification and integration. + +**Goal:** Drill through Package and path components before opening a source file. +**Architecture:** Pure immediate-child projection of validated package paths with existing closure-based SwiftUI NavigationLinks. +**Tech Stack:** Swift6, SwiftUI, XCTest; iOS18 and26. +**Spec:** Canonical docs/mock-diff/SPEC.md at /Users/devonly/Developer/interceptor-live-scripts-20261018/Interceptor, current human Scripts-tree request. + +## Task checklist +- [x] Update canonical mock components/screens first. +- [x] Write focused projection tests; confirm expected failure on native Mac. +- [x] Implement projection and directory/package navigation; update obsolete flat-list UI helpers. +- [ ] Run affected native unit/UI flows and physical M3 check; retain exact capture metadata. +- [ ] Independent actual-diff review, verified commit and PR. + + +## Intent and approach +The user requested drilling through a tree because many scripts share a basename such as POST.js. Replace the flat per-package file list with the existing navigation list pattern: Scripts -> installed Package -> folders -> exact file; tapping a file directly opens the read-only full-screen source reader (no intermediate metadata). + +A push navigation hierarchy is the chosen implementation approach derived from the user's "潜っていける" request. Inline expanding rows keep the list crowded and full-path-only labels are the current problem. Reuse existing row styles and navigation; no new controls, permissions, disk access or execution behavior. + +## Behavior +- Scripts root lists installed packages, with their existing identity and bundled icon. Selecting a package opens its source root. +- The Package detail's Scripts link opens the same source-root view directly. +- Each directory shows immediate child folders first, then immediate files, deterministically sorted by exact name. Do not flatten or collapse single-child folders. +- Folder rows use the folder symbol; file rows use the document symbol. Names are the immediate component, rather than the full path. +- Nested navigation titles show the current folder name and retain package/path context in an unobtrusive section header. System Back returns one level. +- Selecting a leaf presents the existing fullScreenCover PluginSourceReader for that unchanged full relative path, with the title as the basename. Closing returns to the same parent directory; tapping again reopens. Source bytes stay exact and read-only. +- Never derive identities from basename alone. Distinguish folder/file name collisions and duplicate basenames in separate directories and packages. Prefix checks use slash components, so api and api2 are unrelated. +- Legacy schema1 remains a script.js leaf. Empty/loading/error states remain available. Assets are not scripts. +- The tree is a pure projection of already validated sourceFileNames, never FileManager/network traversal. + +## Implementation and ownership +1. Codex updates canonical mock SPEC/component and screen compositions before product code. +2. Independent LocalGPT plan review and Claude feasibility review inspect the actual repository at base7125f8f. +3. Claude implementer owns PluginScriptTree.swift, PluginScriptFilesView's section in PluginBrowserView.swift, focused projection tests, and necessary existing UI navigation helper updates. No other behavior changes or commits. +4. Codex integrates and runs native builds/app-host tests and affected navigation on iOS18.5/26.5, with exact owned simulator cleanup. Codex does physical M3 navigation and captures. Every capture is immediately exact lossless WebP, dimensions/RGBA/ICC verified; retain 16bit original only if conversion impossible. +5. A fresh independent Claude reviewer reads the actual source diff and relevant files. +6. Record Mock Diff comparison or concrete missing/incompatible baseline without changing adopted selections or resizing images. + +## Verification +- Projection tests: root file, nested duplicate POST.js, api/api2 boundary, deterministic order, mixed root/directory contents, folder/file same name, exact leaf paths, legacy script.js and empty input. +- Existing multi-file viewing UI test: enter correct Package and each folder, tap leaf to open source directly; exact source matches, Done returns to the same parent directory, re-tap reopens; no Test entry. +- Native device build and M3: Scripts Package -> hooks -> host -> URL segments -> POST.js; Done returns to the parent directory; Package detail Scripts shares the same tree. +- Reuse canonical Xcode DerivedData and SourcePackages from the current run, never create a per-task build tree. The worktree's default sibling Mudmouth differs from the verified dependency: Codex must fix the build mapping through an owned wrapper/safe worktree move before building, never modify the user's Mudmouth checkout. + +## Plan-review resolutions +- Root SwiftUI identity is immutable revision.id, never manifest UUID alone. Package row identifiers include revision.id; closure destinations capture that exact presentation. Existing optional author/version plus source context distinguish same-named packages; no basename-derived IDs. +- Directory/file row identity is typed kind plus full relative path; the package scope is explicit. Keep leaf accessibility format plugins.file.., and separate prefixes plugins.scriptPackage. and plugins.scriptFolder... +- Root loaded+noerror+noinstalled shows existing localized AUTO_BROWSER_NO_SCRIPTS. Loading/error do not show an empty message simultaneously. Empty projection is total and uses existing same key; product schema2 never has empty sourceFiles. +- No file metadata screen and no path text beyond folder navigation (the directory header already shows it); the PluginFileDetailView metadata UI is removed. Keep PluginManifestJSONView. +- Child views capture immutable presentation, consistent with current file/source metadata views. There is no refresh/delete operation inside the Scripts hierarchy. Reopening the Scripts root reads current installed packages; do not introduce a new live-rebinding system. +- UI ownership includes InterceptorUITests/AutomationUITests.swift. Update openFile and return-to-root helpers and existing multifile EN/JA flow, preserving exact source/rule checks and source viewer reopen behavior. Source constants remain generated; do not edit generated fixture declarations. +- Projection accepts already validated paths (Core rejects empty/dot/dotdot components); no second security validator. It must never trap on empty input and retains exact leaf strings. Include file/folder same-name collision and duplicate basenames as pure projection tests. + +## Projection interface +Create Interceptor/Automation/PluginScriptTree.swift. Immutable PluginScriptTree.Entry has enum Kind { directory, file }, name:String, path:String, kind:Kind and kind-prefixed fullpath id. Static entries(in files:[String], at directory:[String] = []) -> [Entry] returns immediate children, folders first and lexicallysorted within eachkind. It retains original fullrelativepath at leaves and uses exact array-component prefix. No filesystem, networking or mutable state. + +## Verification evidence + +- Projection: 13 XCTest cases passed; unchanged by the direct-source follow-up. +- Direct source: affected EN/JA UI flow passed on disposable iPhone15 simulators, iOS18.5 and26.5. Includes exact UTF8 bytes, read-only, Done returning to parent, reopen and app relaunch. +- Signed M3 build and installation succeeded. Physical navigation on the M3 has not been independently verified. +- Independent Claude actual-source review found no remaining P1/P2. +- Mock Diff compared matching English/light iPhone15 root captures to baseline-20261023:18.5 1.3904983003287845%,26.5 1.2508943018207255%. These are intentional flat-files-to-package-row differences; no baseline adoption was changed. New folder checkpoints and the direct source viewer have captures, but no matching approved regression baseline. +- LocalGPT UI-only image review could not start because its uploader could not access the Mac screenshot path. No UI-only review is claimed.