- {sidebarOpen ? (
- <>
- {/* Backdrop when the sidebar overlays the page on small screens */}
-
toggleSidebar(false)}
- aria-hidden="true"
- />
-
-
-
-
- Claudable
-
-
toggleSidebar(false)}
- className="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-200/70 hover:text-gray-900"
- title="Collapse sidebar"
- >
-
-
-
-
-
- Projects
- {projects.length > 0 && (
- {projects.length}
- )}
-
-
-
- {!projectsLoaded ? (
-
- {[0, 1, 2].map((row) => (
-
- ))}
-
- ) : projects.length === 0 ? (
- No projects yet
- ) : (
-
- {projects.map((project) => {
- const projectCli = sanitizeAssistant(project.preferredCli);
- const projectIcon = ACTIVE_CLI_OPTIONS_MAP[projectCli]?.icon ?? '/claude.png';
- const projectModel = getModelDisplayName(
- projectCli,
- normalizeModelForAssistant(projectCli, project.selectedModel)
- );
-
- if (editingProject?.id === project.id) {
- return (
-
-
-
- );
- }
-
- return (
-
- router.push(`/${project.id}/chat`)}
- title={`${project.name}\n${formatCliInfo(projectCli, project.selectedModel ?? undefined)}`}
- className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-gray-200/60"
- >
-
-
-
-
- {project.name}
-
- {formatTime(project.lastMessageAt || project.createdAt)} · {projectModel}
-
-
-
-
-
duplicateProject(project)}
- className="flex h-6 w-6 items-center justify-center rounded text-gray-500 transition-colors hover:bg-white hover:text-gray-900"
- title="Duplicate / Remix project"
- >
-
-
-
setEditingProject(project)}
- className="flex h-6 w-6 items-center justify-center rounded text-gray-500 transition-colors hover:bg-white hover:text-gray-900"
- title="Edit project name"
- >
-
-
-
openDeleteModal(project)}
- className="flex h-6 w-6 items-center justify-center rounded text-gray-500 transition-colors hover:bg-white hover:text-red-600"
- title="Delete project"
- >
-
-
-
-
- );
- })}
-
- )}
-
-
-
- setShowGlobalSettings(true)}
- className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-200/60 hover:text-gray-900"
- >
-
- Settings
-
-
-
- >
- ) : (
-
-
- toggleSidebar(true)}
- className="flex h-9 w-9 items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-200/70 hover:text-gray-900"
- title="Open sidebar"
- >
-
-
- setShowGlobalSettings(true)}
- className="mt-auto flex h-9 w-9 items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-200/70 hover:text-gray-900"
- title="Settings"
- >
-
-
-
- )}
-
- {/* Main stage */}
-
-
-
-
-
-
-
-
- Claudable
-
-
- Connect CLI Agent • Build what you want • Deploy instantly
-
-
-
- {/* Main Input Form */}
-
-
- {/* Example prompts */}
-
- {EXAMPLE_PROMPTS.map((example) => (
- setPrompt(example.prompt)}
- disabled={isCreatingProject}
- className="rounded-full border border-gray-200 bg-white/70 px-3.5 py-1.5 text-sm text-gray-600 backdrop-blur-sm transition-colors hover:border-gray-300 hover:bg-white hover:text-gray-900 disabled:cursor-not-allowed disabled:opacity-50"
- >
- {example.text}
-
- ))}
-
-
-
-
-
-
- {/* Global Settings Modal */}
-
setShowGlobalSettings(false)}
- />
-
- {/* Delete Project Modal */}
-
- {deleteModal.isOpen && deleteModal.project && (
- {
- if (!isDeleting) closeDeleteModal();
- }}
- >
- e.stopPropagation()}
- className="w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-xl"
- >
-
-
-
-
-
-
Delete Project
-
This action cannot be undone
-
-
-
-
- Are you sure you want to delete "{deleteModal.project.name}" ?
- This will permanently delete all project files and chat history.
-
-
-
-
- Cancel
-
-
- {isDeleting ? (
- <>
-
- Deleting...
- >
- ) : (
- 'Delete Project'
- )}
-
-
-
-
- )}
-
-
- {/* Toast Messages */}
-
- {toast && (
-
-
- {toast.type === 'success' ? (
-
- ) : (
-
- )}
-
{toast.message}
-
-
- )}
-
-
- );
-}
diff --git a/apple/Apps/MorphMac/Info.plist b/apple/Apps/MorphMac/Info.plist
new file mode 100644
index 000000000..f9c5251e1
--- /dev/null
+++ b/apple/Apps/MorphMac/Info.plist
@@ -0,0 +1,48 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ en
+ CFBundleDisplayName
+ Morph Code
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ Morph Code
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ 4.0.0
+ CFBundleVersion
+ 1
+ ATSApplicationFontsPath
+ .
+ CFBundleURLTypes
+
+
+ CFBundleURLName
+ ai.anymorph.morphcode
+ CFBundleURLSchemes
+
+ morphcode
+
+
+
+ LSMinimumSystemVersion
+ 15.0
+ NSAppTransportSecurity
+
+ NSAllowsLocalNetworking
+
+
+ NSMicrophoneUsageDescription
+ Microphone access is required for voice prompt dictation.
+ NSSpeechRecognitionUsageDescription
+ Speech recognition is required to transcribe spoken prompts into text.
+
+
diff --git a/apple/Apps/MorphMac/MorphMac.entitlements b/apple/Apps/MorphMac/MorphMac.entitlements
new file mode 100644
index 000000000..b572d9c04
--- /dev/null
+++ b/apple/Apps/MorphMac/MorphMac.entitlements
@@ -0,0 +1,8 @@
+
+
+
+
+ com.apple.security.device.audio-input
+
+
+
diff --git a/apple/Apps/MorphMac/MorphMacApp.swift b/apple/Apps/MorphMac/MorphMacApp.swift
new file mode 100644
index 000000000..579c000a7
--- /dev/null
+++ b/apple/Apps/MorphMac/MorphMacApp.swift
@@ -0,0 +1,458 @@
+import SwiftUI
+import MorphCore
+import AppKit
+import ObjectiveC
+
+@main
+struct MorphMacApp: App {
+ @State private var appState = MorphAppState()
+
+ init() {
+ Self.preferOverlayScrollBars()
+ Self.preferCrispFontRendering()
+ Self.hideContextMenuRowOutline()
+ }
+
+ private static func preferCrispFontRendering() {
+ let defaults = UserDefaults.standard
+ guard defaults.object(forKey: "AppleFontSmoothing") == nil,
+ defaults.object(forKey: "CGFontRenderingFontSmoothingDisabled") == nil else { return }
+ var arguments = defaults.volatileDomain(forName: UserDefaults.argumentDomain)
+ arguments["CGFontRenderingFontSmoothingDisabled"] = true
+ arguments["AppleFontSmoothing"] = 0
+ defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain)
+ }
+
+ private static func hideContextMenuRowOutline() {
+ let selector = NSSelectorFromString("drawContextMenuHighlightForRow:")
+ guard let method = class_getInstanceMethod(NSTableView.self, selector) else {
+ return
+ }
+ let drawNothing: @convention(block) (NSTableView, Int) -> Void = { _, _ in }
+ method_setImplementation(method, imp_implementationWithBlock(drawNothing))
+ }
+
+ private static func preferOverlayScrollBars() {
+ let defaults = UserDefaults.standard
+ guard defaults.string(forKey: "AppleShowScrollBars") != "Always" else { return }
+ var arguments = defaults.volatileDomain(forName: UserDefaults.argumentDomain)
+ arguments["AppleShowScrollBars"] = "WhenScrolling"
+ defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain)
+ }
+
+ var body: some Scene {
+ Window("Morph Code", id: "main") {
+ MorphMainWindow(state: appState)
+ }
+ .windowStyle(.hiddenTitleBar)
+ .windowResizability(.contentMinSize)
+ .defaultSize(width: 1220, height: 800)
+ .commands {
+ CommandGroup(replacing: .appSettings) {
+ Button("Settings…") { appState.openSettings() }
+ .keyboardShortcut(",", modifiers: .command)
+ }
+ CommandGroup(replacing: .newItem) {
+ Button("New Thread") {
+ appState.startNewCodeThreadHere()
+ }
+ .keyboardShortcut("n", modifiers: .command)
+ MorphNewCodeWindowCommand(state: appState)
+ Button("Refresh") {
+ Task { await appState.syncNow(userInitiated: true) }
+ }
+ .keyboardShortcut("r", modifiers: .command)
+ }
+ CommandGroup(after: .textEditing) {
+ Button("Find in Thread") {
+ appState.isCodeThreadFindPresented.toggle()
+ }
+ .keyboardShortcut("f", modifiers: .command)
+ }
+ CommandMenu("Navigate") {
+ Button("Command Palette") { appState.isCommandPalettePresented = true }
+ .keyboardShortcut("k", modifiers: .command)
+ Button("Toggle Inspector") {
+ appState.isCodeInspectorPresented.toggle()
+ }
+ .keyboardShortcut("j", modifiers: .command)
+ Divider()
+ Button("Changes (Git Diff)") {
+ appState.codeInspectorSection = .changes
+ appState.isCodeInspectorPresented = true
+ }
+ .keyboardShortcut("g", modifiers: [.command, .shift])
+ Button("Terminal") {
+ appState.codeInspectorSection = .terminal
+ appState.isCodeInspectorPresented = true
+ }
+ .keyboardShortcut("t", modifiers: [.command, .shift])
+ Button("Web Preview") {
+ appState.codeInspectorSection = .preview
+ appState.isCodeInspectorPresented = true
+ }
+ .keyboardShortcut("p", modifiers: [.command, .shift])
+ Divider()
+ Button("Import CLI Sessions…") {
+ appState.isSidebarVisible = true
+ appState.isCLISessionImportSheetPresented = true
+ }
+ .keyboardShortcut("i", modifiers: [.command, .shift])
+ Button(appState.isSidebarVisible ? "Hide Sidebar" : "Show Sidebar") {
+ appState.isSidebarVisible.toggle()
+ }
+ .keyboardShortcut("s", modifiers: [.command, .control])
+ Divider()
+ Button("Next Thread Needing Attention") {
+ Task { await appState.selectNextAttentionCodeThread() }
+ }
+ .keyboardShortcut(.downArrow, modifiers: [.command, .option])
+ Button("Open Archive") {
+ appState.isSidebarVisible = true
+ appState.isCodeArchivePresented = true
+ }
+ Button(
+ appState.selectedCodeThread?.isEffectivelyArchived == true
+ ? "Restore Thread from Archive"
+ : "Archive Current Thread"
+ ) {
+ if let thread = appState.selectedCodeThread {
+ Task { await appState.archiveCodeThread(id: thread.id, archived: !thread.isEffectivelyArchived) }
+ }
+ }
+ .keyboardShortcut("e", modifiers: .command)
+ .disabled(appState.selectedCodeThread == nil)
+ }
+ }
+
+ WindowGroup("Morph Code", id: "code-thread", for: String.self) { $threadId in
+ MorphSecondaryCodeWindow(state: appState, threadId: $threadId)
+ }
+ .windowStyle(.hiddenTitleBar)
+ .defaultSize(width: 720, height: 760)
+
+ MenuBarExtra {
+ MorphMenuBarView(state: appState)
+ } label: {
+ let pending = appState.pendingCodeApprovalCount
+ if pending > 0 {
+ Label {
+ Text("\(pending)")
+ } icon: {
+ Image(nsImage: MorphMenuBarIcon.image)
+ }
+ .labelStyle(.titleAndIcon)
+ } else {
+ Image(nsImage: MorphMenuBarIcon.image)
+ }
+ }
+ .menuBarExtraStyle(.window)
+ }
+}
+
+/// Template mark for the macOS menu bar (Morph character figure matching the AppIcon).
+@MainActor
+private enum MorphMenuBarIcon {
+ static let image: NSImage = {
+ let width: CGFloat = 19
+ let size = NSSize(width: width, height: (width * MorphAssistantFigure.aspectRatio).rounded())
+ let image = NSImage(size: size, flipped: true) { rect in
+ NSColor.black.setFill()
+ for shape in MorphAssistantFigure.paths(in: rect.size) {
+ let bz = NSBezierPath(cgPath: shape.cgPath)
+ bz.windingRule = .evenOdd
+ bz.fill()
+ }
+ return true
+ }
+ image.isTemplate = true
+ image.accessibilityDescription = "Morph Code"
+ return image
+ }()
+}
+
+private struct MorphMainWindow: View {
+ @Bindable var state: MorphAppState
+
+ var body: some View {
+ MorphRootView(state: state)
+ .task {
+ state.showCodeAttentionInDock()
+ }
+ }
+}
+
+/// ⌘⇧N: opens the active thread, or a thread picker, in a second Morph Code window.
+private struct MorphNewCodeWindowCommand: View {
+ let state: MorphAppState
+ @Environment(\.openWindow) private var openWindow
+
+ var body: some View {
+ Button("New Morph Code Window") {
+ if let threadId = state.selectedCodeThread?.id {
+ openWindow(id: "code-thread", value: threadId)
+ } else {
+ openWindow(id: "code-thread")
+ }
+ }
+ .keyboardShortcut("n", modifiers: [.command, .shift])
+ }
+}
+
+/// A Morph Code thread in its own secondary window beside the main window.
+struct MorphSecondaryCodeWindow: View {
+ @Bindable var state: MorphAppState
+ @Binding var threadId: String?
+ @Environment(\.openWindow) private var openWindow
+
+ private var thread: CodeThread? {
+ guard let threadId else { return nil }
+ return state.codeThreads.first { $0.id == threadId }
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ if let thread {
+ MorphCodeWorkspaceView(state: state, boundThreadId: thread.id)
+ } else {
+ picker
+ }
+ }
+ .ignoresSafeArea()
+ .frame(minWidth: 560, minHeight: 480)
+ .background(AnymorphColor.bgBase)
+ .morphDialogHost()
+ .morphNotices(state)
+ .preferredColorScheme(preferredScheme)
+ .navigationTitle(thread?.title ?? "Morph Code")
+ }
+
+ private var preferredScheme: ColorScheme? {
+ switch state.themeMode {
+ case .system: return nil
+ case .light: return .light
+ case .dark: return .dark
+ }
+ }
+
+ private var header: some View {
+ HStack(spacing: 6) {
+ Color.clear.frame(width: MorphRootView.trafficLightsWidth, height: 1)
+ if let thread {
+ HStack(spacing: 2) {
+ threadSwitcher(thread)
+ MorphCodeThreadActionsMenu(state: state, thread: thread, includesMainWindowActions: false)
+ }
+ Spacer(minLength: 8)
+ MorphCodeInlineSyncIndicator(state: state, threadId: thread.id)
+ Button("Open in Main Window") {
+ openWindow(id: "main")
+ NSApp.activate(ignoringOtherApps: true)
+ Task { await state.selectCodeThread(thread) }
+ }
+ .morphPill(.secondary)
+ } else {
+ Text("Select a Thread")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .padding(.horizontal, 6)
+ .morphWindowTitlebar()
+ Spacer(minLength: 8)
+ }
+ }
+ .padding(.trailing, 10)
+ .frame(height: MorphRootView.headerHeight)
+ .background {
+ AnymorphColor.bgBase
+ .morphWindowTitlebar()
+ }
+ .overlay(alignment: .bottom) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(height: 1)
+ }
+ }
+
+ private var activeSwitcherThreads: [CodeThread] {
+ state.listedCodeThreads
+ .filter { $0.isActiveForTriage() && !state.isCodeScheduleRun($0) }
+ .sorted { a, b in
+ let sa = state.codeVisualStatus(of: a)
+ let sb = state.codeVisualStatus(of: b)
+ if sa != sb { return sa < sb }
+ return CodeThread.newestFirst(a, b)
+ }
+ }
+
+ private func threadSwitcher(_ thread: CodeThread) -> some View {
+ MorphDropdown(placement: .belowLeading, width: 320, name: "secondary-thread") {
+ ForEach(activeSwitcherThreads.prefix(40)) { item in
+ MorphMenuItem(
+ item.title,
+ subtitle: state.codeProjects.first { $0.id == item.projectId }?.name,
+ icon: .symbol(state.codeLiveRuns[item.id] != nil ? "circle.dotted" : "text.bubble"),
+ isSelected: item.id == thread.id,
+ id: item.id
+ ) {
+ threadId = item.id
+ }
+ }
+ } label: {
+ HStack(spacing: 6) {
+ Text(thread.title)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ .padding(.horizontal, 6)
+ .contentShape(Rectangle())
+ }
+ .help("Switch thread in this window")
+ .accessibilityLabel("Thread \(thread.title), switch")
+ }
+
+ private var picker: some View {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 2) {
+ ForEach(activeSwitcherThreads) { item in
+ let status = state.codeVisualStatus(of: item)
+ MorphSidebarRow(
+ item.title,
+ subtitle: state.codeProjects.first { $0.id == item.projectId }?.name,
+ isSelected: false,
+ action: { threadId = item.id },
+ leading: { EmptyView() },
+ trailing: {
+ if status == .running {
+ MorphRunningDots(dotSize: 2.5, spacing: 2.2)
+ .frame(width: 14, height: 14)
+ } else if status.needsAttention {
+ MorphCodeStatusDot(status, size: 7)
+ }
+ }
+ )
+ }
+ }
+ .padding(12)
+ }
+ }
+}
+
+/// Compact menu bar popover for Morph Code daemon status, running threads, and pending approvals.
+private struct MorphMenuBarView: View {
+ @Bindable var state: MorphAppState
+ @Environment(\.openWindow) private var openWindow
+
+ private var runningThreads: [CodeThread] {
+ state.listedCodeThreads.filter { state.codeLiveRuns[$0.id] != nil }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 8) {
+ MorphAssistantMark(width: 22)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Morph Code")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ Text(state.localBridgeOnline ? "Local daemon connected" : "Local daemon offline")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ Spacer()
+ Circle()
+ .fill(state.localBridgeOnline ? AnymorphColor.statusDone : AnymorphColor.fgQuaternary)
+ .frame(width: 7, height: 7)
+ }
+
+ if state.pendingCodeApprovalCount > 0 {
+ Button {
+ showMainWindow()
+ Task { await state.selectNextAttentionCodeThread() }
+ } label: {
+ HStack {
+ Text("Pending approvals")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Spacer()
+ MorphCountBadge(state.pendingCodeApprovalCount)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.bgSurface)
+ )
+ }
+ .buttonStyle(.morphPlain)
+ }
+
+ if !runningThreads.isEmpty {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Running (\(runningThreads.count))")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ ForEach(runningThreads.prefix(4)) { thread in
+ Button {
+ showMainWindow()
+ Task { await state.selectCodeThread(thread) }
+ } label: {
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 1.8)
+ .frame(width: 12, height: 12)
+ Text(thread.title)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer()
+ }
+ .padding(.vertical, 4)
+ .padding(.horizontal, 6)
+ }
+ .buttonStyle(.morphPlain)
+ }
+ }
+ }
+
+ AnymorphDivider()
+
+ VStack(spacing: 2) {
+ menuBarAction("Open Morph Code", shortcut: nil) {
+ showMainWindow()
+ }
+ menuBarAction("New Thread", shortcut: "⌘N") {
+ showMainWindow()
+ state.startNewCodeThreadHere()
+ }
+ menuBarAction("Settings…", shortcut: "⌘,") {
+ showMainWindow()
+ state.openSettings()
+ }
+ menuBarAction("Quit Morph Code", shortcut: "⌘Q") {
+ NSApp.terminate(nil)
+ }
+ }
+ }
+ .padding(14)
+ .frame(width: 268)
+ .background(AnymorphColor.bgBase)
+ }
+
+ private func menuBarAction(_ title: String, shortcut: String?, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ HStack {
+ Text(title)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Spacer()
+ if let shortcut {
+ Text(shortcut)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, monospaced: true)
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+
+ private func showMainWindow() {
+ openWindow(id: "main")
+ NSApp.activate(ignoringOtherApps: true)
+ }
+}
diff --git a/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-dark.svg b/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-dark.svg
new file mode 100644
index 000000000..c26a54a8f
--- /dev/null
+++ b/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-dark.svg
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-light.svg b/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-light.svg
new file mode 100644
index 000000000..292ff5c5c
--- /dev/null
+++ b/apple/Apps/Shared/AppIcon.icon/Assets/morph-face-light.svg
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/apple/Apps/Shared/AppIcon.icon/icon.json b/apple/Apps/Shared/AppIcon.icon/icon.json
new file mode 100644
index 000000000..d2d73bbbb
--- /dev/null
+++ b/apple/Apps/Shared/AppIcon.icon/icon.json
@@ -0,0 +1,52 @@
+{
+ "fill-specializations": [
+ {
+ "value": {
+ "linear-gradient": [
+ "srgb:1.00000,1.00000,1.00000,1.00000",
+ "srgb:0.93500,0.93500,0.94500,1.00000"
+ ]
+ }
+ },
+ {
+ "appearance": "dark",
+ "value": {
+ "linear-gradient": [
+ "srgb:0.13500,0.13500,0.14500,1.00000",
+ "srgb:0.04500,0.04500,0.05200,1.00000"
+ ]
+ }
+ }
+ ],
+ "groups": [
+ {
+ "layers": [
+ {
+ "glass": true,
+ "image-name-specializations": [
+ {
+ "value": "morph-face-light.svg"
+ },
+ {
+ "appearance": "dark",
+ "value": "morph-face-dark.svg"
+ },
+ {
+ "appearance": "tinted",
+ "value": "morph-face-dark.svg"
+ }
+ ],
+ "name": "MorphFace"
+ }
+ ],
+ "shadow": {
+ "kind": "neutral",
+ "opacity": 0.45
+ },
+ "specular": true
+ }
+ ],
+ "supported-platforms": {
+ "squares": "shared"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/AccentColor.colorset/Contents.json b/apple/Apps/Shared/Assets.xcassets/AccentColor.colorset/Contents.json
new file mode 100644
index 000000000..2fe32ccbd
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -0,0 +1,38 @@
+{
+ "colors": [
+ {
+ "color": {
+ "color-space": "srgb",
+ "components": {
+ "alpha": "1.000",
+ "blue": "0x16",
+ "green": "0x16",
+ "red": "0x16"
+ }
+ },
+ "idiom": "universal"
+ },
+ {
+ "appearances": [
+ {
+ "appearance": "luminosity",
+ "value": "dark"
+ }
+ ],
+ "color": {
+ "color-space": "srgb",
+ "components": {
+ "alpha": "1.000",
+ "blue": "0xFA",
+ "green": "0xFA",
+ "red": "0xFA"
+ }
+ },
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 000000000..9414cfd8f
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,74 @@
+{
+ "images": [
+ {
+ "filename": "ios-1024.png",
+ "idiom": "universal",
+ "platform": "ios",
+ "size": "1024x1024"
+ },
+ {
+ "filename": "mac-16.png",
+ "idiom": "mac",
+ "scale": "1x",
+ "size": "16x16"
+ },
+ {
+ "filename": "mac-32.png",
+ "idiom": "mac",
+ "scale": "2x",
+ "size": "16x16"
+ },
+ {
+ "filename": "mac-32.png",
+ "idiom": "mac",
+ "scale": "1x",
+ "size": "32x32"
+ },
+ {
+ "filename": "mac-64.png",
+ "idiom": "mac",
+ "scale": "2x",
+ "size": "32x32"
+ },
+ {
+ "filename": "mac-128.png",
+ "idiom": "mac",
+ "scale": "1x",
+ "size": "128x128"
+ },
+ {
+ "filename": "mac-256.png",
+ "idiom": "mac",
+ "scale": "2x",
+ "size": "128x128"
+ },
+ {
+ "filename": "mac-256.png",
+ "idiom": "mac",
+ "scale": "1x",
+ "size": "256x256"
+ },
+ {
+ "filename": "mac-512.png",
+ "idiom": "mac",
+ "scale": "2x",
+ "size": "256x256"
+ },
+ {
+ "filename": "mac-512.png",
+ "idiom": "mac",
+ "scale": "1x",
+ "size": "512x512"
+ },
+ {
+ "filename": "mac-1024.png",
+ "idiom": "mac",
+ "scale": "2x",
+ "size": "512x512"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/ios-1024.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/ios-1024.png
new file mode 100644
index 000000000..af0f1ddfd
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/ios-1024.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-1024.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-1024.png
new file mode 100644
index 000000000..49eb98ea2
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-1024.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-128.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-128.png
new file mode 100644
index 000000000..e145cccd5
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-128.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-16.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-16.png
new file mode 100644
index 000000000..06e584b98
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-16.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-256.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-256.png
new file mode 100644
index 000000000..7abe88121
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-256.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-32.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-32.png
new file mode 100644
index 000000000..564bbb387
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-32.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-512.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-512.png
new file mode 100644
index 000000000..57a95c712
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-512.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-64.png b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-64.png
new file mode 100644
index 000000000..4053f9f69
Binary files /dev/null and b/apple/Apps/Shared/Assets.xcassets/AppIcon.appiconset/mac-64.png differ
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/Contents.json
new file mode 100644
index 000000000..73c00596a
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/Contents.json
new file mode 100644
index 000000000..776629cb9
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-atlassian.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/brand-atlassian.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/brand-atlassian.svg
new file mode 100644
index 000000000..583d517a1
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-atlassian.imageset/brand-atlassian.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/Contents.json
new file mode 100644
index 000000000..e448e9df3
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-claude.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/brand-claude.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/brand-claude.svg
new file mode 100644
index 000000000..e9c2aa9b1
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-claude.imageset/brand-claude.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/Contents.json
new file mode 100644
index 000000000..b8a6d7583
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-cloudflare.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/brand-cloudflare.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/brand-cloudflare.svg
new file mode 100644
index 000000000..364ba8085
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-cloudflare.imageset/brand-cloudflare.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/Contents.json
new file mode 100644
index 000000000..d0daad9e2
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-deepseek.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/brand-deepseek.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/brand-deepseek.svg
new file mode 100644
index 000000000..6dc59d8d3
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-deepseek.imageset/brand-deepseek.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/Contents.json
new file mode 100644
index 000000000..0aa5bbfe7
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-figma.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/brand-figma.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/brand-figma.svg
new file mode 100644
index 000000000..3a005e1b3
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-figma.imageset/brand-figma.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/Contents.json
new file mode 100644
index 000000000..cfc07ca79
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-gemini.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/brand-gemini.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/brand-gemini.svg
new file mode 100644
index 000000000..eb5d33362
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gemini.imageset/brand-gemini.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/Contents.json
new file mode 100644
index 000000000..e3600a27e
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-github.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/brand-github.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/brand-github.svg
new file mode 100644
index 000000000..171d56487
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-github.imageset/brand-github.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/Contents.json
new file mode 100644
index 000000000..3886e2b85
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-gmail.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/brand-gmail.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/brand-gmail.svg
new file mode 100644
index 000000000..c96151377
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-gmail.imageset/brand-gmail.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/Contents.json
new file mode 100644
index 000000000..6f9b3165c
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-google.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/brand-google.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/brand-google.svg
new file mode 100644
index 000000000..63f6f5d1e
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-google.imageset/brand-google.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/Contents.json
new file mode 100644
index 000000000..bba725427
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-googlecalendar.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/brand-googlecalendar.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/brand-googlecalendar.svg
new file mode 100644
index 000000000..2f079623f
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-googlecalendar.imageset/brand-googlecalendar.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/Contents.json
new file mode 100644
index 000000000..8907d5d2b
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-jandi.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/brand-jandi.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/brand-jandi.svg
new file mode 100644
index 000000000..3c48e1b3f
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-jandi.imageset/brand-jandi.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/Contents.json
new file mode 100644
index 000000000..394b79a1c
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-kakaotalk.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/brand-kakaotalk.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/brand-kakaotalk.svg
new file mode 100644
index 000000000..a083f0606
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-kakaotalk.imageset/brand-kakaotalk.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/Contents.json
new file mode 100644
index 000000000..0604ebeb7
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-linear.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/brand-linear.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/brand-linear.svg
new file mode 100644
index 000000000..836dab30a
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-linear.imageset/brand-linear.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/Contents.json
new file mode 100644
index 000000000..21528e61f
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-naverworks.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/brand-naverworks.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/brand-naverworks.svg
new file mode 100644
index 000000000..29f177923
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-naverworks.imageset/brand-naverworks.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/Contents.json
new file mode 100644
index 000000000..c372f5638
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-notion.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/brand-notion.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/brand-notion.svg
new file mode 100644
index 000000000..928a0aa39
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-notion.imageset/brand-notion.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/Contents.json
new file mode 100644
index 000000000..91b3257fe
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-onepassword.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/brand-onepassword.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/brand-onepassword.svg
new file mode 100644
index 000000000..ab08a4af4
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-onepassword.imageset/brand-onepassword.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/Contents.json
new file mode 100644
index 000000000..b4cfd37a9
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-openai.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/brand-openai.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/brand-openai.svg
new file mode 100644
index 000000000..445f94543
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-openai.imageset/brand-openai.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/Contents.json
new file mode 100644
index 000000000..da5914554
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-sentry.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/brand-sentry.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/brand-sentry.svg
new file mode 100644
index 000000000..65a1d8493
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-sentry.imageset/brand-sentry.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/Contents.json
new file mode 100644
index 000000000..addf24f44
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-slack.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/brand-slack.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/brand-slack.svg
new file mode 100644
index 000000000..91e5aa127
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-slack.imageset/brand-slack.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/Contents.json
new file mode 100644
index 000000000..749460f76
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-stripe.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/brand-stripe.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/brand-stripe.svg
new file mode 100644
index 000000000..cee324825
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-stripe.imageset/brand-stripe.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/Contents.json
new file mode 100644
index 000000000..c8c7f245b
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-supabase.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/brand-supabase.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/brand-supabase.svg
new file mode 100644
index 000000000..d6fe8298f
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-supabase.imageset/brand-supabase.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/Contents.json
new file mode 100644
index 000000000..240bee2dd
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "brand-teams.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/brand-teams.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/brand-teams.svg
new file mode 100644
index 000000000..84eaf470b
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-teams.imageset/brand-teams.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/Contents.json b/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/Contents.json
new file mode 100644
index 000000000..55fb8c4c6
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images": [
+ {
+ "filename": "brand-vercel.svg",
+ "idiom": "universal"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "preserves-vector-representation": true,
+ "template-rendering-intent": "template"
+ }
+}
diff --git a/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/brand-vercel.svg b/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/brand-vercel.svg
new file mode 100644
index 000000000..75167dd02
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Brands/brand-vercel.imageset/brand-vercel.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/apple/Apps/Shared/Assets.xcassets/Contents.json b/apple/Apps/Shared/Assets.xcassets/Contents.json
new file mode 100644
index 000000000..74d6a722c
--- /dev/null
+++ b/apple/Apps/Shared/Assets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
diff --git a/apple/Apps/Shared/CommandPaletteView.swift b/apple/Apps/Shared/CommandPaletteView.swift
new file mode 100644
index 000000000..4e53a6829
--- /dev/null
+++ b/apple/Apps/Shared/CommandPaletteView.swift
@@ -0,0 +1,375 @@
+import SwiftUI
+import MorphCore
+
+/// ⌘K: quick jump across Morph Code threads, FTS5 message search, projects, and quick actions.
+public struct CommandPaletteView: View {
+ @Bindable var state: MorphAppState
+ @Environment(\.dismiss) private var dismiss
+ @State private var query = ""
+ @State private var highlighted = 0
+ @FocusState private var searchFocused: Bool
+
+ public init(state: MorphAppState) {
+ self.state = state
+ }
+
+ enum CodeQuickAction: String, CaseIterable {
+ case newThread
+ case openChanges
+ case openTerminal
+ case openPreview
+ case forkThread
+ case cycleMode
+ case compact
+ case findInThread
+ case harnessSettings
+ case importCLISession
+ case openArchive
+
+ var title: String {
+ switch self {
+ case .newThread: return "New Thread"
+ case .openChanges: return "Open Changes (Git Diff)"
+ case .openTerminal: return "Open Interactive Terminal"
+ case .openPreview: return "Open Web Preview"
+ case .forkThread: return "Fork Current Thread"
+ case .cycleMode: return "Cycle Permission Mode (Default / Plan / Full)"
+ case .compact: return "Compact Context (/compact)"
+ case .findInThread: return "Find in Thread"
+ case .harnessSettings: return "Open Harness & MCP Settings"
+ case .importCLISession: return "Import Local CLI Sessions (Claude Code / Codex)"
+ case .openArchive: return "Open Archive"
+ }
+ }
+
+ var detail: String {
+ switch self {
+ case .newThread: return "⌘N · Start a new coding thread"
+ case .openChanges: return "⌘⇧G · Diff, staging, and commit"
+ case .openTerminal: return "⌘⇧T · Integrated PTY shell"
+ case .openPreview: return "⌘⇧P · Live local dev server preview"
+ case .forkThread: return "Branch the current conversation into a new thread"
+ case .cycleMode: return "⇧Tab · Switch approval behavior"
+ case .compact: return "Summarize conversation to free context window"
+ case .findInThread: return "⌘F · Search messages in the active thread"
+ case .harnessSettings: return "MCP servers, AGENTS.md, Skills, and Scripts"
+ case .importCLISession: return "⌘⇧I · Import sessions from Claude Code or Codex CLI"
+ case .openArchive: return "View and restore archived or snoozed threads"
+ }
+ }
+
+ var icon: String {
+ switch self {
+ case .newThread: return "plus.bubble"
+ case .openChanges: return "doc.badge.gearshape"
+ case .openTerminal: return "terminal"
+ case .openPreview: return "safari"
+ case .forkThread: return "arrow.triangle.branch"
+ case .cycleMode: return "shield"
+ case .compact: return "rectangle.compress.vertical"
+ case .findInThread: return "text.magnifyingglass"
+ case .harnessSettings: return "wrench.and.screwdriver"
+ case .importCLISession: return "square.and.arrow.down"
+ case .openArchive: return "archivebox"
+ }
+ }
+ }
+
+ enum PaletteItem: Identifiable {
+ case codeAction(CodeQuickAction)
+ case codeThread(CodeThread, projectName: String)
+ case codeProject(CodeProject)
+ case codeMessage(CodeSearchHit)
+
+ var id: String {
+ switch self {
+ case .codeAction(let a): return "code-act:" + a.rawValue
+ case .codeThread(let th, _): return "code-th:" + th.id
+ case .codeProject(let p): return "code-proj:" + p.id
+ case .codeMessage(let hit): return "code-msg:" + hit.threadId
+ }
+ }
+
+ var isCodeMessage: Bool {
+ if case .codeMessage = self { return true }
+ return false
+ }
+ }
+
+ private var trimmedQuery: String {
+ query.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ private var items: [PaletteItem] {
+ let q = trimmedQuery.lowercased()
+ let projectsById = Dictionary(state.codeProjects.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
+
+ if q.isEmpty {
+ var quick: [PaletteItem] = CodeQuickAction.allCases.map { .codeAction($0) }
+ let active = state.listedCodeThreads
+ .filter { $0.isActiveForTriage() }
+ .sorted { a, b in
+ let sa = state.codeVisualStatus(of: a)
+ let sb = state.codeVisualStatus(of: b)
+ if sa != sb { return sa < sb }
+ return CodeThread.newestFirst(a, b)
+ }
+ for th in active.prefix(6) {
+ quick.append(.codeThread(th, projectName: projectsById[th.projectId]?.name ?? "Workspace"))
+ }
+ return quick
+ }
+
+ var result: [PaletteItem] = []
+
+ for action in CodeQuickAction.allCases where action.title.lowercased().contains(q) || action.detail.lowercased().contains(q) {
+ result.append(.codeAction(action))
+ }
+
+ var titleMatchedThreadIds = Set
()
+ for th in state.listedCodeThreads {
+ let projName = projectsById[th.projectId]?.name ?? ""
+ if th.title.lowercased().contains(q) || projName.lowercased().contains(q) || (th.branch?.lowercased().contains(q) ?? false) {
+ result.append(.codeThread(th, projectName: projName))
+ titleMatchedThreadIds.insert(th.id)
+ }
+ }
+ for proj in state.codeFolderProjects where proj.name.lowercased().contains(q) || proj.workspacePath.lowercased().contains(q) {
+ result.append(.codeProject(proj))
+ }
+
+ let knownThreadIds = Set(state.codeThreads.map(\.id))
+ var seenMessageThreads = Set()
+ var messageItems: [PaletteItem] = []
+ for hit in state.codeSearchHits where hit.kind == "message" {
+ guard knownThreadIds.contains(hit.threadId),
+ !titleMatchedThreadIds.contains(hit.threadId),
+ seenMessageThreads.insert(hit.threadId).inserted else { continue }
+ messageItems.append(.codeMessage(hit))
+ if messageItems.count >= 8 { break }
+ }
+ result.append(contentsOf: messageItems)
+
+ return Array(result.prefix(22))
+ }
+
+ public var body: some View {
+ let currentItems = items
+ VStack(spacing: 0) {
+ HStack(spacing: 10) {
+ Image(systemName: "magnifyingglass")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ TextField("Search threads, messages, projects, or actions…", text: $query)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.subhead, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .focused($searchFocused)
+ .onSubmit { run(currentItems.indices.contains(highlighted) ? currentItems[highlighted] : nil) }
+ Text("esc")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgQuaternary, monospaced: true)
+ }
+ .padding(.horizontal, 18)
+ .frame(height: 54)
+
+ if !currentItems.isEmpty {
+ AnymorphDivider()
+ ScrollView {
+ LazyVStack(spacing: 2) {
+ ForEach(Array(currentItems.enumerated()), id: \.element.id) { index, item in
+ if item.isCodeMessage, index == currentItems.firstIndex(where: \.isCodeMessage) {
+ Text("Messages")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 10)
+ .padding(.top, index == 0 ? 2 : 8)
+ .padding(.bottom, 2)
+ }
+ Button {
+ run(item)
+ } label: {
+ row(item, isHighlighted: index == highlighted)
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { inside in
+ if inside { highlighted = index }
+ }
+ }
+ }
+ .padding(8)
+ }
+ .frame(maxHeight: 380)
+ }
+ }
+ .frame(width: 600)
+ .fixedSize(horizontal: false, vertical: true)
+ .focusEffectDisabled()
+ .background(AnymorphColor.bgBase)
+ .onAppear { searchFocused = true }
+ .onChange(of: query) { _, _ in
+ highlighted = 0
+ }
+ .task(id: query) {
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.isEmpty {
+ state.runCodeFullTextSearch(query: "")
+ return
+ }
+ try? await Task.sleep(for: .milliseconds(50))
+ guard !Task.isCancelled else { return }
+ state.runCodeFullTextSearch(query: trimmed)
+ }
+ .onKeyPress(.downArrow) {
+ highlighted = min(highlighted + 1, max(0, currentItems.count - 1))
+ return .handled
+ }
+ .onKeyPress(.upArrow) {
+ highlighted = max(highlighted - 1, 0)
+ return .handled
+ }
+ .onKeyPress(.escape) {
+ dismiss()
+ return .handled
+ }
+ }
+
+ private func row(_ item: PaletteItem, isHighlighted: Bool) -> some View {
+ HStack(spacing: 10) {
+ Image(systemName: icon(for: item))
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 24, height: 24)
+
+ VStack(alignment: .leading, spacing: 1) {
+ Text(title(for: item))
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ if let detail = detail(for: item) {
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ Spacer(minLength: 8)
+ if case .codeThread(let th, _) = item {
+ let status = state.codeVisualStatus(of: th)
+ if status == .running {
+ MorphRunningDots(dotSize: 2.2, spacing: 1.8)
+ .frame(width: 12, height: 12)
+ } else if status.needsAttention {
+ MorphCodeStatusDot(status, size: 7)
+ }
+ }
+ if isHighlighted {
+ Image(systemName: "return")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(isHighlighted ? AnymorphColor.bgSurface : .clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous))
+ }
+
+ private func icon(for item: PaletteItem) -> String {
+ switch item {
+ case .codeAction(let a): return a.icon
+ case .codeThread: return "terminal"
+ case .codeProject: return "folder"
+ case .codeMessage: return "text.bubble"
+ }
+ }
+
+ private func title(for item: PaletteItem) -> String {
+ switch item {
+ case .codeAction(let a): return a.title
+ case .codeThread(let th, _): return th.title
+ case .codeProject(let p): return p.name
+ case .codeMessage(let hit):
+ return state.codeThreads.first { $0.id == hit.threadId }?.title ?? hit.title
+ }
+ }
+
+ private func detail(for item: PaletteItem) -> String? {
+ switch item {
+ case .codeAction(let a): return a.detail
+ case .codeThread(let th, let proj):
+ let br = th.branch.map { " · \($0)" } ?? ""
+ return "\(proj)\(br)"
+ case .codeProject(let p): return p.workspacePath
+ case .codeMessage(let hit):
+ let snippet = hit.snippet.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespacesAndNewlines)
+ return snippet.isEmpty ? "Thread message" : snippet
+ }
+ }
+
+ private func run(_ item: PaletteItem?) {
+ guard let item else { return }
+ dismiss()
+ switch item {
+ case .codeAction(let action):
+ if action == .harnessSettings {
+ state.openSettings(.harness)
+ return
+ }
+ switch action {
+ case .newThread:
+ state.startNewCodeThreadHere()
+ case .openChanges:
+ state.codeInspectorSection = .changes
+ state.isCodeInspectorPresented = true
+ case .openTerminal:
+ state.codeInspectorSection = .terminal
+ state.isCodeInspectorPresented = true
+ case .openPreview:
+ state.codeInspectorSection = .preview
+ state.isCodeInspectorPresented = true
+ case .forkThread:
+ if let tid = state.selectedCodeThreadId {
+ Task { await state.forkCodeThread(threadId: tid) }
+ }
+ case .cycleMode:
+ state.cycleCodeAccessMode()
+ case .compact:
+ if let tid = state.selectedCodeThread?.id {
+ Task { await state.compactCodeThread(threadId: tid) }
+ } else {
+ state.showInfo("Open a thread first to compact its context.")
+ }
+ case .findInThread:
+ state.isCodeThreadFindPresented = true
+ case .importCLISession:
+ state.isSidebarVisible = true
+ Task {
+ try? await Task.sleep(for: .milliseconds(300))
+ state.isCLISessionImportSheetPresented = true
+ }
+ case .openArchive:
+ state.isSidebarVisible = true
+ Task {
+ try? await Task.sleep(for: .milliseconds(300))
+ state.isCodeArchivePresented = true
+ }
+ case .harnessSettings:
+ break
+ }
+ case .codeThread(let th, _):
+ Task { await state.selectCodeThread(th) }
+ case .codeMessage(let hit):
+ if let th = state.codeThreads.first(where: { $0.id == hit.threadId }) {
+ Task { await state.selectCodeThread(th) }
+ }
+ case .codeProject(let proj):
+ if let th = state.codeThreads.first(where: { $0.projectId == proj.id && $0.isActiveForTriage() }) {
+ Task { await state.selectCodeThread(th) }
+ } else {
+ state.startNewCodeThread(projectId: proj.id)
+ }
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+Accounts.swift b/apple/Apps/Shared/MorphAppState+Accounts.swift
new file mode 100644
index 000000000..fa508ed8f
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+Accounts.swift
@@ -0,0 +1,343 @@
+import Foundation
+import MorphCore
+
+extension MorphAppState {
+ // MARK: - Local Custom Providers
+
+ public func loadCustomProviders() async {
+ isLoadingCustomProviders = true
+ defer { isLoadingCustomProviders = false }
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ return
+ }
+ do {
+ let res = try await transport.fetchCustomProviders()
+ customProviders = res.providers
+ if let presets = res.presets, !presets.isEmpty {
+ customProviderPresets = presets
+ }
+ } catch {
+ // Daemon may not expose custom providers yet.
+ }
+ }
+
+ @discardableResult
+ public func saveCustomProvider(_ request: UpsertCustomProviderRequest) async -> Bool {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ showError("Unable to connect to the local morphcode daemon.")
+ return false
+ }
+ do {
+ let res = try await transport.upsertCustomProvider(request)
+ await loadCustomProviders()
+ await refreshCodeState()
+ if let warn = res.discoverWarning, !warn.isEmpty {
+ showInfo("Saved \(res.provider.name) (model discovery warning: \(warn))")
+ } else {
+ showInfo("Saved provider \(res.provider.name).")
+ }
+ return true
+ } catch {
+ showError("Failed to save provider: \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func deleteCustomProvider(id: String) async {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ try await transport.deleteCustomProvider(id: id)
+ await loadCustomProviders()
+ await refreshCodeState()
+ showInfo("Removed provider \(id).")
+ } catch {
+ showError("Failed to remove provider: \(error.localizedDescription)")
+ }
+ }
+
+ public func discoverCustomProviderModels(id: String) async {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let res = try await transport.discoverCustomProviderModels(id: id, save: true)
+ await loadCustomProviders()
+ await refreshCodeState()
+ showInfo("Loaded \(res.models.count) models for \(res.provider.name).")
+ } catch {
+ showError("Failed to discover models: \(error.localizedDescription)")
+ }
+ }
+
+ // MARK: - Per-Provider Execution Harness (Morph Harness vs Native CLI)
+
+ public func loadProviderHarnesses() async {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ return
+ }
+ do {
+ let cfg = try await transport.fetchCodeHarnessConfig(projectId: nil)
+ if let map = cfg.providerHarnesses, !map.isEmpty {
+ providerHarnesses = map
+ } else {
+ providerHarnesses = ["claude": "morphcode", "codex": "morphcode"]
+ }
+ if let orchModel = cfg.orchestratorModel?.trimmingCharacters(in: .whitespacesAndNewlines), !orchModel.isEmpty {
+ orchestratorModel = orchModel
+ } else {
+ orchestratorModel = "claude/claude-sonnet-5-5"
+ }
+ workerDefaultModel = cfg.workerDefaultModel?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ workerEffort = cfg.workerEffort?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""
+ if let workers = cfg.workerHarnesses, !workers.isEmpty {
+ workerHarnesses = workers
+ } else {
+ workerHarnesses = ["claude": "morphcode", "codex": "morphcode"]
+ }
+ nativeCliAvailable = cfg.nativeCliAvailable ?? [:]
+ } catch {
+ // Keep defaults when daemon is offline or older.
+ }
+ }
+
+ public func setOrchestratorModel(_ modelId: String) async {
+ let trimmed = modelId.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ let prev = orchestratorModel
+ orchestratorModel = trimmed
+ isSavingProviderHarnesses = true
+ defer { isSavingProviderHarnesses = false }
+
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ orchestratorModel = prev
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let cfg = try await transport.saveCodeOrchestratorConfig(
+ orchestratorModel: trimmed,
+ workerDefaultModel: nil,
+ workerEffort: nil,
+ workerHarnesses: nil
+ )
+ if let saved = cfg.orchestratorModel, !saved.isEmpty {
+ orchestratorModel = saved
+ }
+ if let avail = cfg.nativeCliAvailable {
+ nativeCliAvailable = avail
+ }
+ await refreshCodeState()
+ let label = CodeModelMenu.name(of: orchestratorModel, in: availableCodeModels)
+ showInfo("Orchestrator model set to \(label).")
+ } catch {
+ orchestratorModel = prev
+ showError("Failed to save orchestrator model: \(error.localizedDescription)")
+ }
+ }
+
+ public func setWorkerDefaultModel(_ modelId: String) async {
+ let trimmed = modelId.trimmingCharacters(in: .whitespacesAndNewlines)
+ let prev = workerDefaultModel
+ workerDefaultModel = trimmed
+ isSavingProviderHarnesses = true
+ defer { isSavingProviderHarnesses = false }
+
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ workerDefaultModel = prev
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ var nextEffort: String? = nil
+ if let currentEffort = CodeReasoningEffort(rawValue: workerEffort) {
+ let effectiveModel = trimmed.isEmpty ? orchestratorModel : trimmed
+ let supported = CodeModelMenu.efforts(of: effectiveModel, in: availableCodeModels)
+ if !supported.isEmpty {
+ let snapped = currentEffort.nearest(in: supported)
+ if snapped != currentEffort {
+ nextEffort = snapped.rawValue
+ workerEffort = snapped.rawValue
+ }
+ }
+ }
+ let cfg = try await transport.saveCodeOrchestratorConfig(
+ orchestratorModel: nil,
+ workerDefaultModel: trimmed,
+ workerEffort: nextEffort,
+ workerHarnesses: nil
+ )
+ workerDefaultModel = cfg.workerDefaultModel?.trimmingCharacters(in: .whitespacesAndNewlines) ?? trimmed
+ if let savedEffort = cfg.workerEffort?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
+ workerEffort = savedEffort
+ }
+ if let avail = cfg.nativeCliAvailable {
+ nativeCliAvailable = avail
+ }
+ let label = workerDefaultModel.isEmpty
+ ? "Same as Orchestrator"
+ : CodeModelMenu.name(of: workerDefaultModel, in: availableCodeModels)
+ showInfo("Default worker model set to \(label).")
+ } catch {
+ workerDefaultModel = prev
+ showError("Failed to save default worker model: \(error.localizedDescription)")
+ }
+ }
+
+ public func setWorkerEffort(_ rawEffort: String) async {
+ let trimmed = rawEffort.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ let prev = workerEffort
+ workerEffort = trimmed
+ isSavingProviderHarnesses = true
+ defer { isSavingProviderHarnesses = false }
+
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ workerEffort = prev
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let cfg = try await transport.saveCodeOrchestratorConfig(
+ orchestratorModel: nil,
+ workerDefaultModel: nil,
+ workerEffort: trimmed,
+ workerHarnesses: nil
+ )
+ workerEffort = cfg.workerEffort?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? trimmed
+ if let avail = cfg.nativeCliAvailable {
+ nativeCliAvailable = avail
+ }
+ let label = CodeReasoningEffort(rawValue: workerEffort)?.label ?? "Same as Orchestrator"
+ showInfo("Worker effort set to \(label).")
+ } catch {
+ workerEffort = prev
+ showError("Failed to save worker effort: \(error.localizedDescription)")
+ }
+ }
+
+ public func setWorkerHarness(provider: String, mode: CodeProviderHarnessMode) async {
+ let key = provider.lowercased()
+ let prev = workerHarnesses
+ workerHarnesses[key] = mode.rawValue
+ isSavingProviderHarnesses = true
+ defer { isSavingProviderHarnesses = false }
+
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ workerHarnesses = prev
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let cfg = try await transport.saveCodeOrchestratorConfig(
+ orchestratorModel: nil,
+ workerDefaultModel: nil,
+ workerEffort: nil,
+ workerHarnesses: [key: mode.rawValue]
+ )
+ if let workers = cfg.workerHarnesses, !workers.isEmpty {
+ workerHarnesses = workers
+ }
+ if let avail = cfg.nativeCliAvailable {
+ nativeCliAvailable = avail
+ }
+ showInfo("\(provider.capitalized) worker harness switched to \(mode.label).")
+ } catch {
+ workerHarnesses = prev
+ showError("Failed to save worker harness: \(error.localizedDescription)")
+ }
+ }
+
+ public func setProviderHarness(provider: String, mode: CodeProviderHarnessMode) async {
+ let key = provider.lowercased()
+ let prev = providerHarnesses
+ providerHarnesses[key] = mode.rawValue
+ isSavingProviderHarnesses = true
+ defer { isSavingProviderHarnesses = false }
+
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ providerHarnesses = prev
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let cfg = try await transport.saveCodeProviderHarnesses([key: mode.rawValue])
+ if let map = cfg.providerHarnesses, !map.isEmpty {
+ providerHarnesses = map
+ }
+ if let avail = cfg.nativeCliAvailable {
+ nativeCliAvailable = avail
+ }
+ showInfo("\(provider.capitalized) harness switched to \(mode.label).")
+ } catch {
+ providerHarnesses = prev
+ showError("Failed to save execution harness: \(error.localizedDescription)")
+ }
+ }
+
+ // MARK: - Local Built-In Provider API Keys & CLI Detection
+
+ public func loadProviderKeys() async {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ return
+ }
+ do {
+ let res = try await transport.fetchProviderKeys()
+ providerKeyStatus = res.providerKeys
+ nativeCliAvailable = res.cliAvailable
+ if let urls = res.baseUrls {
+ providerBaseURLs = urls
+ }
+ } catch {
+ // Keep existing status if daemon is still starting.
+ }
+ }
+
+ @discardableResult
+ public func saveProviderKey(provider: String, apiKey: String, baseURL: String? = nil) async -> Bool {
+ let cleanKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let cleanBase = baseURL?.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !cleanKey.isEmpty || (cleanBase != nil && !cleanBase!.isEmpty) else {
+ showError("Enter an API key.")
+ return false
+ }
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ showError("Unable to connect to the local morphcode daemon.")
+ return false
+ }
+ do {
+ let res = try await transport.setProviderKey(
+ provider: provider,
+ apiKey: cleanKey.isEmpty ? nil : cleanKey,
+ baseURL: cleanBase
+ )
+ providerKeyStatus = res.providerKeys
+ nativeCliAvailable = res.cliAvailable
+ await loadProviderKeys()
+ await refreshCodeState()
+ showInfo("Saved \(provider.capitalized) provider settings.")
+ return true
+ } catch {
+ showError("Failed to save provider settings: \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func clearProviderKey(provider: String) async {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else {
+ showError("Unable to connect to the local morphcode daemon.")
+ return
+ }
+ do {
+ let res = try await transport.setProviderKey(provider: provider, apiKey: "", baseURL: nil)
+ providerKeyStatus = res.providerKeys
+ nativeCliAvailable = res.cliAvailable
+ await refreshCodeState()
+ showInfo("Cleared \(provider.capitalized) API key.")
+ } catch {
+ showError("Failed to clear API key: \(error.localizedDescription)")
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+CodeInspector.swift b/apple/Apps/Shared/MorphAppState+CodeInspector.swift
new file mode 100644
index 000000000..321de9c4b
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+CodeInspector.swift
@@ -0,0 +1,494 @@
+import Foundation
+import Observation
+import os
+import MorphCore
+#if os(macOS)
+import AppKit
+import SystemConfiguration
+#else
+import UIKit
+#endif
+
+extension MorphAppState {
+ public func runCodeTerminalCommand(projectId: String, command: String) async {
+ let isLocal = isLocalCodeProject(projectId)
+ do {
+ let tid = selectedCodeThread?.id
+ let res = try await codeTransport(local: isLocal).execCodeCommand(projectId: projectId, threadId: tid, command: command)
+ if let tid {
+ var current = codeMessagesByThread[tid] ?? []
+ let msg = CodeMessage(
+ id: "cmsg-term-\(UUID().uuidString)",
+ threadId: tid,
+ role: "assistant",
+ content: "",
+ blocks: [res.block],
+ model: selectedCodeModel,
+ provider: nil,
+ routedAccount: nil,
+ executionTarget: isLocal ? .local : selectedCodeTarget,
+ createdAt: MorphPalette.isoString(from: Date())
+ )
+ current.append(msg)
+ codeMessagesByThread[tid] = current
+ }
+ } catch {
+ showError("명령을 실행하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func decideCodeApproval(id: String, decision: String, threadId: String? = nil) async {
+ let removedApproval = localCodeState?.approvals.first(where: { $0.id == id })
+ let liveTid = threadId ?? removedApproval?.threadId
+ let removedLiveApproval: CodeApproval? = liveTid.flatMap { tid in
+ guard codeLiveRuns[tid]?.approval?.id == id else { return nil }
+ let existing = codeLiveRuns[tid]?.approval
+ codeLiveRuns[tid]?.approval = nil
+ return existing
+ }
+ localCodeState = localCodeState?.removingApproval(id)
+ do {
+ _ = try await codeTransport(local: true).decideCodeApproval(id: id, decision: decision)
+ Task { [weak self] in
+ await self?.refreshCodeStateQuietly()
+ }
+ showInfo(decision == "denied" ? "Execution denied." : "Execution approved.")
+ } catch {
+ if let removedApproval {
+ localCodeState = localCodeState?.restoringApproval(removedApproval)
+ }
+ if let liveTid, let removedLiveApproval, codeLiveRuns[liveTid]?.approval == nil {
+ codeLiveRuns[liveTid]?.approval = removedLiveApproval
+ }
+ showError("Could not process approval: \(error.localizedDescription)")
+ }
+ }
+
+ /// Stores Git status keyed by `threadId` (for worktree isolation) alongside backward-compatible project fallback.
+ func storeCodeGitStatus(_ status: CodeGitStatus, projectId: String, threadId: String?) {
+ if let threadId, !threadId.isEmpty {
+ codeGitStatusByThread[threadId] = status
+ }
+ codeGitStatusByProject[projectId] = status
+ }
+
+ /// Stores PR status keyed by `threadId` (for worktree isolation) alongside backward-compatible project fallback.
+ func storeCodeGitPR(_ status: CodeGitPRStatusResponse, projectId: String, threadId: String?) {
+ if let threadId, !threadId.isEmpty {
+ codeGitPRByThread[threadId] = status
+ }
+ codeGitPRByProject[projectId] = status
+ }
+
+ public func codeGitStatus(projectId: String, threadId: String?) -> CodeGitStatus? {
+ if let threadId, let byThread = codeGitStatusByThread[threadId] {
+ return byThread
+ }
+ return codeGitStatusByProject[projectId]
+ }
+
+ public func codeGitPR(projectId: String, threadId: String?) -> CodeGitPRStatusResponse? {
+ if let threadId, let byThread = codeGitPRByThread[threadId] {
+ return byThread
+ }
+ return codeGitPRByProject[projectId]
+ }
+
+ public func refreshCodeGitStatus(projectId: String, threadId: String? = nil) async {
+ codeGitLoadCount += 1
+ isLoadingCodeGit = true
+ defer {
+ codeGitLoadCount = max(0, codeGitLoadCount - 1)
+ isLoadingCodeGit = codeGitLoadCount > 0
+ }
+ do {
+ let status = try await codeTransport(local: true)
+ .fetchCodeGitStatus(projectId: projectId, threadId: threadId)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ } catch {
+ // Non-git folder or offline
+ }
+ }
+
+ public func createCodeWorktreeThread(projectId: String, branch: String, baseBranch: String? = nil) async {
+ let clean = branch.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !clean.isEmpty else { return }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId)).createCodeWorktree(
+ projectId: projectId,
+ branch: clean,
+ baseBranch: baseBranch,
+ createThread: true,
+ model: selectedCodeModel
+ )
+ await refreshCodeState()
+ if let th = res.thread {
+ await selectCodeThread(th)
+ }
+ await refreshCodeGitStatus(projectId: projectId, threadId: res.thread?.id)
+ showInfo("Worktree 브랜치 \(res.branch) 스레드를 만들었습니다.")
+ } catch {
+ showError("Worktree를 만들지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func checkoutCodeBranch(projectId: String, threadId: String?, branch: String) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .checkoutCodeBranch(projectId: projectId, threadId: threadId, branch: branch)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ showInfo("브랜치를 \(branch)(으)로 전환했습니다.")
+ } catch {
+ showError("브랜치를 전환하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func revertCodeFile(projectId: String, threadId: String?, path: String) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .revertCodeFile(projectId: projectId, threadId: threadId, path: path)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ showInfo("\(path) 변경을 되돌렸습니다.")
+ } catch {
+ showError("파일을 되돌리지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public struct CodeModelIssue: Equatable {
+ public let modelName: String
+ public let reason: String
+ public let fallback: CodeModelOption?
+ }
+
+ /// Returns a recovery hint when the model has 0 healthy accounts in the active pool.
+ public func codeModelIssue(for modelId: String) -> CodeModelIssue? {
+ let options = availableCodeModels
+ guard let current = options.first(where: { $0.id == modelId }),
+ current.available == false else {
+ return nil
+ }
+ let reason = current.unavailableReason?.trimmingCharacters(in: .whitespacesAndNewlines)
+ let fallback = options.first { $0.id != "auto" && $0.id != "orchestrator" && $0.id != current.id && $0.available == true }
+ ?? options.first { $0.id == "auto" && $0.available == true }
+ return CodeModelIssue(
+ modelName: CodeModelMenu.name(current),
+ reason: (reason?.isEmpty == false ? reason! : "가용 계정 없음"),
+ fallback: fallback
+ )
+ }
+
+ /// Moves the composer to the next permission mode (bound to Shift+Tab).
+ public func cycleCodeAccessMode() {
+ selectedCodeAccessMode = selectedCodeAccessMode.next
+ showInfo("권한 모드: \(selectedCodeAccessMode.label)")
+ }
+
+ @discardableResult
+ public func answerCodeQuestion(
+ id: String,
+ action: String = "accept",
+ answers: [String: [String]],
+ threadId: String? = nil
+ ) async -> Bool {
+ let isLocal = threadId.map { isLocalCodeThread($0) } ?? (selectedCodeTarget == .local)
+ do {
+ let answered = try await codeTransport(local: isLocal).answerCodeQuestion(questionId: id, action: action, answers: answers)
+ let resolvedEvent = CodeStreamEvent(
+ type: "question_answered",
+ threadId: threadId ?? answered.threadId,
+ question: answered
+ )
+ if let tid = threadId ?? Optional(answered.threadId), let run = codeLiveRuns[tid], run.question?.id == id {
+ run.apply(resolvedEvent)
+ } else {
+ for run in codeLiveRuns.values where run.question?.id == id {
+ run.apply(resolvedEvent)
+ }
+ }
+ localCodeState = localCodeState?.removingQuestion(id)
+ Task { [weak self] in
+ await self?.refreshCodeStateQuietly()
+ }
+ return true
+ } catch {
+ showError("질문 응답을 보내지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func forkCodeThread(threadId: String, messageId: String? = nil) async {
+ do {
+ let res = try await codeTransport(local: isLocalCodeThread(threadId))
+ .forkCodeThread(threadId: threadId, messageId: messageId, title: nil)
+ codeMessagesByThread[res.thread.id] = res.messages
+ await refreshCodeState()
+ await selectCodeThread(res.thread)
+ showInfo("대화를 새 스레드로 분기했습니다.")
+ } catch {
+ showError("대화를 분기하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ func codeGitDiffKey(projectId: String, threadId: String?, path: String, staged: Bool) -> String {
+ "\(projectId)|\(threadId ?? "")|\(staged ? "S" : "U")|\(path)"
+ }
+
+ public func cachedCodeGitFileDiff(projectId: String, threadId: String? = nil, path: String, staged: Bool) -> CodeGitFileDiff? {
+ codeGitFileDiffs[codeGitDiffKey(projectId: projectId, threadId: threadId, path: path, staged: staged)]
+ }
+
+ public func fetchCodeGitFileDiff(projectId: String, threadId: String?, path: String, staged: Bool = false) async {
+ do {
+ let diff = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: staged)
+ codeGitFileDiffs[codeGitDiffKey(projectId: projectId, threadId: threadId, path: path, staged: staged)] = diff
+ } catch {
+ // File may have been reverted or deleted.
+ }
+ }
+
+ public func stageCodeGit(projectId: String, threadId: String?, path: String? = nil, all: Bool = false, hunkIndex: Int? = nil) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .stageCodeGit(projectId: projectId, threadId: threadId, path: path, all: all, hunkIndex: hunkIndex)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ if let path {
+ await fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: false)
+ await fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: true)
+ }
+ } catch {
+ showError("스테이징하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func unstageCodeGit(projectId: String, threadId: String?, path: String? = nil, all: Bool = false, hunkIndex: Int? = nil) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .unstageCodeGit(projectId: projectId, threadId: threadId, path: path, all: all, hunkIndex: hunkIndex)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ if let path {
+ await fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: false)
+ await fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: true)
+ }
+ } catch {
+ showError("스테이징을 해제하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func discardCodeGitHunk(projectId: String, threadId: String?, path: String, hunkIndex: Int) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .discardCodeGitHunk(projectId: projectId, threadId: threadId, path: path, hunkIndex: hunkIndex)
+ storeCodeGitStatus(status, projectId: projectId, threadId: threadId)
+ await fetchCodeGitFileDiff(projectId: projectId, threadId: threadId, path: path, staged: false)
+ showInfo("선택한 변경 블록을 되돌렸습니다.")
+ } catch {
+ showError("변경 블록을 되돌리지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func commitCodeGit(projectId: String, threadId: String?, message: String) async -> Bool {
+ let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .commitCodeGit(projectId: projectId, threadId: threadId, message: trimmed)
+ storeCodeGitStatus(res.git, projectId: projectId, threadId: threadId)
+ codeGitFileDiffs = codeGitFileDiffs.filter { !$0.key.hasPrefix("\(projectId)|") }
+ let shortSHA = res.commit.map { " (\($0))" } ?? ""
+ showInfo("커밋을 완료했습니다\(shortSHA).")
+ return true
+ } catch {
+ showError("커밋하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ /// The terminal a thread opens. A thread with its own worktree gets a shell in that worktree, and the project's
+ /// other threads and its new-thread screen share the shell in the project folder.
+ public func codeTerminalKey(projectId: String, threadId: String?) -> String {
+ let worktree = threadId.flatMap { id in codeThreads.first { $0.id == id }?.worktreePath } ?? ""
+ return worktree.isEmpty ? projectId : "\(projectId)|\(worktree)"
+ }
+
+ public func ensureCodeTerminalSession(projectId: String, threadId: String?) async {
+ let key = codeTerminalKey(projectId: projectId, threadId: threadId)
+ if let existing = codeTerminalSessions[key], existing.running {
+ return
+ }
+ await restartCodeTerminalSession(projectId: projectId, threadId: threadId)
+ }
+
+ public func restartCodeTerminalSession(projectId: String, threadId: String?) async {
+ let key = codeTerminalKey(projectId: projectId, threadId: threadId)
+ await closeCodeTerminalSession(projectId: projectId, threadId: threadId)
+ do {
+ let transport = try await codeTransport(local: isLocalCodeProject(projectId))
+ let session = try await transport.createCodeTerminalSession(projectId: projectId, threadId: threadId, cols: 100, rows: 28)
+ let stream = transport.streamCodeTerminalSession(sessionId: session.id)
+ codeTerminalSessions[key] = session
+ codeTerminalScreens[key] = TerminalScreen(columns: session.cols, rows: session.rows)
+ codeTerminalOutputs[key] = ""
+ let sid = session.id
+ let task = Task { [weak self] in
+ for await ev in stream {
+ guard let self, !Task.isCancelled else { break }
+ if let raw = ev.data, !raw.isEmpty {
+ self.codeTerminalScreens[key]?.write(raw)
+ self.publishTerminalSnapshot(forKey: key)
+ }
+ if ev.type == "exit" {
+ if var s = self.codeTerminalSessions[key], s.id == sid {
+ s.running = false
+ s.exitCode = ev.exitCode
+ self.codeTerminalSessions[key] = s
+ }
+ }
+ }
+ // The stream ended without the shell's exit: the server closed the session or the connection dropped.
+ // The session shows as stopped, so opening the terminal again starts a new one.
+ guard let self, !Task.isCancelled, var s = self.codeTerminalSessions[key], s.id == sid, s.running else {
+ return
+ }
+ s.running = false
+ self.codeTerminalSessions[key] = s
+ self.codeTerminalOutputs[key, default: ""] += "\n터미널 연결이 끊겼습니다. 다시 시작하려면 ↻를 누르세요.\n"
+ }
+ codeTerminalStreamTasks[key] = task
+ } catch {
+ let message = "터미널 세션을 열지 못했습니다. \(error.localizedDescription)"
+ // The pane keeps the reason after the toast fades.
+ codeTerminalOutputs[key] = message
+ showError(message)
+ }
+ }
+
+ public func sendCodeTerminalInput(projectId: String, threadId: String?, data: String) async {
+ let key = codeTerminalKey(projectId: projectId, threadId: threadId)
+ guard let session = codeTerminalSessions[key] else { return }
+ do {
+ try await codeTransport(local: isLocalCodeProject(projectId)).sendCodeTerminalInput(sessionId: session.id, data: data)
+ } catch {
+ showError("터미널 입력을 보내지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func clearCodeTerminalOutput(projectId: String, threadId: String?) {
+ let key = codeTerminalKey(projectId: projectId, threadId: threadId)
+ if let session = codeTerminalSessions[key] {
+ codeTerminalScreens[key] = TerminalScreen(columns: session.cols, rows: session.rows)
+ }
+ codeTerminalOutputs[key] = ""
+ }
+
+ public func closeCodeTerminalSession(projectId: String, threadId: String?) async {
+ let key = codeTerminalKey(projectId: projectId, threadId: threadId)
+ codeTerminalStreamTasks.removeValue(forKey: key)?.cancel()
+ codeTerminalScreens.removeValue(forKey: key)
+ guard let session = codeTerminalSessions.removeValue(forKey: key) else { return }
+ try? await codeTransport(local: isLocalCodeProject(projectId)).closeCodeTerminalSession(sessionId: session.id)
+ }
+
+ public func searchCodeFiles(projectId: String, threadId: String?, query: String) async {
+ codeFileSearchTask?.cancel()
+ let task = Task { [weak self] in
+ try? await Task.sleep(for: .milliseconds(150))
+ guard !Task.isCancelled, let self else { return }
+ do {
+ let results = try await self.codeTransport(local: self.isLocalCodeProject(projectId))
+ .searchCodeFiles(projectId: projectId, threadId: threadId, query: query)
+ guard !Task.isCancelled else { return }
+ self.codeFileSearchResults = results
+ } catch {
+ if !Task.isCancelled {
+ self.codeFileSearchResults = []
+ }
+ }
+ }
+ codeFileSearchTask = task
+ await task.value
+ }
+
+ /// Resolves a local macOS filesystem URL for a workspace, worktree, or absolute file path.
+ /// Returns nil for remote API/HTTP URLs or paths that do not exist as regular files.
+ public func resolveLocalCodeFileURL(source: String, projectId: String?, threadId: String?, isLocal: Bool) -> URL? {
+ #if os(macOS)
+ guard isLocal else { return nil }
+ let thread = threadId.flatMap { id in codeThreads.first { $0.id == id } }
+ let proj = projectId.flatMap { id in codeProjects.first { $0.id == id } }
+ let candidates = MorphFileViewerSupport.localCandidatePaths(
+ source: source,
+ worktreePath: thread?.worktreePath,
+ workspacePath: proj?.workspacePath
+ )
+ for path in candidates {
+ var isDir: ObjCBool = false
+ if FileManager.default.fileExists(atPath: path, isDirectory: &isDir), !isDir.boolValue {
+ return URL(fileURLWithPath: path)
+ }
+ }
+ return nil
+ #else
+ return nil
+ #endif
+ }
+
+ /// Loads an image's or a file's bytes from this Mac's disk, the member's Mac bridge or the authenticated Morph
+ /// server, with a size-bounded in-memory LRU cache.
+ public func loadCodeFileData(source: String, projectId: String?, threadId: String?, isLocal: Bool) async -> Data? {
+ let cacheKey = "\(isLocal ? "L" : "C")|\(projectId ?? "")|\(threadId ?? "")|\(source)"
+ if let cached = codeFileCache[cacheKey] {
+ return cached
+ }
+ let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+
+ let maxCachedEntryBytes = 8 * 1024 * 1024
+ func cacheAndReturn(_ data: Data) -> Data {
+ if data.count <= maxCachedEntryBytes {
+ codeFileCache[cacheKey] = data
+ codeFileCacheOrder.append(cacheKey)
+ if codeFileCacheOrder.count > 64 {
+ let oldest = codeFileCacheOrder.removeFirst()
+ codeFileCache.removeValue(forKey: oldest)
+ }
+ }
+ return data
+ }
+
+ #if os(macOS)
+ if let localURL = resolveLocalCodeFileURL(source: trimmed, projectId: projectId, threadId: threadId, isLocal: isLocal),
+ let data = try? Data(contentsOf: localURL) {
+ return cacheAndReturn(data)
+ }
+ #endif
+
+ let apiPath: String
+ if trimmed.hasPrefix("/v1/code/") {
+ apiPath = trimmed
+ } else if trimmed.hasPrefix("http://") || trimmed.hasPrefix("https://") {
+ apiPath = trimmed
+ } else if let pid = projectId, !pid.isEmpty {
+ var comps = URLComponents()
+ comps.path = "/v1/code/files/raw"
+ var items = [
+ URLQueryItem(name: "projectId", value: pid),
+ URLQueryItem(name: "path", value: trimmed),
+ ]
+ if let tid = threadId, !tid.isEmpty {
+ items.append(URLQueryItem(name: "threadId", value: tid))
+ }
+ comps.queryItems = items
+ apiPath = comps.string ?? trimmed
+ } else {
+ return nil
+ }
+
+ do {
+ return cacheAndReturn(try await codeTransport(local: isLocal).fetchRawData(path: apiPath))
+ } catch {
+ return nil
+ }
+ }
+
+}
diff --git a/apple/Apps/Shared/MorphAppState+CodeParityV2.swift b/apple/Apps/Shared/MorphAppState+CodeParityV2.swift
new file mode 100644
index 000000000..caf3e0e3f
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+CodeParityV2.swift
@@ -0,0 +1,536 @@
+import Foundation
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+public struct CodePreviewConsoleEntry: Identifiable, Sendable, Equatable {
+ public enum Level: String, Sendable, Equatable {
+ case error
+ case warning
+ case network
+ case log
+ }
+
+ public let id: String
+ public let level: Level
+ public let message: String
+ public let detail: String?
+ public let timestamp: Date
+
+ public init(
+ id: String = UUID().uuidString,
+ level: Level,
+ message: String,
+ detail: String? = nil,
+ timestamp: Date = Date()
+ ) {
+ self.id = id
+ self.level = level
+ self.message = message
+ self.detail = detail
+ self.timestamp = timestamp
+ }
+}
+
+extension MorphAppState {
+ // MARK: - Prompt History
+
+ public func recordCodePromptHistory(_ rawPrompt: String) {
+ let trimmed = rawPrompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ var next = codePromptHistory.filter { $0 != trimmed }
+ next.insert(trimmed, at: 0)
+ if next.count > 100 {
+ next = Array(next.prefix(100))
+ }
+ codePromptHistory = next
+ }
+
+ // MARK: - Independent Thread Composer / Multi-Window Helpers
+
+ public func insertCodeTextIntoComposer(_ snippet: String, threadId: String? = nil) {
+ let trimmed = snippet.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ if let tid = threadId, tid != selectedCodeThreadId {
+ let key = "thread:\(tid)"
+ var draft = codeDraftsByKey[key] ?? CodeComposerDraft()
+ if draft.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ draft.text = trimmed
+ } else {
+ draft.text += "\n\n" + trimmed
+ }
+ codeDraftsByKey[key] = draft
+ codeDraftRevisionByThread[tid, default: 0] += 1
+ return
+ }
+ if codeComposerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ codeComposerText = trimmed
+ } else {
+ codeComposerText += "\n\n" + trimmed
+ }
+ if let active = selectedCodeThreadId {
+ codeDraftRevisionByThread[active, default: 0] += 1
+ }
+ }
+
+ public func sendPreviewContextToComposer(
+ text: String,
+ imageData: Data? = nil,
+ imageName: String? = nil,
+ threadId: String? = nil
+ ) {
+ if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ insertCodeTextIntoComposer(text, threadId: threadId)
+ }
+ if let data = imageData, !data.isEmpty {
+ let picked = MorphPickedImage.data(data, name: imageName ?? "preview-snapshot.png")
+ if let tid = threadId, tid != selectedCodeThreadId {
+ Task {
+ let result = await Task.detached(priority: .userInitiated) { Self.readCodeImage(picked) }.value
+ if case .success(let att) = result {
+ let key = "thread:\(tid)"
+ var draft = codeDraftsByKey[key] ?? CodeComposerDraft()
+ draft.attachments.append(att)
+ codeDraftsByKey[key] = draft
+ codeDraftRevisionByThread[tid, default: 0] += 1
+ }
+ }
+ } else {
+ attachCodeImages([picked])
+ }
+ }
+ showInfo("프리뷰 정보를 입력창에 넣었습니다.")
+ }
+
+ /// Sends or steers a prompt directly to a specific thread (used by independent secondary windows
+ /// and programmatic plan-implementation triggers without changing `selectedCodeThreadId`).
+ /// Optimistic submission state for a bound thread window, committed synchronously on frame 0.
+ enum CodePreparedBoundSubmission {
+ case followUp(thread: CodeThread, mode: CodeFollowUpMode, prompt: String, attachments: [CodeImageAttachment])
+ case turn(
+ thread: CodeThread,
+ run: CodeLiveRun,
+ prompt: String,
+ attachments: [CodeImageAttachment],
+ model: String,
+ accessMode: CodeAccessMode,
+ effort: CodeReasoningEffort
+ )
+ }
+
+ func beginCodePromptForThread(
+ threadId: String,
+ rawPrompt: String,
+ attachments: [CodeImageAttachment] = [],
+ model: String? = nil,
+ effort: CodeReasoningEffort? = nil,
+ accessMode: CodeAccessMode? = nil,
+ followUpMode: CodeFollowUpMode? = nil
+ ) -> CodePreparedBoundSubmission? {
+ let trimmed = rawPrompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty || !attachments.isEmpty else { return nil }
+ guard let thread = codeThreads.first(where: { $0.id == threadId }) else {
+ showError("스레드를 찾지 못했습니다.")
+ return nil
+ }
+ let prompt = trimmed.isEmpty ? "첨부한 이미지를 분석해 주세요." : trimmed
+ if !trimmed.isEmpty {
+ recordCodePromptHistory(trimmed)
+ }
+ if codeLiveRuns[threadId] != nil {
+ return .followUp(
+ thread: thread,
+ mode: followUpMode ?? codeFollowUpMode,
+ prompt: prompt,
+ attachments: attachments
+ )
+ }
+ clearOptimisticCodeThreadTriageState(threadId: threadId)
+ let requestedModel = model ?? thread.model
+ let requestedAccess = accessMode ?? thread.accessMode ?? selectedCodeAccessMode
+ let requestedEffort = effort ?? thread.reasoningEffort ?? selectedCodeEffort
+ let run = CodeLiveRun(
+ threadId: threadId,
+ pendingPrompt: prompt,
+ pendingImages: attachments,
+ pendingModel: requestedModel,
+ pendingEffort: requestedEffort
+ )
+ codeLiveRuns[threadId] = run
+ return .turn(
+ thread: thread,
+ run: run,
+ prompt: prompt,
+ attachments: attachments,
+ model: requestedModel,
+ accessMode: requestedAccess,
+ effort: requestedEffort
+ )
+ }
+
+ @discardableResult
+ func finishCodePromptForThread(_ submission: CodePreparedBoundSubmission) async -> Bool {
+ switch submission {
+ case .followUp(let thread, let mode, let prompt, let attachments):
+ await sendCodeFollowUp(to: thread, mode: mode, prompt: prompt, attachments: attachments)
+ return true
+ case .turn(let thread, let run, let prompt, let attachments, let requestedModel, let requestedAccess, let requestedEffort):
+ let threadId = thread.id
+ let isLocal = isLocalCodeThread(threadId)
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ let images = try await uploadCodeImages(attachments, for: thread, transport: transport)
+ let res = try await transport.sendCodeMessage(
+ threadId: threadId,
+ prompt: prompt,
+ images: images.isEmpty ? nil : images,
+ model: requestedModel,
+ executionTarget: codeTarget(of: thread),
+ accessMode: requestedAccess,
+ reasoningEffort: requestedEffort
+ )
+ run.submittedMessageId = res.userMessage.id
+ appendCodeMessages([res.userMessage] + [res.reply].compactMap { $0 }, threadId: threadId)
+ applyThreadUpdateInMemory(res.thread, isLocal: isLocal)
+ if res.reply == nil {
+ followCodeThread(threadId)
+ let remaining = max(0, 0.38 - Date().timeIntervalSince(run.launchedAt))
+ if remaining > 0.01 {
+ Task { [weak self, weak run] in
+ try? await Task.sleep(for: .seconds(remaining))
+ guard let self, let run, self.codeLiveRuns[threadId] === run else { return }
+ run.pendingPrompt = nil
+ }
+ } else {
+ run.pendingPrompt = nil
+ }
+ if run.isCancelling {
+ run.isCancelling = false
+ await cancelCodeTurn(threadId: threadId)
+ }
+ } else {
+ run.pendingPrompt = nil
+ endCodeRun(threadId)
+ }
+ return true
+ } catch {
+ endCodeRun(threadId)
+ showError("메시지를 보내지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+ }
+
+ @discardableResult
+ public func sendCodePromptForThread(
+ threadId: String,
+ rawPrompt: String,
+ attachments: [CodeImageAttachment] = [],
+ model: String? = nil,
+ effort: CodeReasoningEffort? = nil,
+ accessMode: CodeAccessMode? = nil,
+ followUpMode: CodeFollowUpMode? = nil
+ ) async -> Bool {
+ guard let submission = beginCodePromptForThread(
+ threadId: threadId,
+ rawPrompt: rawPrompt,
+ attachments: attachments,
+ model: model,
+ effort: effort,
+ accessMode: accessMode,
+ followUpMode: followUpMode
+ ) else {
+ return false
+ }
+ return await finishCodePromptForThread(submission)
+ }
+
+ // MARK: - Interactive Plan Approval & Plan -> Implement Transition
+
+ public func decideCodePlanApproval(
+ id: String,
+ threadId: String,
+ approve: Bool,
+ targetAccessMode: CodeAccessMode = .defaultPermissions,
+ clearContext: Bool = false,
+ revisionReason: String = ""
+ ) async {
+ let localApproval = (localCodeState?.approvals.contains(where: { $0.id == id }) ?? false)
+ || isLocalCodeThread(threadId)
+ let decision = approve ? "allow_once" : "denied"
+ let trimmedReason = revisionReason.trimmingCharacters(in: .whitespacesAndNewlines)
+ do {
+ _ = try await codeTransport(local: localApproval).decideCodeApproval(
+ id: id,
+ decision: decision,
+ reason: approve ? nil : (trimmedReason.isEmpty ? "계획을 수정해 주세요." : trimmedReason),
+ prefix: nil,
+ scope: nil,
+ targetAccessMode: approve ? targetAccessMode : nil,
+ clearContext: approve ? clearContext : nil
+ )
+ if approve, selectedCodeThreadId == threadId {
+ selectedCodeAccessMode = targetAccessMode
+ }
+ Task { [weak self] in
+ await self?.refreshCodeStateQuietly()
+ }
+ if approve {
+ showInfo(clearContext ? "계획을 승인해 새 컨텍스트에서 구현을 시작합니다." : "계획을 승인하고 구현으로 전환했습니다.")
+ } else {
+ showInfo("계획 수정을 요청했습니다.")
+ }
+ } catch {
+ showError("계획 승인 처리에 실패했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Transitions a thread that completed a turn in `plan` mode
+ /// into implementation mode, optionally starting from a fresh context via compact + implement turn.
+ public func startImplementingPlanMessage(
+ thread: CodeThread,
+ planMarkdown: String,
+ targetAccessMode: CodeAccessMode = .defaultPermissions,
+ clearContext: Bool = false
+ ) async {
+ let isLocal = isLocalCodeThread(thread.id)
+ if selectedCodeThreadId == thread.id {
+ selectedCodeAccessMode = targetAccessMode
+ }
+ if clearContext {
+ _ = try? await codeTransport(local: isLocal).compactCodeThread(threadId: thread.id)
+ }
+ let cleanPlan = planMarkdown.trimmingCharacters(in: .whitespacesAndNewlines)
+ let prompt: String
+ if cleanPlan.isEmpty {
+ prompt = "방금 합의한 구현 계획대로 바로 구현을 진행해 주세요."
+ } else {
+ let truncated = cleanPlan.count > 12_000 ? String(cleanPlan.prefix(12_000)) + "\n…" : cleanPlan
+ prompt = "아래 승인된 계획에 따라 구현을 진행해 주세요:\n\n\(truncated)"
+ }
+ _ = await sendCodePromptForThread(
+ threadId: thread.id,
+ rawPrompt: prompt,
+ model: thread.model,
+ effort: thread.reasoningEffort,
+ accessMode: targetAccessMode
+ )
+ }
+
+ // MARK: - PR Details, Failing CI Logs, Commit History & AI Code Review
+
+ public func refreshCodeGitPRDetails(projectId: String, threadId: String? = nil, number: Int? = nil) async {
+ isLoadingCodePRDetails = true
+ defer { isLoadingCodePRDetails = false }
+ do {
+ let details = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitPRDetails(projectId: projectId, threadId: threadId, number: number)
+ codeGitPRDetailsByProject[projectId] = details
+ } catch {
+ // Optional PR details when gh is offline or no PR exists
+ }
+ }
+
+ public func fetchCodeGitPRCILogs(
+ projectId: String,
+ threadId: String? = nil,
+ number: Int? = nil,
+ check: String? = nil
+ ) async -> CodeGitCILogResponse? {
+ isLoadingCodeCILogs = true
+ defer { isLoadingCodeCILogs = false }
+ let cacheKey = "\(projectId)|\(number ?? 0)|\(check ?? "")"
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitPRCILogs(projectId: projectId, threadId: threadId, number: number, check: check, tailLines: 250)
+ codeGitCILogsByKey[cacheKey] = res
+ return res
+ } catch {
+ showError("CI 로그를 불러오지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ @discardableResult
+ public func replyCodeGitPR(
+ projectId: String,
+ threadId: String? = nil,
+ number: Int? = nil,
+ reviewThreadId: String? = nil,
+ body: String,
+ resolve: Bool = false
+ ) async -> Bool {
+ do {
+ _ = try await codeTransport(local: isLocalCodeProject(projectId))
+ .replyCodeGitPR(
+ projectId: projectId,
+ threadId: threadId,
+ number: number,
+ reviewThreadId: reviewThreadId,
+ body: body,
+ resolve: resolve
+ )
+ await refreshCodeGitPRDetails(projectId: projectId, threadId: threadId, number: number)
+ showInfo(resolve ? "PR 리뷰 스레드를 해결 처리했습니다." : "PR 답글을 등록했습니다.")
+ return true
+ } catch {
+ showError("PR 응답을 보내지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func refreshCodeGitLog(projectId: String, threadId: String? = nil, limit: Int = 40) async {
+ isLoadingCodeCommitLog = true
+ defer { isLoadingCodeCommitLog = false }
+ do {
+ let commits = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitLog(projectId: projectId, threadId: threadId, limit: limit)
+ codeGitCommitLogByProject[projectId] = commits
+ } catch {
+ // Ignore when folder is not a git repo
+ }
+ }
+
+ public func loadCodeGitCommitDiff(projectId: String, threadId: String? = nil, sha: String) async -> CodeGitCommitDiff? {
+ let key = "\(projectId)|\(sha)"
+ if let cached = codeGitCommitDiffByKey[key] {
+ return cached
+ }
+ do {
+ let diff = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitCommitDiff(projectId: projectId, threadId: threadId, sha: sha)
+ codeGitCommitDiffByKey[key] = diff
+ return diff
+ } catch {
+ showError("커밋 diff를 불러오지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ public func runCodeGitReview(
+ projectId: String,
+ threadId: String? = nil,
+ scope: String = "working",
+ baseBranch: String? = nil
+ ) async -> CodeReviewResponse? {
+ isRunningCodeReview = true
+ defer { isRunningCodeReview = false }
+ do {
+ let result = try await codeTransport(local: isLocalCodeProject(projectId))
+ .runCodeGitReview(projectId: projectId, threadId: threadId, scope: scope, baseBranch: baseBranch)
+ codeReviewResultByProject[projectId] = result
+ if result.findings.isEmpty {
+ showInfo("코드 리뷰 완료: 지적된 항목이 없습니다.")
+ } else {
+ showInfo("코드 리뷰 완료: \(result.findings.count)개 항목을 확인해 주세요.")
+ }
+ return result
+ } catch {
+ showError("AI 코드 리뷰를 실행하지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ // MARK: - Local CLI Session Discovery, Import & Terminal Handoff
+
+ public func refreshCodeCLISessions(provider: String = "all") async {
+ isLoadingCodeCLISessions = true
+ defer { isLoadingCodeCLISessions = false }
+ do {
+ codeCLISessions = try await codeTransport(local: true)
+ .fetchCodeCLISessions(provider: provider, limit: 50)
+ } catch {
+ codeCLISessions = []
+ }
+ }
+
+ @discardableResult
+ public func importCodeCLISession(_ session: CodeCLISessionSummary) async -> CodeThread? {
+ do {
+ let res = try await codeTransport(local: true).importCodeCLISession(
+ provider: session.provider,
+ sessionId: session.id,
+ cwd: session.cwd,
+ sourcePath: session.sourcePath
+ )
+ await refreshCodeState()
+ codeMessagesByThread[res.thread.id] = res.messages
+ await selectCodeThread(res.thread)
+ isCLISessionImportSheetPresented = false
+ showInfo("\(session.provider.uppercased()) CLI 세션을 가져왔습니다.")
+ return res.thread
+ } catch {
+ showError("CLI 세션을 가져오지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ public func fetchCodeCLIHandoff(threadId: String) async -> CodeCLISessionHandoff? {
+ do {
+ return try await codeTransport(local: isLocalCodeThread(threadId))
+ .fetchCodeCLIHandoff(threadId: threadId)
+ } catch {
+ showError("터미널 이어가기 명령을 가져오지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ // MARK: - Advanced Terminal (Split Panes, Search, Links, Mouse) & Preview URL Detection
+
+ public func openCodeTerminalSplit(primaryKey: String, projectId: String, threadId: String?) async {
+ if let existing = codeTerminalSplitKeyByPrimary[primaryKey], !existing.isEmpty {
+ return
+ }
+ let splitKey = "\(primaryKey)|split:\(UUID().uuidString.prefix(6))"
+ codeTerminalSplitKeyByPrimary[primaryKey] = splitKey
+ await ensureCodeTerminalSession(sessionKey: splitKey, projectId: projectId, threadId: threadId, cols: 80, rows: 24)
+ }
+
+ public func closeCodeTerminalSplit(primaryKey: String, projectId: String) async {
+ guard let splitKey = codeTerminalSplitKeyByPrimary.removeValue(forKey: primaryKey) else { return }
+ await closeCodeTerminalSession(sessionKey: splitKey, projectId: projectId)
+ }
+
+ public func searchCodeTerminal(sessionKey: String, query: String, caseSensitive: Bool = false) -> [TerminalSearchMatch] {
+ guard let screen = codeTerminalScreens[sessionKey] else { return [] }
+ return screen.search(query: query, caseSensitive: caseSensitive)
+ }
+
+ public func detectCodeTerminalLinks(sessionKey: String) -> [TerminalLinkMatch] {
+ guard let screen = codeTerminalScreens[sessionKey] else { return [] }
+ return screen.detectLinks()
+ }
+
+ public func recordPreviewConsoleEntry(projectId: String, entry: CodePreviewConsoleEntry) {
+ var list = codePreviewConsoleByProject[projectId] ?? []
+ list.append(entry)
+ if list.count > 200 {
+ list.removeFirst(list.count - 200)
+ }
+ codePreviewConsoleByProject[projectId] = list
+ }
+
+ public func clearPreviewConsoleEntries(projectId: String) {
+ codePreviewConsoleByProject[projectId] = []
+ }
+
+ func detectPreviewURLFromTerminal(key: String, text: String) {
+ guard let session = codeTerminalSessions[key] else { return }
+ let projectId = session.projectId
+ guard !projectId.isEmpty else { return }
+ let pattern = #"https?://(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]):\d{2,5}(?:/[^\s"'<>]*)?"#
+ guard let regex = try? NSRegularExpression(pattern: pattern) else { return }
+ let ns = text as NSString
+ let matches = regex.matches(in: text, range: NSRange(location: 0, length: ns.length))
+ guard let last = matches.last else { return }
+ var urlString = ns.substring(with: last.range)
+ urlString = urlString.replacingOccurrences(of: "0.0.0.0", with: "localhost")
+ urlString = urlString.replacingOccurrences(of: "[::1]", with: "localhost")
+ if codeDetectedPreviewURLByProject[projectId] != urlString {
+ codeDetectedPreviewURLByProject[projectId] = urlString
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+CodeProduction.swift b/apple/Apps/Shared/MorphAppState+CodeProduction.swift
new file mode 100644
index 000000000..e4ed1daff
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+CodeProduction.swift
@@ -0,0 +1,944 @@
+import Foundation
+import UniformTypeIdentifiers
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+// MARK: - Production Coding Agent Extensions for MorphAppState
+
+extension MorphAppState {
+ // MARK: - Per-Thread Composer Drafts
+
+ var currentCodeDraftKey: String {
+ CodeComposerDraftKey.key(forSelectedThreadId: selectedCodeThreadId)
+ }
+
+ func appendCodeAttachment(_ attachment: CodeImageAttachment, toDraftKey targetKey: String) {
+ if currentCodeDraftKey == targetKey {
+ codeComposerAttachments.append(attachment)
+ saveCurrentCodeDraft()
+ } else {
+ var draft = codeDraftsByKey[targetKey] ?? CodeComposerDraft()
+ draft.attachments.append(attachment)
+ codeDraftsByKey[targetKey] = draft
+ }
+ }
+
+ func saveCurrentCodeDraft() {
+ let key = currentCodeDraftKey
+ let draft = CodeComposerDraft(text: codeComposerText, attachments: codeComposerAttachments)
+ if draft.isEmpty {
+ codeDraftsByKey.removeValue(forKey: key)
+ } else {
+ codeDraftsByKey[key] = draft
+ }
+ store.saveCodeDraftAsync(key: key, text: codeComposerText)
+ }
+
+ func restoreCurrentCodeDraft() {
+ let key = currentCodeDraftKey
+ let draft = codeDraftsByKey[key] ?? CodeComposerDraft()
+ codeComposerText = draft.text
+ codeComposerAttachments = draft.attachments
+ }
+
+ public func clearCurrentCodeDraft() {
+ let key = currentCodeDraftKey
+ codeDraftsByKey.removeValue(forKey: key)
+ store.saveCodeDraftAsync(key: key, text: "")
+ }
+
+ /// Empties the composer for a request that is on its way, along with the draft kept for this screen. Sending
+ /// from the new-thread screen moves to the new thread without saving the draft again, so a kept draft would
+ /// come back the next time the member opens a new thread.
+ func clearSentCodeComposer() {
+ codeComposerText = ""
+ codeComposerAttachments = []
+ clearCurrentCodeDraft()
+ }
+
+ // MARK: - General Non-Image File Attachments
+
+ /// Attaches both images (normalized via `attachCodeImages`) and general workspace/document files
+ /// (PDF, CSV, JSON, Markdown, code, text, ZIP up to 15 MB) to the composer.
+ public func attachCodeFiles(_ urls: [URL]) {
+ guard !urls.isEmpty else { return }
+ var imagePicks: [MorphPickedImage] = []
+ var generalURLs: [URL] = []
+
+ for url in urls {
+ let ext = url.pathExtension.lowercased()
+ let imageExts: Set = ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tiff", "tif", "bmp"]
+ if imageExts.contains(ext) {
+ imagePicks.append(.file(url))
+ } else {
+ generalURLs.append(url)
+ }
+ }
+
+ if !imagePicks.isEmpty {
+ attachCodeImages(imagePicks)
+ }
+
+ guard !generalURLs.isEmpty else { return }
+ let targetDraftKey = currentCodeDraftKey
+ let maxBytes = 15 * 1024 * 1024
+ Task {
+ var failed: [String] = []
+ for url in generalURLs {
+ let attachment: CodeImageAttachment? = await Task.detached(priority: .userInitiated) { () -> CodeImageAttachment? in
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ do {
+ let data = try Data(contentsOf: url)
+ guard !data.isEmpty, data.count <= maxBytes else {
+ return nil
+ }
+ let mime = Self.mimeTypeForFileURL(url)
+ return CodeImageAttachment(
+ id: UUID().uuidString,
+ path: url.path,
+ name: url.lastPathComponent,
+ mimeType: mime,
+ sizeBytes: Int64(data.count),
+ dataBase64: data.base64EncodedString()
+ )
+ } catch {
+ return nil
+ }
+ }.value
+ if let att = attachment {
+ appendCodeAttachment(att, toDraftKey: targetDraftKey)
+ } else {
+ failed.append(url.lastPathComponent)
+ }
+ }
+ if !failed.isEmpty {
+ let joined = failed.map { "‘\($0)’" }.joined(separator: ", ")
+ showError("파일을 첨부하지 못했습니다: \(joined) (15MB 이하 파일만 지원합니다).")
+ }
+ }
+ }
+
+ private nonisolated static func mimeTypeForFileURL(_ url: URL) -> String {
+ if let utType = UTType(filenameExtension: url.pathExtension), let preferred = utType.preferredMIMEType {
+ return preferred
+ }
+ switch url.pathExtension.lowercased() {
+ case "md", "markdown": return "text/markdown"
+ case "json": return "application/json"
+ case "csv": return "text/csv"
+ case "pdf": return "application/pdf"
+ case "yaml", "yml": return "text/yaml"
+ case "zip": return "application/zip"
+ case "swift", "go", "ts", "tsx", "js", "jsx", "py", "rs", "sh", "sql", "txt", "log":
+ return "text/plain"
+ default:
+ return "application/octet-stream"
+ }
+ }
+
+ // MARK: - Pagination, Pinning, Compaction, Fork, Export
+
+ public func loadOlderCodeMessages(threadId: String) async {
+ guard !isLoadingOlderCodeMessages else { return }
+ guard codeThreadHasMoreByThread[threadId] == true else { return }
+ guard let oldestId = codeMessagesByThread[threadId]?.first?.id else { return }
+ isLoadingOlderCodeMessages = true
+ defer { isLoadingOlderCodeMessages = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeThread(threadId))
+ .fetchCodeMessagesPage(threadId: threadId, before: oldestId, limit: 80)
+ var current = codeMessagesByThread[threadId] ?? []
+ let existingIds = Set(current.map(\.id))
+ let prepended = res.messages.filter { !existingIds.contains($0.id) }
+ current.insert(contentsOf: prepended, at: 0)
+ codeMessagesByThread[threadId] = current
+ codeThreadHasMoreByThread[threadId] = res.hasMore ?? false
+ codeThreadTotalCountByThread[threadId] = res.totalCount ?? current.count
+ store.cacheCodeMessagesAsync(current, threadId: threadId)
+ store.indexCodeMessagesAsync(threadId: threadId, projectId: res.thread.projectId, threadTitle: res.thread.title, messages: current)
+ } catch {
+ showError("이전 메시지를 불러오지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func toggleCodeThreadPinned(id: String) async {
+ guard var thread = codeThreads.first(where: { $0.id == id }) else { return }
+ let isLocal = isLocalCodeThread(id)
+ let previous = thread
+ let nextPinned = !thread.isPinned
+ thread.pinned = nextPinned
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ do {
+ let updated = try await codeTransport(local: isLocal).updateCodeThreadPinned(threadId: id, pinned: nextPinned)
+ applyThreadUpdateInMemory(updated, isLocal: isLocal)
+ } catch {
+ applyThreadUpdateInMemory(previous, isLocal: isLocal)
+ showError("스레드 고정을 변경하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func compactCodeThread(threadId: String) async {
+ guard !isCompactingCodeThread else { return }
+ isCompactingCodeThread = true
+ defer { isCompactingCodeThread = false }
+ let isLocal = isLocalCodeThread(threadId)
+ do {
+ let res = try await codeTransport(local: isLocal).compactCodeThread(threadId: threadId)
+ if let thread = res.thread {
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ } else if let usage = res.usage, var thread = codeThreads.first(where: { $0.id == threadId }) {
+ thread.usage = usage
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ await loadCodeMessages(threadId: threadId)
+ showInfo("대화를 압축해 컨텍스트 여유를 확보했습니다.")
+ } catch {
+ showError("컨텍스트를 압축하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func forkCodeThreadWithOptions(
+ threadId: String,
+ upToMessageId: String? = nil,
+ createWorktree: Bool = false,
+ branch: String? = nil,
+ baseBranch: String? = nil
+ ) async {
+ do {
+ let res = try await codeTransport(local: isLocalCodeThread(threadId)).forkCodeThread(
+ threadId: threadId,
+ upToMessageId: upToMessageId,
+ createWorktree: createWorktree,
+ branch: branch,
+ baseBranch: baseBranch
+ )
+ codeMessagesByThread[res.thread.id] = res.messages
+ await refreshCodeState()
+ await selectCodeThread(res.thread)
+ if createWorktree, let br = res.thread.branch {
+ showInfo("새 worktree(\(br))로 대화를 분기했습니다.")
+ } else if res.nativeFork == true {
+ showInfo("세션 컨텍스트를 유지한 채 대화를 분기했습니다.")
+ } else {
+ showInfo("대화를 새 스레드로 분기했습니다.")
+ }
+ } catch {
+ showError("대화를 분기하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func exportCodeThreadMarkdown(threadId: String) async -> CodeThreadExportResponse? {
+ do {
+ return try await codeTransport(local: isLocalCodeThread(threadId)).exportCodeThread(threadId: threadId)
+ } catch {
+ showError("Markdown 내보내기에 실패했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ // MARK: - Enhanced Approvals & Prefix Allowlist Rules
+
+ public func decideCodeApprovalWithFeedback(
+ id: String,
+ decision: String,
+ reason: String? = nil,
+ prefix: String? = nil,
+ scope: String? = nil,
+ threadId: String? = nil
+ ) async {
+ // Optimistic removal from pending approvals & live run with targeted rollback on failure.
+ let removedApproval = localCodeState?.approvals.first(where: { $0.id == id })
+ let liveTid = threadId ?? removedApproval?.threadId
+ let removedLiveApproval: CodeApproval? = liveTid.flatMap { tid in
+ guard codeLiveRuns[tid]?.approval?.id == id else { return nil }
+ let existing = codeLiveRuns[tid]?.approval
+ codeLiveRuns[tid]?.approval = nil
+ return existing
+ }
+ localCodeState = localCodeState?.removingApproval(id)
+ do {
+ _ = try await codeTransport(local: true).decideCodeApproval(
+ id: id,
+ decision: decision,
+ reason: reason?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty,
+ prefix: prefix?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty,
+ scope: scope
+ )
+ Task { [weak self] in
+ await self?.refreshCodeStateQuietly()
+ await self?.refreshCodeApprovalRules()
+ }
+ switch decision {
+ case "denied":
+ showInfo(reason?.isEmpty == false ? "Denied with feedback." : "Execution denied.")
+ case "allow_prefix":
+ showInfo("Added prefix rule and approved execution.")
+ default:
+ showInfo("Execution approved.")
+ }
+ } catch {
+ if let removedApproval {
+ localCodeState = localCodeState?.restoringApproval(removedApproval)
+ }
+ if let liveTid, let removedLiveApproval, codeLiveRuns[liveTid]?.approval == nil {
+ codeLiveRuns[liveTid]?.approval = removedLiveApproval
+ }
+ showError("Could not process approval: \(error.localizedDescription)")
+ }
+ }
+
+ public func refreshCodeApprovalRules() async {
+ if let rules = try? await codeTransport(local: true).fetchCodeApprovalRules() {
+ codeApprovalRules = rules
+ }
+ }
+
+ public func createCodeApprovalRule(projectId: String?, actionKind: String?, prefix: String, local: Bool = true) async -> Bool {
+ let clean = prefix.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !clean.isEmpty else { return false }
+ do {
+ let rule = try await codeTransport(local: local).createCodeApprovalRule(
+ projectId: projectId,
+ actionKind: actionKind,
+ prefix: clean
+ )
+ codeApprovalRules.insert(rule, at: 0)
+ showInfo("허용 규칙 ‘\(rule.prefix)’을(를) 추가했습니다.")
+ return true
+ } catch {
+ showError("허용 규칙을 추가하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func deleteCodeApprovalRule(id: String) async {
+ for isLocal in [true, false] {
+ _ = try? await codeTransport(local: isLocal).deleteCodeApprovalRule(id: id)
+ }
+ codeApprovalRules.removeAll { $0.id == id }
+ showInfo("허용 규칙을 삭제했습니다.")
+ }
+
+ // MARK: - Git Remote, Branch Diff, PR/CI & Worktree Lifecycle
+
+ public func gitPushCode(projectId: String, threadId: String?, setUpstream: Bool = true, forceWithLease: Bool = false) async {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId)).gitPush(
+ projectId: projectId,
+ threadId: threadId,
+ remote: nil,
+ branch: nil,
+ setUpstream: setUpstream,
+ forceWithLease: forceWithLease
+ )
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: threadId) }
+ await refreshCodeGitPR(projectId: projectId, threadId: threadId)
+ showInfo("원격 저장소로 푸시했습니다.")
+ } catch {
+ showError("푸시하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func gitPullCode(projectId: String, threadId: String?, rebase: Bool = false) async {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId)).gitPull(
+ projectId: projectId,
+ threadId: threadId,
+ rebase: rebase
+ )
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: threadId) }
+ showInfo(rebase ? "원격 변경을 Rebase로 반영했습니다." : "원격 변경을 가져왔습니다.")
+ } catch {
+ showError("풀하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func gitFetchCode(projectId: String, threadId: String?) async {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId)).gitFetch(projectId: projectId, threadId: threadId)
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: threadId) }
+ showInfo("원격 브랜치 정보를 새로고침했습니다.")
+ } catch {
+ showError("Fetch하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func gitStashCode(projectId: String, threadId: String?, action: String, message: String? = nil, includeUntracked: Bool = true) async {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId)).gitStash(
+ projectId: projectId,
+ threadId: threadId,
+ action: action,
+ message: message,
+ includeUntracked: includeUntracked
+ )
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: threadId) }
+ if let stashes = res.stashes { codeGitStashesByProject[projectId] = stashes }
+ if action == "push" {
+ showInfo("변경사항을 Stash에 임시 보관했습니다.")
+ } else if action == "pop" {
+ showInfo("최근 Stash를 꺼내 복원했습니다.")
+ }
+ } catch {
+ showError("Stash 작업에 실패했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func refreshCodeGitBranchDiff(projectId: String, threadId: String?, base: String? = nil) async {
+ do {
+ let diff = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitBranchDiff(projectId: projectId, threadId: threadId, base: base)
+ codeGitBranchDiffByProject[projectId] = diff
+ } catch {
+ // Non-git or single-commit repo
+ }
+ }
+
+ public func generateCodeCommitMessage(projectId: String, threadId: String?, stagedOnly: Bool = false) async -> String? {
+ do {
+ return try await codeTransport(local: isLocalCodeProject(projectId))
+ .generateCodeCommitMessage(projectId: projectId, threadId: threadId, stagedOnly: stagedOnly)
+ } catch {
+ showError("커밋 메시지를 생성하지 못했습니다. \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ public func commitCodeGitWithOptions(projectId: String, threadId: String?, message: String, amend: Bool) async -> Bool {
+ let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .commitCodeGit(projectId: projectId, threadId: threadId, message: trimmed, amend: amend)
+ storeCodeGitStatus(res.git, projectId: projectId, threadId: threadId)
+ codeGitFileDiffs = codeGitFileDiffs.filter { !$0.key.hasPrefix("\(projectId)|") }
+ let shortSHA = res.commit.map { " (\($0))" } ?? ""
+ showInfo(amend ? "직전 커밋을 수정했습니다\(shortSHA)." : "커밋을 완료했습니다\(shortSHA).")
+ return true
+ } catch {
+ showError("커밋하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func refreshCodeGitPR(projectId: String, threadId: String?) async {
+ do {
+ let status = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeGitPR(projectId: projectId, threadId: threadId)
+ storeCodeGitPR(status, projectId: projectId, threadId: threadId)
+ } catch {
+ // gh unavailable or offline
+ }
+ }
+
+ public func createCodeGitPR(projectId: String, threadId: String?, title: String, body: String, base: String? = nil, draft: Bool = false) async -> Bool {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .createCodeGitPR(projectId: projectId, threadId: threadId, title: title, body: body, base: base, draft: draft)
+ if let pr = res.pr {
+ storeCodeGitPR(CodeGitPRStatusResponse(available: true, pr: pr, error: nil), projectId: projectId, threadId: threadId)
+ showInfo("PR #\(pr.number)을(를) 생성했습니다.")
+ } else {
+ await refreshCodeGitPR(projectId: projectId, threadId: threadId)
+ showInfo("Pull Request를 생성했습니다.")
+ }
+ return true
+ } catch {
+ showError("PR을 생성하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func mergeCodeGitPR(projectId: String, threadId: String?, number: Int? = nil, method: String = "squash", deleteBranch: Bool = true) async -> Bool {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .mergeCodeGitPR(projectId: projectId, threadId: threadId, number: number, method: method, deleteBranch: deleteBranch)
+ if let pr = res.pr {
+ storeCodeGitPR(CodeGitPRStatusResponse(available: true, pr: pr, error: nil), projectId: projectId, threadId: threadId)
+ } else {
+ await refreshCodeGitPR(projectId: projectId, threadId: threadId)
+ }
+ await refreshCodeGitStatus(projectId: projectId, threadId: threadId)
+ showInfo("PR 병합을 완료했습니다.")
+ return true
+ } catch {
+ showError("PR을 병합하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func removeCodeWorktree(projectId: String, worktreePath: String, branch: String?, deleteBranch: Bool, force: Bool = false) async -> Bool {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .removeCodeWorktree(projectId: projectId, worktreePath: worktreePath, branch: branch, deleteBranch: deleteBranch, force: force)
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: nil) }
+ await refreshCodeStateQuietly()
+ showInfo(deleteBranch ? "Worktree와 브랜치를 정리했습니다." : "Worktree를 정리했습니다.")
+ return true
+ } catch {
+ showError("Worktree를 삭제하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func applyCodeWorktree(projectId: String, threadId: String?, worktreePath: String, targetBranch: String? = nil, mode: String = "merge") async -> Bool {
+ isBusyCodeGitOp = true
+ defer { isBusyCodeGitOp = false }
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .applyCodeWorktree(projectId: projectId, threadId: threadId, worktreePath: worktreePath, targetBranch: targetBranch, mode: mode)
+ if let git = res.git { storeCodeGitStatus(git, projectId: projectId, threadId: threadId) }
+ showInfo("Worktree 변경사항을 메인 체크아웃에 반영했습니다.")
+ return true
+ } catch {
+ showError("Worktree 반영에 실패했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ // MARK: - Workspace File Tree & File Reader Jump
+
+ public func workspaceTreeKey(projectId: String, threadId: String?, path: String) -> String {
+ "\(projectId)|\(threadId ?? "")|\(path)"
+ }
+
+ public func loadCodeWorkspaceTree(projectId: String, threadId: String?, path: String = "") async {
+ let key = workspaceTreeKey(projectId: projectId, threadId: threadId, path: path)
+ codeWorkspaceTreeLoadingKeys.insert(key)
+ codeWorkspaceTreeErrorByKey.removeValue(forKey: key)
+ isLoadingCodeTree = !codeWorkspaceTreeLoadingKeys.isEmpty
+ defer {
+ codeWorkspaceTreeLoadingKeys.remove(key)
+ isLoadingCodeTree = !codeWorkspaceTreeLoadingKeys.isEmpty
+ }
+ do {
+ let res = try await codeTransport(local: true)
+ .fetchCodeWorkspaceTree(projectId: projectId, threadId: threadId, path: path.isEmpty ? nil : path)
+ guard !Task.isCancelled else { return }
+ codeWorkspaceTreeByKey[key] = res.entries
+ codeWorkspaceTreeErrorByKey.removeValue(forKey: key)
+ } catch is CancellationError {
+ // Superseded by project/thread switch.
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ // Superseded by project/thread switch.
+ } catch {
+ if codeWorkspaceTreeByKey[key] == nil {
+ codeWorkspaceTreeErrorByKey[key] = error.localizedDescription
+ }
+ }
+ }
+
+ public func openCodeFileInReader(projectId: String, threadId: String?, path: String, line: Int? = nil) {
+ codePendingFileViewer = CodeFileOpenRequest(
+ projectId: projectId,
+ threadId: threadId,
+ path: path,
+ line: line,
+ isLocal: isLocalCodeProject(projectId)
+ )
+ }
+
+ public func insertReviewCommentIntoComposer(path: String, lineRange: String?, diffSnippet: String?, instruction: String) {
+ let loc = lineRange.map { "\(path):\($0)" } ?? path
+ var parts = ["`\(loc)` 수정 요청: \(instruction.trimmingCharacters(in: .whitespacesAndNewlines))"]
+ if let snippet = diffSnippet?.trimmingCharacters(in: .whitespacesAndNewlines), !snippet.isEmpty {
+ let trimmed = String(snippet.prefix(1200))
+ parts.append("```diff\n\(trimmed)\n```")
+ }
+ let block = parts.joined(separator: "\n")
+ if codeComposerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ codeComposerText = block
+ } else {
+ codeComposerText += "\n\n" + block
+ }
+ showInfo("리뷰 코멘트를 입력창에 추가했습니다.")
+ }
+
+ // MARK: - Interactive Multi-Tab ANSI Terminal
+
+ public func terminalTabs(projectId: String, threadId: String?) -> [CodeTerminalTab] {
+ let scope = codeTerminalKey(projectId: projectId, threadId: threadId)
+ if let tabs = codeTerminalTabsByScope[scope], !tabs.isEmpty {
+ return tabs
+ }
+ return [CodeTerminalTab(id: "default", title: "Terminal 1", sessionKey: scope)]
+ }
+
+ public func activeTerminalSessionKey(projectId: String, threadId: String?) -> String {
+ let scope = codeTerminalKey(projectId: projectId, threadId: threadId)
+ let tabs = terminalTabs(projectId: projectId, threadId: threadId)
+ if let activeId = activeCodeTerminalTabByScope[scope],
+ let found = tabs.first(where: { $0.id == activeId }) {
+ return found.sessionKey
+ }
+ return tabs[0].sessionKey
+ }
+
+ public func selectTerminalTab(_ tabId: String, projectId: String, threadId: String?) {
+ let scope = codeTerminalKey(projectId: projectId, threadId: threadId)
+ activeCodeTerminalTabByScope[scope] = tabId
+ }
+
+ public func createAdditionalTerminalTab(projectId: String, threadId: String?) async {
+ let scope = codeTerminalKey(projectId: projectId, threadId: threadId)
+ var tabs = terminalTabs(projectId: projectId, threadId: threadId)
+ let nextIndex = tabs.count + 1
+ let tabId = UUID().uuidString
+ let sessionKey = "\(scope)#\(tabId)"
+ let tab = CodeTerminalTab(id: tabId, title: "터미널 \(nextIndex)", sessionKey: sessionKey)
+ tabs.append(tab)
+ codeTerminalTabsByScope[scope] = tabs
+ activeCodeTerminalTabByScope[scope] = tabId
+ await ensureCodeTerminalSession(sessionKey: sessionKey, projectId: projectId, threadId: threadId, cols: 100, rows: 28)
+ }
+
+ public func closeTerminalTab(_ tabId: String, projectId: String, threadId: String?) async {
+ let scope = codeTerminalKey(projectId: projectId, threadId: threadId)
+ var tabs = terminalTabs(projectId: projectId, threadId: threadId)
+ guard let idx = tabs.firstIndex(where: { $0.id == tabId }) else { return }
+ let removed = tabs.remove(at: idx)
+ await closeCodeTerminalSession(sessionKey: removed.sessionKey, projectId: projectId)
+ if tabs.isEmpty {
+ codeTerminalTabsByScope.removeValue(forKey: scope)
+ activeCodeTerminalTabByScope.removeValue(forKey: scope)
+ } else {
+ codeTerminalTabsByScope[scope] = tabs
+ if activeCodeTerminalTabByScope[scope] == tabId {
+ activeCodeTerminalTabByScope[scope] = tabs[max(0, idx - 1)].id
+ }
+ }
+ }
+
+ public func ensureCodeTerminalSession(sessionKey: String, projectId: String, threadId: String?, cols: Int = 100, rows: Int = 28) async {
+ if let existing = codeTerminalSessions[sessionKey], existing.running {
+ return
+ }
+ await restartCodeTerminalSession(sessionKey: sessionKey, projectId: projectId, threadId: threadId, cols: cols, rows: rows)
+ }
+
+ public func restartCodeTerminalSession(sessionKey: String, projectId: String, threadId: String?, cols: Int = 100, rows: Int = 28) async {
+ await closeCodeTerminalSession(sessionKey: sessionKey, projectId: projectId)
+ do {
+ let transport = try await codeTransport(local: isLocalCodeProject(projectId))
+ let session = try await transport.createCodeTerminalSession(projectId: projectId, threadId: threadId, cols: max(20, cols), rows: max(6, rows))
+ let stream = transport.streamCodeTerminalSession(sessionId: session.id)
+ codeTerminalSessions[sessionKey] = session
+ codeTerminalScreens[sessionKey] = TerminalScreen(columns: session.cols, rows: session.rows)
+ publishTerminalSnapshot(forKey: sessionKey)
+ let sid = session.id
+ let task = Task { [weak self] in
+ for await ev in stream {
+ guard let self, !Task.isCancelled else { break }
+ if let raw = ev.data, !raw.isEmpty {
+ self.codeTerminalScreens[sessionKey]?.write(raw)
+ self.publishTerminalSnapshot(forKey: sessionKey)
+ }
+ if ev.type == "exit" {
+ if var s = self.codeTerminalSessions[sessionKey], s.id == sid {
+ s.running = false
+ s.exitCode = ev.exitCode
+ self.codeTerminalSessions[sessionKey] = s
+ }
+ }
+ }
+ guard let self, !Task.isCancelled, var s = self.codeTerminalSessions[sessionKey], s.id == sid, s.running else {
+ return
+ }
+ s.running = false
+ self.codeTerminalSessions[sessionKey] = s
+ self.codeTerminalScreens[sessionKey]?.write("\r\n터미널 연결이 끊겼습니다. 다시 시작하려면 ↻를 누르세요.\r\n")
+ self.publishTerminalSnapshot(forKey: sessionKey)
+ }
+ codeTerminalStreamTasks[sessionKey] = task
+ } catch {
+ let message = "터미널 세션을 열지 못했습니다. \(error.localizedDescription)"
+ codeTerminalOutputs[sessionKey] = message
+ showError(message)
+ }
+ }
+
+ public func sendCodeTerminalInput(sessionKey: String, projectId: String, data: String) async {
+ guard let session = codeTerminalSessions[sessionKey] else { return }
+ do {
+ try await codeTransport(local: isLocalCodeProject(projectId)).sendCodeTerminalInput(sessionId: session.id, data: data)
+ } catch {
+ showError("터미널 입력을 보내지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func resizeCodeTerminalSession(sessionKey: String, projectId: String, cols: Int, rows: Int) async {
+ let clampedCols = max(20, min(300, cols))
+ let clampedRows = max(6, min(120, rows))
+ guard let session = codeTerminalSessions[sessionKey], session.running else { return }
+ if codeTerminalScreens[sessionKey]?.columns == clampedCols && codeTerminalScreens[sessionKey]?.rows == clampedRows {
+ return
+ }
+ codeTerminalScreens[sessionKey]?.resize(columns: clampedCols, rows: clampedRows)
+ publishTerminalSnapshot(forKey: sessionKey)
+ try? await codeTransport(local: isLocalCodeProject(projectId))
+ .resizeCodeTerminalSession(sessionId: session.id, cols: clampedCols, rows: clampedRows)
+ }
+
+ public func clearCodeTerminalOutput(sessionKey: String) {
+ if let session = codeTerminalSessions[sessionKey] {
+ let cols = codeTerminalScreens[sessionKey]?.columns ?? session.cols
+ let rows = codeTerminalScreens[sessionKey]?.rows ?? session.rows
+ codeTerminalScreens[sessionKey] = TerminalScreen(columns: cols, rows: rows)
+ }
+ publishTerminalSnapshot(forKey: sessionKey)
+ }
+
+ public func closeCodeTerminalSession(sessionKey: String, projectId: String) async {
+ codeTerminalStreamTasks.removeValue(forKey: sessionKey)?.cancel()
+ codeTerminalScreens.removeValue(forKey: sessionKey)
+ codeTerminalStyledLines.removeValue(forKey: sessionKey)
+ codeTerminalCursorByKey.removeValue(forKey: sessionKey)
+ guard let session = codeTerminalSessions.removeValue(forKey: sessionKey) else { return }
+ try? await codeTransport(local: isLocalCodeProject(projectId)).closeCodeTerminalSession(sessionId: session.id)
+ }
+
+ func publishTerminalSnapshot(forKey key: String) {
+ guard let screen = codeTerminalScreens[key] else {
+ codeTerminalOutputs[key] = ""
+ codeTerminalStyledLines[key] = []
+ return
+ }
+ codeTerminalOutputs[key] = screen.text
+ codeTerminalStyledLines[key] = screen.styledLines()
+ codeTerminalMouseModeByKey[key] = screen.mouseTrackingMode
+ codeTerminalSGRMouseByKey[key] = screen.sgrMouseMode
+ codeTerminalCursorByKey[key] = CodeTerminalCursorState(
+ row: screen.cursorRow,
+ column: screen.cursorColumn,
+ visible: screen.cursorVisible,
+ columns: screen.columns,
+ rows: screen.rows,
+ isAlternateScreen: screen.isAlternateScreen
+ )
+ detectPreviewURLFromTerminal(key: key, text: screen.text)
+ }
+
+ public func sendTerminalOutputToAgent(sessionKey: String) {
+ let raw = (codeTerminalOutputs[sessionKey] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !raw.isEmpty else {
+ showInfo("전달할 터미널 출력이 없습니다.")
+ return
+ }
+ let lines = raw.split(separator: "\n", omittingEmptySubsequences: false)
+ let tail = lines.suffix(60).joined(separator: "\n")
+ let snippet = "터미널 출력을 확인해 주세요:\n```\n\(tail)\n```"
+ if codeComposerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ codeComposerText = snippet
+ } else {
+ codeComposerText += "\n\n" + snippet
+ }
+ showInfo("터미널 출력을 입력창에 넣었습니다.")
+ }
+
+ // MARK: - Skills, Harness Config (MCP / AGENTS.md), Project Scripts & Bridge Health
+
+ public func refreshCodeSkills(projectId: String? = nil) async {
+ let isLocal = projectId.map { isLocalCodeProject($0) } ?? (localBridgeOnline || selectedCodeTarget == .local)
+ do {
+ codeSkills = try await codeTransport(local: isLocal).fetchCodeSkills(projectId: projectId)
+ } catch {
+ // Keep previously loaded skills
+ }
+ }
+
+ public func saveCodeSkill(name: String, description: String, content: String, projectId: String? = nil) async -> Bool {
+ let isLocal = projectId.map { isLocalCodeProject($0) } ?? (localBridgeOnline || selectedCodeTarget == .local)
+ do {
+ _ = try await codeTransport(local: isLocal).saveCodeSkill(name: name, description: description, content: content, projectId: projectId)
+ await refreshCodeSkills(projectId: projectId)
+ showInfo("스킬 /\(name)을(를) 저장했습니다.")
+ return true
+ } catch {
+ showError("스킬을 저장하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func deleteCodeSkill(name: String, projectId: String? = nil) async -> Bool {
+ let isLocal = projectId.map { isLocalCodeProject($0) } ?? (localBridgeOnline || selectedCodeTarget == .local)
+ do {
+ try await codeTransport(local: isLocal).deleteCodeSkill(name: name, projectId: projectId)
+ await refreshCodeSkills(projectId: projectId)
+ showInfo("스킬 /\(name)을(를) 삭제했습니다.")
+ return true
+ } catch {
+ showError("스킬을 삭제하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func refreshCodeHarnessConfig(projectId: String? = nil, local: Bool = true) async {
+ isLoadingCodeHarnessConfig = true
+ defer { isLoadingCodeHarnessConfig = false }
+ do {
+ codeHarnessConfig = try await codeTransport(local: true).fetchCodeHarnessConfig(projectId: projectId)
+ } catch {
+ // Keep cached harness config if local daemon is unavailable.
+ }
+ }
+
+ public func saveCodeHarnessConfig(
+ projectId: String? = nil,
+ agentsMd: String? = nil,
+ projectAgentsMd: String? = nil,
+ mcpServers: [CodeMCPServerConfig]? = nil,
+ hooks: [CodeHarnessHook]? = nil,
+ permissionRules: [CodeHarnessPermissionRule]? = nil,
+ autoCompactEnabled: Bool? = nil,
+ autoCompactTokens: Int? = nil,
+ networkSandbox: String? = nil,
+ local: Bool = true
+ ) async -> Bool {
+ do {
+ codeHarnessConfig = try await codeTransport(local: true).saveCodeHarnessConfig(
+ projectId: projectId,
+ agentsMd: agentsMd,
+ projectAgentsMd: projectAgentsMd,
+ mcpServers: mcpServers,
+ hooks: hooks,
+ permissionRules: permissionRules,
+ autoCompactEnabled: autoCompactEnabled,
+ autoCompactTokens: autoCompactTokens,
+ networkSandbox: networkSandbox
+ )
+ showInfo("Saved harness configuration (AGENTS.md & MCP servers).")
+ return true
+ } catch {
+ showError("Failed to save harness configuration: \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func refreshCodeProjectScripts(projectId: String) async {
+ do {
+ codeProjectScriptsByProject[projectId] = try await codeTransport(local: isLocalCodeProject(projectId))
+ .fetchCodeProjectScripts(projectId: projectId)
+ } catch {
+ if let fromProject = codeProjects.first(where: { $0.id == projectId })?.scripts {
+ codeProjectScriptsByProject[projectId] = fromProject
+ }
+ }
+ }
+
+ public func saveCodeProjectScripts(projectId: String, scripts: [CodeProjectScript]) async -> Bool {
+ do {
+ let saved = try await codeTransport(local: isLocalCodeProject(projectId))
+ .saveCodeProjectScripts(projectId: projectId, scripts: scripts)
+ codeProjectScriptsByProject[projectId] = saved
+ await refreshCodeStateQuietly()
+ showInfo("프로젝트 스크립트를 저장했습니다.")
+ return true
+ } catch {
+ showError("스크립트를 저장하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func runCodeProjectScript(projectId: String, scriptId: String, threadId: String?) async {
+ do {
+ let res = try await codeTransport(local: isLocalCodeProject(projectId))
+ .runCodeProjectScript(projectId: projectId, scriptId: scriptId, threadId: threadId)
+ if let tid = threadId ?? selectedCodeThread?.id {
+ let msg = CodeMessage(
+ id: "cmsg-script-\(UUID().uuidString)",
+ threadId: tid,
+ role: "assistant",
+ content: "",
+ blocks: [res.block],
+ model: selectedCodeModel,
+ executionTarget: isLocalCodeProject(projectId) ? .local : selectedCodeTarget,
+ createdAt: ISO8601DateFormatter().string(from: Date())
+ )
+ appendCodeMessages([msg], threadId: tid)
+ }
+ showInfo(res.exitCode == 0 ? "스크립트 실행을 완료했습니다." : "스크립트가 종료 코드 \(res.exitCode)(으)로 끝났습니다.")
+ } catch {
+ showError("스크립트를 실행하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ public func refreshCodeDaemonHealth() async {
+ if let localHealth = try? await codeTransport(local: true).fetchCodeDaemonHealth() {
+ localBridgeHealth = localHealth
+ }
+ }
+
+ public var isLocalBridgeOutdated: Bool {
+ let ver = localBridgeHealth?.version ?? localCodeDaemonVersion
+ guard let ver, !ver.isEmpty else { return false }
+ return ver.compare(Self.minimumSupportedDaemonVersion, options: .numeric) == .orderedAscending
+ }
+
+ // MARK: - FTS5 Search & Background Notifications
+
+ func syncCodeSearchAndApprovalRulesFromState() {
+ store.indexCodeThreadsAsync(codeThreads)
+ var mergedRules: [CodeApprovalRule] = []
+ var seen = Set()
+ for r in (localCodeState?.approvalRules ?? []) {
+ if seen.insert(r.id).inserted { mergedRules.append(r) }
+ }
+ if !mergedRules.isEmpty {
+ codeApprovalRules = mergedRules
+ }
+ }
+
+ public func runCodeFullTextSearch(query: String) {
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else {
+ codeSearchHits = []
+ return
+ }
+ codeSearchHits = (try? store.searchCode(query: trimmed, limit: 30)) ?? []
+ }
+
+ func emitCodeNotificationIfBackground(
+ kind: CodeNotificationEvent.Kind,
+ threadId: String,
+ title: String,
+ subtitle: String? = nil,
+ body: String
+ ) {
+ guard isCodeNotificationEnabled(for: kind) else { return }
+ let viewingThisThread: Bool = {
+ #if os(macOS)
+ return NSApp.isActive && appMode == .code && selectedCodeThread?.id == threadId
+ #else
+ return UIApplication.shared.applicationState == .active && appMode == .code && isCodeThreadOnScreen && selectedCodeThread?.id == threadId
+ #endif
+ }()
+ // Always notify on approval/question/handoff when app is inactive or another thread is focused.
+ guard !viewingThisThread else { return }
+ codeOnNotificationEvent?(CodeNotificationEvent(kind: kind, threadId: threadId, title: title, subtitle: subtitle, body: body))
+ }
+}
+
+private extension String {
+ var nilIfEmpty: String? {
+ isEmpty ? nil : self
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+CodeTurns.swift b/apple/Apps/Shared/MorphAppState+CodeTurns.swift
new file mode 100644
index 000000000..15f41463e
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+CodeTurns.swift
@@ -0,0 +1,1269 @@
+import Foundation
+import Observation
+import os
+import MorphCore
+#if os(macOS)
+import AppKit
+import SystemConfiguration
+#else
+import UIKit
+import UserNotifications
+#endif
+
+extension MorphAppState {
+ func attachCodeImages(_ picked: [MorphPickedImage]) {
+ guard !picked.isEmpty else { return }
+ let targetDraftKey = currentCodeDraftKey
+ codeComposerProcessingImages += picked.count
+ Task {
+ var unreadable: [String] = []
+ for item in picked {
+ let result = await Task.detached(priority: .userInitiated) { Self.readCodeImage(item) }.value
+ codeComposerProcessingImages -= 1
+ switch result {
+ case .success(let attachment):
+ appendCodeAttachment(attachment, toDraftKey: targetDraftKey)
+ case .failure(let failure):
+ unreadable.append(failure.name)
+ }
+ }
+ if !unreadable.isEmpty {
+ let names = unreadable.map { "‘\($0)’" }.joined(separator: ", ")
+ showError("이미지를 첨부하지 못했습니다: \(names). PNG, JPEG, HEIC 같은 이미지 파일인지 확인해 주세요.")
+ }
+ }
+ }
+
+ struct CodeImageReadFailure: Error {
+ let name: String
+ }
+
+ nonisolated static func readCodeImage(_ item: MorphPickedImage) -> Result {
+ let data: Data?
+ let originalName: String?
+ switch item {
+ case .file(let url):
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ data = try? Data(contentsOf: url)
+ originalName = url.lastPathComponent
+ case .data(let bytes, let name):
+ data = bytes
+ originalName = name
+ }
+ guard let data, let image = try? CodeImageNormalizer.normalize(data) else {
+ return .failure(CodeImageReadFailure(name: originalName ?? "이미지"))
+ }
+ return .success(CodeImageAttachment(
+ id: UUID().uuidString,
+ name: CodeImageNormalizer.fileName(original: originalName, fileExtension: image.fileExtension),
+ mimeType: image.mimeType,
+ dataBase64: image.data.base64EncodedString()
+ ))
+ }
+
+ public func removeCodeAttachment(id: String) {
+ codeComposerAttachments.removeAll { $0.id == id }
+ saveCurrentCodeDraft()
+ }
+
+ /// Optimistic submit state committed synchronously on frame 0 before any async network hop.
+ enum CodePreparedPromptSubmission {
+ case followUp(
+ thread: CodeThread,
+ mode: CodeFollowUpMode,
+ prompt: String,
+ attachments: [CodeImageAttachment],
+ previousComposerText: String,
+ previousThread: CodeThread?,
+ pendingInputId: String?
+ )
+ case existingThread(
+ thread: CodeThread,
+ run: CodeLiveRun,
+ rawPrompt: String,
+ prompt: String,
+ attachments: [CodeImageAttachment],
+ model: String,
+ accessMode: CodeAccessMode,
+ effort: CodeReasoningEffort
+ )
+ case newDraft(
+ draft: CodeNewThreadDraft,
+ run: CodeLiveRun,
+ rawPrompt: String,
+ prompt: String,
+ attachments: [CodeImageAttachment],
+ model: String,
+ accessMode: CodeAccessMode,
+ effort: CodeReasoningEffort
+ )
+ }
+
+ /// Commits composer clearing and optimistic run/queue UI synchronously on the submit frame so the prompt
+ /// and scroll transition start together with zero async MainActor hop.
+ func beginCodePromptSubmit(mode: CodeFollowUpMode? = nil) -> CodePreparedPromptSubmission? {
+ let rawPrompt = codeComposerText.trimmingCharacters(in: .whitespacesAndNewlines)
+ let pendingAttachments = codeComposerAttachments
+ guard !rawPrompt.isEmpty || !pendingAttachments.isEmpty else { return nil }
+ // An image still being read would be left behind; the send button waits for it.
+ guard codeComposerProcessingImages == 0 else { return nil }
+ let prompt = rawPrompt.isEmpty ? "첨부한 이미지를 분석해 주세요." : rawPrompt
+ if !rawPrompt.isEmpty {
+ recordCodePromptHistory(rawPrompt)
+ }
+
+ let requestedModel = selectedCodeModel
+ let requestedAccess = selectedCodeAccessMode
+ let requestedEffort = selectedCodeEffort
+
+ if let open = selectedCodeThread {
+ if codeLiveRuns[open.id] != nil {
+ let resolvedMode = mode ?? codeFollowUpMode
+ let previousComposerText = codeComposerText
+ let previousThread = codeThreads.first(where: { $0.id == open.id })
+ let isLocal = isLocalCodeThread(open.id)
+ clearSentCodeComposer()
+ let pendingInputId = showOptimisticCodeFollowUp(
+ threadId: open.id,
+ mode: resolvedMode,
+ prompt: prompt,
+ previousThread: previousThread,
+ isLocal: isLocal
+ )
+ return .followUp(
+ thread: open,
+ mode: resolvedMode,
+ prompt: prompt,
+ attachments: pendingAttachments,
+ previousComposerText: previousComposerText,
+ previousThread: previousThread,
+ pendingInputId: pendingInputId
+ )
+ }
+ clearSentCodeComposer()
+ clearOptimisticCodeThreadTriageState(threadId: open.id)
+ let createdRun = CodeLiveRun(
+ threadId: open.id,
+ pendingPrompt: prompt,
+ pendingImages: pendingAttachments,
+ pendingModel: requestedModel,
+ pendingEffort: requestedEffort
+ )
+ codeLiveRuns[open.id] = createdRun
+ return .existingThread(
+ thread: open,
+ run: createdRun,
+ rawPrompt: rawPrompt,
+ prompt: prompt,
+ attachments: pendingAttachments,
+ model: requestedModel,
+ accessMode: requestedAccess,
+ effort: requestedEffort
+ )
+ } else if let draft = codeNewThreadDraft {
+ guard pendingDraftCodeRun == nil, !isCreatingDraftedThread else { return nil }
+ clearSentCodeComposer()
+ let draftRun = CodeLiveRun(threadId: "", pendingPrompt: prompt, pendingImages: pendingAttachments)
+ pendingDraftCodeRun = draftRun
+ return .newDraft(
+ draft: draft,
+ run: draftRun,
+ rawPrompt: rawPrompt,
+ prompt: prompt,
+ attachments: pendingAttachments,
+ model: requestedModel,
+ accessMode: requestedAccess,
+ effort: requestedEffort
+ )
+ } else {
+ return nil
+ }
+ }
+
+ /// Completes the network half of a synchronously committed `beginCodePromptSubmit`.
+ func finishCodePromptSubmit(_ submission: CodePreparedPromptSubmission) async {
+ let thread: CodeThread
+ let run: CodeLiveRun
+ let rawPrompt: String
+ let prompt: String
+ let pendingAttachments: [CodeImageAttachment]
+ let requestedModel: String
+ let requestedAccess: CodeAccessMode
+ let requestedEffort: CodeReasoningEffort
+ var createdFromDraft: CodeNewThreadDraft?
+
+ switch submission {
+ case .followUp(let targetThread, let mode, let followPrompt, let attachments, let previousComposerText, let previousThread, let pendingInputId):
+ await dispatchPreparedCodeFollowUp(
+ to: targetThread,
+ mode: mode,
+ prompt: followPrompt,
+ attachments: attachments,
+ previousComposerText: previousComposerText,
+ previousThread: previousThread,
+ pendingInputId: pendingInputId
+ )
+ return
+ case .existingThread(let open, let createdRun, let raw, let text, let attachments, let model, let access, let effort):
+ thread = open
+ run = createdRun
+ rawPrompt = raw
+ prompt = text
+ pendingAttachments = attachments
+ requestedModel = model
+ requestedAccess = access
+ requestedEffort = effort
+ case .newDraft(let draft, let draftRun, let raw, let text, let attachments, let model, let access, let effort):
+ guard let made = await createDraftedCodeThread(draft) else {
+ pendingDraftCodeRun = nil
+ if codeComposerText.isEmpty {
+ codeComposerText = raw
+ if codeComposerAttachments.isEmpty {
+ codeComposerAttachments = attachments
+ }
+ saveCurrentCodeDraft()
+ }
+ return
+ }
+ createdFromDraft = draft
+ thread = made
+ draftRun.threadId = thread.id
+ codeLiveRuns[thread.id] = draftRun
+ pendingDraftCodeRun = nil
+ run = draftRun
+ rawPrompt = raw
+ prompt = text
+ pendingAttachments = attachments
+ requestedModel = model
+ requestedAccess = access
+ requestedEffort = effort
+ }
+
+ let threadId = thread.id
+ let isLocal = isLocalCodeThread(threadId)
+
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ let images = try await uploadCodeImages(pendingAttachments, for: thread, transport: transport)
+ let res = try await transport.sendCodeMessage(
+ threadId: threadId,
+ prompt: prompt,
+ images: images.isEmpty ? nil : images,
+ model: requestedModel,
+ executionTarget: codeTarget(of: thread),
+ accessMode: requestedAccess,
+ reasoningEffort: requestedEffort
+ )
+ run.submittedMessageId = res.userMessage.id
+ appendCodeMessages([res.userMessage] + [res.reply].compactMap { $0 }, threadId: threadId)
+ applyThreadUpdateInMemory(res.thread, isLocal: isLocal)
+ if res.reply == nil {
+ followCodeThread(threadId)
+ // Let the 300ms upward submit glide finish settling before swapping out the optimistic bubble.
+ let remaining = max(0, 0.38 - Date().timeIntervalSince(run.launchedAt))
+ if remaining > 0.01 {
+ Task { [weak self, weak run] in
+ try? await Task.sleep(for: .seconds(remaining))
+ guard let self, let run, self.codeLiveRuns[threadId] === run else { return }
+ run.pendingPrompt = nil
+ }
+ } else {
+ run.pendingPrompt = nil
+ }
+ if run.isCancelling {
+ run.isCancelling = false
+ await cancelCodeTurn(threadId: threadId)
+ }
+ } else {
+ run.pendingPrompt = nil
+ // The server answered at once: a local action waiting on approval, or a server that waits for turns.
+ endCodeRun(threadId)
+ }
+ } catch {
+ endCodeRun(threadId)
+ // If this turn failed before any message landed on a freshly drafted thread (e.g. image upload dropped),
+ // clean up the empty orphaned "새 작업" thread and return the user to the draft screen with their input intact.
+ if let draft = createdFromDraft, (codeMessagesByThread[threadId]?.isEmpty ?? true) {
+ let isCurrentlyViewing = selectedCodeThreadId == threadId
+ removeDeletedCodeThread(threadId, isLocal: isLocal)
+ Task { [weak self] in
+ guard let self else { return }
+ try? await self.codeTransport(local: isLocal).deleteCodeThread(id: threadId)
+ }
+ if isCurrentlyViewing {
+ codeNewThread = draft
+ selectedCodeThreadId = nil
+ if codeComposerText.isEmpty {
+ codeComposerText = rawPrompt
+ if codeComposerAttachments.isEmpty {
+ codeComposerAttachments = pendingAttachments
+ }
+ saveCurrentCodeDraft()
+ }
+ }
+ } else if selectedCodeThreadId == threadId, codeComposerText.isEmpty {
+ codeComposerText = rawPrompt
+ if codeComposerAttachments.isEmpty {
+ codeComposerAttachments = pendingAttachments
+ }
+ }
+ showError("작업을 보내지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Sends the composer's request. While the thread's turn runs it goes into that turn or its queue, by the
+ /// follow-up setting unless mode says otherwise.
+ public func sendCodePrompt(mode: CodeFollowUpMode? = nil) async {
+ guard let submission = beginCodePromptSubmit(mode: mode) else { return }
+ await finishCodePromptSubmit(submission)
+ }
+
+ /// Uploads images to the thread's workspace in parallel, preserving original order.
+ func uploadCodeImages(_ attachments: [CodeImageAttachment], for thread: CodeThread, transport: MorphTransport) async throws -> [CodeImageAttachment] {
+ guard !attachments.isEmpty else { return [] }
+ let projectId = thread.projectId
+ let threadId = thread.id
+ return try await withThrowingTaskGroup(of: (Int, CodeImageAttachment).self) { group in
+ for (index, image) in attachments.enumerated() {
+ group.addTask {
+ guard let base64 = image.dataBase64, !base64.isEmpty else {
+ return (index, image)
+ }
+ let uploaded: CodeUploadResponse
+ do {
+ uploaded = try await transport.uploadCodeFile(
+ projectId: projectId,
+ threadId: threadId,
+ name: image.name,
+ mimeType: image.mimeType,
+ dataBase64: base64
+ )
+ } catch {
+ throw CodeImageUploadError(name: image.name, underlying: error)
+ }
+ let resolved = CodeImageAttachment(
+ id: uploaded.upload.id,
+ path: uploaded.upload.path,
+ name: uploaded.upload.name,
+ mimeType: uploaded.upload.mimeType,
+ dataBase64: base64,
+ url: uploaded.upload.url
+ )
+ return (index, resolved)
+ }
+ }
+ var ordered = Array(repeating: nil, count: attachments.count)
+ for try await (index, uploaded) in group {
+ ordered[index] = uploaded
+ }
+ return ordered.compactMap { $0 }
+ }
+ }
+
+ /// An image the server did not take, which stops its request.
+ struct CodeImageUploadError: LocalizedError {
+ let name: String
+ let underlying: Error
+
+ var errorDescription: String? {
+ "‘\(name)’ 이미지를 올리지 못했습니다. \(underlying.localizedDescription)"
+ }
+ }
+
+ /// Sends a request to a thread whose turn runs, into that turn or its queue as mode says, with optimistic UI
+ /// and rollback on failure.
+ func sendCodeFollowUp(to thread: CodeThread, mode: CodeFollowUpMode, prompt: String, attachments: [CodeImageAttachment]) async {
+ let isLocal = isLocalCodeThread(thread.id)
+ let composerText = codeComposerText
+ let previousThread = codeThreads.first(where: { $0.id == thread.id })
+ clearSentCodeComposer()
+ let pendingInputId = showOptimisticCodeFollowUp(
+ threadId: thread.id,
+ mode: mode,
+ prompt: prompt,
+ previousThread: previousThread,
+ isLocal: isLocal
+ )
+ await dispatchPreparedCodeFollowUp(
+ to: thread,
+ mode: mode,
+ prompt: prompt,
+ attachments: attachments,
+ previousComposerText: composerText,
+ previousThread: previousThread,
+ pendingInputId: pendingInputId
+ )
+ }
+
+ /// Shows a request sent to a running turn before the server answers: a queued one at the end of the queue, a
+ /// steered one as the turn's latest entry. Returns the steered entry's id, which the server's echo replaces.
+ func showOptimisticCodeFollowUp(
+ threadId: String,
+ mode: CodeFollowUpMode,
+ prompt: String,
+ previousThread: CodeThread?,
+ isLocal: Bool
+ ) -> String? {
+ switch mode {
+ case .queue:
+ guard let currentThread = previousThread else { return nil }
+ let optimisticItem = CodeQueuedPrompt(
+ id: "optimistic-\(UUID().uuidString)",
+ prompt: prompt,
+ images: nil,
+ createdAt: MorphPalette.isoString(from: Date())
+ )
+ var nextQueue = currentThread.queue ?? []
+ nextQueue.append(optimisticItem)
+ applyThreadUpdateInMemory(currentThread.withOptimistic(queue: nextQueue), isLocal: isLocal)
+ return nil
+ case .steer:
+ guard let run = codeLiveRuns[threadId] else { return nil }
+ let id = "pending-input-\(UUID().uuidString)"
+ run.addPendingInput(id: id, content: prompt)
+ return id
+ }
+ }
+
+ /// Dispatches a follow-up request whose composer clear and optimistic queue entry were already committed.
+ func dispatchPreparedCodeFollowUp(
+ to thread: CodeThread,
+ mode: CodeFollowUpMode,
+ prompt: String,
+ attachments: [CodeImageAttachment],
+ previousComposerText: String,
+ previousThread: CodeThread?,
+ pendingInputId: String?
+ ) async {
+ let isLocal = isLocalCodeThread(thread.id)
+ // The run that shows the steered request, which a later turn would replace.
+ let steeredRun = pendingInputId == nil ? nil : codeLiveRuns[thread.id]
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ let images = try await uploadCodeImages(attachments, for: thread, transport: transport)
+ let res = try await transport.sendCodeFollowUp(
+ threadId: thread.id,
+ mode: mode,
+ prompt: prompt,
+ images: images.isEmpty ? nil : images,
+ model: selectedCodeModel,
+ executionTarget: isLocal ? .local : selectedCodeTarget,
+ accessMode: selectedCodeAccessMode,
+ reasoningEffort: selectedCodeEffort
+ )
+ if let pendingInputId, res.steered != true {
+ // The turn had stopped taking input, so the request went to the queue or started its own turn.
+ steeredRun?.removePendingInput(id: pendingInputId)
+ }
+ applyCodeFollowUp(res, threadId: thread.id, isLocal: isLocal)
+ } catch {
+ if let pendingInputId {
+ steeredRun?.removePendingInput(id: pendingInputId)
+ }
+ if let previousThread {
+ applyThreadUpdateInMemory(previousThread, isLocal: isLocal)
+ }
+ if selectedCodeThreadId == thread.id, codeComposerText.isEmpty {
+ codeComposerText = previousComposerText
+ if codeComposerAttachments.isEmpty {
+ codeComposerAttachments = attachments
+ }
+ }
+ showError("메시지를 보내지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Shows what the server did with a request sent to a running turn. A queued request shows in the thread's
+ /// queue. A request that started a turn of its own, because the turn it was meant for had ended, becomes the
+ /// thread's next message and its turn is followed.
+ func applyCodeFollowUp(_ res: CodeFollowUpResponse, threadId: String, isLocal: Bool) {
+ if let thread = res.thread {
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ guard let userMessage = res.userMessage else { return }
+ appendCodeMessages([userMessage] + [res.reply].compactMap { $0 }, threadId: threadId)
+ guard res.reply == nil else { return }
+ endCodeRun(threadId)
+ codeLiveRuns[threadId] = CodeLiveRun(threadId: threadId)
+ followCodeThread(threadId)
+ // The reply of the turn that ended may not have reached this device yet.
+ Task { await loadCodeMessages(threadId: threadId) }
+ }
+
+ /// Changes a thread's queue on its server with optimistic local update and rollback on failure.
+ func changeCodeQueue(
+ threadId: String,
+ failure: String,
+ optimistic: (([CodeQueuedPrompt]) -> [CodeQueuedPrompt])? = nil,
+ _ change: (MorphTransport) async throws -> CodeThread
+ ) async {
+ let isLocal = isLocalCodeThread(threadId)
+ let previousThread = codeThreads.first(where: { $0.id == threadId })
+ if let optimistic, let current = previousThread {
+ let updatedQueue = optimistic(current.queue ?? [])
+ applyThreadUpdateInMemory(current.withOptimistic(queue: updatedQueue), isLocal: isLocal)
+ }
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ let thread = try await change(transport)
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ } catch {
+ if let previousThread {
+ applyThreadUpdateInMemory(previousThread, isLocal: isLocal)
+ }
+ showError("\(failure) \(error.localizedDescription)")
+ }
+ }
+
+ public func editCodeQueueItem(threadId: String, itemId: String, prompt: String) async {
+ let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { return }
+ await changeCodeQueue(
+ threadId: threadId,
+ failure: "대기 중인 메시지를 고치지 못했습니다.",
+ optimistic: { queue in
+ queue.map { item in
+ item.id == itemId
+ ? CodeQueuedPrompt(id: item.id, prompt: text, images: item.images, createdAt: item.createdAt)
+ : item
+ }
+ }
+ ) {
+ try await $0.editCodeQueueItem(threadId: threadId, itemId: itemId, prompt: text)
+ }
+ }
+
+ public func deleteCodeQueueItem(threadId: String, itemId: String) async {
+ await changeCodeQueue(
+ threadId: threadId,
+ failure: "대기 중인 메시지를 지우지 못했습니다.",
+ optimistic: { queue in queue.filter { $0.id != itemId } }
+ ) {
+ try await $0.deleteCodeQueueItem(threadId: threadId, itemId: itemId)
+ }
+ }
+
+ /// Moves a queued request one place up (-1) or down (+1).
+ public func moveCodeQueueItem(threadId: String, itemId: String, by offset: Int) async {
+ var ids = (codeThreads.first { $0.id == threadId }?.queue ?? []).map(\.id)
+ guard let from = ids.firstIndex(of: itemId), ids.indices.contains(from + offset) else { return }
+ ids.swapAt(from, from + offset)
+ let targetIndex = from + offset
+ await changeCodeQueue(
+ threadId: threadId,
+ failure: "대기열 순서를 바꾸지 못했습니다.",
+ optimistic: { queue in
+ var copy = queue
+ if copy.indices.contains(from), copy.indices.contains(targetIndex) {
+ copy.swapAt(from, targetIndex)
+ }
+ return copy
+ }
+ ) {
+ try await $0.reorderCodeQueue(threadId: threadId, ids: ids)
+ }
+ }
+
+ /// Sends a queued request without waiting, with optimistic removal from queue and rollback on failure.
+ public func sendCodeQueueItemNow(threadId: String, itemId: String) async {
+ let isLocal = isLocalCodeThread(threadId)
+ let previousThread = codeThreads.first(where: { $0.id == threadId })
+ if let current = previousThread {
+ let remaining = (current.queue ?? []).filter { $0.id != itemId }
+ applyThreadUpdateInMemory(current.withOptimistic(queue: remaining), isLocal: isLocal)
+ }
+ do {
+ let res = try await codeTransport(local: isLocal).sendCodeQueueItemNow(threadId: threadId, itemId: itemId)
+ applyCodeFollowUp(res, threadId: threadId, isLocal: isLocal)
+ } catch {
+ if let previousThread {
+ applyThreadUpdateInMemory(previousThread, isLocal: isLocal)
+ }
+ showError("메시지를 보내지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Edits a request the member sent: the conversation goes back to before it, with the files the turns since
+ /// then changed when restoreFiles is set, and the edited request runs from there with the composer's settings.
+ public func editCodeMessage(threadId: String, messageId: String, prompt: String, restoreFiles: Bool) async {
+ let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty, codeLiveRuns[threadId] == nil else { return }
+ let isLocal = isLocalCodeThread(threadId)
+ do {
+ let res = try await codeTransport(local: isLocal).rewindCodeThread(
+ threadId: threadId,
+ messageId: messageId,
+ prompt: text,
+ restoreFiles: restoreFiles,
+ model: selectedCodeModel,
+ executionTarget: isLocal ? .local : selectedCodeTarget,
+ accessMode: selectedCodeAccessMode,
+ reasoningEffort: selectedCodeEffort
+ )
+ var messages = codeMessagesByThread[threadId] ?? []
+ if let edited = messages.firstIndex(where: { $0.id == messageId }) {
+ messages.removeSubrange(edited...)
+ }
+ codeMessagesByThread[threadId] = messages
+ appendCodeMessages([res.userMessage] + [res.reply].compactMap { $0 }, threadId: threadId)
+ applyThreadUpdateInMemory(res.thread, isLocal: isLocal)
+ if res.reply == nil {
+ codeLiveRuns[threadId] = CodeLiveRun(threadId: threadId)
+ followCodeThread(threadId)
+ }
+ if let conflicts = res.conflicts, !conflicts.isEmpty {
+ showInfo("그 뒤에 다시 바뀐 파일 \(conflicts.count)개는 그대로 두었습니다.")
+ }
+ } catch {
+ showError("요청을 고치지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Puts back the files the turn behind a reply changed, or brings them back when the message is a revert's
+ /// note. The note the server leaves tells the agent on its next request.
+ public func revertCodeTurn(threadId: String, messageId: String) async {
+ let isLocal = isLocalCodeThread(threadId)
+ do {
+ let res = try await codeTransport(local: isLocal).revertCodeTurn(threadId: threadId, messageId: messageId)
+ appendCodeMessages([res.message], threadId: threadId)
+ if let conflicts = res.conflicts, !conflicts.isEmpty {
+ showInfo("그 뒤에 다시 바뀐 파일 \(conflicts.count)개는 그대로 두었습니다.")
+ }
+ } catch let SyncError.httpStatus(code, reason) where code == 409 && reason == "nothing_to_revert" {
+ showInfo("되돌릴 변경이 없습니다. 파일이 이미 그 상태이거나 그 뒤에 다시 바뀌었습니다.")
+ } catch let SyncError.httpStatus(code, reason) where code == 409 && reason == "thread_busy" {
+ showInfo("작업이 끝난 뒤에 되돌릴 수 있습니다.")
+ } catch {
+ showError("되돌리지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Routes all Morph Code requests directly to this Mac's local `morphcode` daemon.
+ func codeTransport(local: Bool = true) async throws -> MorphTransport {
+ if let bridge = await localBridgeTransport(startIfNeeded: true) {
+ return bridge
+ }
+ throw LocalBridgeUnavailable()
+ }
+
+ func macWorkspaceTransport(startIfNeeded: Bool) async -> MorphTransport? {
+ await localBridgeTransport(startIfNeeded: startIfNeeded)
+ }
+
+ /// Follows a running turn on its thread's stream until the turn ends.
+ func followCodeThread(_ threadId: String) {
+ guard codeStreamTasks[threadId] == nil else { return }
+ codeStreamTasks[threadId] = Task { [weak self] in
+ var retries = 0
+ while !Task.isCancelled, let self, self.codeLiveRuns[threadId] != nil {
+ if let transport = try? await self.codeTransport(local: true) {
+ for await event in transport.streamCodeThread(threadId: threadId) {
+ retries = 0
+ self.handleCodeStreamEvent(event, threadId: threadId)
+ }
+ }
+ retries += 1
+ try? await Task.sleep(for: .milliseconds(min(16_000, 250 << min(retries, 7))))
+ }
+ }
+ }
+
+ func handleCodeStreamEvent(_ event: CodeStreamEvent, threadId: String) {
+ guard let run = codeLiveRuns[threadId] else { return }
+ let isLocal = isLocalCodeThread(threadId)
+ switch event.type {
+ case "ready":
+ guard let thread = event.thread else { return }
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ if thread.status != "running" && thread.status != "awaiting_approval" {
+ // The turn ended while the stream was away; its reply is already stored.
+ endCodeRun(threadId)
+ Task {
+ await loadCodeMessages(threadId: threadId)
+ markCodeThreadReadIfViewing(threadId)
+ }
+ }
+ case "done", "error":
+ appendCodeMessages([event.message].compactMap { $0 }, threadId: threadId)
+ if let thread = event.thread {
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ let resolvedThread = event.thread ?? codeThreads.first(where: { $0.id == threadId })
+ let rawThreadTitle = resolvedThread?.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let threadTitle = (rawThreadTitle.isEmpty || rawThreadTitle == "새 작업") ? "Morph Code" : rawThreadTitle
+ let projectName = resolvedThread.flatMap { th in
+ codeProjects.first(where: { $0.id == th.projectId })?.name
+ }?.trimmingCharacters(in: .whitespacesAndNewlines)
+ if event.type == "error", let errMsg = event.error, !errMsg.isEmpty {
+ codeTurnErrorBanner = (threadId: threadId, message: errMsg)
+ showError(errMsg)
+ let subtitle = [projectName, "작업 실패"].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
+ let cleanError = MorphNotificationText.excerpt(errMsg, limit: 160)
+ emitCodeNotificationIfBackground(
+ kind: .turnFailed,
+ threadId: threadId,
+ title: threadTitle,
+ subtitle: subtitle,
+ body: cleanError.isEmpty ? "오류가 발생해 작업이 중단되었습니다." : cleanError
+ )
+ } else {
+ if codeTurnErrorBanner?.threadId == threadId {
+ codeTurnErrorBanner = nil
+ }
+ let subtitle = [projectName, "작업 완료"].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
+ let cleanSummary = MorphNotificationText.excerpt(event.message?.content ?? "", limit: 160)
+ emitCodeNotificationIfBackground(
+ kind: .turnCompleted,
+ threadId: threadId,
+ title: threadTitle,
+ subtitle: subtitle,
+ body: cleanSummary.isEmpty ? "응답이 도착했습니다." : cleanSummary
+ )
+ }
+ endCodeRun(threadId)
+ if event.thread?.status == "running" {
+ // The thread's next queued request started as this turn ended; its request is stored already.
+ codeLiveRuns[threadId] = CodeLiveRun(threadId: threadId)
+ followCodeThread(threadId)
+ Task { await loadCodeMessages(threadId: threadId) }
+ } else if event.message == nil {
+ // `applyThreadUpdateInMemory` already updated `updatedAt`, so `refreshCodeStateQuietly` would skip
+ // reloading if the `done`/`error` event omitted the inline message. Fetch explicitly so the final
+ // reply never stays missing on screen.
+ Task { [weak self] in
+ await self?.loadCodeMessages(threadId: threadId)
+ self?.markCodeThreadReadIfViewing(threadId)
+ }
+ }
+ let readTask = markCodeThreadReadTaskIfViewing(threadId)
+ // Files the turn produced show up in the inspector (and refresh Git diff if open).
+ // Await the mark-read PATCH first so the refreshed snapshot never reverts `unreadCount` back to 1.
+ Task {
+ await readTask?.value
+ await refreshCodeStateQuietly()
+ if isCodeInspectorPresented, let pid = selectedCodeThread?.projectId {
+ await refreshCodeGitStatus(projectId: pid, threadId: selectedCodeThreadId)
+ }
+ }
+ case "token_usage":
+ if let usage = event.usage, var thread = codeThreads.first(where: { $0.id == threadId }) {
+ thread.usage = usage
+ applyMinorThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ case "auto_compacted", "compacted":
+ appendCodeMessages([event.message].compactMap { $0 }, threadId: threadId)
+ if let thread = event.thread {
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ } else if let usage = event.usage, var thread = codeThreads.first(where: { $0.id == threadId }) {
+ thread.usage = usage
+ applyMinorThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ case "title":
+ if let thread = event.thread {
+ applyMinorThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ case "queue":
+ // A queue change persists so a reload keeps the latest queue.
+ if let thread = event.thread {
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ }
+ case "gone":
+ removeDeletedCodeThread(threadId, isLocal: isLocal)
+ showInfo("다른 기기에서 스레드를 삭제했습니다.")
+ default:
+ run.apply(event)
+ if event.type == "approval_required", let apr = event.approval {
+ let thread = codeThreads.first(where: { $0.id == threadId })
+ let rawTitle = thread?.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let threadTitle = (rawTitle.isEmpty || rawTitle == "새 작업") ? "Morph Code" : rawTitle
+ let projectName = thread.flatMap { th in codeProjects.first(where: { $0.id == th.projectId })?.name }
+ let subtitle = [projectName, threadTitle].compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }.joined(separator: " · ")
+ let primary = MorphNotificationText.cleanInline(apr.title, limit: 80)
+ let detail = MorphNotificationText.excerpt(apr.summary ?? "", limit: 120)
+ let bodyText: String
+ if !primary.isEmpty && !detail.isEmpty && primary.lowercased() != detail.lowercased() {
+ bodyText = "\(primary)\n\(detail)"
+ } else {
+ bodyText = primary.isEmpty ? (detail.isEmpty ? "에이전트가 실행 승인을 기다립니다." : detail) : primary
+ }
+ emitCodeNotificationIfBackground(
+ kind: .approvalRequired,
+ threadId: threadId,
+ title: "승인 필요",
+ subtitle: subtitle,
+ body: bodyText
+ )
+ } else if event.type == "question_required", let q = event.question {
+ let thread = codeThreads.first(where: { $0.id == threadId })
+ let rawTitle = thread?.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let threadTitle = (rawTitle.isEmpty || rawTitle == "새 작업") ? "Morph Code" : rawTitle
+ let projectName = thread.flatMap { th in codeProjects.first(where: { $0.id == th.projectId })?.name }
+ let subtitle = [projectName, threadTitle].compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }.joined(separator: " · ")
+ let primary = MorphNotificationText.cleanInline(q.title ?? "", limit: 80)
+ let detail = MorphNotificationText.excerpt(q.message ?? "", limit: 120)
+ let bodyText: String
+ if !primary.isEmpty && !detail.isEmpty && primary.lowercased() != detail.lowercased() {
+ bodyText = "\(primary)\n\(detail)"
+ } else {
+ bodyText = primary.isEmpty ? (detail.isEmpty ? "에이전트가 응답을 기다립니다." : detail) : primary
+ }
+ emitCodeNotificationIfBackground(
+ kind: .questionRequired,
+ threadId: threadId,
+ title: "답변 필요",
+ subtitle: subtitle,
+ body: bodyText
+ )
+ }
+ }
+ }
+
+ /// Stops following a thread's turn here. The turn itself keeps running in the local daemon unless cancelled.
+ func endCodeRun(_ threadId: String) {
+ codeLiveRuns[threadId] = nil
+ codeStreamTasks.removeValue(forKey: threadId)?.cancel()
+ }
+
+ /// Follows every running turn reported by the local daemon that this window is not already streaming.
+ func attachRunningCodeThreads() {
+ for thread in codeThreads where codeLiveRuns[thread.id] == nil && thread.status == "running" {
+ codeLiveRuns[thread.id] = CodeLiveRun(threadId: thread.id, startedAt: MorphPalette.parseDate(thread.updatedAt) ?? Date())
+ followCodeThread(thread.id)
+ }
+ }
+
+ /// Reconciles stale `codeLiveRuns` against refreshed `thread.status`.
+ func reconcileStaleCodeLiveRuns() {
+ for tid in Array(codeLiveRuns.keys) {
+ guard let thread = codeThreads.first(where: { $0.id == tid }) else { continue }
+ if thread.status != "running" && thread.status != "awaiting_approval", codeLiveRuns[tid]?.pendingPrompt == nil {
+ endCodeRun(tid)
+ Task { [weak self] in
+ await self?.loadCodeMessages(threadId: tid)
+ self?.markCodeThreadReadIfViewing(tid)
+ }
+ }
+ }
+ }
+
+ /// Subscribes to the local daemon's `/v1/code/events` SSE feed so workspace updates, scheduled runs,
+ /// approvals, and CLI changes reflect automatically without manual refresh.
+ func startLocalBridgeObserver() {
+ guard localBridgeTask == nil else { return }
+ localBridgeTask = Task { [weak self] in
+ var coalesceTask: Task?
+ defer { coalesceTask?.cancel() }
+ while !Task.isCancelled, let self {
+ if let transport = await self.localBridgeTransport(startIfNeeded: false) {
+ do {
+ for try await rawEvent in transport.streamCodeEvents() {
+ if Task.isCancelled { break }
+ let trimmed = rawEvent.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lower = trimmed.lowercased()
+ guard !trimmed.isEmpty,
+ lower != "ping",
+ lower != "keepalive",
+ lower != "ready",
+ !(trimmed.hasPrefix("{\"ok\":true") && trimmed.count < 32)
+ else { continue }
+ coalesceTask?.cancel()
+ coalesceTask = Task { [weak self] in
+ try? await Task.sleep(for: .milliseconds(250))
+ guard !Task.isCancelled, let self else { return }
+ await self.refreshCodeStateQuietly()
+ }
+ }
+ } catch {
+ // Stream closed or daemon restarted; retry below.
+ }
+ }
+ try? await Task.sleep(for: .seconds(3))
+ }
+ self?.localBridgeTask = nil
+ }
+ }
+
+ /// Adds messages the server stored to a thread's conversation, once each, and keeps the cache in step.
+ func appendCodeMessages(_ messages: [CodeMessage], threadId: String) {
+ var current = codeMessagesByThread[threadId] ?? []
+ for message in messages where !current.contains(where: { $0.id == message.id }) {
+ current.append(message)
+ }
+ codeMessagesByThread[threadId] = current
+ store.cacheCodeMessagesAsync(current, threadId: threadId)
+ if let thread = codeThreads.first(where: { $0.id == threadId }) {
+ store.indexCodeMessagesAsync(threadId: threadId, projectId: thread.projectId, threadTitle: thread.title, messages: current)
+ }
+ }
+
+ /// Clears a thread's unread mark when the member is looking at it: the selected thread on screen (or an open
+ /// secondary thread window when `allowBoundWindow` is true), with the app in front, unless the member just
+ /// marked it unread.
+ public func markCodeThreadReadIfViewing(_ threadId: String, allowBoundWindow: Bool = false) {
+ _ = markCodeThreadReadTaskIfViewing(threadId, allowBoundWindow: allowBoundWindow)
+ }
+
+ @discardableResult
+ func markCodeThreadReadTaskIfViewing(_ threadId: String, allowBoundWindow: Bool = false) -> Task? {
+ let visible = allowBoundWindow || (isCodeThreadOnScreen && selectedCodeThread?.id == threadId)
+ guard visible, isAppActive, keptUnreadThreadId != threadId,
+ var thread = codeThreads.first(where: { $0.id == threadId }), thread.unreadCount > 0 else { return nil }
+ let isLocal = isLocalCodeThread(threadId)
+ pendingReadThreadIds.insert(threadId)
+ thread.unreadCount = 0
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ return Task { [weak self] in
+ defer { self?.pendingReadThreadIds.remove(threadId) }
+ guard let self else { return }
+ try? await self.codeTransport(local: isLocal).markCodeThreadRead(threadId: threadId)
+ }
+ }
+
+ var isAppActive: Bool {
+ #if os(macOS)
+ NSApp.isActive
+ #else
+ UIApplication.shared.applicationState == .active
+ #endif
+ }
+
+ #if os(macOS)
+ /// Keeps the Dock icon's badge on the number of threads that want the member, with the window open or not.
+ public func showCodeAttentionInDock() {
+ guard !isShowingCodeAttentionInDock else { return }
+ isShowingCodeAttentionInDock = true
+ updateCodeAttentionBadge()
+ }
+
+ func updateCodeAttentionBadge() {
+ withObservationTracking {
+ let count = codeAttentionCount
+ NSApp.dockTile.badgeLabel = count > 0 ? "\(count)" : nil
+ } onChange: {
+ Task { @MainActor [weak self] in
+ self?.updateCodeAttentionBadge()
+ }
+ }
+ }
+ #endif
+
+ /// Asks the thread's server to stop the turn. Marks the run cancelling on frame 1 so the UI responds
+ /// immediately while the server cancels the provider session and emits the final stopped message.
+ public func cancelCodeTurn(threadId: String? = nil) async {
+ let resolvedId = threadId ?? selectedCodeThread?.id ?? ""
+ if resolvedId.isEmpty {
+ pendingDraftCodeRun?.isCancelling = true
+ return
+ }
+ let tid = resolvedId
+ if let run = codeLiveRuns[tid] {
+ if run.isCancelling { return }
+ run.isCancelling = true
+ }
+ do {
+ try await codeTransport(local: isLocalCodeThread(tid)).cancelCodeThread(threadId: tid)
+ // Safety net: if the SSE stream disconnected mid-cancel and didn't deliver `done`, sync cleanly.
+ Task { [weak self] in
+ try? await Task.sleep(for: .seconds(2.5))
+ guard let self, self.codeLiveRuns[tid]?.isCancelling == true else { return }
+ await self.refreshCodeStateQuietly()
+ await self.loadCodeMessages(threadId: tid)
+ if let th = self.codeThreads.first(where: { $0.id == tid }), th.status != "running" {
+ self.endCodeRun(tid)
+ }
+ }
+ } catch {
+ codeLiveRuns[tid]?.isCancelling = false
+ showError("작업을 중지하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ #if os(macOS)
+ /// Ensures the local `morphcode bridge` daemon is running.
+ func ensureLocalBridgeReady(startIfNeeded: Bool = true) async -> URL? {
+ let listen = MacBridgeAgent.activeListenAddress
+ let baseURL = URL(string: "http://\(listen)")!
+ if startIfNeeded, !hasSyncedBundledBridgeThisLaunch, !MacBridgeAgent.hasCustomRuntimeOverride {
+ hasSyncedBundledBridgeThisLaunch = true
+ let upgraded = await Self.syncBundledBridgeIfNeeded(baseURL: baseURL)
+ if upgraded {
+ lastLocalBridgeVerifiedAt = nil
+ localBridgeHealth = nil
+ }
+ }
+ if localBridgeOnline, let verifiedAt = lastLocalBridgeVerifiedAt, Date().timeIntervalSince(verifiedAt) < 5 {
+ return baseURL
+ }
+ var health = URLRequest(url: baseURL.appendingPathComponent("health"))
+ health.timeoutInterval = 1.5
+ if await Self.bridgeAnswers(health) {
+ assignIfChanged(\.localBridgeOnline, true)
+ lastLocalBridgeVerifiedAt = Date()
+ return baseURL
+ }
+ lastLocalBridgeVerifiedAt = nil
+ guard startIfNeeded else {
+ localBridgeOnline = false
+ return nil
+ }
+ let start = localBridgeStart ?? Task { await Self.startLocalBridge(health: health) }
+ localBridgeStart = start
+ let started = await start.value
+ if localBridgeStart == start {
+ localBridgeStart = nil
+ }
+ localBridgeOnline = started
+ return started ? baseURL : nil
+ }
+
+ /// Starts this Mac's bridge and waits up to 4 s for it to answer. The bridge runs as a launchd agent, so it and
+ /// the turns it runs keep going after the app quits, and launchd starts it again at login or if it stops. The
+ /// app installs the agent where it is missing. A bridge this app ran beside the agent's would hold the port while
+ /// launchd's own fails to listen every 10 s, and would keep running an old binary after the agent's is replaced.
+ /// A Mac where the agent cannot be loaded runs the bridge as this app's process.
+ static func startLocalBridge(health: URLRequest) async -> Bool {
+ let home = FileManager.default.homeDirectoryForCurrentUser
+ let process = Process()
+ let useDirectProcess = MacBridgeAgent.hasCustomRuntimeOverride
+ || !MacBridgeAgent.isStableBundleLocation(Bundle.main.bundleURL, home: home)
+ if !useDirectProcess, await installBridgeAgent(home: home) {
+ process.executableURL = URL(fileURLWithPath: "/bin/launchctl")
+ process.arguments = ["kickstart", "gui/\(getuid())/\(MacBridgeAgent.label)"]
+ } else {
+ let bundled = MacBridgeAgent.bundledBinaryPath(bundleURL: Bundle.main.bundleURL)
+ let binPath = FileManager.default.isExecutableFile(atPath: bundled)
+ ? bundled
+ : bridgeBinary(home: home)
+ guard let binPath else {
+ return false
+ }
+ let dataDir = MacBridgeAgent.activeDataDir(home: home).path
+ process.executableURL = URL(fileURLWithPath: binPath)
+ process.arguments = ["bridge", "--listen", MacBridgeAgent.activeListenAddress, "--data-dir", dataDir]
+ }
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try? process.run()
+ // A bridge that just started answers in well under a second. One that hangs never does, so each check gives
+ // up quickly and the wait has a fixed end.
+ var poll = health
+ poll.timeoutInterval = 0.5
+ let deadline = Date().addingTimeInterval(4)
+ while !Task.isCancelled, Date() < deadline {
+ try? await Task.sleep(for: .milliseconds(200))
+ guard !Task.isCancelled else { return false }
+ if await bridgeAnswers(poll) {
+ return true
+ }
+ }
+ return false
+ }
+
+ /// The bundled `morphcode` helper inside an installed `Morph.app`, when present and executable.
+ private static func stableBundledBridgeBinary(home: URL) -> String? {
+ let bundleURL = Bundle.main.bundleURL
+ guard MacBridgeAgent.isStableBundleLocation(bundleURL, home: home) else { return nil }
+ let bundled = MacBridgeAgent.bundledBinaryPath(bundleURL: bundleURL)
+ return FileManager.default.isExecutableFile(atPath: bundled) ? bundled : nil
+ }
+
+ /// The morphcode command on this Mac, preferring the bundled helper inside an installed `Morph.app`.
+ private static func bridgeBinary(home: URL) -> String? {
+ MacBridgeAgent.binaryCandidates(home: home, bundleURL: Bundle.main.bundleURL)
+ .first { FileManager.default.isExecutableFile(atPath: $0) }
+ }
+
+ /// Upgrades and gracefully restarts the launchd bridge when this installed `Morph.app` contains a newer
+ /// bundled `morphcode` binary after an app update. Returns true if restarted.
+ private static func syncBundledBridgeIfNeeded(baseURL: URL) async -> Bool {
+ let home = FileManager.default.homeDirectoryForCurrentUser
+ guard let bundled = stableBundledBridgeBinary(home: home) else { return false }
+
+ let plist = MacBridgeAgent.plistURL(home: home)
+ let existingProgram = (try? Data(contentsOf: plist)).flatMap { MacBridgeAgent.installedProgram(plist: $0) }
+ let currentStamp = MacBridgeAgent.binaryStamp(atPath: bundled)
+ let stampURL = MacBridgeAgent.bundledStampURL(home: home)
+ let storedStamp = (try? String(contentsOf: stampURL, encoding: .utf8))?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+
+ guard MacBridgeAgent.shouldUpgradeBundledBridge(
+ existingProgram: existingProgram,
+ bundledBinary: bundled,
+ currentStamp: currentStamp,
+ storedStamp: storedStamp
+ ) else {
+ return false
+ }
+
+ let domain = "gui/\(getuid())"
+ let path = MacBridgeAgent.searchPath(shellPath: await loginShellPath(), binaryPath: bundled, home: home)
+ do {
+ let data = try MacBridgeAgent.plistData(binaryPath: bundled, path: path, home: home)
+ try FileManager.default.createDirectory(at: plist.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: MacBridgeAgent.activeDataDir(home: home), withIntermediateDirectories: true)
+ try data.write(to: plist, options: .atomic)
+ } catch {
+ return false
+ }
+
+ // Gracefully reload the launchd agent (`bootout` sends SIGTERM so morphcode pauses active turns and resumes
+ // them cleanly once the new binary starts).
+ _ = await runTool("/bin/launchctl", ["bootout", "\(domain)/\(MacBridgeAgent.label)"])
+ try? await Task.sleep(for: .milliseconds(300))
+ let bootstrapped = await runTool("/bin/launchctl", ["bootstrap", domain, plist.path]) == 0
+ if !bootstrapped {
+ _ = await runTool("/bin/launchctl", ["kickstart", "-k", "\(domain)/\(MacBridgeAgent.label)"])
+ } else {
+ _ = await runTool("/bin/launchctl", ["kickstart", "\(domain)/\(MacBridgeAgent.label)"])
+ }
+
+ var poll = URLRequest(url: baseURL.appendingPathComponent("health"))
+ poll.timeoutInterval = 0.5
+ let deadline = Date().addingTimeInterval(5)
+ while !Task.isCancelled, Date() < deadline {
+ if await bridgeAnswers(poll) {
+ if let currentStamp {
+ try? (currentStamp + "\n").write(to: stampURL, atomically: true, encoding: .utf8)
+ }
+ return true
+ }
+ try? await Task.sleep(for: .milliseconds(200))
+ }
+ return false
+ }
+
+ /// Makes sure the bridge's launchd agent is installed and loaded, and reports whether it is. An agent already
+ /// there is kept as it is, unless the program it runs is gone or an installed `Morph.app` bundles a newer helper.
+ private static func installBridgeAgent(home: URL) async -> Bool {
+ let plist = MacBridgeAgent.plistURL(home: home)
+ let domain = "gui/\(getuid())"
+ let bundled = stableBundledBridgeBinary(home: home)
+ if let existing = try? Data(contentsOf: plist) {
+ let program = MacBridgeAgent.installedProgram(plist: existing)
+ let keepExisting = program.map { existingPath in
+ FileManager.default.isExecutableFile(atPath: existingPath)
+ && (bundled == nil || existingPath == bundled)
+ } ?? (bundled == nil)
+ if keepExisting {
+ // launchd loads the agent at login; one installed since needs loading. A loaded one refuses, which is fine.
+ _ = await runTool("/bin/launchctl", ["bootstrap", domain, plist.path])
+ return true
+ }
+ guard bridgeBinary(home: home) != nil else { return true }
+ _ = await runTool("/bin/launchctl", ["bootout", "\(domain)/\(MacBridgeAgent.label)"])
+ }
+ guard let binPath = bridgeBinary(home: home) else { return false }
+ let path = MacBridgeAgent.searchPath(shellPath: await loginShellPath(), binaryPath: binPath, home: home)
+ do {
+ let data = try MacBridgeAgent.plistData(binaryPath: binPath, path: path, home: home)
+ try FileManager.default.createDirectory(at: plist.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: MacBridgeAgent.activeDataDir(home: home), withIntermediateDirectories: true)
+ try data.write(to: plist, options: .atomic)
+ } catch {
+ return false
+ }
+ if await runTool("/bin/launchctl", ["bootstrap", domain, plist.path]) == 0 {
+ if let bundled, binPath == bundled, let stamp = MacBridgeAgent.binaryStamp(atPath: bundled) {
+ try? (stamp + "\n").write(to: MacBridgeAgent.bundledStampURL(home: home), atomically: true, encoding: .utf8)
+ }
+ return true
+ }
+ if await runTool("/bin/launchctl", ["print", "\(domain)/\(MacBridgeAgent.label)"]) == 0 {
+ return true
+ }
+ // launchd would not take the agent; this app runs the bridge itself, as before there was one.
+ try? FileManager.default.removeItem(at: plist)
+ return false
+ }
+
+ /// The PATH the member's terminal has, read from their login shell, or nil when it does not answer in 3 s.
+ private static func loginShellPath() async -> String? {
+ let shell = ProcessInfo.processInfo.environment["SHELL"].flatMap { $0.isEmpty ? nil : $0 } ?? "/bin/zsh"
+ return await Task.detached { () -> String? in
+ let output = Pipe()
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: shell)
+ process.arguments = ["-ilc", "printf '\\n__MORPH_PATH__%s' \"$PATH\""]
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = output
+ process.standardError = FileHandle.nullDevice
+ guard (try? process.run()) != nil else { return nil }
+ let deadline = Date().addingTimeInterval(3)
+ while process.isRunning, Date() < deadline {
+ usleep(50_000)
+ }
+ if process.isRunning {
+ process.terminate()
+ return nil
+ }
+ let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ guard let range = text.range(of: "__MORPH_PATH__", options: .backwards) else { return nil }
+ let path = text[range.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines)
+ return path.isEmpty ? nil : path
+ }.value
+ }
+
+ /// Runs a command line tool to its end and returns its exit status, or -1 when it does not start.
+ private static func runTool(_ path: String, _ arguments: [String]) async -> Int32 {
+ await Task.detached {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: path)
+ process.arguments = arguments
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ guard (try? process.run()) != nil else { return -1 }
+ process.waitUntilExit()
+ return process.terminationStatus
+ }.value
+ }
+
+ static func bridgeAnswers(_ health: URLRequest) async -> Bool {
+ guard let (_, response) = try? await localBridgeHealthSession.data(for: health) else { return false }
+ return (response as? HTTPURLResponse).map { (200..<300).contains($0.statusCode) } ?? false
+ }
+
+ func localBridgeTransport(startIfNeeded: Bool) async -> URLSessionMorphTransport? {
+ guard let base = await ensureLocalBridgeReady(startIfNeeded: startIfNeeded) else { return nil }
+ return URLSessionMorphTransport(
+ baseURL: base,
+ token: Self.localBridgeToken(),
+ memberId: memberId,
+ session: Self.codeRPCSession,
+ streamSession: Self.codeStreamSession
+ )
+ }
+
+ /// The token the bridge keeps in its data folder, readable by this Mac user only. A bridge from before
+ /// tokens keeps none and takes requests without one.
+ static func localBridgeToken() -> String? {
+ let dataDir = MacBridgeAgent.activeDataDir(home: FileManager.default.homeDirectoryForCurrentUser)
+ let saved = try? String(contentsOf: dataDir.appendingPathComponent("bridge-token"), encoding: .utf8)
+ let token = saved?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return token.isEmpty ? nil : token
+ }
+
+ /// Fetches `/v1/code/state` directly from this Mac's local daemon (`127.0.0.1:4411`).
+ func fetchThisMacBridgeStateIfAvailable() async -> MorphCodeStateSnapshot? {
+ guard let transport = await localBridgeTransport(startIfNeeded: true) else { return nil }
+ do {
+ return try await transport.fetchCodeState()
+ } catch SyncError.httpStatus(401, _) {
+ showError("The local morphcode daemon rejected the connection. Restart the daemon in Settings.")
+ return nil
+ } catch {
+ return nil
+ }
+ }
+
+ func fetchLocalCodeStateIfAvailable() async -> MorphCodeStateSnapshot? {
+ await fetchThisMacBridgeStateIfAvailable()
+ }
+
+ static func systemMacDeviceName() -> String {
+ let raw = (SCDynamicStoreCopyComputerName(nil, nil) as String?) ?? ""
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? "Local Mac" : trimmed
+ }
+ #endif
+}
diff --git a/apple/Apps/Shared/MorphAppState+CodeWorkspace.swift b/apple/Apps/Shared/MorphAppState+CodeWorkspace.swift
new file mode 100644
index 000000000..cf0089740
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+CodeWorkspace.swift
@@ -0,0 +1,1354 @@
+import Foundation
+import Observation
+import os
+import MorphCore
+#if os(macOS)
+import AppKit
+import SystemConfiguration
+#else
+import UIKit
+#endif
+
+extension MorphAppState {
+ // MARK: - Morph Code Workspace & Team Login
+
+ /// Stores a value only when it differs. The `@Observable` macro of Swift 6.1, which builds the shipped app,
+ /// redraws every view that read a property on each assignment, an equal value included.
+ func assignIfChanged(_ keyPath: ReferenceWritableKeyPath, _ value: Value) {
+ if self[keyPath: keyPath] != value {
+ self[keyPath: keyPath] = value
+ }
+ }
+
+ /// Recomputes merged/sorted Morph Code projections once per snapshot update so SwiftUI rows read O(1) arrays & sets.
+ /// Each projection is stored only when it changed, so a snapshot that differs in a thread's usage alone redraws the
+ /// context meter and nothing else.
+ func rebuildCodeCaches() {
+ let localProjects = localCodeState?.projects ?? []
+ let localThreads = localCodeState?.threads ?? []
+ let localSchedules = localCodeState?.schedules ?? []
+
+ assignIfChanged(\.localProjectIds, Set(localProjects.map(\.id)))
+ assignIfChanged(\.localThreadIds, Set(localThreads.map(\.id)))
+ assignIfChanged(\.localScheduleIds, Set(localSchedules.map(\.id)))
+ assignIfChanged(\.localCodeDaemonVersion, localCodeState?.daemonVersion)
+
+ assignIfChanged(\.codeProjects, localProjects)
+
+ var seenThreads = Set(minimumCapacity: localThreads.count)
+ var mergedThreads: [CodeThread] = []
+ var usageByThread: [String: CodeTokenUsage] = [:]
+ mergedThreads.reserveCapacity(localThreads.count)
+ for var t in localThreads where seenThreads.insert(t.id).inserted {
+ if pendingReadThreadIds.contains(t.id) && t.unreadCount > 0 { t.unreadCount = 0 }
+ usageByThread[t.id] = t.usage
+ t.usage = nil
+ mergedThreads.append(t)
+ }
+ mergedThreads.sort(by: CodeThread.newestFirst)
+ assignIfChanged(\.codeThreads, mergedThreads)
+ assignIfChanged(\.codeThreadUsage, usageByThread)
+
+ let now = Date()
+ let hiddenProjectIds = Set(localProjects.lazy.filter(\.isConversations).map(\.id))
+ let visible = hiddenProjectIds.isEmpty
+ ? mergedThreads
+ : mergedThreads.filter { !hiddenProjectIds.contains($0.projectId) }
+ assignIfChanged(\.visibleCodeThreads, visible)
+ assignIfChanged(\.listedCodeThreads, visible.filter { !$0.isEffectivelyArchived })
+ assignIfChanged(\.archivedCodeThreads, visible
+ .filter(\.isEffectivelyArchived)
+ .sorted { ($0.archiveTimestamp ?? $0.updatedAt) > ($1.archiveTimestamp ?? $1.updatedAt) })
+ assignIfChanged(\.snoozedCodeThreads, listedCodeThreads
+ .filter { $0.isSnoozed(now: now) }
+ .sorted { ($0.snoozedUntil ?? "") < ($1.snoozedUntil ?? "") })
+
+ var seenApprovals = Set()
+ var mergedApprovals: [CodeApproval] = []
+ var byThread: [String: [CodeApproval]] = [:]
+ var pendingByThread: [String: Int] = [:]
+ for a in (localCodeState?.approvals ?? []) where seenApprovals.insert(a.id).inserted {
+ mergedApprovals.append(a)
+ byThread[a.threadId, default: []].append(a)
+ if a.status == "pending" { pendingByThread[a.threadId, default: 0] += 1 }
+ }
+ assignIfChanged(\.codeApprovals, mergedApprovals)
+ assignIfChanged(\.codeApprovalsByThread, byThread)
+ assignIfChanged(\.pendingCodeApprovalCountByThread, pendingByThread)
+
+ var seenQuestions = Set()
+ var questionsByThread: [String: [CodeUserQuestion]] = [:]
+ for q in (localCodeState?.questions ?? []) where q.status == "pending" && seenQuestions.insert(q.id).inserted {
+ questionsByThread[q.threadId, default: []].append(q)
+ }
+ assignIfChanged(\.pendingCodeQuestionsByThread, questionsByThread)
+
+ if let stickyId = stickyTriageThreadId {
+ let stillValid = selectedCodeThreadId == stickyId
+ && codeLiveRuns[stickyId] == nil
+ && listedCodeThreads.contains(where: { $0.id == stickyId && $0.isActiveForTriage(now: now) && $0.status != "running" })
+ if !stillValid {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ }
+ scheduleNextSnoozeWakeup(now: now)
+
+ assignIfChanged(\.codeArtifacts, localCodeState?.artifacts ?? [])
+ assignIfChanged(\.codeAccounts, localCodeState?.accounts ?? [])
+
+ var mergedSchedules = localSchedules
+ mergedSchedules.sort { a, b in
+ if a.enabled != b.enabled { return a.enabled }
+ return (a.nextRunAt ?? a.createdAt) < (b.nextRunAt ?? b.createdAt)
+ }
+ assignIfChanged(\.codeSchedules, mergedSchedules)
+
+ let localModels = localCodeState?.availableModels ?? []
+ assignIfChanged(\.cachedLocalCodeModels, Self.mergedCodeModels(primary: localModels, secondary: []))
+ }
+
+ private static func mergedCodeModels(primary: [CodeModelOption], secondary: [CodeModelOption]) -> [CodeModelOption] {
+ let dynamic = !primary.isEmpty ? primary : secondary
+ guard !dynamic.isEmpty else { return CodeModelOption.catalog }
+ var seen = Set(minimumCapacity: dynamic.count + CodeModelOption.catalog.count)
+ var result: [CodeModelOption] = []
+ result.reserveCapacity(dynamic.count + CodeModelOption.catalog.count)
+ for topId in ["auto", "orchestrator"] {
+ if let topOpt = dynamic.first(where: { $0.id == topId })
+ ?? CodeModelOption.catalog.first(where: { $0.id == topId }) {
+ if seen.insert(topOpt.id).inserted {
+ result.append(topOpt)
+ }
+ }
+ }
+ for m in dynamic where seen.insert(m.id).inserted {
+ result.append(m)
+ }
+ for m in CodeModelOption.catalog where seen.insert(m.id).inserted {
+ result.append(m)
+ }
+ return result
+ }
+
+ public func isLocalCodeProject(_ projectId: String) -> Bool {
+ true
+ }
+
+ public func isLocalCodeThread(_ threadId: String) -> Bool {
+ true
+ }
+
+ public func codeTarget(of thread: CodeThread) -> CodeExecutionTarget {
+ .local
+ }
+
+ public func isLocalCodeSchedule(_ id: String) -> Bool {
+ true
+ }
+
+ public var localDeviceDisplayName: String {
+ Self.systemMacDeviceName()
+ }
+
+ public func codeTargetLabel(_ target: CodeExecutionTarget) -> String {
+ localDeviceDisplayName
+ }
+
+ public func codeTargetShelfLabel(_ target: CodeExecutionTarget) -> String {
+ localDeviceDisplayName
+ }
+
+ public func codeNewThreadModeLabel(_ mode: CodeNewThreadMode) -> String {
+ switch mode {
+ case .local: return localDeviceDisplayName
+ case .worktree: return mode.label
+ }
+ }
+
+ /// Structured header display model for Morph Code: separates the project/branch prefix from the execution target
+ /// so UI headers can place a small target icon inline before the Mac name / `Cloud` instead of beside the title.
+ public struct CodeHeaderInfo: Equatable, Sendable {
+ public let systemImage: String
+ public let isTargetIcon: Bool
+ public let title: String
+ public let contextPrefix: String
+ public let targetLabel: String
+
+ public var context: String {
+ [contextPrefix, targetLabel].filter { !$0.isEmpty }.joined(separator: " · ")
+ }
+ }
+
+ /// Morph Code's header: the open thread with its project and where it runs, or 예약됨.
+ public var codeHeader: CodeHeaderInfo {
+ switch codeDestination {
+ case .scheduled:
+ guard let task = selectedCodeSchedule else {
+ return CodeHeaderInfo(
+ systemImage: "clock",
+ isTargetIcon: false,
+ title: "Scheduled",
+ contextPrefix: "",
+ targetLabel: ""
+ )
+ }
+ return CodeHeaderInfo(
+ systemImage: "clock",
+ isTargetIcon: false,
+ title: task.title,
+ contextPrefix: CodeScheduleCadence.label(for: task.rrule, timezone: task.timezone),
+ targetLabel: ""
+ )
+ case .threads:
+ if let draft = codeNewThreadDraft {
+ let project = draft.projectId.flatMap { id in codeProjects.first { $0.id == id } }
+ return CodeHeaderInfo(
+ systemImage: draft.mode.systemImage,
+ isTargetIcon: true,
+ title: "New Thread",
+ contextPrefix: project?.name ?? "",
+ targetLabel: project != nil ? codeNewThreadModeLabel(draft.mode) : ""
+ )
+ }
+ let thread = selectedCodeThread
+ let project = codeProjects.first { $0.id == thread?.projectId }
+ let target = thread.map { codeTarget(of: $0) }
+ let prefix = [project?.name, thread?.branch]
+ .compactMap { $0 }
+ .filter { !$0.isEmpty }
+ .joined(separator: " · ")
+ return CodeHeaderInfo(
+ systemImage: target?.systemImage ?? "laptopcomputer",
+ isTargetIcon: target != nil,
+ title: thread?.title ?? "Morph Code",
+ contextPrefix: prefix,
+ targetLabel: target.map { codeTargetShelfLabel($0) } ?? ""
+ )
+ }
+ }
+
+ public var availableCodeModels: [CodeModelOption] {
+ cachedLocalCodeModels
+ }
+
+ /// Schedules a single lightweight wakeup at the earliest upcoming snooze expiry so expired threads reappear automatically.
+ private func scheduleNextSnoozeWakeup(now: Date) {
+ snoozeWakeupTask?.cancel()
+ snoozeWakeupTask = nil
+ let earliest = listedCodeThreads.compactMap { thread -> Date? in
+ guard let date = thread.snoozedUntilDate, date > now else { return nil }
+ return date
+ }.min()
+ guard let earliest else { return }
+ // Clamp to 12 hours max so very far future snoozes re-check cleanly without long sleep drift.
+ let delay = min(max(earliest.timeIntervalSince(now) + 0.5, 0.5), 43_200)
+ snoozeWakeupTask = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(delay))
+ guard !Task.isCancelled, let self else { return }
+ self.snoozeClockTick &+= 1
+ self.rebuildCodeCaches()
+ }
+ }
+
+ /// Runtime signals used to compute a thread's unified visual triage status.
+ public func codeThreadSignals(for thread: CodeThread) -> CodeThreadSignals {
+ let run = codeLiveRuns[thread.id]
+ let hasApproval = run?.approval != nil || (pendingCodeApprovalCountByThread[thread.id] ?? 0) > 0
+ let hasQuestion = run?.question != nil || !(pendingCodeQuestionsByThread[thread.id] ?? []).isEmpty
+ return CodeThreadSignals(
+ isRunning: run != nil,
+ hasPendingApproval: hasApproval,
+ hasPendingQuestion: hasQuestion,
+ hasBrowserHandoff: false
+ )
+ }
+
+ /// Single source of truth for a Morph Code thread's visual triage status across sidebar, folder headers, and badges.
+ public func codeVisualStatus(of thread: CodeThread) -> CodeThreadVisualStatus {
+ thread.visualStatus(signals: codeThreadSignals(for: thread))
+ }
+
+ /// Preferred initial thread before the member makes an explicit pick: active (not archived/settled, not snoozed,
+ /// not a scheduled run) with pinned threads first, then highest-priority triage thread, then falling back.
+ var defaultInitialCodeThread: CodeThread? {
+ let now = Date()
+ let nonScheduled = listedCodeThreads.filter { !isCodeScheduleRun($0) }
+ let active = nonScheduled.filter { $0.isActiveForTriage(now: now) }
+ if let pinned = active.first(where: { $0.pinned == true }) {
+ return pinned
+ }
+ return active.first ?? nonScheduled.first
+ }
+
+ public var selectedCodeThread: CodeThread? {
+ if let id = selectedCodeThreadId, let match = codeThreads.first(where: { $0.id == id }) {
+ return match
+ }
+ // The new-thread screen shows no thread.
+ guard codeNewThread == nil else { return nil }
+ // Before a pick, the newest active thread in the list that the member started. Scheduled runs wait in 예약됨.
+ return defaultInitialCodeThread
+ }
+
+ public var pendingCodeApprovalCount: Int {
+ codeApprovals.filter { $0.status == "pending" }.count
+ }
+
+ /// Active (non-archived, non-snoozed) threads that want the member: awaiting action, failed unread, or completed unread.
+ public var codeAttentionCount: Int {
+ _ = snoozeClockTick
+ let now = Date()
+ return listedCodeThreads.filter { thread in
+ thread.isActiveForTriage(now: now) && codeVisualStatus(of: thread).needsAttention
+ }.count
+ }
+
+ /// Highest-priority attention status across active Morph Code threads, for the `Code` tab dot in `MorphModeSwitcher`.
+ public var codeHighestAttentionStatus: CodeThreadVisualStatus? {
+ _ = snoozeClockTick
+ let now = Date()
+ var best: CodeThreadVisualStatus?
+ for thread in listedCodeThreads where thread.isActiveForTriage(now: now) {
+ let status = codeVisualStatus(of: thread)
+ guard status.needsAttention else { continue }
+ if let current = best {
+ if status < current { best = status }
+ } else {
+ best = status
+ }
+ }
+ return best
+ }
+
+ func applyThreadUpdateInMemory(_ updated: CodeThread, isLocal: Bool = true) {
+ var updated = updated
+ if updated.usage == nil {
+ updated.usage = codeThreadUsage[updated.id]
+ }
+ assignIfChanged(\.localCodeState, localCodeState?.replacingThread(updated))
+ }
+
+ func applyMinorThreadUpdateInMemory(_ updated: CodeThread, isLocal: Bool = true) {
+ suppressCodeStateDiskCache = true
+ defer { suppressCodeStateDiskCache = false }
+ applyThreadUpdateInMemory(updated, isLocal: true)
+ }
+
+ func refreshCodeStateQuietly() async {
+ await refreshLocalCodeStateOnly(hydrateSelected: false)
+ }
+
+ public func refreshCodeState() async {
+ await refreshLocalCodeStateOnly(hydrateSelected: true)
+ }
+
+ public var isSyncingRemoteCodeWorkspace: Bool {
+ false
+ }
+
+ public func codeThreadSyncSource(for threadId: String) -> CodeThreadSyncSource {
+ .localBridge
+ }
+
+ private func refreshLocalCodeStateOnly(hydrateSelected: Bool) async {
+ let previousShown = selectedCodeThread
+ localCodeWorkspaceSyncCount += 1
+ assignIfChanged(\.isSyncingLocalCodeWorkspace, true)
+ defer {
+ localCodeWorkspaceSyncCount = max(0, localCodeWorkspaceSyncCount - 1)
+ assignIfChanged(\.isSyncingLocalCodeWorkspace, localCodeWorkspaceSyncCount > 0)
+ }
+ if let localSnap = await fetchLocalCodeStateIfAvailable() {
+ assignIfChanged(\.localCodeState, localSnap)
+ assignIfChanged(\.localBridgeOnline, true)
+ syncCodeSearchAndApprovalRulesFromState()
+ reconcileStaleCodeLiveRuns()
+ attachRunningCodeThreads()
+ if hydrateSelected {
+ scheduleSelectedCodeThreadHydration(forLocalSource: true)
+ } else {
+ reloadSelectedCodeThreadIfChanged(previousShown: previousShown, in: localSnap)
+ }
+ }
+ }
+
+ /// Reloads the open thread when a freshly arrived snapshot updated it or its messages have not loaded yet.
+ private func reloadSelectedCodeThreadIfChanged(previousShown: CodeThread?, in snapshot: MorphCodeStateSnapshot) {
+ guard let shown = selectedCodeThread, codeLiveRuns[shown.id] == nil,
+ let current = snapshot.threads.first(where: { $0.id == shown.id }) else {
+ return
+ }
+ let needsLoad = CodeThreadSyncPresentation.shouldReloadOnSnapshot(
+ updatedAtChanged: current.updatedAt != previousShown?.updatedAt,
+ hasMessages: !(codeMessagesByThread[current.id]?.isEmpty ?? true),
+ hasSyncedOnce: codeSyncedMessageThreadIds.contains(current.id),
+ hasLoadError: codeMessageLoadErrorByThread[current.id] != nil,
+ isLoading: codeLoadingMessageThreadIds.contains(current.id)
+ )
+ guard needsLoad else { return }
+ Task {
+ await hydrateAndLoadCodeMessages(threadId: current.id)
+ markCodeThreadReadIfViewing(current.id)
+ }
+ }
+
+ /// Updates selection from the refreshed workspace immediately and hydrates the selected thread's messages
+ /// in the background only when this source owns it, so pull-to-refresh never stalls on a slow thread load
+ /// or fires duplicate fetches for the same thread.
+ private func scheduleSelectedCodeThreadHydration(forLocalSource isLocalSource: Bool) {
+ if codeNewThread == nil {
+ let currentMatch = selectedCodeThreadId.flatMap { id in codeThreads.first(where: { $0.id == id }) }
+ let preferred = defaultInitialCodeThread
+ var nextThreadId = selectedCodeThreadId
+ if currentMatch == nil {
+ nextThreadId = preferred?.id
+ } else if !didUserSelectCodeThread,
+ let currentMatch,
+ !currentMatch.isActiveForTriage(),
+ let preferred,
+ preferred.isActiveForTriage(),
+ preferred.id != currentMatch.id {
+ nextThreadId = preferred.id
+ }
+ if nextThreadId != selectedCodeThreadId {
+ saveCurrentCodeDraft()
+ selectedCodeThreadId = nextThreadId
+ restoreCurrentCodeDraft()
+ }
+ }
+ guard let current = selectedCodeThread, isLocalCodeThread(current.id) == isLocalSource else { return }
+ if codeLiveRuns[current.id] == nil {
+ adoptComposerSettings(of: current)
+ }
+ hydrateCachedCodeMessagesIfNeeded(threadId: current.id)
+ let threadId = current.id
+ Task { [weak self] in
+ guard let self else { return }
+ await self.loadCodeMessages(threadId: threadId)
+ self.markCodeThreadReadIfViewing(threadId)
+ }
+ }
+
+ /// Sets the composer to the model, place, permission mode and effort the thread last ran with.
+ func adoptComposerSettings(of thread: CodeThread) {
+ selectedCodeModel = thread.model
+ selectedCodeTarget = codeTarget(of: thread)
+ if let mode = thread.accessMode {
+ selectedCodeAccessMode = mode
+ }
+ if let effort = thread.reasoningEffort {
+ selectedCodeEffort = effort
+ }
+ }
+
+ /// Shows the member's Mac workspace that just arrived: what the Mac sent a phone, or this Mac's bridge after it
+ /// changed. Turns that started there are followed, and the open thread's conversation reloads when the Mac
+ /// changed it or when its messages have not loaded yet (for example right after a bridge restart).
+ func applyMacWorkspace(_ snapshot: MorphCodeStateSnapshot) {
+ let previousShown = selectedCodeThread
+ assignIfChanged(\.localCodeState, snapshot)
+ assignIfChanged(\.localBridgeOnline, true)
+ reconcileStaleCodeLiveRuns()
+ attachRunningCodeThreads()
+ reloadSelectedCodeThreadIfChanged(previousShown: previousShown, in: snapshot)
+ }
+
+ /// Synchronously prepares selection state and local-cache hydration before pushing/opening a thread view so
+ /// drafts are saved under the previous thread and cached messages render on frame 0 without a blank flash.
+ public func prepareSelectCodeThread(_ thread: CodeThread) {
+ if selectedCodeThreadId != thread.id || codeNewThread != nil {
+ saveCurrentCodeDraft()
+ }
+ codeDestination = .threads
+ codeNewThread = nil
+ pendingDraftCodeRun = nil
+ selectedCodeThreadId = thread.id
+ didUserSelectCodeThread = true
+ restoreCurrentCodeDraft()
+ hydrateCachedCodeMessagesIfNeeded(threadId: thread.id)
+ }
+
+ public func selectCodeThread(_ thread: CodeThread) async {
+ prepareSelectCodeThread(thread)
+ let latest = codeThreads.first(where: { $0.id == thread.id }) ?? thread
+ let priorStatus = codeVisualStatus(of: latest)
+ if priorStatus == .completedUnread || priorStatus == .failed {
+ stickyTriageThreadId = latest.id
+ stickyTriageStatus = priorStatus
+ } else if stickyTriageThreadId != latest.id {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ keptUnreadThreadId = nil
+ selectedCodeModel = thread.model
+ selectedCodeTarget = codeTarget(of: thread)
+ selectedCodeAccessMode = thread.accessMode ?? .defaultPermissions
+ selectedCodeEffort = thread.reasoningEffort ?? .medium
+ markCodeThreadReadIfViewing(thread.id)
+ await loadCodeMessages(threadId: thread.id)
+ }
+
+ private static let maxInMemoryCodeMessageThreads = 12
+
+ /// Records a thread as recently viewed and evicts cold inactive threads from RAM (they remain in SQLite WAL).
+ func touchCodeMessageCache(threadId: String) {
+ codeMessageAccessOrder.removeAll { $0 == threadId }
+ codeMessageAccessOrder.append(threadId)
+ guard codeMessagesByThread.count > Self.maxInMemoryCodeMessageThreads else { return }
+ var idx = 0
+ while codeMessagesByThread.count > Self.maxInMemoryCodeMessageThreads, idx < codeMessageAccessOrder.count {
+ let candidate = codeMessageAccessOrder[idx]
+ if candidate == threadId
+ || candidate == selectedCodeThreadId
+ || codeLiveRuns[candidate] != nil {
+ idx += 1
+ continue
+ }
+ codeMessagesByThread.removeValue(forKey: candidate)
+ codeSyncedMessageThreadIds.remove(candidate)
+ codeMessageAccessOrder.remove(at: idx)
+ }
+ }
+
+ /// Populates `codeMessagesByThread[threadId]` from the local SQLite cache if memory does not hold messages yet.
+ public func hydrateCachedCodeMessagesIfNeeded(threadId: String) {
+ if (codeMessagesByThread[threadId]?.isEmpty ?? true),
+ let cached = try? store.cachedCodeMessages(threadId: threadId),
+ !cached.isEmpty {
+ codeMessagesByThread[threadId] = cached
+ codeMessageLoadErrorByThread[threadId] = nil
+ }
+ if codeMessagesByThread[threadId] != nil {
+ touchCodeMessageCache(threadId: threadId)
+ }
+ }
+
+ /// Hydrates cached messages immediately and refreshes the latest page from the bridge or server.
+ public func hydrateAndLoadCodeMessages(threadId: String) async {
+ hydrateCachedCodeMessagesIfNeeded(threadId: threadId)
+ await loadCodeMessages(threadId: threadId)
+ }
+
+ public func loadCodeMessages(threadId: String) async {
+ hydrateCachedCodeMessagesIfNeeded(threadId: threadId)
+ codeMessageLoadTasks[threadId]?.cancel()
+ let seq = (codeMessageLoadSeq[threadId] ?? 0) + 1
+ codeMessageLoadSeq[threadId] = seq
+ codeLoadingMessageThreadIds.insert(threadId)
+ codeMessageLoadErrorByThread[threadId] = nil
+ let task = Task { [weak self] in
+ guard let self else { return }
+ defer {
+ if self.codeMessageLoadSeq[threadId] == seq {
+ self.codeLoadingMessageThreadIds.remove(threadId)
+ self.codeMessageLoadTasks[threadId] = nil
+ }
+ }
+ do {
+ let res = try await self.codeTransport(local: true)
+ .fetchCodeMessagesPage(threadId: threadId, before: nil, limit: 80)
+ guard !Task.isCancelled, seq >= (self.codeMessageAppliedSeq[threadId] ?? 0) else { return }
+ let merged = CodeMessagePagination.mergeLatestPage(
+ existing: self.codeMessagesByThread[threadId] ?? [],
+ existingHasMore: self.codeThreadHasMoreByThread[threadId],
+ latest: res.messages,
+ latestHasMore: res.hasMore ?? false,
+ latestTotalCount: res.totalCount
+ )
+ self.codeMessageAppliedSeq[threadId] = seq
+ self.codeMessagesByThread[threadId] = merged.messages
+ self.codeSyncedMessageThreadIds.insert(threadId)
+ self.touchCodeMessageCache(threadId: threadId)
+ self.codeMessageLoadErrorByThread[threadId] = nil
+ self.codeThreadHasMoreByThread[threadId] = merged.hasMore
+ self.codeThreadTotalCountByThread[threadId] = merged.totalCount
+ self.store.cacheCodeMessagesAsync(merged.messages, threadId: threadId)
+ self.store.indexCodeMessagesAsync(threadId: threadId, projectId: res.thread.projectId, threadTitle: res.thread.title, messages: merged.messages)
+ } catch is CancellationError {
+ // Superseded by a newer load for the same thread.
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ // Superseded by a newer load for the same thread.
+ } catch {
+ // Keep any cached conversation on screen; record the failure only when nothing is loaded yet.
+ if self.codeMessageLoadSeq[threadId] == seq, (self.codeMessagesByThread[threadId]?.isEmpty ?? true) {
+ self.codeMessageLoadErrorByThread[threadId] = error.localizedDescription
+ }
+ }
+ }
+ codeMessageLoadTasks[threadId] = task
+ await task.value
+ }
+
+ /// Adds a folder on the member's Mac as a project named after it, or finds the member's project for that folder,
+ /// and opens the new-thread screen in it. A phone or iPad adds it through the Mac it reaches.
+ public func addCodeProject(folder path: String) async {
+ do {
+ let transport = try await codeTransport(local: true)
+ let project = try await transport.createCodeProject(
+ name: URL(fileURLWithPath: path).lastPathComponent,
+ workspacePath: path,
+ repoUrl: nil,
+ defaultTarget: .local,
+ defaultModel: selectedCodeModel
+ )
+ await refreshCodeState()
+ startNewCodeThread(projectId: project.id)
+ } catch {
+ showError("프로젝트를 추가하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Lets the member pick a folder to add as a project, then opens the new-thread screen in it. When targeting this
+ /// Mac locally on macOS, opens the native folder panel; when targeting a remote Mac (on iOS or macOS), browses
+ /// that Mac's folders over the relay.
+ public func pickCodeFolder() {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = true
+ panel.canChooseFiles = false
+ panel.allowsMultipleSelection = false
+ panel.prompt = "Add Project"
+ let newestProject = codeFolderProjects.max { $0.createdAt < $1.createdAt }
+ if let newestProject {
+ panel.directoryURL = URL(fileURLWithPath: newestProject.workspacePath).deletingLastPathComponent()
+ }
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ Task { await addCodeProject(folder: url.path) }
+ }
+
+ public func deleteCodeProject(id: String) async {
+ do {
+ try await codeTransport(local: true).deleteCodeProject(id: id)
+ } catch SyncError.httpStatus(404, _) {
+ } catch {
+ showError("Failed to remove project: \(error.localizedDescription)")
+ return
+ }
+ let threadIds = codeThreads.filter { $0.projectId == id }.map(\.id)
+ for threadId in threadIds {
+ forgetCodeThread(threadId)
+ }
+ localCodeState = localCodeState?.removingProject(id)
+ if codeNewThread?.projectId == id {
+ codeNewThread = nil
+ }
+ showInfo("Removed project.")
+ await refreshCodeState()
+ }
+
+ func defaultCodeNewThreadMode(projectId: String?) -> CodeNewThreadMode {
+ codeNewThreadChoices(projectId: projectId).first ?? .local
+ }
+
+ /// Opens the new-thread screen for a folder project, set to the first way of working that fits, or with no
+ /// project while the member has none.
+ public func startNewCodeThread(projectId: String?) {
+ saveCurrentCodeDraft()
+ codeDestination = .threads
+ selectedCodeThreadId = nil
+ pendingDraftCodeRun = nil
+ keptUnreadThreadId = nil
+ let mode = defaultCodeNewThreadMode(projectId: projectId)
+ codeNewThread = CodeNewThreadDraft(projectId: projectId, mode: mode)
+ codeNewThreadBaseBranch = nil
+ selectedCodeTarget = mode.target
+ restoreCurrentCodeDraft()
+ }
+
+ /// Opens the new-thread screen where the member is: the project of the new-thread screen or of the open thread,
+ /// else the first project in the sidebar.
+ public func startNewCodeThreadHere() {
+ let threadProjectId = selectedCodeThread.flatMap { codeListedProjectIds[$0.projectId] }
+ startNewCodeThread(projectId: codeNewThreadDraft?.projectId ?? threadProjectId ?? codeFolderProjects.first?.id)
+ }
+
+ /// What the new-thread screen shows: the thread the member opened it for, or one in the first project in the
+ /// sidebar while no thread is open.
+ public var codeNewThreadDraft: CodeNewThreadDraft? {
+ if let codeNewThread {
+ return codeNewThread
+ }
+ guard selectedCodeThread == nil else { return nil }
+ let projectId = codeFolderProjects.first?.id
+ return CodeNewThreadDraft(projectId: projectId, mode: defaultCodeNewThreadMode(projectId: projectId))
+ }
+
+ /// The ways a new thread can work in the project, none before a project is picked.
+ public func codeNewThreadChoices(projectId: String?) -> [CodeNewThreadMode] {
+ guard let projectId else { return [] }
+ let isGitRepo = codeGitStatusByProject[projectId]?.isRepo ?? false
+ let onGitHub = codeProjects.first { $0.id == projectId }?.gitHubRepo != nil
+ return CodeNewThreadMode.choices(projectOnMac: isLocalCodeProject(projectId), isGitRepo: isGitRepo, onGitHub: onGitHub)
+ }
+
+ public func setCodeNewThreadMode(_ mode: CodeNewThreadMode) {
+ var draft = codeNewThreadDraft ?? CodeNewThreadDraft(projectId: nil, mode: mode)
+ draft.mode = mode
+ codeNewThread = draft
+ selectedCodeTarget = mode.target
+ }
+
+ /// Folder projects, from the Mac and the server, in fixed user-controlled order. The projects the servers keep
+ /// for conversations stay hidden, and so does the server's clone of a Mac project's GitHub repository, whose
+ /// threads list under the Mac project.
+ public var codeFolderProjects: [CodeProject] {
+ let listed = codeListedProjectIds
+ let folders = codeProjects.filter { listed[$0.id] == $0.id }
+ return CodeProject.ordered(folders, savedIds: codeProjectOrder)
+ }
+
+ /// Reorders a project folder via drag-and-drop and persists the fixed order locally.
+ public func reorderCodeProject(moving sourceId: String, to targetId: String) {
+ let currentIds = codeFolderProjects.map(\.id)
+ let updated = CodeProject.reorderedIds(current: currentIds, moving: sourceId, to: targetId)
+ guard updated != codeProjectOrder else { return }
+ codeProjectOrder = updated
+ }
+
+ /// Toggles a project folder's collapsed state and persists it locally.
+ public func toggleCodeProjectCollapsed(_ projectId: String) {
+ if collapsedCodeProjectIds.contains(projectId) {
+ collapsedCodeProjectIds.remove(projectId)
+ } else {
+ collapsedCodeProjectIds.insert(projectId)
+ }
+ }
+
+ /// The folder project each project's threads list under in the sidebar, by project id: the project itself, or for
+ /// the server's clone of a Mac project's GitHub repository the Mac project. The conversations projects have none.
+ public var codeListedProjectIds: [String: String] {
+ let projects = codeProjects
+ var macProjectByRepo: [String: String] = [:]
+ for project in projects where isLocalCodeProject(project.id) {
+ if let repo = project.gitHubRepo, macProjectByRepo[repo] == nil {
+ macProjectByRepo[repo] = project.id
+ }
+ }
+ var listed: [String: String] = [:]
+ for project in projects where !project.isConversations {
+ let macProjectId = isLocalCodeProject(project.id) ? nil : project.gitHubRepo.flatMap { macProjectByRepo[$0] }
+ listed[project.id] = macProjectId ?? project.id
+ }
+ return listed
+ }
+
+ /// Makes the thread the new-thread screen describes and opens it. It returns nil after telling the member why
+ /// it could not, or while the thread is still being made.
+ func createDraftedCodeThread(_ draft: CodeNewThreadDraft) async -> CodeThread? {
+ guard !isCreatingDraftedThread else { return nil }
+ guard let projectId = draft.projectId else {
+ showError("Add a project folder first to start a thread.")
+ return nil
+ }
+ isCreatingDraftedThread = true
+ defer { isCreatingDraftedThread = false }
+ do {
+ let thread = try await codeTransport(local: true).createCodeThread(
+ projectId: projectId,
+ title: "New Thread",
+ model: selectedCodeModel,
+ executionTarget: .local,
+ accessMode: selectedCodeAccessMode,
+ reasoningEffort: selectedCodeEffort,
+ worktree: draft.mode == .worktree,
+ baseBranch: draft.mode == .worktree ? codeNewThreadBaseBranch : nil,
+ titleStyle: codeTitleStyle,
+ titleFormat: codeTitleFormat
+ )
+ applyThreadUpdateInMemory(thread, isLocal: true)
+ codeSyncedMessageThreadIds.insert(thread.id)
+ codeNewThread = nil
+ selectedCodeThreadId = thread.id
+ didUserSelectCodeThread = true
+ return thread
+ } catch {
+ showError("Failed to start thread: \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ public func deleteCodeThread(id: String) async {
+ endCodeRun(id)
+ do {
+ try await codeTransport(local: true).deleteCodeThread(id: id)
+ } catch SyncError.httpStatus(404, _) {
+ } catch {
+ attachRunningCodeThreads()
+ showError("Failed to delete thread: \(error.localizedDescription)")
+ return
+ }
+ removeDeletedCodeThread(id, isLocal: true)
+ showInfo("Deleted thread.")
+ await refreshCodeState()
+ }
+
+ func removeDeletedCodeThread(_ id: String, isLocal: Bool = true) {
+ forgetCodeThread(id)
+ localCodeState = localCodeState?.removingThread(id)
+ }
+
+ func forgetCodeThread(_ id: String) {
+ endCodeRun(id)
+ codeMessagesByThread.removeValue(forKey: id)
+ codeMessageLoadSeq.removeValue(forKey: id)
+ codeMessageAppliedSeq.removeValue(forKey: id)
+ codeLoadingMessageThreadIds.remove(id)
+ codeSyncedMessageThreadIds.remove(id)
+ codeMessageLoadErrorByThread.removeValue(forKey: id)
+ codeDraftsByKey.removeValue(forKey: CodeComposerDraftKey.thread(id))
+ store.forgetCodeThreadAsync(threadId: id)
+ if selectedCodeThreadId == id {
+ selectedCodeThreadId = nil
+ restoreCurrentCodeDraft()
+ }
+ if keptUnreadThreadId == id {
+ keptUnreadThreadId = nil
+ }
+ if stickyTriageThreadId == id {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ pendingReadThreadIds.remove(id)
+ if codeTurnErrorBanner?.threadId == id {
+ codeTurnErrorBanner = nil
+ }
+ }
+
+ // MARK: - Morph Code Scheduled Tasks
+
+ /// The task 예약됨 shows: the one picked, or the first task.
+ public var selectedCodeSchedule: CodeSchedule? {
+ let schedules = codeSchedules
+ return schedules.first { $0.id == selectedCodeScheduleId } ?? schedules.first
+ }
+
+ /// Whether a thread is a run of a task that still exists. Such threads live in 예약됨, and go back to their
+ /// project's list once their task is deleted.
+ public func isCodeScheduleRun(_ thread: CodeThread) -> Bool {
+ guard let scheduleId = thread.scheduleId else { return false }
+ return codeSchedules.contains { $0.id == scheduleId }
+ }
+
+ /// Whether 예약됨 is open: its list in the sidebar, with a task or one of the task's runs in the main area.
+ public var isCodeScheduledOpen: Bool {
+ switch codeDestination {
+ case .scheduled:
+ return true
+ case .threads:
+ return selectedCodeThread.map(isCodeScheduleRun) ?? false
+ }
+ }
+
+ /// Where a task's runs are: each run's own thread, newest first, or the one thread a task in a thread runs in.
+ /// Archived threads wait in the archive until a new run brings them back.
+ public func codeRunThreads(of schedule: CodeSchedule) -> [CodeThread] {
+ if let threadId = schedule.threadId {
+ return listedCodeThreads.filter { $0.id == threadId }
+ }
+ return listedCodeThreads.filter { $0.scheduleId == schedule.id }.sorted { $0.createdAt > $1.createdAt }
+ }
+
+ /// Opens 예약됨 on a task, or on the task picked last. Coming from a thread, it remembers it for the way back.
+ public func openCodeScheduled(_ scheduleId: String? = nil) {
+ if !isCodeScheduledOpen {
+ codeThreadBeforeScheduled = selectedCodeThreadId
+ }
+ if let scheduleId {
+ selectedCodeScheduleId = scheduleId
+ }
+ codeDestination = .scheduled
+ }
+
+ /// Leaves 예약됨 for the thread open before it, else the newest active thread the member started.
+ public func closeCodeScheduled() async {
+ let previous = codeThreads.first { $0.id == codeThreadBeforeScheduled && $0.isActiveForTriage() && !isCodeScheduleRun($0) }
+ if let thread = previous ?? listedCodeThreads.first(where: { !isCodeScheduleRun($0) && $0.isActiveForTriage() }) {
+ await selectCodeThread(thread)
+ } else {
+ saveCurrentCodeDraft()
+ selectedCodeThreadId = nil
+ codeDestination = .threads
+ restoreCurrentCodeDraft()
+ }
+ }
+
+ /// Opens the scheduled task editor on a task to change, or on a new task that runs in a thread.
+ public func editCodeSchedule(_ schedule: CodeSchedule? = nil, threadId: String? = nil) {
+ codeScheduleDraft = CodeScheduleDraft(schedule: schedule, threadId: threadId)
+ }
+
+ /// Saves the editor's task where it runs: this Mac's bridge for a local project, otherwise the cloud server.
+ /// The saved task becomes the one 예약됨 shows. Returns whether it saved, so the editor stays open with the
+ /// member's input after a refusal.
+ public func saveCodeSchedule(_ input: CodeScheduleInput, editing schedule: CodeSchedule?) async -> Bool {
+ let isLocal = schedule.map { isLocalCodeSchedule($0.id) } ?? isLocalCodeProject(input.projectId ?? "")
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ let saved: CodeSchedule
+ if let schedule {
+ saved = try await transport.updateCodeSchedule(id: schedule.id, input)
+ } else {
+ saved = try await transport.createCodeSchedule(input)
+ }
+ await refreshCodeStateQuietly()
+ selectedCodeScheduleId = saved.id
+ let when = CodeScheduleCadence.label(for: saved.rrule, timezone: saved.timezone)
+ showInfo(saved.enabled ? "\(when)에 실행합니다." : "예약을 저장했습니다. 꺼져 있어 실행하지 않습니다.")
+ return true
+ } catch {
+ showError("예약을 저장하지 못했습니다. \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ public func setCodeScheduleEnabled(_ schedule: CodeSchedule, _ enabled: Bool) async {
+ do {
+ let transport = try await codeTransport(local: isLocalCodeSchedule(schedule.id))
+ _ = try await transport.updateCodeSchedule(id: schedule.id, CodeScheduleInput(enabled: enabled))
+ await refreshCodeStateQuietly()
+ } catch {
+ showError("예약을 \(enabled ? "켜지" : "끄지") 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Active recurring schedules (`/loop`) pinned to a specific thread.
+ public func activeCodeLoops(for threadId: String) -> [CodeSchedule] {
+ codeSchedules.filter { $0.enabled && $0.threadId == threadId }
+ }
+
+ /// Executes a parsed `/loop` command directly against morphcode's unified scheduler.
+ public func handleCodeLoopCommand(
+ _ command: CodeLoopCommand,
+ thread: CodeThread?,
+ project: CodeProject?,
+ model: String,
+ effort: CodeReasoningEffort,
+ accessMode: CodeAccessMode
+ ) async {
+ switch command {
+ case .help(let message):
+ showInfo(message)
+ case .stop:
+ guard let threadId = thread?.id else {
+ showInfo("중지할 활성 루프가 있는 스레드가 없습니다.")
+ return
+ }
+ let loops = activeCodeLoops(for: threadId)
+ guard !loops.isEmpty else {
+ showInfo("이 스레드에 실행 중인 반복 루프가 없습니다.")
+ return
+ }
+ var stopped = 0
+ for loop in loops {
+ do {
+ let transport = try await codeTransport(local: isLocalCodeSchedule(loop.id))
+ _ = try await transport.updateCodeSchedule(id: loop.id, CodeScheduleInput(enabled: false))
+ stopped += 1
+ } catch {
+ showError("루프를 중지하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+ await refreshCodeStateQuietly()
+ if stopped > 0 {
+ showInfo("이 스레드의 반복 루프 \(stopped)개를 중지했습니다.")
+ }
+ case .start(let rrule, let intervalLabel, let prompt):
+ guard let projectId = thread?.projectId ?? project?.id else {
+ showError("반복 루프를 시작하려면 먼저 프로젝트 폴더를 선택해 주세요.")
+ return
+ }
+ let isLocal = thread.map { isLocalCodeThread($0.id) } ?? isLocalCodeProject(projectId)
+ let trimmedTitle = String(prompt.prefix(48))
+ let input = CodeScheduleInput(
+ title: trimmedTitle,
+ prompt: prompt,
+ projectId: projectId,
+ threadId: thread?.id,
+ rrule: rrule,
+ timezone: TimeZone.current.identifier,
+ model: model,
+ reasoningEffort: effort,
+ accessMode: accessMode,
+ enabled: true
+ )
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ _ = try await transport.createCodeSchedule(input)
+ await refreshCodeStateQuietly()
+ showInfo("\(intervalLabel) 반복 루프를 시작했습니다. (/loop stop 으로 중지)")
+ } catch {
+ showError("반복 루프를 시작하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+ }
+
+ /// Deletes a task. The threads its runs made stay, and go back to their project's list.
+ public func deleteCodeSchedule(_ schedule: CodeSchedule) async {
+ do {
+ try await codeTransport(local: isLocalCodeSchedule(schedule.id)).deleteCodeSchedule(id: schedule.id)
+ await refreshCodeStateQuietly()
+ showInfo("예약을 삭제했습니다.")
+ } catch {
+ showError("예약을 삭제하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Runs a task now without moving its next run, then opens the thread the run went to.
+ public func runCodeScheduleNow(_ schedule: CodeSchedule) async {
+ do {
+ let res = try await codeTransport(local: isLocalCodeSchedule(schedule.id)).runCodeSchedule(id: schedule.id)
+ await refreshCodeStateQuietly()
+ switch res.run.status {
+ case "started":
+ if let thread = codeThreads.first(where: { $0.id == res.run.threadId }) {
+ await selectCodeThread(thread)
+ }
+ case "skipped":
+ showInfo(res.run.note ?? "이전 실행이 아직 끝나지 않아 건너뛰었습니다.")
+ default:
+ showError("실행하지 못했습니다. \(res.run.note ?? "")")
+ }
+ } catch {
+ showError("실행하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Puts a thread away or brings it back into the list. Unifies legacy `settledAt` with `archivedAt`:
+ /// restoring clears both so the thread returns to the active sidebar immediately.
+ public func archiveCodeThread(id: String, archived: Bool) async {
+ guard var thread = codeThreads.first(where: { $0.id == id }), thread.isEffectivelyArchived != archived else { return }
+ let isLocal = isLocalCodeThread(id)
+ let previous = thread
+ thread.archivedAt = archived ? MorphPalette.isoString(from: Date()) : nil
+ if !archived {
+ thread.settledAt = nil
+ }
+ if archived {
+ if stickyTriageThreadId == id {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ if keptUnreadThreadId == id {
+ keptUnreadThreadId = nil
+ }
+ }
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ do {
+ let updated = try await codeTransport(local: isLocal).archiveCodeThread(threadId: id, archived: archived)
+ applyThreadUpdateInMemory(updated, isLocal: isLocal)
+ if updated.isEffectivelyArchived != archived {
+ // A server from before archiving keeps the thread as it was.
+ showError(isLocal
+ ? "Mac의 morphcode가 스레드 보관을 지원하지 않습니다. morphcode를 업데이트해 주세요."
+ : "서버가 스레드 보관을 지원하지 않습니다.")
+ return
+ }
+ #if os(iOS)
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+ #endif
+ } catch {
+ applyThreadUpdateInMemory(previous, isLocal: isLocal)
+ showError("\(archived ? "스레드를 보관하지" : "스레드를 목록으로 되돌리지") 못했습니다. \(error.localizedDescription)")
+ return
+ }
+ // The open thread went to the archive: open the next active non-scheduled thread in its place.
+ if archived, selectedCodeThreadId == id {
+ if let next = listedCodeThreads.first(where: { !isCodeScheduleRun($0) && $0.isActiveForTriage() }) {
+ await selectCodeThread(next)
+ } else {
+ saveCurrentCodeDraft()
+ selectedCodeThreadId = nil
+ restoreCurrentCodeDraft()
+ }
+ }
+ }
+
+ /// Renames a thread on its server with optimistic UI update and rollback on failure.
+ public func renameCodeThread(id: String, title: String) async throws {
+ let clean = title.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !clean.isEmpty else { return }
+ let isLocal = isLocalCodeThread(id)
+ let previous = codeThreads.first(where: { $0.id == id })
+ if let previous {
+ applyThreadUpdateInMemory(previous.withOptimistic(title: clean), isLocal: isLocal)
+ }
+ do {
+ let updated = try await codeTransport(local: isLocal).renameCodeThread(threadId: id, title: clean)
+ applyThreadUpdateInMemory(updated, isLocal: isLocal)
+ } catch {
+ if let previous {
+ applyThreadUpdateInMemory(previous, isLocal: isLocal)
+ }
+ throw error
+ }
+ }
+
+ /// Snoozes a thread until the given ISO-8601 timestamp (or unsnoozes when `until` is nil), with optimistic UI.
+ public func snoozeCodeThread(id: String, until: String?) async {
+ guard var thread = codeThreads.first(where: { $0.id == id }) else { return }
+ let isLocal = isLocalCodeThread(id)
+ let previous = thread
+ thread.snoozedUntil = until
+ if until != nil, stickyTriageThreadId == id {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ do {
+ let updated = try await codeTransport(local: isLocal).snoozeCodeThread(threadId: id, until: until)
+ applyThreadUpdateInMemory(updated, isLocal: isLocal)
+ showInfo(until == nil ? "스레드 보류를 해제했습니다." : "스레드를 나중에 보기로 보류했습니다.")
+ } catch {
+ applyThreadUpdateInMemory(previous, isLocal: isLocal)
+ showError("스레드 보류를 변경하지 못했습니다. \(error.localizedDescription)")
+ return
+ }
+ if until != nil, selectedCodeThreadId == id {
+ if let next = listedCodeThreads.first(where: { !isCodeScheduleRun($0) && $0.isActiveForTriage() }) {
+ await selectCodeThread(next)
+ } else {
+ selectedCodeThreadId = nil
+ }
+ }
+ }
+
+ /// Asks the server to regenerate a concise title for the thread.
+ public func regenerateCodeThreadTitle(id: String) async {
+ let isLocal = isLocalCodeThread(id)
+ do {
+ let updated = try await codeTransport(local: isLocal).regenerateCodeThreadTitle(threadId: id)
+ applyThreadUpdateInMemory(updated, isLocal: isLocal)
+ showInfo("스레드 제목을 다시 지었습니다.")
+ } catch {
+ showError("제목을 다시 짓지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Delegates a sub-task to a new child thread under `parentThreadId`.
+ public func delegateCodeTask(
+ parentThreadId: String,
+ prompt: String,
+ worktree: Bool = false,
+ model: String? = nil,
+ effort: String? = nil,
+ accessMode: String? = nil
+ ) async {
+ let clean = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !clean.isEmpty else { return }
+ let isLocal = isLocalCodeThread(parentThreadId)
+ do {
+ let child = try await codeTransport(local: isLocal).delegateCodeTask(
+ parentThreadId: parentThreadId,
+ prompt: clean,
+ worktree: worktree,
+ model: model,
+ effort: effort,
+ accessMode: accessMode
+ )
+ applyThreadUpdateInMemory(child, isLocal: isLocal)
+ showInfo("위임 작업을 시작했습니다: \(child.title)")
+ await selectCodeThread(child)
+ attachRunningCodeThreads()
+ } catch {
+ showError("위임 작업을 시작하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Selects the next active thread needing attention in triage priority order (awaiting action → failed → completed).
+ public func selectNextAttentionCodeThread() async {
+ let now = Date()
+ let attentionThreads = listedCodeThreads
+ .filter { thread in
+ !isCodeScheduleRun(thread)
+ && thread.isActiveForTriage(now: now)
+ && codeVisualStatus(of: thread).needsAttention
+ }
+ .sorted { a, b in
+ let sa = codeVisualStatus(of: a)
+ let sb = codeVisualStatus(of: b)
+ if sa != sb { return sa < sb }
+ return CodeThread.newestFirst(a, b)
+ }
+ guard !attentionThreads.isEmpty else {
+ showInfo("확인이 필요한 스레드가 없습니다.")
+ return
+ }
+ if let currentId = selectedCodeThreadId,
+ let idx = attentionThreads.firstIndex(where: { $0.id == currentId }) {
+ let next = attentionThreads[(idx + 1) % attentionThreads.count]
+ await selectCodeThread(next)
+ } else if let first = attentionThreads.first {
+ await selectCodeThread(first)
+ }
+ }
+
+ /// Optimistically clears unread/archive/settle/snooze state when a new prompt is sent to an existing thread.
+ func clearOptimisticCodeThreadTriageState(threadId: String) {
+ if stickyTriageThreadId == threadId {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ if keptUnreadThreadId == threadId {
+ keptUnreadThreadId = nil
+ }
+ pendingReadThreadIds.remove(threadId)
+ guard var thread = codeThreads.first(where: { $0.id == threadId }) else { return }
+ if thread.unreadCount > 0 || thread.archivedAt != nil || thread.settledAt != nil || thread.snoozedUntil != nil {
+ thread.unreadCount = 0
+ thread.archivedAt = nil
+ thread.settledAt = nil
+ thread.snoozedUntil = nil
+ applyThreadUpdateInMemory(thread, isLocal: isLocalCodeThread(threadId))
+ }
+ }
+
+ /// Marks a thread's finished turn as seen, or as not seen yet the way Mail marks a message unread. The open
+ /// thread marked unread stays unread until the member opens another thread.
+ public func setCodeThreadUnread(id: String, unread: Bool) async {
+ guard var thread = codeThreads.first(where: { $0.id == id }) else { return }
+ let isLocal = isLocalCodeThread(id)
+ let previous = thread
+ thread.unreadCount = unread ? max(thread.unreadCount, 1) : 0
+ if stickyTriageThreadId == id {
+ stickyTriageThreadId = nil
+ stickyTriageStatus = nil
+ }
+ if unread {
+ pendingReadThreadIds.remove(id)
+ } else {
+ pendingReadThreadIds.insert(id)
+ }
+ applyThreadUpdateInMemory(thread, isLocal: isLocal)
+ keptUnreadThreadId = unread ? id : nil
+ defer {
+ if !unread {
+ pendingReadThreadIds.remove(id)
+ }
+ }
+ do {
+ let transport = try await codeTransport(local: isLocal)
+ if unread {
+ applyThreadUpdateInMemory(try await transport.markCodeThreadUnread(threadId: id), isLocal: isLocal)
+ } else {
+ try await transport.markCodeThreadRead(threadId: id)
+ }
+ } catch {
+ applyThreadUpdateInMemory(previous, isLocal: isLocal)
+ showError("읽음 표시를 바꾸지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+
+ /// Adds images to the composer once each is read and made into a PNG, JPEG, GIF or WebP every engine takes
+ /// (`CodeImageNormalizer`). They are read off the main thread, in the order given, with a placeholder tile each
+ /// meanwhile. One that cannot be read is named in an error and the rest still attach.
+
+ /// ISO-8601 timestamp 1 hour from now for Snooze.
+ public static func snoozeOneHourISO() -> String {
+ MorphPalette.isoString(from: Date().addingTimeInterval(3600))
+ }
+
+ /// ISO-8601 timestamp for tomorrow 09:00 local time for Snooze.
+ public static func snoozeTomorrowMorningISO() -> String {
+ let cal = Calendar.current
+ let tomorrow = cal.date(byAdding: .day, value: 1, to: Date()) ?? Date().addingTimeInterval(86400)
+ let morning = cal.date(bySettingHour: 9, minute: 0, second: 0, of: tomorrow) ?? tomorrow
+ return MorphPalette.isoString(from: morning)
+ }
+}
+
+extension CodeThread {
+ /// Creates an optimistic local copy with updated `title` and/or `queue` without mutating server-owned fields.
+ func withOptimistic(title newTitle: String? = nil, queue newQueue: [CodeQueuedPrompt]?? = nil) -> CodeThread {
+ CodeThread(
+ id: id,
+ projectId: projectId,
+ memberId: memberId,
+ title: newTitle ?? title,
+ model: model,
+ provider: provider,
+ executionTarget: executionTarget,
+ accessMode: accessMode,
+ reasoningEffort: reasoningEffort,
+ branch: branch,
+ baseBranch: baseBranch,
+ worktreePath: worktreePath,
+ status: status,
+ pinned: pinned,
+ routedAccountId: routedAccountId,
+ routedAccountLabel: routedAccountLabel,
+ usage: usage,
+ scheduleId: scheduleId,
+ unreadCount: unreadCount,
+ queue: newQueue ?? queue,
+ archivedAt: archivedAt,
+ createdAt: createdAt,
+ updatedAt: updatedAt,
+ settledAt: settledAt,
+ snoozedUntil: snoozedUntil,
+ parentThreadId: parentThreadId,
+ linkedPRs: linkedPRs,
+ linkedIssues: linkedIssues
+ )
+ }
+}
+
+extension MorphCodeStateSnapshot {
+ /// Returns a copy with an approval removed (for optimistic approval decisions).
+ func removingApproval(_ approvalId: String) -> MorphCodeStateSnapshot {
+ MorphCodeStateSnapshot(
+ memberId: memberId,
+ memberOsUser: memberOsUser,
+ hostRuntime: hostRuntime,
+ daemonVersion: daemonVersion,
+ projects: projects,
+ threads: threads,
+ approvals: approvals.filter { $0.id != approvalId },
+ questions: questions,
+ approvalRules: approvalRules,
+ artifacts: artifacts,
+ plugins: plugins,
+ accounts: accounts,
+ availableModels: availableModels,
+ schedules: schedules
+ )
+ }
+
+ func restoringApproval(_ approval: CodeApproval) -> MorphCodeStateSnapshot {
+ guard !approvals.contains(where: { $0.id == approval.id }) else { return self }
+ return MorphCodeStateSnapshot(
+ memberId: memberId,
+ memberOsUser: memberOsUser,
+ hostRuntime: hostRuntime,
+ daemonVersion: daemonVersion,
+ projects: projects,
+ threads: threads,
+ approvals: approvals + [approval],
+ questions: questions,
+ approvalRules: approvalRules,
+ artifacts: artifacts,
+ plugins: plugins,
+ accounts: accounts,
+ availableModels: availableModels,
+ schedules: schedules
+ )
+ }
+
+ func removingQuestion(_ questionId: String) -> MorphCodeStateSnapshot {
+ MorphCodeStateSnapshot(
+ memberId: memberId,
+ memberOsUser: memberOsUser,
+ hostRuntime: hostRuntime,
+ daemonVersion: daemonVersion,
+ projects: projects,
+ threads: threads,
+ approvals: approvals,
+ questions: questions?.filter { $0.id != questionId },
+ approvalRules: approvalRules,
+ artifacts: artifacts,
+ plugins: plugins,
+ accounts: accounts,
+ availableModels: availableModels,
+ schedules: schedules
+ )
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+Notifications.swift b/apple/Apps/Shared/MorphAppState+Notifications.swift
new file mode 100644
index 000000000..9f5433934
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+Notifications.swift
@@ -0,0 +1,15 @@
+import Foundation
+import MorphCore
+
+// MARK: - Local notification preferences
+
+extension MorphAppState {
+ public func isCodeNotificationEnabled(for kind: CodeNotificationEvent.Kind) -> Bool {
+ guard codeNotificationsEnabled else { return false }
+ switch kind {
+ case .turnCompleted: return codeNotifyTurnDone
+ case .turnFailed: return codeNotifyTurnFailed
+ case .approvalRequired, .questionRequired: return codeNotifyAttention
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState+Settings.swift b/apple/Apps/Shared/MorphAppState+Settings.swift
new file mode 100644
index 000000000..defec11f9
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState+Settings.swift
@@ -0,0 +1,110 @@
+import Foundation
+import MorphCore
+
+extension MorphAppState {
+ // MARK: - Settings & App Lifecycle
+
+ public func openSettings(_ section: MorphSettingsSection? = nil) {
+ if let section {
+ settingsSection = section
+ }
+ isSettingsPresented = true
+ }
+
+ public func startRealtimeSync() {
+ startLocalBridgeObserver()
+ Task {
+ let ready = await ensureLocalBridgeReady() != nil
+ if ready {
+ await refreshCodeState()
+ await refreshCodeDaemonHealth()
+ await loadCustomProviders()
+ await loadProviderHarnesses()
+ await refreshCodeHarnessConfig()
+ }
+ }
+ }
+
+ public func handleIncomingURL(_ url: URL) async {
+ let scheme = url.scheme?.lowercased()
+ guard scheme == "morphcode" || scheme == "morph" else { return }
+ let host = url.host?.lowercased() ?? ""
+ let comps = URLComponents(url: url, resolvingAgainstBaseURL: false)
+ if host == "settings" {
+ if let sec = comps?.queryItems?.first(where: { $0.name == "section" })?.value,
+ let parsed = MorphSettingsSection(rawValue: sec.lowercased()) {
+ openSettings(parsed)
+ } else {
+ openSettings()
+ }
+ return
+ }
+ if host == "thread", let id = comps?.queryItems?.first(where: { $0.name == "id" })?.value, !id.isEmpty,
+ let thread = codeThreads.first(where: { $0.id == id }) {
+ await selectCodeThread(thread)
+ }
+ }
+
+ public func syncNow(userInitiated: Bool = false) async {
+ _ = await ensureLocalBridgeReady()
+ await refreshCodeState()
+ await refreshCodeDaemonHealth()
+ await loadCustomProviders()
+ await loadProviderHarnesses()
+ if userInitiated {
+ showInfo(localBridgeOnline ? "Synced with local daemon." : "Local daemon is offline.")
+ }
+ }
+
+ public func restartLocalDaemon() async {
+ isStartingLocalDaemon = true
+ defer { isStartingLocalDaemon = false }
+ if !MacBridgeAgent.hasCustomRuntimeOverride {
+ let uid = getuid()
+ await Task.detached(priority: .userInitiated) {
+ let kickstart = Process()
+ kickstart.executableURL = URL(fileURLWithPath: "/bin/launchctl")
+ kickstart.arguments = ["kickstart", "-k", "gui/\(uid)/\(MacBridgeAgent.label)"]
+ try? kickstart.run()
+ kickstart.waitUntilExit()
+ }.value
+ }
+ lastLocalBridgeVerifiedAt = nil
+ localBridgeOnline = false
+ let ready = await ensureLocalBridgeReady() != nil
+ if ready {
+ await refreshCodeState()
+ await refreshCodeDaemonHealth()
+ showInfo("Local morphcode daemon restarted.")
+ } else {
+ showError("Failed to restart the local morphcode daemon.")
+ }
+ }
+
+ // MARK: - Realtime Voice Dictation Session
+
+ public func requestVoiceTranscriptionSession(
+ keywords: [String] = [],
+ prompt: String? = nil,
+ forceRefresh: Bool = false
+ ) async throws -> (session: VoiceTranscriptionSession, fromCache: Bool) {
+ let serverKey = "\(serverURLString)|local"
+ if !forceRefresh, let cached = voiceSessionCache.validSession(forServerKey: serverKey) {
+ return (cached, true)
+ }
+ if let existingTask = voiceSessionFetchTask {
+ let session = try await existingTask.value
+ return (session, false)
+ }
+ let req = VoiceTranscriptionSessionRequest(languages: ["en", "ko"], keywords: keywords, prompt: prompt)
+ let engine = syncEngine
+ let task = Task {
+ try await engine.createVoiceTranscriptionSession(req)
+ }
+ voiceSessionFetchTask = task
+ defer { voiceSessionFetchTask = nil }
+ let session = try await task.value
+ voiceSessionCache.store(session, forServerKey: serverKey)
+ return (session, false)
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppState.swift b/apple/Apps/Shared/MorphAppState.swift
new file mode 100644
index 000000000..6097c6095
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppState.swift
@@ -0,0 +1,423 @@
+import Foundation
+import Observation
+import os
+import AppKit
+import SystemConfiguration
+import MorphCore
+
+@MainActor
+@Observable
+public final class MorphAppState {
+ // Navigation (pure local-first Morph Code)
+ public var appMode: MorphAppMode = .code
+ public var isCommandPalettePresented = false
+ public var isSettingsPresented = false
+ public var settingsSection: MorphSettingsSection = .general
+ public var isSidebarVisible = true
+ public var themeMode: MorphThemeMode = .system {
+ didSet {
+ UserDefaults.standard.set(themeMode.rawValue, forKey: Self.savedThemeModeKey)
+ }
+ }
+
+ // Morph Code workspace state (projects, threads, streaming, approvals, schedules, providers)
+ @ObservationIgnored var suppressCodeStateDiskCache = false
+ public internal(set) var localCodeState: MorphCodeStateSnapshot? {
+ didSet {
+ rebuildCodeCaches()
+ if !suppressCodeStateDiskCache, let localCodeState {
+ store.cacheMacCodeStateAsync(localCodeState)
+ }
+ }
+ }
+ var localProjectIds: Set = []
+ var localThreadIds: Set = []
+ var localScheduleIds: Set = []
+ public internal(set) var codeProjects: [CodeProject] = []
+ public internal(set) var codeThreads: [CodeThread] = []
+ var visibleCodeThreads: [CodeThread] = []
+ public internal(set) var listedCodeThreads: [CodeThread] = []
+ public internal(set) var archivedCodeThreads: [CodeThread] = []
+ public internal(set) var snoozedCodeThreads: [CodeThread] = []
+ public internal(set) var codeThreadUsage: [String: CodeTokenUsage] = [:]
+ public internal(set) var localCodeDaemonVersion: String?
+ public internal(set) var codeApprovals: [CodeApproval] = []
+ public internal(set) var codeApprovalsByThread: [String: [CodeApproval]] = [:]
+ public internal(set) var pendingCodeApprovalCountByThread: [String: Int] = [:]
+ public internal(set) var pendingCodeQuestionsByThread: [String: [CodeUserQuestion]] = [:]
+ public internal(set) var codeArtifacts: [CodeArtifact] = []
+ public internal(set) var codeAccounts: [CodeAccountView] = []
+ public internal(set) var codeSchedules: [CodeSchedule] = []
+ var cachedLocalCodeModels: [CodeModelOption] = CodeModelOption.catalog
+ @ObservationIgnored var codeMessageAccessOrder: [String] = []
+
+ // Local morphcode daemon status
+ public internal(set) var localBridgeOnline = false
+ public internal(set) var isStartingLocalDaemon = false
+ @ObservationIgnored var lastLocalBridgeVerifiedAt: Date?
+ @ObservationIgnored var localBridgeStart: Task?
+ @ObservationIgnored var localBridgeTask: Task?
+ @ObservationIgnored var hasSyncedBundledBridgeThisLaunch = false
+
+ static let codeRPCSession = URLSessionMorphTransport.makeDedicatedSession(maxConnectionsPerHost: 24, timeoutIntervalForRequest: 30)
+ static let codeStreamSession = URLSessionMorphTransport.makeDedicatedSession(maxConnectionsPerHost: 32, timeoutIntervalForRequest: 300)
+ static let localBridgeHealthSession = URLSessionMorphTransport.makeDedicatedSession(maxConnectionsPerHost: 8, timeoutIntervalForRequest: 5)
+
+ // Message hydration & workspace sync tracking
+ @ObservationIgnored var codeMessageLoadSeq: [String: Int] = [:]
+ @ObservationIgnored var codeMessageAppliedSeq: [String: Int] = [:]
+ @ObservationIgnored var codeMessageLoadTasks: [String: Task] = [:]
+ public internal(set) var codeLoadingMessageThreadIds: Set = []
+ public internal(set) var codeSyncedMessageThreadIds: Set = []
+ public internal(set) var codeMessageLoadErrorByThread: [String: String] = [:]
+ @ObservationIgnored var localCodeWorkspaceSyncCount = 0
+ public internal(set) var isSyncingLocalCodeWorkspace = false
+ @ObservationIgnored var codeFileSearchTask: Task?
+
+ // Active selection & composer drafts
+ public var selectedCodeThreadId: String?
+ @ObservationIgnored var didUserSelectCodeThread = false
+ public internal(set) var codeNewThread: CodeNewThreadDraft?
+ @ObservationIgnored var isCreatingDraftedThread = false
+ public var codeMessagesByThread: [String: [CodeMessage]] = [:]
+ public var codeComposerText = ""
+ public var codeComposerAttachments: [CodeImageAttachment] = []
+ public var codeDraftsByKey: [String: CodeComposerDraft] = [:]
+ public var codeNewThreadBaseBranch: String? = nil
+ public var isCodeThreadFindPresented = false
+ public var codeThreadFindQuery = ""
+ public var codeThreadHasMoreByThread: [String: Bool] = [:]
+ public var codeThreadTotalCountByThread: [String: Int] = [:]
+ public var isLoadingOlderCodeMessages = false
+ public var isCompactingCodeThread = false
+ public var codeApprovalRules: [CodeApprovalRule] = []
+
+ // Git, PR, CI, Review & Inspector state
+ public var codeGitStatusByProject: [String: CodeGitStatus] = [:]
+ public var codeGitStatusByThread: [String: CodeGitStatus] = [:]
+ public var codeGitFileDiffs: [String: CodeGitFileDiff] = [:]
+ public var isLoadingCodeGit = false
+ @ObservationIgnored var codeGitLoadCount = 0
+ public var codeGitBranchDiffByProject: [String: CodeGitBranchDiff] = [:]
+ public var codeGitPRByProject: [String: CodeGitPRStatusResponse] = [:]
+ public var codeGitPRByThread: [String: CodeGitPRStatusResponse] = [:]
+ public var codeGitPRDetailsByProject: [String: CodeGitPRDetails] = [:]
+ public var codeGitCILogsByKey: [String: CodeGitCILogResponse] = [:]
+ public var codeGitCommitLogByProject: [String: [CodeGitCommitEntry]] = [:]
+ public var codeGitCommitDiffByKey: [String: CodeGitCommitDiff] = [:]
+ public var codeReviewResultByProject: [String: CodeReviewResponse] = [:]
+ public var codeGitStashesByProject: [String: [CodeGitStashEntry]] = [:]
+ public var isBusyCodeGitOp = false
+ public var isLoadingCodePRDetails = false
+ public var isLoadingCodeCILogs = false
+ public var isLoadingCodeCommitLog = false
+ public var isRunningCodeReview = false
+
+ // Local CLI session discovery & import
+ public var codeCLISessions: [CodeCLISessionSummary] = []
+ public var isLoadingCodeCLISessions = false
+ public var isCLISessionImportSheetPresented = false
+
+ // Built-in Web Preview state
+ public var codePreviewURLByProject: [String: String] = [:]
+ public var codeDetectedPreviewURLByProject: [String: String] = [:]
+ public var codePreviewConsoleByProject: [String: [CodePreviewConsoleEntry]] = [:]
+ public var codePreviewDevServerSessionByProject: [String: String] = [:]
+
+ // Workspace file tree
+ public var codeWorkspaceTreeByKey: [String: [CodeWorkspaceTreeEntry]] = [:]
+ public internal(set) var codeWorkspaceTreeLoadingKeys: Set = []
+ public internal(set) var codeWorkspaceTreeErrorByKey: [String: String] = [:]
+ public var isLoadingCodeTree = false
+
+ // Multi-tab & split-pane interactive PTY terminal
+ public var codeTerminalSessions: [String: CodeTerminalSession] = [:]
+ public var codeTerminalOutputs: [String: String] = [:]
+ @ObservationIgnored var codeTerminalScreens: [String: TerminalScreen] = [:]
+ @ObservationIgnored var codeTerminalStreamTasks: [String: Task] = [:]
+ public var codeTerminalTabsByScope: [String: [CodeTerminalTab]] = [:]
+ public var activeCodeTerminalTabByScope: [String: String] = [:]
+ public var codeTerminalSplitKeyByPrimary: [String: String] = [:]
+ public var codeTerminalStyledLines: [String: [TerminalStyledLine]] = [:]
+ public var codeTerminalCursorByKey: [String: CodeTerminalCursorState] = [:]
+ public var codeTerminalMouseModeByKey: [String: TerminalMouseMode] = [:]
+ public var codeTerminalSGRMouseByKey: [String: Bool] = [:]
+
+ // Composer history & drafts
+ public var codePromptHistory: [String] = [] {
+ didSet {
+ UserDefaults.standard.set(Array(codePromptHistory.prefix(100)), forKey: Self.savedCodePromptHistoryKey)
+ }
+ }
+ public var codeDraftRevisionByThread: [String: Int] = [:]
+
+ // Skills, Harness config, Project scripts & Daemon health
+ public var codeSkills: [CodeSkillItem] = []
+ public var codeHarnessConfig: CodeHarnessConfig? = nil
+ public var isLoadingCodeHarnessConfig = false
+ public var codeProjectScriptsByProject: [String: [CodeProjectScript]] = [:]
+ public var localBridgeHealth: CodeDaemonHealth? = nil
+
+ // Custom providers & per-provider execution harness
+ public var customProviders: [CustomProvider] = []
+ public var customProviderPresets: [CustomProviderPreset] = []
+ public var isLoadingCustomProviders = false
+ public var providerHarnesses: [String: String] = ["claude": "morphcode", "codex": "morphcode"]
+ public var orchestratorModel: String = "claude/claude-sonnet-5-5"
+ public var workerDefaultModel: String = ""
+ public var workerEffort: String = ""
+ public var workerHarnesses: [String: String] = ["claude": "morphcode", "codex": "morphcode"]
+ public var nativeCliAvailable: [String: Bool] = [:]
+ public var providerKeyStatus: [String: Bool] = [:]
+ public var providerBaseURLs: [String: String] = [:]
+ public var isSavingProviderHarnesses = false
+
+ // Archive, project ordering, triage & search
+ public var isCodeArchivePresented = false
+ public var codeProjectOrder: [String] = [] {
+ didSet {
+ UserDefaults.standard.set(codeProjectOrder, forKey: Self.savedCodeProjectOrderKey)
+ }
+ }
+ public var collapsedCodeProjectIds: Set = [] {
+ didSet {
+ UserDefaults.standard.set(Array(collapsedCodeProjectIds).sorted(), forKey: Self.savedCollapsedCodeProjectsKey)
+ }
+ }
+ public internal(set) var stickyTriageThreadId: String? = nil
+ public internal(set) var stickyTriageStatus: CodeThreadVisualStatus? = nil
+ @ObservationIgnored var pendingReadThreadIds: Set = []
+ @ObservationIgnored var snoozeWakeupTask: Task? = nil
+ public internal(set) var snoozeClockTick: Int = 0
+ public var codeSearchHits: [CodeSearchHit] = []
+ public var codePendingFileViewer: CodeFileOpenRequest? = nil
+
+ // Layout & Notification preferences
+ public var codeSidebarWidth: CGFloat = 272 {
+ didSet {
+ let clamped = min(420, max(220, codeSidebarWidth))
+ if clamped != codeSidebarWidth { codeSidebarWidth = clamped; return }
+ UserDefaults.standard.set(Double(clamped), forKey: Self.savedCodeSidebarWidthKey)
+ }
+ }
+ public var codeInspectorWidth: CGFloat = 380 {
+ didSet {
+ let clamped = min(760, max(320, codeInspectorWidth))
+ if clamped != codeInspectorWidth { codeInspectorWidth = clamped; return }
+ UserDefaults.standard.set(Double(clamped), forKey: Self.savedCodeInspectorWidthKey)
+ }
+ }
+ public var codeNotificationsEnabled: Bool = true {
+ didSet { UserDefaults.standard.set(codeNotificationsEnabled, forKey: Self.savedCodeNotificationsKey) }
+ }
+ public var codeNotifyTurnDone: Bool = true {
+ didSet { UserDefaults.standard.set(codeNotifyTurnDone, forKey: Self.savedCodeNotifyTurnDoneKey) }
+ }
+ public var codeNotifyTurnFailed: Bool = true {
+ didSet { UserDefaults.standard.set(codeNotifyTurnFailed, forKey: Self.savedCodeNotifyTurnFailedKey) }
+ }
+ public var codeNotifyAttention: Bool = true {
+ didSet { UserDefaults.standard.set(codeNotifyAttention, forKey: Self.savedCodeNotifyAttentionKey) }
+ }
+ public var codeNotificationSoundEnabled: Bool = true {
+ didSet { UserDefaults.standard.set(codeNotificationSoundEnabled, forKey: Self.savedCodeNotificationSoundKey) }
+ }
+ @ObservationIgnored public var codeOnNotificationEvent: ((CodeNotificationEvent) -> Void)? = nil
+
+ // Dialogs & composer settings
+ public var codeThreadPendingRename: CodeThread?
+ public var codeThreadPendingDelete: CodeThread?
+ public var codeThreadPendingDelegate: CodeThread?
+ public internal(set) var codeComposerProcessingImages = 0
+ public var codeFollowUpMode: CodeFollowUpMode = .steer {
+ didSet { UserDefaults.standard.set(codeFollowUpMode.rawValue, forKey: Self.savedCodeFollowUpModeKey) }
+ }
+ public var codeTitleStyle: CodeTitleStyle = .summary {
+ didSet { UserDefaults.standard.set(codeTitleStyle.rawValue, forKey: Self.savedCodeTitleStyleKey) }
+ }
+ public var codeTitleFormat: String = MorphAppState.defaultCodeTitleFormat {
+ didSet { UserDefaults.standard.set(codeTitleFormat, forKey: Self.savedCodeTitleFormatKey) }
+ }
+ public static let defaultCodeTitleFormat = "[TAG] Concise summary"
+
+ // Live streaming runs
+ public internal(set) var codeLiveRuns: [String: CodeLiveRun] = [:]
+ public internal(set) var pendingDraftCodeRun: CodeLiveRun?
+ var codeStreamTasks: [String: Task] = [:]
+ @ObservationIgnored public var isCodeThreadOnScreen = true
+ @ObservationIgnored var keptUnreadThreadId: String?
+ public var codeTurnErrorBanner: (threadId: String, message: String)?
+ public internal(set) var codeFileSearchResults: [String] = []
+ var codeFileCache: [String: Data] = [:]
+ var codeFileCacheOrder: [String] = []
+
+ public var selectedCodeModel: String = "claude/claude-sonnet-5-5"
+ public var selectedCodeTarget: CodeExecutionTarget = .local
+ public var selectedCodeAccessMode: CodeAccessMode = .defaultPermissions
+ public var selectedCodeEffort: CodeReasoningEffort = .medium
+ public var isCodeInspectorPresented = false
+ public var codeInspectorSection: CodeInspectorSection = .preview
+ public var codeDestination: CodeDestination = .threads
+ public var selectedCodeScheduleId: String?
+ var codeThreadBeforeScheduled: String?
+ public var codeScheduleDraft: CodeScheduleDraft?
+ public internal(set) var composerFocusRequest = 0
+
+ // Connection & Notices
+ public var notice: MorphNotice?
+ public internal(set) var serverURLString: String
+ public internal(set) var memberId: String = "local"
+
+ let store: LocalStore
+ var syncEngine: SyncEngine
+ public internal(set) var isRefreshingCodeQuotas: Bool = false
+ @ObservationIgnored var loginSessionTransports: [String: any MorphTransport] = [:]
+ @ObservationIgnored var voiceSessionCache = VoiceTranscriptionSessionCache()
+ @ObservationIgnored var voiceSessionFetchTask: Task?
+ @ObservationIgnored var isShowingCodeAttentionInDock = false
+
+ public static let defaultDaemonURL = URL(string: "http://\(MacBridgeAgent.listenAddress)")!
+ public static let minimumSupportedDaemonVersion = "0.3.0"
+ static let savedThemeModeKey = "ai.anymorph.morphcode.themeMode"
+ static let savedCodeFollowUpModeKey = "ai.anymorph.morphcode.codeFollowUpMode"
+ static let savedCodeTitleStyleKey = "ai.anymorph.morphcode.codeTitleStyle"
+ static let savedCodeTitleFormatKey = "ai.anymorph.morphcode.codeTitleFormat"
+ static let savedCodeSidebarWidthKey = "ai.anymorph.morphcode.codeSidebarWidth"
+ static let savedCodeInspectorWidthKey = "ai.anymorph.morphcode.codeInspectorWidth"
+ static let savedCodeNotificationsKey = "ai.anymorph.morphcode.codeNotificationsEnabled"
+ static let savedCodeNotifyTurnDoneKey = "ai.anymorph.morphcode.codeNotifyTurnDone"
+ static let savedCodeNotifyTurnFailedKey = "ai.anymorph.morphcode.codeNotifyTurnFailed"
+ static let savedCodeNotifyAttentionKey = "ai.anymorph.morphcode.codeNotifyAttention"
+ static let savedCodeNotificationSoundKey = "ai.anymorph.morphcode.codeNotificationSoundEnabled"
+ static let savedCodePromptHistoryKey = "ai.anymorph.morphcode.codePromptHistory"
+ static let savedCodeProjectOrderKey = "ai.anymorph.morphcode.codeProjectOrder"
+ static let savedCollapsedCodeProjectsKey = "ai.anymorph.morphcode.collapsedCodeProjects"
+
+ public init(daemonURL: URL? = nil) {
+ let environment = ProcessInfo.processInfo.environment
+ let resolvedURL = daemonURL
+ ?? environment["MORPHCODE_DAEMON_URL"].flatMap(URL.init(string:))
+ ?? Self.defaultDaemonURL
+ self.serverURLString = resolvedURL.absoluteString
+
+ if let savedTheme = UserDefaults.standard.string(forKey: Self.savedThemeModeKey),
+ let parsedTheme = MorphThemeMode(rawValue: savedTheme) {
+ self.themeMode = parsedTheme
+ }
+ if let savedFollowUp = UserDefaults.standard.string(forKey: Self.savedCodeFollowUpModeKey),
+ let parsedFollowUp = CodeFollowUpMode(rawValue: savedFollowUp) {
+ self.codeFollowUpMode = parsedFollowUp
+ }
+ if let savedTitleStyle = UserDefaults.standard.string(forKey: Self.savedCodeTitleStyleKey),
+ let parsedTitleStyle = CodeTitleStyle(rawValue: savedTitleStyle) {
+ self.codeTitleStyle = parsedTitleStyle
+ }
+ if let savedTitleFormat = UserDefaults.standard.string(forKey: Self.savedCodeTitleFormatKey),
+ !savedTitleFormat.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ self.codeTitleFormat = savedTitleFormat
+ }
+ let savedSidebarW = UserDefaults.standard.double(forKey: Self.savedCodeSidebarWidthKey)
+ if savedSidebarW >= 220 && savedSidebarW <= 420 {
+ self.codeSidebarWidth = CGFloat(savedSidebarW)
+ }
+ let savedInspectorW = UserDefaults.standard.double(forKey: Self.savedCodeInspectorWidthKey)
+ if savedInspectorW >= 320 && savedInspectorW <= 760 {
+ self.codeInspectorWidth = CGFloat(savedInspectorW)
+ }
+ if UserDefaults.standard.object(forKey: Self.savedCodeNotificationsKey) != nil {
+ self.codeNotificationsEnabled = UserDefaults.standard.bool(forKey: Self.savedCodeNotificationsKey)
+ }
+ if UserDefaults.standard.object(forKey: Self.savedCodeNotifyTurnDoneKey) != nil {
+ self.codeNotifyTurnDone = UserDefaults.standard.bool(forKey: Self.savedCodeNotifyTurnDoneKey)
+ }
+ if UserDefaults.standard.object(forKey: Self.savedCodeNotifyTurnFailedKey) != nil {
+ self.codeNotifyTurnFailed = UserDefaults.standard.bool(forKey: Self.savedCodeNotifyTurnFailedKey)
+ }
+ if UserDefaults.standard.object(forKey: Self.savedCodeNotifyAttentionKey) != nil {
+ self.codeNotifyAttention = UserDefaults.standard.bool(forKey: Self.savedCodeNotifyAttentionKey)
+ }
+ if UserDefaults.standard.object(forKey: Self.savedCodeNotificationSoundKey) != nil {
+ self.codeNotificationSoundEnabled = UserDefaults.standard.bool(forKey: Self.savedCodeNotificationSoundKey)
+ }
+ if let savedHistory = UserDefaults.standard.stringArray(forKey: Self.savedCodePromptHistoryKey) {
+ self.codePromptHistory = savedHistory
+ }
+ if let savedOrder = UserDefaults.standard.stringArray(forKey: Self.savedCodeProjectOrderKey) {
+ self.codeProjectOrder = savedOrder
+ }
+ if let savedCollapsed = UserDefaults.standard.stringArray(forKey: Self.savedCollapsedCodeProjectsKey) {
+ self.collapsedCodeProjectIds = Set(savedCollapsed)
+ }
+
+ let dbPath = Self.defaultDatabasePath()
+ let openedStore = (try? LocalStore(path: dbPath)) ?? (try! LocalStore(path: ":memory:"))
+ self.store = openedStore
+ let daemonTransport = URLSessionMorphTransport(
+ baseURL: resolvedURL,
+ token: nil,
+ memberId: "local",
+ session: Self.codeRPCSession,
+ streamSession: Self.codeStreamSession
+ )
+ self.syncEngine = SyncEngine(store: openedStore, transport: daemonTransport)
+
+ if let cachedMac = try? openedStore.cachedMacCodeState() {
+ self.localCodeState = cachedMac
+ }
+ rebuildCodeCaches()
+ let initialThread = defaultInitialCodeThread
+ self.selectedCodeThreadId = initialThread?.id
+ if let initialThread {
+ adoptComposerSettings(of: initialThread)
+ }
+ if let firstId = selectedCodeThreadId,
+ let msgs = try? openedStore.cachedCodeMessages(threadId: firstId),
+ !msgs.isEmpty {
+ self.codeMessagesByThread[firstId] = msgs
+ }
+ if let persistedDrafts = try? openedStore.loadAllCodeDrafts() {
+ for (key, text) in persistedDrafts where !text.isEmpty {
+ self.codeDraftsByKey[key] = CodeComposerDraft(text: text)
+ }
+ self.restoreCurrentCodeDraft()
+ }
+ }
+
+ public var appVersionDisplay: String {
+ let info = Bundle.main.infoDictionary
+ let short = (info?["CFBundleShortVersionString"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "4.0.0"
+ let build = (info?["CFBundleVersion"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return build.isEmpty ? "v\(short)" : "v\(short) (\(build))"
+ }
+
+ // MARK: - Notices
+
+ public func showInfo(_ text: String) {
+ notice = MorphNotice(kind: .info, text: text)
+ }
+
+ public func showError(_ text: String) {
+ notice = MorphNotice(kind: .error, text: text)
+ }
+
+ // MARK: - Storage
+
+ static func defaultDatabasePath() -> String {
+ if ProcessInfo.processInfo.environment["MORPH_EPHEMERAL_DB"] == "1" {
+ return ":memory:"
+ }
+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
+ let dir = base?.appendingPathComponent("MorphCode", isDirectory: true)
+ if let dir {
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ return dir.appendingPathComponent("morphcode-v4.sqlite3").path
+ }
+ return ":memory:"
+ }
+}
+
+struct LocalBridgeUnavailable: LocalizedError {
+ var errorDescription: String? {
+ "Unable to connect to the local morphcode daemon on \(MacBridgeAgent.listenAddress)."
+ }
+}
diff --git a/apple/Apps/Shared/MorphAppTypes.swift b/apple/Apps/Shared/MorphAppTypes.swift
new file mode 100644
index 000000000..f17e5544c
--- /dev/null
+++ b/apple/Apps/Shared/MorphAppTypes.swift
@@ -0,0 +1,235 @@
+import Foundation
+import Observation
+import MorphCore
+
+public enum MorphThemeMode: String, CaseIterable, Identifiable {
+ case system
+ case light
+ case dark
+
+ public var id: String { rawValue }
+
+ public var label: String {
+ switch self {
+ case .system: return "System"
+ case .light: return "Light"
+ case .dark: return "Dark"
+ }
+ }
+}
+
+/// Sections of the Morph Code settings dialog.
+public enum MorphSettingsSection: String, CaseIterable, Identifiable, Hashable {
+ case general
+ case notifications
+ case providers
+ case harness
+
+ public var id: String { rawValue }
+
+ public var title: String {
+ switch self {
+ case .general: return "General"
+ case .notifications: return "Notifications"
+ case .providers: return "Providers & Models"
+ case .harness: return "Harness & MCP"
+ }
+ }
+
+ public var systemImage: String {
+ switch self {
+ case .general: return "gearshape"
+ case .notifications: return "bell"
+ case .providers: return "cpu"
+ case .harness: return "wrench.and.screwdriver"
+ }
+ }
+}
+
+/// One interactive terminal tab inside a project or worktree scope.
+public struct CodeTerminalTab: Identifiable, Equatable, Sendable {
+ public let id: String
+ public var title: String
+ public let sessionKey: String
+
+ public init(id: String = UUID().uuidString, title: String, sessionKey: String) {
+ self.id = id
+ self.title = title
+ self.sessionKey = sessionKey
+ }
+}
+
+/// Snapshot of cursor and dimensions for rendering a live interactive terminal view.
+public struct CodeTerminalCursorState: Equatable, Sendable {
+ public var row: Int
+ public var column: Int
+ public var visible: Bool
+ public var columns: Int
+ public var rows: Int
+ public var isAlternateScreen: Bool
+
+ public init(row: Int = 0, column: Int = 0, visible: Bool = true, columns: Int = 100, rows: Int = 28, isAlternateScreen: Bool = false) {
+ self.row = row
+ self.column = column
+ self.visible = visible
+ self.columns = columns
+ self.rows = rows
+ self.isAlternateScreen = isAlternateScreen
+ }
+}
+
+/// Request to open a workspace file in the code reader, optionally scrolled to a 1-based line number.
+public struct CodeFileOpenRequest: Identifiable, Equatable, Sendable {
+ public let id = UUID()
+ public let projectId: String
+ public let threadId: String?
+ public let path: String
+ public let line: Int?
+ public let isLocal: Bool
+
+ public init(projectId: String, threadId: String?, path: String, line: Int? = nil, isLocal: Bool = true) {
+ self.projectId = projectId
+ self.threadId = threadId
+ self.path = path
+ self.line = line
+ self.isLocal = isLocal
+ }
+}
+
+/// Background event emitted for macOS desktop notifications and optional completion sounds.
+public struct CodeNotificationEvent: Sendable, Equatable {
+ public enum Kind: String, Sendable {
+ case turnCompleted
+ case turnFailed
+ case approvalRequired
+ case questionRequired
+ }
+
+ public let kind: Kind
+ public let threadId: String
+ public let title: String
+ public let subtitle: String?
+ public let body: String
+
+ public init(kind: Kind, threadId: String, title: String, subtitle: String? = nil, body: String) {
+ self.kind = kind
+ self.threadId = threadId
+ self.title = title
+ self.subtitle = subtitle
+ self.body = body
+ }
+}
+
+public struct MorphNotice: Identifiable, Equatable {
+ public enum Kind: Equatable {
+ case info
+ case error
+ }
+
+ public let id = UUID()
+ public let kind: Kind
+ public let text: String
+}
+
+/// What Morph Code's main area shows: the open thread or scheduled tasks.
+public enum CodeDestination: Hashable, Sendable {
+ case threads
+ case scheduled
+}
+
+/// What the scheduled task editor opens on: an existing task or a new task draft.
+public struct CodeScheduleDraft: Identifiable {
+ public let id = UUID()
+ public var schedule: CodeSchedule?
+ public var threadId: String?
+}
+
+/// A turn running on a Morph Code thread. Stream events update its timeline immediately, and published snapshots
+/// are throttled to ~66 ms so active streaming stays smooth.
+@MainActor
+@Observable
+public final class CodeLiveRun {
+ public let launchId = UUID()
+ public var threadId: String
+ public var pendingPrompt: String?
+ public var pendingImages: [CodeImageAttachment]
+ public var submittedMessageId: String?
+ public let pendingModel: String?
+ public let pendingEffort: CodeReasoningEffort?
+ @ObservationIgnored public let launchedAt: Date
+ public private(set) var startedAt: Date
+ public private(set) var entries: [CodeTurnBlock] = []
+ public internal(set) var approval: CodeApproval?
+ public private(set) var question: CodeUserQuestion?
+ public private(set) var activity = "Working.."
+ public var isCancelling = false
+
+ @ObservationIgnored private var timeline = CodeLiveTimeline()
+ @ObservationIgnored private var isPublishScheduled = false
+
+ public init(
+ threadId: String,
+ pendingPrompt: String? = nil,
+ pendingImages: [CodeImageAttachment] = [],
+ pendingModel: String? = nil,
+ pendingEffort: CodeReasoningEffort? = nil,
+ startedAt: Date = Date()
+ ) {
+ self.threadId = threadId
+ self.pendingPrompt = pendingPrompt
+ self.pendingImages = pendingImages
+ self.pendingModel = pendingModel
+ self.pendingEffort = pendingEffort
+ self.launchedAt = Date()
+ self.startedAt = startedAt
+ }
+
+ func apply(_ event: CodeStreamEvent) {
+ timeline.apply(event)
+ switch event.type {
+ case "snapshot":
+ if let started = event.message.flatMap({ MorphPalette.parseDate($0.createdAt) }) {
+ startedAt = started
+ }
+ publish()
+ case "approval_required", "approval_decided", "question_required", "question_answered":
+ publish()
+ default:
+ schedulePublish()
+ }
+ }
+
+ func addPendingInput(id: String, content: String) {
+ timeline.addPendingInput(id: id, content: content)
+ publish()
+ }
+
+ func removePendingInput(id: String) {
+ timeline.removePendingInput(id: id)
+ publish()
+ }
+
+ private func schedulePublish() {
+ guard !isPublishScheduled else { return }
+ isPublishScheduled = true
+ Task { [weak self] in
+ try? await Task.sleep(for: .milliseconds(66))
+ self?.publish()
+ }
+ }
+
+ private func publish() {
+ isPublishScheduled = false
+ entries = timeline.entries
+ if approval != timeline.approval {
+ approval = timeline.approval
+ }
+ if question != timeline.question {
+ question = timeline.question
+ }
+ let current = CodeTurnSummary.activity(timeline.entries, approval: timeline.approval, question: timeline.question)
+ if current != activity {
+ activity = current
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphCLISessionImportSheet.swift b/apple/Apps/Shared/MorphCLISessionImportSheet.swift
new file mode 100644
index 000000000..41ebc2e88
--- /dev/null
+++ b/apple/Apps/Shared/MorphCLISessionImportSheet.swift
@@ -0,0 +1,197 @@
+import SwiftUI
+import MorphCore
+
+/// 로컬 CLI 세션 가져오기: the Claude Code and Codex sessions on this Mac, newest first, to bring one into Morph Code as
+/// a thread with its conversation. Opened from the Morph Code sidebar, ⌘⇧I and ⌘K. Filters by CLI, and searches the
+/// session title, project and folder.
+struct MorphCLISessionImportSheet: View {
+ @Bindable var state: MorphAppState
+ @Environment(\.dismiss) private var dismiss
+ @State private var provider: CLISessionProviderFilter = .all
+ @State private var query = ""
+ /// The session being imported, so its button waits and the others stay put.
+ @State private var importingSessionId: String?
+
+ private var sessions: [CodeCLISessionSummary] {
+ let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ return state.codeCLISessions.filter { session in
+ let matchesProvider = provider == .all || session.provider.lowercased() == provider.rawValue
+ let matchesQuery = needle.isEmpty
+ || session.title.lowercased().contains(needle)
+ || session.projectName.lowercased().contains(needle)
+ || session.cwd.lowercased().contains(needle)
+ return matchesProvider && matchesQuery
+ }
+ }
+
+ var body: some View {
+ NavigationStack {
+ VStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphSegmentControl(
+ items: CLISessionProviderFilter.allCases,
+ selection: $provider,
+ label: { $0.label }
+ )
+ .fixedSize()
+ AnymorphTextField(
+ "세션 제목, 프로젝트, 폴더 검색",
+ text: $query,
+ leadingSystemImage: "magnifyingglass",
+ appearance: .filled
+ )
+ }
+ .padding(.horizontal, 16)
+ .padding(.top, 8)
+ .padding(.bottom, 12)
+
+ AnymorphDivider()
+
+ content
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .background(AnymorphColor.bgBase)
+ .navigationTitle("로컬 CLI 세션 가져오기")
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("닫기") { dismiss() }
+ .font(AnymorphFonts.font(.body, weight: .emphasis))
+ }
+ ToolbarItem(placement: .primaryAction) {
+ Button {
+ Task { await state.refreshCodeCLISessions(provider: provider.rawValue) }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .disabled(state.isLoadingCodeCLISessions)
+ .help("다시 불러오기")
+ .accessibilityLabel("다시 불러오기")
+ }
+ }
+ }
+ .tint(AnymorphColor.fgPrimary)
+ #if os(macOS)
+ .frame(minWidth: 520, idealWidth: 600, minHeight: 520, idealHeight: 620)
+ #else
+ .presentationDetents([.medium, .large])
+ .presentationDragIndicator(.visible)
+ #endif
+ .task(id: provider) {
+ await state.refreshCodeCLISessions(provider: provider.rawValue)
+ }
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ let list = sessions
+ if state.isLoadingCodeCLISessions && state.codeCLISessions.isEmpty {
+ VStack(spacing: 10) {
+ ProgressView()
+ .controlSize(.small)
+ Text("이 Mac의 CLI 세션을 찾고 있습니다")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else if list.isEmpty {
+ VStack(spacing: 8) {
+ MorphTileIcon("terminal", size: 40)
+ Text(state.codeCLISessions.isEmpty ? "찾은 CLI 세션이 없습니다" : "검색과 맞는 세션이 없습니다")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Text(state.codeCLISessions.isEmpty
+ ? "이 Mac에서 Claude Code나 Codex로 작업한 세션이 여기에 나옵니다."
+ : "다른 검색어나 CLI를 골라 보세요.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ }
+ .padding(24)
+ } else {
+ List {
+ ForEach(list) { session in
+ row(session)
+ .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .environment(\.defaultMinListRowHeight, 0)
+ }
+ }
+
+ private func row(_ session: CodeCLISessionSummary) -> some View {
+ let kind = CLISessionProviderFilter(provider: session.provider)
+ let isImporting = importingSessionId == session.id
+ return HStack(alignment: .center, spacing: 12) {
+ if let brand = kind?.brand {
+ MorphServiceIcon(brand: brand)
+ } else {
+ MorphServiceIcon("terminal")
+ }
+
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ Text(session.title.isEmpty ? "제목 없는 세션" : session.title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ AnymorphBadge(kind?.label ?? session.provider)
+ }
+ Text(session.projectName.isEmpty ? session.cwd : "\(session.projectName) · \(session.cwd)")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ .truncationMode(.head)
+ Text("메시지 \(session.messageCount)개 · \(MorphPalette.listTimeLabel(session.updatedAt))")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Button(isImporting ? "가져오는 중…" : "가져오기") {
+ importingSessionId = session.id
+ Task {
+ await state.importCodeCLISession(session)
+ importingSessionId = nil
+ }
+ }
+ .morphPill(.secondary)
+ .disabled(importingSessionId != nil)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ .contentShape(Rectangle())
+ }
+}
+
+/// The CLIs the import sheet lists, and the provider value the bridge filters by.
+private enum CLISessionProviderFilter: String, CaseIterable, Identifiable, Hashable {
+ case all
+ case claude
+ case codex
+
+ var id: String { rawValue }
+
+ init?(provider: String) {
+ switch provider.lowercased() {
+ case "claude": self = .claude
+ case "codex": self = .codex
+ default: return nil
+ }
+ }
+
+ var label: String {
+ switch self {
+ case .all: return "전체"
+ case .claude: return "Claude Code"
+ case .codex: return "Codex"
+ }
+ }
+
+ var brand: MorphBrand? {
+ switch self {
+ case .all: return nil
+ case .claude: return .claude
+ case .codex: return .openai
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodeArchiveView.swift b/apple/Apps/Shared/MorphCodeArchiveView.swift
new file mode 100644
index 000000000..688f96883
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeArchiveView.swift
@@ -0,0 +1,264 @@
+import SwiftUI
+import MorphCore
+
+/// Unified archive and snoozed drawer opened from the profile menu (`설정` → `보관함`) or `⌘K`.
+/// Lists archived threads (including legacy settled threads) latest-first, plus a `나중에 보기` section whenever
+/// snoozed threads exist, with search, 1-click restore, and delete.
+struct MorphCodeArchiveView: View {
+ @Bindable var state: MorphAppState
+ /// Opens a thread once the archive has closed.
+ var onOpenThread: (CodeThread) -> Void
+ @Environment(\.dismiss) private var dismiss
+ @State private var query = ""
+ @State private var threadPendingDelete: CodeThread?
+
+ private var trimmedQuery: String {
+ query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ }
+
+ private func projectName(for thread: CodeThread) -> String? {
+ state.codeProjects.first { $0.id == thread.projectId }?.name
+ }
+
+ private func matchesQuery(_ thread: CodeThread) -> Bool {
+ guard !trimmedQuery.isEmpty else { return true }
+ let proj = projectName(for: thread)?.lowercased() ?? ""
+ return thread.title.lowercased().contains(trimmedQuery)
+ || proj.contains(trimmedQuery)
+ || (thread.branch?.lowercased().contains(trimmedQuery) ?? false)
+ }
+
+ var body: some View {
+ let _ = state.snoozeClockTick
+ NavigationStack {
+ VStack(spacing: 0) {
+ if !state.archivedCodeThreads.isEmpty || !state.snoozedCodeThreads.isEmpty {
+ AnymorphTextField("보관함 검색", text: $query, leadingSystemImage: "magnifyingglass", appearance: .filled)
+ .padding(.horizontal, 12)
+ .padding(.top, 8)
+ .padding(.bottom, 6)
+ }
+ content
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .background(AnymorphColor.bgBase)
+ .navigationTitle("보관함")
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("완료") { dismiss() }
+ .font(AnymorphFonts.font(.body, weight: .emphasis))
+ }
+ }
+ }
+ .tint(AnymorphColor.fgPrimary)
+ #if os(macOS)
+ .frame(minWidth: 460, minHeight: 500)
+ #else
+ .presentationDetents([.medium, .large])
+ .presentationDragIndicator(.visible)
+ #endif
+ .morphDialog(item: $threadPendingDelete) { thread in
+ MorphDialogContent.deleteCodeThread(thread, state: state)
+ }
+ // The archive is a sheet on its own window: its dialog shows over the sheet.
+ .morphDialogHost()
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ let archived = state.archivedCodeThreads.filter(matchesQuery)
+ let snoozed = state.snoozedCodeThreads.filter(matchesQuery)
+ let hasAny = !state.archivedCodeThreads.isEmpty || !state.snoozedCodeThreads.isEmpty
+ if !hasAny {
+ VStack(spacing: 8) {
+ MorphTileIcon("archivebox", size: 40)
+ Text("보관한 스레드가 없습니다")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Text("스레드를 보관하면 여기에서 다시 찾거나 목록으로 되돌릴 수 있습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 24)
+ }
+ } else if archived.isEmpty && snoozed.isEmpty {
+ VStack(spacing: 8) {
+ MorphTileIcon("magnifyingglass", size: 36)
+ Text("일치하는 스레드가 없습니다")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ } else {
+ List {
+ if !snoozed.isEmpty {
+ sectionHeader("나중에 보기", count: snoozed.count)
+ ForEach(snoozed) { thread in
+ snoozedRow(thread)
+ }
+ }
+ if !archived.isEmpty {
+ if !snoozed.isEmpty {
+ sectionHeader("보관됨", count: archived.count)
+ }
+ ForEach(archived) { thread in
+ archivedRow(thread)
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .environment(\.defaultMinListRowHeight, 0)
+ .animation(AnymorphMotion.base, value: archived.map(\.id) + snoozed.map(\.id))
+ }
+ }
+
+ private func sectionHeader(_ title: String, count: Int) -> some View {
+ HStack(spacing: 6) {
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Text("\(count)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 12)
+ .padding(.top, 8)
+ .padding(.bottom, 2)
+ .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ }
+
+ private func archivedRow(_ thread: CodeThread) -> some View {
+ let target = state.codeTarget(of: thread)
+ let project = projectName(for: thread)
+ return MorphSidebarRow(
+ thread.title,
+ subtitle: [project, state.codeTargetLabel(target)].compactMap { $0 }.joined(separator: " · "),
+ meta: MorphPalette.listTimeLabel(thread.archiveTimestamp ?? thread.updatedAt),
+ action: { onOpenThread(thread) },
+ leading: {
+ Image(systemName: target.systemImage)
+ .symbolRenderingMode(.monochrome)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ },
+ trailing: {
+ #if os(macOS)
+ Button {
+ restore(thread)
+ } label: {
+ Image(systemName: "tray.and.arrow.up")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 24, height: 24)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("목록으로 되돌리기")
+ .accessibilityLabel("목록으로 되돌리기")
+ #endif
+ }
+ )
+ .listRowInsets(EdgeInsets(top: 1, leading: 8, bottom: 1, trailing: 8))
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {
+ Button {
+ restore(thread)
+ } label: {
+ Label("되돌리기", systemImage: "tray.and.arrow.up")
+ }
+ .tint(AnymorphColor.swipePrimary)
+ Button {
+ threadPendingDelete = thread
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ .tint(AnymorphColor.swipeSecondary)
+ }
+ .contextMenu {
+ Button {
+ restore(thread)
+ } label: {
+ Label("목록으로 되돌리기", systemImage: "tray.and.arrow.up")
+ }
+ Divider()
+ Button(role: .destructive) {
+ threadPendingDelete = thread
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ }
+ }
+
+ private func snoozedRow(_ thread: CodeThread) -> some View {
+ let project = projectName(for: thread)
+ let untilLabel = thread.snoozedUntil.map { MorphPalette.listTimeLabel($0) }
+ return MorphSidebarRow(
+ thread.title,
+ subtitle: [project, untilLabel.map { "\($0)까지 보류" } ?? "나중에 보기"].compactMap { $0 }.joined(separator: " · "),
+ action: { onOpenThread(thread) },
+ leading: {
+ Image(systemName: "moon.zzz")
+ .symbolRenderingMode(.monochrome)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ },
+ trailing: {
+ Button("보류 해제") {
+ unsnooze(thread)
+ }
+ .morphPill(.secondary)
+ }
+ )
+ .listRowInsets(EdgeInsets(top: 1, leading: 8, bottom: 1, trailing: 8))
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {
+ Button {
+ unsnooze(thread)
+ } label: {
+ Label("보류 해제", systemImage: "sun.max")
+ }
+ .tint(AnymorphColor.swipePrimary)
+ Button {
+ archiveFromSnooze(thread)
+ } label: {
+ Label("보관", systemImage: "archivebox")
+ }
+ .tint(AnymorphColor.swipeSecondary)
+ }
+ .contextMenu {
+ Button {
+ unsnooze(thread)
+ } label: {
+ Label("보류 해제", systemImage: "sun.max")
+ }
+ Button {
+ archiveFromSnooze(thread)
+ } label: {
+ Label("보관", systemImage: "archivebox")
+ }
+ Divider()
+ Button(role: .destructive) {
+ threadPendingDelete = thread
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ }
+ }
+
+ private func restore(_ thread: CodeThread) {
+ Task { await state.archiveCodeThread(id: thread.id, archived: false) }
+ }
+
+ private func unsnooze(_ thread: CodeThread) {
+ Task { await state.snoozeCodeThread(id: thread.id, until: nil) }
+ }
+
+ private func archiveFromSnooze(_ thread: CodeThread) {
+ Task { await state.archiveCodeThread(id: thread.id, archived: true) }
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodeComposerMenus.swift b/apple/Apps/Shared/MorphCodeComposerMenus.swift
new file mode 100644
index 000000000..cc614fc06
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeComposerMenus.swift
@@ -0,0 +1,1124 @@
+import SwiftUI
+import UniformTypeIdentifiers
+import MorphCore
+#if os(macOS)
+import AppKit
+#endif
+
+// MARK: - Morph Code composer menus
+//
+// The controls on the Morph Code composer, each opening a dropdown drawn as Claude's model menu is: the model and its
+// effort in one button, the permission mode, the + menu, and on the new-thread screen the project and where the
+// thread works.
+
+/// The composer's model button: clean model title only (effort lives in the standalone gauge button beside it).
+/// The menu lists Auto, compact capability tiers (`Best`, `Standard`, `Stealth`), and `다른 모델` (including GPT).
+struct MorphCodeModelMenu: View {
+ @Bindable var state: MorphAppState
+ @Binding var model: String
+ @Binding var effort: CodeReasoningEffort
+
+ var body: some View {
+ let options = state.availableCodeModels
+ let selection = model
+ let current = CodeModelMenu.current(selection, in: options)
+ let name = current.map(CodeModelMenu.name) ?? CodeModelMenu.name(of: selection, in: options)
+ let unavailableReason = current.flatMap(CodeModelMenu.unavailableReason)
+ MorphDropdown(placement: .aboveTrailing, width: 300, name: "code-model") {
+ let sections = CodeModelMenu.sections(options, selection: selection)
+ MorphCodeModelRows(sections: sections, selection: selection) { id in
+ select(id, in: options)
+ }
+ MorphCodeMoreModels(groups: sections.more, selection: selection) { id in
+ select(id, in: options)
+ }
+ } label: {
+ MorphComposerControlLabel(
+ glyph: selection == "orchestrator"
+ ? .symbol("point.3.connected.trianglepath.dotted")
+ : (current.flatMap(MorphBrand.init(codeModel:)).map { .brand($0) } ?? .symbol("sparkles")),
+ title: name,
+ tint: unavailableReason == nil ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary,
+ showsChevron: false
+ )
+ }
+ .help(unavailableReason.map { "\(name): \($0)" } ?? "모델 선택")
+ .accessibilityLabel("모델 \(name)")
+ }
+
+ /// Picks a model. An effort the model does not run at moves to the model's nearest level.
+ private func select(_ id: String, in options: [CodeModelOption]) {
+ model = id
+ effort = effort.nearest(in: CodeModelMenu.efforts(of: id, in: options))
+ }
+}
+
+/// Standalone Effort gauge icon button on the composer bar (no box/border — bare precision gauge icon).
+/// Opens a clean interactive dial popover adapted to the active model's supported effort levels.
+struct MorphCodeEffortMenu: View {
+ @Bindable var state: MorphAppState
+ let model: String
+ @Binding var effort: CodeReasoningEffort
+
+ var body: some View {
+ let levels = CodeModelMenu.efforts(of: model, in: state.availableCodeModels)
+ if !levels.isEmpty {
+ let active = effort.nearest(in: levels)
+ MorphDropdown(placement: .aboveTrailing, width: 252, name: "code-effort") {
+ MorphEffortGaugeDial(selection: $effort, levels: levels)
+ } label: {
+ MorphEffortGaugeIcon(selection: active, levels: levels)
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ .modifier(MorphComposerHoverPlate())
+ }
+ .help("Effort: \(active.label)")
+ .accessibilityLabel("Effort \(active.label)")
+ }
+ }
+}
+
+/// Minimalist monochrome semi-circle gauge icon rendered directly on the composer bar (no enclosing box).
+struct MorphEffortGaugeIcon: View {
+ let selection: CodeReasoningEffort
+ let levels: [CodeReasoningEffort]
+ var tint: Color = AnymorphColor.fgPrimary
+
+ private var fraction: Double {
+ guard levels.count > 1 else { return 0.5 }
+ let idx = levels.firstIndex(of: selection) ?? 0
+ return Double(idx) / Double(levels.count - 1)
+ }
+
+ var body: some View {
+ Canvas { context, size in
+ let w = size.width
+ let h = size.height
+ let cx = w / 2
+ let cy = h * 0.72
+ let r = min(w * 0.41, h * 0.56)
+ let startDeg = -175.0
+ let sweepDeg = 170.0
+ let activeSweep = max(14.0, sweepDeg * (fraction == 0 ? 0.12 : fraction))
+ let needleRad = (startDeg + sweepDeg * fraction) * .pi / 180.0
+
+ // Background arc
+ var track = Path()
+ track.addArc(
+ center: CGPoint(x: cx, y: cy),
+ radius: r,
+ startAngle: .degrees(startDeg),
+ endAngle: .degrees(startDeg + sweepDeg),
+ clockwise: false
+ )
+ context.stroke(
+ track,
+ with: .color(tint.opacity(0.26)),
+ style: StrokeStyle(lineWidth: 1.85, lineCap: .round)
+ )
+
+ // Active progress arc
+ var fill = Path()
+ fill.addArc(
+ center: CGPoint(x: cx, y: cy),
+ radius: r,
+ startAngle: .degrees(startDeg),
+ endAngle: .degrees(startDeg + activeSweep),
+ clockwise: false
+ )
+ context.stroke(
+ fill,
+ with: .color(tint),
+ style: StrokeStyle(lineWidth: 2.0, lineCap: .round)
+ )
+
+ // Needle
+ let tip = CGPoint(
+ x: cx + (r - 1.6) * cos(needleRad),
+ y: cy + (r - 1.6) * sin(needleRad)
+ )
+ var needle = Path()
+ needle.move(to: CGPoint(x: cx, y: cy))
+ needle.addLine(to: tip)
+ context.stroke(
+ needle,
+ with: .color(tint),
+ style: StrokeStyle(lineWidth: 1.6, lineCap: .round)
+ )
+
+ // Hub dot
+ let hub = CGRect(x: cx - 1.5, y: cy - 1.5, width: 3.0, height: 3.0)
+ context.fill(Path(ellipseIn: hub), with: .color(tint))
+ }
+ .frame(width: 20, height: 18)
+ }
+}
+
+/// Interactive precision tachometer dial for picking reasoning effort (supports click and drag right on the dial).
+/// Automatically adapts its major ticks and stop dots to the active model's supported effort levels.
+private struct MorphEffortGaugeDial: View {
+ @Binding var selection: CodeReasoningEffort
+ let levels: [CodeReasoningEffort]
+
+ private var activeIndex: Int {
+ guard !levels.isEmpty else { return 0 }
+ let clamped = selection.nearest(in: levels)
+ return levels.firstIndex(of: clamped) ?? 0
+ }
+
+ private var activeEffort: CodeReasoningEffort {
+ guard levels.indices.contains(activeIndex) else { return selection }
+ return levels[activeIndex]
+ }
+
+ private var progress: Double {
+ guard levels.count > 1 else { return 0.5 }
+ return Double(activeIndex) / Double(levels.count - 1)
+ }
+
+ /// Angle in degrees relative to straight up (0° = top, -84° = far left, +84° = far right).
+ private func angleForStop(_ index: Int) -> Double {
+ guard levels.count > 1 else { return 0 }
+ let t = Double(index) / Double(levels.count - 1)
+ return -84.0 + 168.0 * t
+ }
+
+ private func subtitle(for effort: CodeReasoningEffort) -> String {
+ switch effort {
+ case .low: return "가볍고 즉시 응답"
+ case .medium: return "속도와 품질의 기본 균형"
+ case .high: return "복잡한 디버깅과 설계"
+ case .xhigh: return "여러 경로를 꼼꼼히 검증"
+ case .max: return "가능한 최고 깊이로 사고"
+ }
+ }
+
+ var body: some View {
+ let dialWidth: CGFloat = 216
+ let dialHeight: CGFloat = 114
+ let center = CGPoint(x: dialWidth / 2, y: 100)
+ let radius: CGFloat = 76
+ let activeAngle = angleForStop(activeIndex)
+
+ VStack(spacing: 10) {
+ ZStack {
+ Canvas { context, _ in
+ // Outer radial ticks: major ticks aligned with every supported effort stop + minor subdivisions.
+ let intervals = max(1, levels.count - 1)
+ let subdivisionsPerInterval = 4
+ let totalTicks = intervals * subdivisionsPerInterval
+ for i in 0...totalTicks {
+ let t = Double(i) / Double(totalTicks)
+ let degFromTop = -84.0 + 168.0 * t
+ let rad = (degFromTop - 90.0) * .pi / 180.0
+ let isMajor = (i % subdivisionsPerInterval == 0)
+ let innerR = radius + 9
+ let outerR = radius + (isMajor ? 15.5 : 12.0)
+ var tick = Path()
+ tick.move(to: CGPoint(x: center.x + innerR * cos(rad), y: center.y + innerR * sin(rad)))
+ tick.addLine(to: CGPoint(x: center.x + outerR * cos(rad), y: center.y + outerR * sin(rad)))
+ context.stroke(
+ tick,
+ with: .color(AnymorphColor.fgPrimary.opacity(isMajor ? 0.55 : 0.2)),
+ style: StrokeStyle(lineWidth: isMajor ? 1.7 : 1.0, lineCap: .round)
+ )
+ }
+
+ // Background track arc
+ var track = Path()
+ track.addArc(
+ center: center,
+ radius: radius,
+ startAngle: .degrees(-174),
+ endAngle: .degrees(-6),
+ clockwise: false
+ )
+ context.stroke(
+ track,
+ with: .color(AnymorphColor.fgPrimary.opacity(0.14)),
+ style: StrokeStyle(lineWidth: 7.5, lineCap: .round)
+ )
+
+ // Inner stop dots for each supported level
+ for i in levels.indices {
+ let degFromTop = angleForStop(i)
+ let rad = (degFromTop - 90.0) * .pi / 180.0
+ let dotR = radius - 14.5
+ let pt = CGPoint(x: center.x + dotR * cos(rad), y: center.y + dotR * sin(rad))
+ let isLit = i <= activeIndex
+ let dotRect = CGRect(x: pt.x - 2.2, y: pt.y - 2.2, width: 4.4, height: 4.4)
+ context.fill(
+ Path(ellipseIn: dotRect),
+ with: .color(AnymorphColor.fgPrimary.opacity(isLit ? 0.9 : 0.22))
+ )
+ }
+ }
+ .frame(width: dialWidth, height: dialHeight)
+
+ // Animated active arc
+ MorphDialArcShape(
+ center: center,
+ radius: radius,
+ startDegrees: -174,
+ endDegrees: -6
+ )
+ .trim(from: 0, to: max(0.06, progress))
+ .stroke(AnymorphColor.fgPrimary, style: StrokeStyle(lineWidth: 7.5, lineCap: .round))
+ .frame(width: dialWidth, height: dialHeight)
+ .animation(.spring(response: 0.26, dampingFraction: 0.82), value: progress)
+
+ // Animated tapered precision needle + hub
+ ZStack {
+ MorphDialNeedleShape(pivot: center, tipY: center.y - (radius - 11))
+ .fill(AnymorphColor.fgPrimary)
+ .rotationEffect(
+ .degrees(activeAngle),
+ anchor: UnitPoint(x: center.x / dialWidth, y: center.y / dialHeight)
+ )
+ .animation(.spring(response: 0.26, dampingFraction: 0.82), value: activeAngle)
+
+ Circle()
+ .fill(AnymorphColor.fgPrimary)
+ .frame(width: 11, height: 11)
+ .position(center)
+
+ Circle()
+ .fill(AnymorphColor.menuSurface)
+ .frame(width: 4.5, height: 4.5)
+ .position(center)
+ }
+ .frame(width: dialWidth, height: dialHeight)
+ }
+ .frame(width: dialWidth, height: dialHeight)
+ .contentShape(Rectangle())
+ .highPriorityGesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { value in
+ pickLevel(at: value.location, center: center)
+ }
+ )
+ .sensoryFeedback(.selection, trigger: activeIndex)
+
+ VStack(spacing: 3) {
+ Text(activeEffort.label)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .contentTransition(.numericText())
+ Text(subtitle(for: activeEffort))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.top, 14)
+ .padding(.bottom, 12)
+ }
+
+ private func pickLevel(at point: CGPoint, center: CGPoint) {
+ guard levels.count > 1 else { return }
+ let dx = Double(point.x - center.x)
+ let dy = Double(point.y - center.y)
+ var degFromTop = atan2(dy, dx) * 180.0 / .pi + 90.0
+ if degFromTop > 180.0 { degFromTop -= 360.0 }
+ let clamped = max(-84.0, min(84.0, degFromTop))
+ let ratio = (clamped + 84.0) / 168.0
+ let idx = Int(round(ratio * Double(levels.count - 1)))
+ let safeIdx = max(0, min(levels.count - 1, idx))
+ if levels[safeIdx] != selection {
+ selection = levels[safeIdx]
+ }
+ }
+}
+
+private struct MorphDialArcShape: Shape {
+ let center: CGPoint
+ let radius: CGFloat
+ let startDegrees: Double
+ let endDegrees: Double
+
+ func path(in _: CGRect) -> Path {
+ var p = Path()
+ p.addArc(
+ center: center,
+ radius: radius,
+ startAngle: .degrees(startDegrees),
+ endAngle: .degrees(endDegrees),
+ clockwise: false
+ )
+ return p
+ }
+}
+
+private struct MorphDialNeedleShape: Shape {
+ let pivot: CGPoint
+ let tipY: CGFloat
+
+ func path(in _: CGRect) -> Path {
+ var p = Path()
+ p.move(to: CGPoint(x: pivot.x, y: tipY))
+ p.addLine(to: CGPoint(x: pivot.x + 2.4, y: pivot.y))
+ p.addLine(to: CGPoint(x: pivot.x - 2.4, y: pivot.y))
+ p.closeSubpath()
+ return p
+ }
+}
+
+/// Auto and the curated tier groups (`Best`, `Standard`, `Stealth`), for the composer's model menu and the scheduled
+/// task editor. Unavailable models stay in the list, drawn quieter, with the reason on their subtitle (or header for
+/// single-engine groups).
+struct MorphCodeModelRows: View {
+ let sections: CodeModelMenu.Sections
+ let selection: String
+ let onSelect: (String) -> Void
+
+ var body: some View {
+ if let auto = sections.auto {
+ MorphMenuItem(
+ auto.name,
+ subtitle: CodeModelMenu.unavailableReason(auto) ?? CodeModelMenu.purpose(auto),
+ isSelected: selection == auto.id,
+ isMuted: auto.available == false,
+ id: auto.id
+ ) {
+ onSelect(auto.id)
+ }
+ MorphMenuDivider()
+ }
+ MorphCodeModelGroups(groups: sections.main, selection: selection, onSelect: onSelect)
+ }
+}
+
+/// 다른 모델 at the end of a model menu: the models Morph does not feature up front, opening beside it.
+struct MorphCodeMoreModels: View {
+ let groups: [CodeModelMenu.EngineGroup]
+ let selection: String
+ let onSelect: (String) -> Void
+
+ var body: some View {
+ if !groups.isEmpty {
+ MorphMenuDivider()
+ MorphMenuSubmenu("다른 모델", width: 280, id: "more-models") {
+ MorphCodeModelGroups(groups: groups, selection: selection, onSelect: onSelect)
+ }
+ }
+ }
+}
+
+/// Each tier or engine group header over its models.
+private struct MorphCodeModelGroups: View {
+ let groups: [CodeModelMenu.EngineGroup]
+ let selection: String
+ let onSelect: (String) -> Void
+
+ var body: some View {
+ ForEach(Array(groups.enumerated()), id: \.element.id) { index, group in
+ if index > 0 {
+ MorphMenuDivider()
+ }
+ let headerStatus = group.status
+ MorphMenuSectionHeader(group.title ?? MorphEngine.name(for: group.provider), status: headerStatus)
+ ForEach(group.options) { option in
+ let defaultSubtitle: String? = {
+ if option.id == "orchestrator" {
+ let live = option.detail.trimmingCharacters(in: .whitespacesAndNewlines)
+ return live.isEmpty ? CodeModelMenu.purpose(option) : live
+ }
+ return CodeModelMenu.purpose(option)
+ }()
+ let itemSubtitle: String? = {
+ if headerStatus == nil, let reason = CodeModelMenu.unavailableReason(option) {
+ return reason
+ }
+ return defaultSubtitle
+ }()
+ MorphMenuItem(
+ CodeModelMenu.name(option),
+ subtitle: itemSubtitle,
+ isSelected: CodeModelMenu.isSameModel(option.id, selection),
+ isMuted: option.available == false,
+ id: option.id
+ ) {
+ onSelect(option.id)
+ }
+ }
+ }
+ }
+}
+
+/// The Effort submenu, as Claude's: what effort changes, then each level the model runs at, Medium marked 추천.
+struct MorphEffortRows: View {
+ let selection: CodeReasoningEffort
+ let levels: [CodeReasoningEffort]
+ let onSelect: (CodeReasoningEffort) -> Void
+
+ var body: some View {
+ MorphMenuNote("높일수록 더 꼼꼼하게 작업하지만 오래 걸리고 한도를 더 빨리 씁니다.")
+ ForEach(levels) { effort in
+ MorphMenuItem(
+ effort.label,
+ tag: effort == .medium ? MorphMenuTag("추천") : nil,
+ isSelected: effort == selection,
+ id: "effort-\(effort.rawValue)"
+ ) {
+ onSelect(effort)
+ }
+ }
+ }
+}
+
+/// The permission mode, muted for Default, amber for Full access and indigo for Plan, as Codex marks them. It sets
+/// the mode it is given: the composer's own, or a thread window's.
+struct MorphCodeAccessModeMenu: View {
+ @Binding var mode: CodeAccessMode
+ #if os(iOS)
+ @Environment(\.horizontalSizeClass) private var sizeClass
+ #endif
+
+ var body: some View {
+ MorphDropdown(placement: .aboveLeading, width: 304, name: "code-access") {
+ MorphAccessModeRows(selection: mode) { option in
+ mode = option
+ }
+ #if os(macOS)
+ MorphMenuDivider()
+ MorphMenuNote("입력창에서 ⇧⇥를 누르면 다음 모드로 바뀝니다.")
+ #endif
+ } label: {
+ MorphComposerControlLabel(
+ glyph: mode == .defaultPermissions ? .symbol(mode.systemImage) : .none,
+ title: title(mode),
+ collapsedSymbol: mode.systemImage,
+ tint: mode.composerTint,
+ titleWeight: mode == .defaultPermissions ? .emphasis : .strong
+ )
+ }
+ #if os(macOS)
+ .help("권한 모드 · ⇧⇥")
+ #else
+ .help("권한 모드")
+ #endif
+ .accessibilityLabel("권한 모드 \(mode.label)")
+ }
+
+ /// An iPhone's composer has room for the model and its effort only with the mode's short name, Default.
+ private func title(_ mode: CodeAccessMode) -> String {
+ #if os(iOS)
+ if sizeClass == .compact {
+ return mode.shortLabel
+ }
+ #endif
+ return mode.label
+ }
+}
+
+/// Each permission mode with what it lets the agent do, for the composer and the scheduled task editor.
+struct MorphAccessModeRows: View {
+ let selection: CodeAccessMode
+ let onSelect: (CodeAccessMode) -> Void
+
+ var body: some View {
+ ForEach(CodeAccessMode.allCases) { option in
+ MorphMenuItem(
+ option.label,
+ subtitle: option.detail,
+ icon: .symbol(option.systemImage),
+ isSelected: option == selection,
+ id: option.rawValue
+ ) {
+ onSelect(option)
+ }
+ }
+ }
+}
+
+/// One way the + menu attaches images.
+struct MorphComposerAttachAction: Identifiable {
+ let id: String
+ let title: String
+ let icon: String
+ var shortcut: String?
+ let perform: () -> Void
+}
+
+/// The + at the start of the action bar: attach images, open a pane, or manage plugins.
+struct MorphCodeToolsMenu: View {
+ @Bindable var state: MorphAppState
+ let attachActions: [MorphComposerAttachAction]
+
+ var body: some View {
+ MorphDropdown(placement: .aboveLeading, width: 248, name: "code-tools") {
+ ForEach(attachActions) { attach in
+ MorphMenuItem(attach.title, icon: .symbol(attach.icon), trailing: attach.shortcut, action: attach.perform)
+ }
+ MorphMenuDivider()
+ MorphMenuItem("터미널 패널 열기", icon: .symbol("terminal")) {
+ state.codeInspectorSection = .terminal
+ state.isCodeInspectorPresented = true
+ }
+ MorphMenuItem("문서·산출물 보기", icon: .symbol("doc.text")) {
+ state.codeInspectorSection = .artifacts
+ state.isCodeInspectorPresented = true
+ }
+ MorphMenuDivider()
+ MorphMenuItem("Harness & MCP Settings", icon: .symbol("wrench.and.screwdriver")) {
+ state.openSettings(.harness)
+ }
+ } label: {
+ MorphComposerPlusLabel()
+ }
+ .help("첨부 · 도구")
+ .accessibilityLabel("첨부 · 도구")
+ }
+}
+
+/// Where the new thread goes, on the new-thread screen's shelf: a folder project, or a folder to add.
+struct MorphCodeProjectMenu: View {
+ @Bindable var state: MorphAppState
+ let project: CodeProject?
+
+ var body: some View {
+ MorphDropdown(placement: .aboveLeading, width: 256, name: "code-project") {
+ MorphCodeProjectRows(state: state, isChecked: { $0 == project?.id }) { projectId in
+ state.startNewCodeThread(projectId: projectId)
+ }
+ } label: {
+ MorphComposerControlLabel(
+ glyph: .symbol("folder"),
+ title: project?.name ?? "Select project",
+ tint: AnymorphColor.fgSecondary,
+ titleWeight: .base
+ )
+ }
+ .help("프로젝트")
+ }
+}
+
+/// The places a new thread can go, for the sidebar's new-thread button and the new-thread screen's project menu:
+/// the folder projects, and 폴더 추가…, which adds a folder as a project and opens the new-thread screen there.
+struct MorphCodeProjectRows: View {
+ @Bindable var state: MorphAppState
+ /// Whether a project carries the check, by its id. The sidebar's button checks none.
+ var isChecked: (String) -> Bool = { _ in false }
+ let onSelect: (String) -> Void
+
+ var body: some View {
+ let projects = state.codeFolderProjects
+ if !projects.isEmpty {
+ MorphMenuSectionHeader("프로젝트")
+ ForEach(projects) { option in
+ MorphMenuItem(option.name, icon: .symbol("folder"), isSelected: isChecked(option.id), id: option.id) {
+ onSelect(option.id)
+ }
+ }
+ MorphMenuDivider()
+ }
+ MorphMenuItem("폴더 추가…", icon: .symbol("folder.badge.plus"), id: "add-folder") {
+ state.pickCodeFolder()
+ }
+ }
+}
+
+/// How the new thread works: directly in the project's local folder or in an isolated git worktree.
+struct MorphCodeRunModeMenu: View {
+ @Bindable var state: MorphAppState
+
+ var body: some View {
+ let draft = state.codeNewThreadDraft
+ let mode = draft?.mode ?? .local
+ MorphDropdown(placement: .aboveLeading, width: 280, name: "code-mode") {
+ ForEach(state.codeNewThreadChoices(projectId: draft?.projectId)) { option in
+ MorphMenuItem(
+ state.codeNewThreadModeLabel(option),
+ subtitle: detail(option),
+ icon: .symbol(option.systemImage),
+ isSelected: option == mode,
+ id: option.rawValue
+ ) {
+ state.setCodeNewThreadMode(option)
+ }
+ }
+ } label: {
+ MorphComposerControlLabel(
+ glyph: .symbol(mode.systemImage),
+ title: state.codeNewThreadModeLabel(mode),
+ collapsedSymbol: mode.systemImage,
+ tint: AnymorphColor.fgPrimary
+ )
+ .symbolRenderingMode(.monochrome)
+ }
+ .help("Execution mode")
+ .task(id: draft?.projectId) {
+ guard let projectId = draft?.projectId else { return }
+ await state.refreshCodeGitStatus(projectId: projectId)
+ }
+ }
+
+ private func detail(_ mode: CodeNewThreadMode) -> String {
+ switch mode {
+ case .local:
+ return "Work directly in the local repository folder"
+ case .worktree:
+ return "Create an isolated git worktree on a new branch"
+ }
+ }
+}
+
+extension MorphBrand {
+ /// The logo of a Morph Code model: its maker's or its provider's.
+ init?(codeModel option: CodeModelOption) {
+ let model = option.id.split(separator: "/").last.map(String.init) ?? option.id
+ guard let brand = MorphBrand(model: model) ?? MorphBrand(provider: option.provider) else { return nil }
+ self = brand
+ }
+
+ /// The engine of a model id such as claude/claude-opus-5-5 or codex/gpt-6.2-astra, also when the model list
+ /// no longer has it; nil for Auto.
+ init?(codeModelId id: String) {
+ let parts = id.split(separator: "/").map(String.init)
+ guard let model = parts.last,
+ let brand = MorphBrand(model: model) ?? (parts.count > 1 ? MorphBrand(provider: parts[0]) : nil) else { return nil }
+ self = brand
+ }
+}
+
+/// The open thread's actions beside its title in the header, as Codex keeps them under … at the top of a chat. The
+/// main window and a thread's own window both head the thread with it.
+struct MorphCodeThreadActionsMenu: View {
+ @Bindable var state: MorphAppState
+ let thread: CodeThread
+ /// Renaming, scheduling and deleting ask over the main window, so a thread's own window leaves them out.
+ var includesMainWindowActions = true
+
+ var body: some View {
+ MorphDropdown(placement: .belowLeading, width: 236, name: "code-thread-actions") {
+ if includesMainWindowActions {
+ MorphMenuItem("이름 변경…", icon: .symbol("pencil")) {
+ state.codeThreadPendingRename = thread
+ }
+ MorphMenuItem("제목 다시 짓기", icon: .symbol("sparkles")) {
+ Task { await state.regenerateCodeThreadTitle(id: thread.id) }
+ }
+ if thread.isSnoozed {
+ MorphMenuItem("보류 해제", icon: .symbol("sun.max")) {
+ Task { await state.snoozeCodeThread(id: thread.id, until: nil) }
+ }
+ } else {
+ MorphMenuItem("1시간 뒤 다시 보기", icon: .symbol("moon.zzz")) {
+ Task { await state.snoozeCodeThread(id: thread.id, until: MorphAppState.snoozeOneHourISO()) }
+ }
+ MorphMenuItem("내일 오전 9시 다시 보기", icon: .symbol("sunrise")) {
+ Task { await state.snoozeCodeThread(id: thread.id, until: MorphAppState.snoozeTomorrowMorningISO()) }
+ }
+ }
+ MorphMenuItem("위임 작업 시작…", icon: .symbol("arrow.triangle.branch")) {
+ state.codeThreadPendingDelegate = thread
+ }
+ MorphMenuItem("이 스레드에서 예약…", icon: .symbol("clock")) {
+ state.editCodeSchedule(threadId: thread.id)
+ }
+ }
+ MorphMenuItem("Markdown 내보내기", icon: .symbol("square.and.arrow.down")) {
+ exportMarkdown()
+ }
+ if thread.provider.lowercased() == "claude" || thread.provider.lowercased() == "codex" {
+ MorphMenuItem("터미널 CLI에서 이어서 하기", icon: .symbol("terminal")) {
+ continueInCLI()
+ }
+ }
+ MorphMenuDivider()
+ MorphMenuItem("대화 분기", icon: .symbol("arrow.triangle.branch")) {
+ Task { await state.forkCodeThread(threadId: thread.id) }
+ }
+ if state.codeGitStatusByProject[thread.projectId]?.isRepo != false {
+ MorphMenuItem("새 Worktree로 분기", icon: .symbol("arrow.triangle.pull")) {
+ Task { await state.forkCodeThreadWithOptions(threadId: thread.id, createWorktree: true) }
+ }
+ }
+ MorphMenuDivider()
+ MorphMenuItem(
+ thread.isEffectivelyArchived ? "목록으로 되돌리기" : "보관",
+ icon: .symbol(thread.isEffectivelyArchived ? "tray.and.arrow.up" : "archivebox")
+ ) {
+ Task { await state.archiveCodeThread(id: thread.id, archived: !thread.isEffectivelyArchived) }
+ }
+ if includesMainWindowActions {
+ MorphMenuDivider()
+ MorphMenuItem("삭제", icon: .symbol("trash")) {
+ state.codeThreadPendingDelete = thread
+ }
+ }
+ } label: {
+ Image(systemName: "ellipsis")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 26, height: 26)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxl))
+ }
+ .help("스레드 작업")
+ .accessibilityLabel("스레드 작업")
+ }
+
+ private func continueInCLI() {
+ let threadId = thread.id
+ Task {
+ guard let handoff = await state.fetchCodeCLIHandoff(threadId: threadId) else { return }
+ let command = handoff.command?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ guard handoff.available, !command.isEmpty else {
+ let reason = handoff.reason?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ state.showInfo(reason.isEmpty ? "이 스레드는 터미널 CLI에서 이어갈 수 없습니다." : reason)
+ return
+ }
+ #if os(macOS)
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(command, forType: .string)
+ #else
+ UIPasteboard.general.string = command
+ #endif
+ state.showInfo("터미널 CLI 재개 명령을 복사했습니다.")
+ }
+ }
+
+ /// Saves the conversation as a Markdown file on a Mac; iPhone and iPad copy it to the clipboard.
+ private func exportMarkdown() {
+ let threadId = thread.id
+ Task {
+ guard let export = await state.exportCodeThreadMarkdown(threadId: threadId) else { return }
+ #if os(macOS)
+ let panel = NSSavePanel()
+ panel.nameFieldStringValue = export.filename
+ panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]
+ panel.canCreateDirectories = true
+ panel.prompt = "저장"
+ let save: (NSApplication.ModalResponse) -> Void = { response in
+ guard response == .OK, let url = panel.url else { return }
+ do {
+ try export.markdown.write(to: url, atomically: true, encoding: .utf8)
+ state.showInfo("\(url.lastPathComponent)(으)로 내보냈습니다.")
+ } catch {
+ state.showError("Markdown 파일을 저장하지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+ if let window = NSApp.keyWindow ?? NSApp.mainWindow {
+ panel.beginSheetModal(for: window, completionHandler: save)
+ } else {
+ save(panel.runModal())
+ }
+ #else
+ MorphClipboard.copy(export.markdown)
+ state.showInfo("대화를 Markdown으로 클립보드에 복사했습니다.")
+ #endif
+ }
+ }
+}
+
+/// The branch a new worktree thread starts from, on the new-thread screen's shelf.
+struct MorphCodeBaseBranchMenu: View {
+ @Bindable var state: MorphAppState
+ let projectId: String
+
+ var body: some View {
+ let status = state.codeGitStatusByProject[projectId]
+ let branches = status?.branches ?? []
+ let current = state.codeNewThreadBaseBranch ?? status?.branch ?? "main"
+ MorphDropdown(placement: .aboveLeading, width: 260, name: "code-base-branch") {
+ MorphMenuSectionHeader("기준 브랜치")
+ ForEach(branches, id: \.self) { branch in
+ MorphMenuItem(branch, icon: .symbol("arrow.triangle.branch"), isSelected: branch == current, id: "base-\(branch)") {
+ state.codeNewThreadBaseBranch = branch
+ }
+ }
+ } label: {
+ MorphComposerControlLabel(
+ glyph: .symbol("arrow.triangle.branch"),
+ title: "기준 브랜치: \(current)",
+ shortTitle: current,
+ tint: AnymorphColor.fgSecondary,
+ titleWeight: .base
+ )
+ }
+ .disabled(branches.isEmpty)
+ .help("새 worktree가 시작할 브랜치")
+ }
+}
+
+/// How full the open thread's context window is, "42% · 84k/200k", amber from 75%, with 압축 to summarize the
+/// conversation and free room.
+struct MorphCodeContextMeter: View {
+ @Bindable var state: MorphAppState
+ let threadId: String
+ let usage: CodeTokenUsage
+ var compact = false
+
+ static func tokens(_ count: Int64) -> String {
+ if count >= 1_000_000 {
+ return String(format: "%.1fM", Double(count) / 1_000_000)
+ }
+ if count >= 1_000 {
+ return "\(Int((Double(count) / 1_000).rounded()))k"
+ }
+ return String(count)
+ }
+
+ var body: some View {
+ let fraction = usage.contextFraction
+ let percent = Int((fraction * 100).rounded())
+ let tint = fraction > 0.75 ? AnymorphColor.caution : AnymorphColor.fgTertiary
+ HStack(spacing: 6) {
+ ZStack {
+ Circle().stroke(AnymorphColor.strokeBase, lineWidth: 2)
+ Circle()
+ .trim(from: 0, to: fraction)
+ .stroke(tint, style: StrokeStyle(lineWidth: 2, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ }
+ .frame(width: 12, height: 12)
+ Text(compact ? "\(percent)%" : "\(percent)% · \(Self.tokens(usage.contextTokens))/\(Self.tokens(usage.contextWindow))")
+ .anymorphText(.caption, weight: .base, color: tint, tabular: true)
+ .lineLimit(1)
+ if state.isCompactingCodeThread {
+ ProgressView().controlSize(.mini)
+ } else {
+ Button("압축") {
+ Task { await state.compactCodeThread(threadId: threadId) }
+ }
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .help("대화를 요약해 컨텍스트 여유를 확보합니다 (/compact)")
+ }
+ }
+ .padding(.horizontal, 7)
+ .frame(height: 28)
+ .fixedSize()
+ .modifier(MorphComposerHoverPlate())
+ .help("컨텍스트 \(Self.tokens(usage.contextTokens)) / \(Self.tokens(usage.contextWindow)) 토큰")
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("컨텍스트 \(percent)% 사용")
+ }
+}
+
+// MARK: - Slash commands and @ mentions
+
+/// A `/` command in the composer: a built-in mode, effort or action, or a skill found for the project.
+struct MorphCodeSlashCommand: Identifiable {
+ enum Action {
+ case accessMode(CodeAccessMode)
+ case effort(CodeReasoningEffort)
+ case compact
+ case loop
+ case review
+ case clear
+ case diff
+ case terminal
+ case fork
+ case newThread
+ case skill(CodeSkillItem)
+ }
+
+ let id: String
+ let command: String
+ let title: String
+ let detail: String
+ let icon: String
+ let action: Action
+
+ static let builtIns: [MorphCodeSlashCommand] = [
+ MorphCodeSlashCommand(id: "plan", command: "/plan", title: "계획 모드", detail: "읽기 전용 분석·설계 후 승인 구현", icon: "list.bullet.clipboard", action: .accessMode(.plan)),
+ MorphCodeSlashCommand(id: "default", command: "/default", title: "기본 권한 모드", detail: "위험 작업 실행 전 승인 요청", icon: "checkmark.shield", action: .accessMode(.defaultPermissions)),
+ MorphCodeSlashCommand(id: "full", command: "/full", title: "전체 접근 모드", detail: "워크스페이스 자동 실행 허용", icon: "bolt", action: .accessMode(.fullAccess)),
+ MorphCodeSlashCommand(id: "low", command: "/low", title: "추론 강도: Low", detail: "가장 빠른 응답", icon: "gauge.low", action: .effort(.low)),
+ MorphCodeSlashCommand(id: "medium", command: "/medium", title: "추론 강도: Medium", detail: "속도·품질 균형 기본값", icon: "gauge.medium", action: .effort(.medium)),
+ MorphCodeSlashCommand(id: "high", command: "/high", title: "추론 강도: High", detail: "복잡한 설계·디버깅", icon: "gauge.high", action: .effort(.high)),
+ MorphCodeSlashCommand(id: "xhigh", command: "/xhigh", title: "추론 강도: Extra high", detail: "High보다 꼼꼼하게", icon: "gauge.with.dots.needle.67percent", action: .effort(.xhigh)),
+ MorphCodeSlashCommand(id: "max", command: "/max", title: "추론 강도: Max", detail: "가장 꼼꼼하게", icon: "gauge.with.dots.needle.100percent", action: .effort(.max)),
+ MorphCodeSlashCommand(id: "compact", command: "/compact", title: "대화 압축", detail: "대화를 요약해 컨텍스트 여유 확보", icon: "arrow.down.right.and.arrow.up.left", action: .compact),
+ MorphCodeSlashCommand(id: "loop", command: "/loop", title: "반복 루프", detail: "주기 반복 실행 · /loop 5m CI 확인 · /loop stop", icon: "repeat", action: .loop),
+ MorphCodeSlashCommand(id: "review", command: "/review", title: "변경사항 리뷰", detail: "작업 트리·브랜치 diff 리뷰 요청", icon: "checklist", action: .review),
+ MorphCodeSlashCommand(id: "clear", command: "/clear", title: "새 대화", detail: "현재 프로젝트에서 새 스레드 시작", icon: "square.and.pencil", action: .clear),
+ MorphCodeSlashCommand(id: "diff", command: "/diff", title: "변경사항 (Git Diff)", detail: "파일·Hunk 단위 diff·스테이징·커밋", icon: "doc.badge.gearshape", action: .diff),
+ MorphCodeSlashCommand(id: "terminal", command: "/terminal", title: "인터랙티브 터미널", detail: "실시간 PTY 셸 열기", icon: "terminal", action: .terminal),
+ MorphCodeSlashCommand(id: "fork", command: "/fork", title: "대화 분기", detail: "현재 시점에서 새 스레드로 복제", icon: "arrow.triangle.branch", action: .fork),
+ MorphCodeSlashCommand(id: "new", command: "/new", title: "새 작업 스레드", detail: "현재 프로젝트에서 새 스레드 시작", icon: "plus.bubble", action: .newThread),
+ ]
+
+ /// The built-ins, then one command per skill whose name no built-in takes.
+ static func all(skills: [CodeSkillItem]) -> [MorphCodeSlashCommand] {
+ let taken = Set(builtIns.map(\.id))
+ var seen = Set()
+ let skillCommands = skills.compactMap { skill -> MorphCodeSlashCommand? in
+ let name = skill.name.lowercased()
+ guard !taken.contains(name), seen.insert(name).inserted else { return nil }
+ return MorphCodeSlashCommand(
+ id: "skill:\(skill.id)",
+ command: "/\(skill.name)",
+ title: skill.name,
+ detail: skill.description,
+ icon: "book.closed",
+ action: .skill(skill)
+ )
+ }
+ return builtIns + skillCommands
+ }
+
+ /// The commands the composer's text calls up: the text is one `/word` with nothing after it.
+ static func matching(_ text: String, skills: [CodeSkillItem], limit: Int = 8) -> [MorphCodeSlashCommand] {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard trimmed.hasPrefix("/"), !trimmed.contains(" "), !trimmed.contains("\n") else { return [] }
+ let needle = String(trimmed.dropFirst()).lowercased()
+ let commands = all(skills: skills)
+ guard !needle.isEmpty else { return Array(commands.prefix(limit)) }
+ // Commands whose name starts with the text come first, then ones that mention it.
+ let prefixed = commands.filter { $0.command.dropFirst().lowercased().hasPrefix(needle) }
+ let mentioned = commands.filter { command in
+ !command.command.dropFirst().lowercased().hasPrefix(needle)
+ && (command.command.lowercased().contains(needle)
+ || command.title.lowercased().contains(needle)
+ || command.detail.lowercased().contains(needle))
+ }
+ return Array((prefixed + mentioned).prefix(limit))
+ }
+
+ /// The request a skill command starts: the agent reads the skill's SKILL.md and follows it.
+ static func skillPrompt(_ skill: CodeSkillItem) -> String {
+ "\(skill.name) 스킬(`\(skill.path)`)을 읽고 그 지침대로 다음 작업을 해 주세요: "
+ }
+
+ static let reviewPrompt = """
+ 현재 변경사항을 리뷰해 주세요. 작업 트리의 `git diff`와 기준 브랜치 대비 이 브랜치의 변경을 모두 확인하고, \
+ 버그, 동작 회귀, 보안 문제, 빠진 테스트를 심각한 순서로 파일:줄과 함께 짚어 주세요.
+ """
+}
+
+/// An `@` mention being typed in the composer: where its `@` starts, where it ends, and what follows the `@`.
+/// Offsets count characters of the composer's text.
+struct MorphComposerMention: Equatable {
+ let start: Int
+ let end: Int
+ let query: String
+
+ /// The prefix that turns a mention into a folder search, as in `@folder:src`.
+ static let folderPrefix = "folder:"
+
+ var isFolderSearch: Bool { query.lowercased().hasPrefix(Self.folderPrefix) }
+
+ /// What the search looks for: the query, or the part after `folder:`.
+ var searchText: String {
+ isFolderSearch ? String(query.dropFirst(Self.folderPrefix.count)) : query
+ }
+
+ /// Where the caret is after an edit turned `old` into `new`: the end of what the edit inserted. The field
+ /// does not report its caret, and typing happens at the caret, so the edit marks it.
+ static func caret(old: String, new: String) -> Int {
+ let oldChars = Array(old)
+ let newChars = Array(new)
+ var prefix = 0
+ while prefix < oldChars.count, prefix < newChars.count, oldChars[prefix] == newChars[prefix] {
+ prefix += 1
+ }
+ var suffix = 0
+ while suffix < oldChars.count - prefix, suffix < newChars.count - prefix,
+ oldChars[oldChars.count - 1 - suffix] == newChars[newChars.count - 1 - suffix] {
+ suffix += 1
+ }
+ return newChars.count - suffix
+ }
+
+ /// The mention the caret is in: the word before the caret starts with `@` at the start of the text or after
+ /// whitespace, and runs to the next whitespace.
+ static func active(in text: String, caret: Int) -> MorphComposerMention? {
+ let chars = Array(text)
+ let caret = min(max(0, caret), chars.count)
+ var start = caret
+ while start > 0, !chars[start - 1].isWhitespace {
+ start -= 1
+ }
+ guard start < chars.count, chars[start] == "@" else { return nil }
+ var end = caret
+ while end < chars.count, !chars[end].isWhitespace {
+ end += 1
+ }
+ let query = String(chars[(start + 1).. String {
+ let chars = Array(text)
+ guard start <= end, end <= chars.count else { return text + replacement + " " }
+ let before = String(chars[.. [MorphComposerMentionItem] {
+ let needle = mention.searchText.lowercased()
+ if mention.isFolderSearch {
+ var folders: [String] = []
+ for file in files {
+ var parts = file.split(separator: "/").dropLast()
+ while !parts.isEmpty {
+ let folder = parts.joined(separator: "/") + "/"
+ if (needle.isEmpty || folder.lowercased().contains(needle)), !folders.contains(folder) {
+ folders.append(folder)
+ }
+ parts = parts.dropLast()
+ }
+ }
+ return folders.sorted { $0.count < $1.count }.prefix(limit).map { .folder($0) }
+ }
+ var specials: [MorphComposerMentionItem] = []
+ if "diff".hasPrefix(needle) {
+ specials.append(.diff)
+ }
+ if "folder".hasPrefix(needle) {
+ specials.append(.folderSearch)
+ }
+ return Array((specials + files.map { .file($0) }).prefix(limit))
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodeInspectorView.swift b/apple/Apps/Shared/MorphCodeInspectorView.swift
new file mode 100644
index 000000000..269691a13
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeInspectorView.swift
@@ -0,0 +1,3869 @@
+import SwiftUI
+import MorphCore
+#if os(macOS)
+import AppKit
+#endif
+
+public enum CodeInspectorSection: String, CaseIterable, Identifiable, Hashable, Sendable {
+ case changes
+ case artifacts
+ case terminal
+ case preview
+
+ public var id: String { rawValue }
+
+ public var title: String {
+ switch self {
+ case .changes: return "Changes"
+ case .artifacts: return "Files"
+ case .terminal: return "Terminal"
+ case .preview: return "Preview"
+ }
+ }
+}
+
+/// Which changes the `변경사항` tab lists: the working tree, the branch against its base branch, or recent commits.
+enum InspectorDiffScope: String, CaseIterable, Identifiable, Hashable {
+ case workingTree
+ case branch
+ case commits
+
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .workingTree: return "Working Tree"
+ case .branch: return "Branch Diff"
+ case .commits: return "Commits"
+ }
+ }
+}
+
+enum InspectorDiffLayout: String, CaseIterable, Identifiable, Hashable {
+ case unified
+ case split
+
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .unified: return "Unified"
+ case .split: return "Side-by-Side"
+ }
+ }
+}
+
+enum InspectorFilesMode: String, CaseIterable, Identifiable, Hashable {
+ case tree
+ case artifacts
+
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .tree: return "File Explorer"
+ case .artifacts: return "Artifacts"
+ }
+ }
+}
+
+struct InspectorPendingMerge: Identifiable {
+ let id = UUID()
+ let number: Int
+ let method: String
+ let head: String
+ let base: String
+
+ var methodLabel: String {
+ switch method {
+ case "merge": return "Merge 커밋"
+ case "rebase": return "Rebase"
+ default: return "Squash"
+ }
+ }
+}
+
+/// Right-hand inspector pane (macOS) / sheet (iPhone) for Morph Code:
+/// 1) `변경사항`: working tree or branch diff and commit history, Fetch/Pull/Push/Stash, PR & CI status with failing
+/// CI logs and review threads, syntax-highlighted unified or side-by-side diff with inline review comments,
+/// stage/unstage/discard, AI commit message & amend, AI code review, worktrees.
+/// 2) `파일`: Workspace file tree explorer and project artifacts.
+/// 3) `터미널`: Multi-tab interactive ANSI PTY terminal with search, links, split panes, send-to-agent, clear, restart
+/// and saved scripts.
+/// 4) `프리뷰`: The project's dev server in a built-in web view.
+public struct MorphCodeInspectorView: View {
+ @Bindable var state: MorphAppState
+ @Environment(\.openURL) private var openURL
+ #if os(iOS)
+ @Environment(\.horizontalSizeClass) private var horizontalSizeClass
+ #endif
+ @AppStorage("morph.code.developerInspector") private var showDeveloperInspector = false
+ @State private var lightboxImage: MorphLightboxImageItem?
+ @State private var openedFile: MorphFileItem?
+ @State private var inspectorWidth: CGFloat = 360
+
+ // Changes
+ @State private var showDetailedDiffs = false
+ @State private var diffScope: InspectorDiffScope = .workingTree
+ @State private var diffLayout: InspectorDiffLayout = .unified
+ @State private var branchDiffBase: String?
+ @State private var branchHunks: [String: [InspectorDiffHunk]] = [:]
+ @State private var expandedFileKeys: Set = []
+ @State private var commitMessage = ""
+ @State private var isCommitting = false
+ @State private var amendCommit = false
+ @State private var isGeneratingCommitMessage = false
+
+ // Worktrees
+ @State private var showWorktreePanel = false
+ @State private var worktreeBranchDraft = ""
+ @State private var worktreeBaseBranch: String?
+ @State private var worktreePendingRemoval: String?
+ @State private var removeBranchToo = false
+
+ // PR, Review Guide & Watch
+ @State private var showPRForm = false
+ @State private var prTitleDraft = ""
+ @State private var prBodyDraft = ""
+ @State private var prBaseDraft: String?
+ @State private var prIsDraft = false
+ @State private var showAllChecks = false
+ @State private var pendingMerge: InspectorPendingMerge?
+ @State private var expandedCheckLogs: Set = []
+ @State private var loadingCheckLogs: Set = []
+ @State private var showReviewThreads = true
+ @State private var resolvingReviewThreads: Set = []
+ @State private var prGuideByThread: [String: CodePRGuide] = [:]
+ @State private var isLoadingPRGuide = false
+ @State private var showPRGuideDetails = true
+ @State private var prWatchOverrideByKey: [String: Bool] = [:]
+ @State private var isUpdatingPRWatch = false
+
+ // Commit history & AI review
+ @State private var expandedCommits: Set = []
+ @State private var commitHunks: [String: [String: [InspectorDiffHunk]]] = [:]
+ @State private var showReviewResult = true
+
+ // Files
+ @State private var filesMode: InspectorFilesMode = .artifacts
+ @State private var expandedTreeKeys: Set = []
+
+ // Terminal
+ @State private var showAgentLog = false
+ @State private var showTerminalSearch = false
+ @State private var terminalSearchQuery = ""
+ @State private var terminalSearchIndex = 0
+
+ public init(state: MorphAppState) {
+ self.state = state
+ }
+
+ private var activeThread: CodeThread? { state.selectedCodeThread }
+ /// The open thread's project, or on the new-thread screen the folder project picked there.
+ private var activeProject: CodeProject? {
+ let projectId = activeThread?.projectId ?? state.codeNewThreadDraft?.projectId
+ return state.codeProjects.first { $0.id == projectId }
+ }
+ private var activeGit: CodeGitStatus? {
+ guard let pid = activeProject?.id else { return nil }
+ return state.codeGitStatus(projectId: pid, threadId: activeThread?.id)
+ }
+ private var activeWorkDir: String? {
+ if let wt = activeThread?.worktreePath, !wt.isEmpty { return wt }
+ return activeProject?.workspacePath
+ }
+ private var isWide: Bool { inspectorWidth >= 540 }
+ private var effectiveDiffLayout: InspectorDiffLayout { isWide ? diffLayout : .unified }
+
+ private var visibleSections: [CodeInspectorSection] {
+ showDeveloperInspector
+ ? [.changes, .artifacts, .terminal, .preview]
+ : [.preview, .artifacts, .changes]
+ }
+
+ private func sectionLabel(_ section: CodeInspectorSection) -> String {
+ if showDeveloperInspector {
+ return section.title
+ }
+ switch section {
+ case .preview: return "Preview"
+ case .artifacts: return "Artifacts"
+ case .changes: return "Changes"
+ case .terminal: return section.title
+ }
+ }
+
+ private var showsHeaderCloseButton: Bool {
+ #if os(macOS)
+ return true
+ #else
+ return horizontalSizeClass == .regular
+ #endif
+ }
+
+ public var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 8) {
+ AnymorphSegmentControl(
+ items: visibleSections,
+ selection: $state.codeInspectorSection,
+ label: { sectionLabel($0) }
+ )
+ Spacer(minLength: 4)
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ showDeveloperInspector.toggle()
+ }
+ } label: {
+ Image(systemName: "chevron.left.forwardslash.chevron.right")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(showDeveloperInspector ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ }
+ .anymorphButton(size: .inline, appearance: showDeveloperInspector ? .light : .ghost, iconOnly: true)
+ .help(showDeveloperInspector ? "개발자 보기 끄기" : "개발자 보기 켜기")
+ .accessibilityLabel("개발자 보기")
+ .accessibilityAddTraits(showDeveloperInspector ? .isSelected : [])
+
+ if showsHeaderCloseButton {
+ Button {
+ state.isCodeInspectorPresented = false
+ } label: {
+ MorphLucideIcon(.x, size: 13)
+ }
+ .morphRound(diameter: 26)
+ }
+ }
+ .padding(.horizontal, 14)
+ .frame(height: 52)
+ .background {
+ AnymorphColor.bgBase
+ .morphWindowTitlebar()
+ }
+ .overlay(alignment: .bottom) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(height: 1)
+ }
+
+ MorphKeepAliveStack(
+ active: state.codeInspectorSection,
+ items: CodeInspectorSection.allCases
+ ) { section in
+ switch section {
+ case .changes:
+ ScrollView {
+ changesPane
+ .padding(.horizontal, 14)
+ .padding(.vertical, 14)
+ }
+ .id("\(activeProject?.id ?? "")|\(activeThread?.id ?? "")|\(diffScope.rawValue)")
+ .scrollIndicators(.never)
+ case .artifacts:
+ filesPane
+ case .terminal:
+ terminalPane
+ case .preview:
+ MorphWebPreviewView(state: state, project: activeProject, thread: activeThread)
+ }
+ }
+ }
+ .background(AnymorphColor.bgBase)
+ #if os(macOS)
+ .onChange(of: state.codeInspectorSection) { _, _ in
+ NSApp.keyWindow?.makeFirstResponder(nil)
+ }
+ #endif
+ .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { inspectorWidth = $0 }
+ .onAppear {
+ if !showDeveloperInspector && state.codeInspectorSection == .terminal {
+ showDeveloperInspector = true
+ }
+ }
+ .onChange(of: showDeveloperInspector) { _, isDev in
+ if !isDev {
+ if state.codeInspectorSection == .terminal {
+ state.codeInspectorSection = .preview
+ }
+ filesMode = .artifacts
+ }
+ }
+ .morphImagePreview($lightboxImage)
+ .morphFilePreview($openedFile, load: fileLoader) { message in
+ state.showError(message)
+ }
+ #if os(iOS)
+ .sheet(item: $state.codePendingFileViewer) { request in
+ inspectorFileReader(request)
+ }
+ .morphNotices(state)
+ #endif
+ .morphDialog(item: $pendingMerge) { merge in
+ MorphDialogContent(
+ title: "PR #\(merge.number)을(를) 병합할까요?",
+ message: "\(merge.methodLabel) 방식으로 \(merge.head)을(를) \(merge.base)에 병합하고 원격 브랜치를 삭제합니다.",
+ confirmTitle: "병합"
+ ) { _ in
+ guard let pid = activeProject?.id else { return }
+ _ = await state.mergeCodeGitPR(projectId: pid, threadId: activeThread?.id, number: merge.number, method: merge.method, deleteBranch: true)
+ }
+ }
+ .task(id: "\(activeProject?.id ?? "")|\(activeThread?.id ?? "")|\(state.codeInspectorSection.rawValue)|\(state.localBridgeOnline)") {
+ guard let pid = activeProject?.id else { return }
+ let tid = activeThread?.id
+ switch state.codeInspectorSection {
+ case .changes:
+ await state.refreshCodeGitStatus(projectId: pid, threadId: tid)
+ if state.codeGitStatus(projectId: pid, threadId: tid)?.isRepo == true {
+ await state.refreshCodeGitPR(projectId: pid, threadId: tid)
+ await refreshOpenPRDetails(projectId: pid, threadId: tid)
+ }
+ case .terminal:
+ if state.codeProjectScriptsByProject[pid] == nil {
+ await state.refreshCodeProjectScripts(projectId: pid)
+ }
+ case .artifacts:
+ let rootKey = state.workspaceTreeKey(projectId: pid, threadId: tid, path: "")
+ if state.codeWorkspaceTreeByKey[rootKey] == nil,
+ !state.codeWorkspaceTreeLoadingKeys.contains(rootKey) {
+ await state.loadCodeWorkspaceTree(projectId: pid, threadId: tid, path: "")
+ }
+ case .preview:
+ if state.codeProjectScriptsByProject[pid] == nil {
+ await state.refreshCodeProjectScripts(projectId: pid)
+ }
+ }
+ }
+ }
+
+ /// Loads a file of the open project, from this Mac or the server.
+ private var fileLoader: (String) async -> Data? {
+ let projectId = activeProject?.id
+ let threadId = activeThread?.id
+ let isLocal = projectId.map { state.isLocalCodeProject($0) } ?? false
+ return { source in
+ await state.loadCodeFileData(source: source, projectId: projectId, threadId: threadId, isLocal: isLocal)
+ }
+ }
+
+ #if os(iOS)
+ private func inspectorFileReader(_ request: CodeFileOpenRequest) -> some View {
+ let name = (request.path as NSString).lastPathComponent
+ let state = state
+ return MorphFileReader(
+ file: MorphFileItem(
+ id: request.id.uuidString,
+ name: name.isEmpty ? request.path : name,
+ path: request.path,
+ mimeType: nil,
+ text: nil,
+ source: request.path
+ ),
+ load: { source in
+ await state.loadCodeFileData(
+ source: source,
+ projectId: request.projectId,
+ threadId: request.threadId,
+ isLocal: request.isLocal
+ )
+ },
+ initialLine: request.line
+ )
+ }
+ #endif
+
+ // MARK: - Shared Controls
+
+ private func toolButton(_ title: String, icon: String, detail: String? = nil, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ toolLabel(title, icon: icon, detail: detail)
+ }
+ .buttonStyle(.morphPlain)
+ }
+
+ private func toolLabel(_ title: String, icon: String, detail: String? = nil, showsChevron: Bool = false) -> some View {
+ HStack(spacing: 4) {
+ Image(systemName: icon)
+ .font(.system(size: 10.5, weight: .medium))
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ if let detail, !detail.isEmpty {
+ Text(detail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true, monospaced: true)
+ .lineLimit(1)
+ }
+ if showsChevron {
+ Image(systemName: "chevron.down")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous))
+ }
+
+ private func branchChip(_ title: String, prefix: String? = nil) -> some View {
+ HStack(spacing: 5) {
+ MorphLucideIcon(.gitBranch, size: 11)
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ if let prefix {
+ Text(prefix)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ Text(title)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+
+ private func sectionTitle(_ text: String) -> some View {
+ Text(text)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+
+ /// Loads review threads and comments when the branch has an open PR.
+ private func refreshOpenPRDetails(projectId: String, threadId: String?) async {
+ guard let pr = state.codeGitPR(projectId: projectId, threadId: threadId)?.pr, pr.state.uppercased() == "OPEN" else { return }
+ await state.refreshCodeGitPRDetails(projectId: projectId, threadId: threadId, number: pr.number)
+ }
+
+ private func groupedPanel(@ViewBuilder _ content: () -> Content) -> some View {
+ VStack(alignment: .leading, spacing: 8, content: content)
+ .padding(10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+}
+
+// MARK: - 1. Changes
+
+extension MorphCodeInspectorView {
+ @ViewBuilder
+ private var changesPane: some View {
+ if let proj = activeProject {
+ let git = activeGit
+ VStack(alignment: .leading, spacing: 14) {
+ branchBar(proj: proj, git: git)
+
+ #if os(macOS)
+ if state.isLocalCodeProject(proj.id), let dir = activeWorkDir {
+ quickOpenBar(dir: dir)
+ }
+ #endif
+
+ if let git, git.isRepo {
+ if showDeveloperInspector {
+ remoteToolbar(projectId: proj.id, git: git)
+ if showWorktreePanel {
+ worktreePanel(projectId: proj.id, git: git)
+ }
+ prSection(projectId: proj.id, git: git)
+ scopeBar(projectId: proj.id)
+ reviewResultSection(projectId: proj.id)
+ switch diffScope {
+ case .workingTree:
+ workingTreeChanges(projectId: proj.id, git: git)
+ case .branch:
+ branchChanges(projectId: proj.id)
+ case .commits:
+ commitHistory(projectId: proj.id)
+ }
+ } else {
+ if showWorktreePanel {
+ worktreePanel(projectId: proj.id, git: git)
+ }
+ prSection(projectId: proj.id, git: git)
+ detailedDiffDisclosure(projectId: proj.id, git: git)
+ }
+ } else if state.isLoadingCodeGit && git == nil {
+ HStack(spacing: 8) {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ Text("Git 상태 확인 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else if git != nil {
+ Text("이 폴더는 Git 저장소가 아닙니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ .task(id: "\(proj.id)|\(activeThread?.id ?? "")|\(diffScope.rawValue)|\(branchDiffBase ?? "")") {
+ guard activeGit?.isRepo == true else { return }
+ switch diffScope {
+ case .workingTree:
+ break
+ case .branch:
+ await state.refreshCodeGitBranchDiff(projectId: proj.id, threadId: activeThread?.id, base: branchDiffBase)
+ case .commits:
+ await state.refreshCodeGitLog(projectId: proj.id, threadId: activeThread?.id)
+ }
+ }
+ .onChange(of: state.codeGitBranchDiffByProject[proj.id]?.diff ?? "", initial: true) { _, diff in
+ branchHunks = InspectorDiffParser.parseFiles(diff: diff)
+ }
+ } else {
+ Text("프로젝트를 선택하면 변경사항이 표시됩니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+
+ @ViewBuilder
+ private func detailedDiffDisclosure(projectId: String, git: CodeGitStatus) -> some View {
+ let changedCount = git.files.count
+ VStack(alignment: .leading, spacing: 10) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { showDetailedDiffs.toggle() }
+ } label: {
+ HStack(spacing: 8) {
+ Image(systemName: showDetailedDiffs ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: 10)
+ Text("Changed files")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ if changedCount > 0 {
+ AnymorphBadge("\(changedCount)")
+ }
+ Spacer(minLength: 4)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+
+ if showDetailedDiffs {
+ remoteToolbar(projectId: projectId, git: git)
+ scopeBar(projectId: projectId)
+ reviewResultSection(projectId: projectId)
+ switch diffScope {
+ case .workingTree:
+ workingTreeChanges(projectId: projectId, git: git)
+ case .branch:
+ branchChanges(projectId: projectId)
+ case .commits:
+ commitHistory(projectId: projectId)
+ }
+ }
+ }
+ }
+
+ private func branchBar(proj: CodeProject, git: CodeGitStatus?) -> some View {
+ HStack(spacing: 6) {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ if let git, git.isRepo {
+ MorphDropdown(placement: .belowLeading, width: 280, name: "code-branch") {
+ MorphMenuSectionHeader("브랜치")
+ ForEach(git.branches, id: \.self) { br in
+ MorphMenuItem(br, isSelected: br == git.branch, id: "branch-\(br)") {
+ Task { await state.checkoutCodeBranch(projectId: proj.id, threadId: activeThread?.id, branch: br) }
+ }
+ }
+ } label: {
+ branchChip(git.branch.isEmpty ? "HEAD" : git.branch)
+ }
+ .fixedSize()
+ .accessibilityLabel("브랜치 \(git.branch.isEmpty ? "HEAD" : git.branch)")
+ } else {
+ Text(proj.name)
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+
+ if git?.isRepo == true {
+ Button(showWorktreePanel ? "Close Worktree" : "Worktree") {
+ withAnimation(AnymorphMotion.fast) { showWorktreePanel.toggle() }
+ }
+ .morphPill(.plain)
+ .fixedSize()
+ }
+ }
+ }
+
+ Button {
+ Task {
+ await state.refreshCodeGitStatus(projectId: proj.id, threadId: activeThread?.id)
+ await state.refreshCodeGitPR(projectId: proj.id, threadId: activeThread?.id)
+ await refreshOpenPRDetails(projectId: proj.id, threadId: activeThread?.id)
+ switch diffScope {
+ case .workingTree:
+ break
+ case .branch:
+ await state.refreshCodeGitBranchDiff(projectId: proj.id, threadId: activeThread?.id, base: branchDiffBase)
+ case .commits:
+ await state.refreshCodeGitLog(projectId: proj.id, threadId: activeThread?.id)
+ }
+ }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("Git 상태 새로고침")
+ }
+ }
+
+ #if os(macOS)
+ private func quickOpenBar(dir: String) -> some View {
+ HStack(spacing: 6) {
+ toolButton("Finder", icon: "folder") {
+ NSWorkspace.shared.open(URL(fileURLWithPath: dir))
+ }
+ toolButton("IDE", icon: "chevron.left.forwardslash.chevron.right") {
+ openInPreferredIDE(dir: dir)
+ }
+ toolButton("External Terminal", icon: "terminal") {
+ openInExternalTerminal(dir: dir)
+ }
+ }
+ }
+
+ private func openInPreferredIDE(dir: String) {
+ let dirURL = URL(fileURLWithPath: dir)
+ let bundleIDs = ["com.todesktop.230313mzl4w4u92", "com.microsoft.VSCode", "dev.zed.Zed"]
+ for bid in bundleIDs {
+ if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bid) {
+ NSWorkspace.shared.open([dirURL], withApplicationAt: appURL, configuration: NSWorkspace.OpenConfiguration())
+ return
+ }
+ }
+ NSWorkspace.shared.open(dirURL)
+ }
+
+ private func openInExternalTerminal(dir: String) {
+ let dirURL = URL(fileURLWithPath: dir)
+ let bundleIDs = ["com.mitchellh.ghostty", "com.googlecode.iterm2", "com.apple.Terminal"]
+ for bid in bundleIDs {
+ if let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bid) {
+ NSWorkspace.shared.open([dirURL], withApplicationAt: appURL, configuration: NSWorkspace.OpenConfiguration())
+ return
+ }
+ }
+ }
+ #endif
+
+ // MARK: Remote toolbar
+
+ private func remoteToolbar(projectId: String, git: CodeGitStatus) -> some View {
+ let tid = activeThread?.id
+ let ahead = git.ahead ?? 0
+ let behind = git.behind ?? 0
+ let stashCount = git.stashCount ?? 0
+ let hasRemote = git.hasRemote != false
+ let busy = state.isBusyCodeGitOp
+ var pushDetail: String?
+ if ahead > 0 || behind > 0 { pushDetail = "↑\(ahead) ↓\(behind)" }
+
+ return ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ toolButton("Fetch", icon: "arrow.triangle.2.circlepath") {
+ Task { await state.gitFetchCode(projectId: projectId, threadId: tid) }
+ }
+ .fixedSize()
+ .disabled(busy || !hasRemote)
+ .help("원격 브랜치 정보 새로고침")
+
+ toolButton("Pull", icon: "arrow.down", detail: behind > 0 ? "\(behind)" : nil) {
+ Task { await state.gitPullCode(projectId: projectId, threadId: tid) }
+ }
+ .fixedSize()
+ .disabled(busy || !hasRemote)
+ .help("원격 변경 가져오기")
+
+ toolButton("Push", icon: "arrow.up", detail: pushDetail) {
+ Task { await state.gitPushCode(projectId: projectId, threadId: tid) }
+ }
+ .fixedSize()
+ .disabled(busy || !hasRemote)
+ .help(hasRemote ? "원격 저장소로 푸시 (앞섬 \(ahead) · 뒤처짐 \(behind))" : "원격 저장소가 없습니다")
+
+ if busy {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ }
+
+ MorphDropdown(placement: .belowTrailing, width: 240, name: "code-stash") {
+ MorphMenuSectionHeader("Stash", status: stashCount > 0 ? "\(stashCount)개" : nil)
+ MorphMenuItem("임시 보관", subtitle: "추적 안 된 파일 포함", icon: .symbol("tray.and.arrow.down"), isEnabled: !git.files.isEmpty, id: "stash-push") {
+ Task { await state.gitStashCode(projectId: projectId, threadId: tid, action: "push") }
+ }
+ MorphMenuItem("복원", subtitle: "최근 Stash 꺼내기", icon: .symbol("tray.and.arrow.up"), isEnabled: stashCount > 0, id: "stash-pop") {
+ Task { await state.gitStashCode(projectId: projectId, threadId: tid, action: "pop") }
+ }
+ if let stashes = state.codeGitStashesByProject[projectId], !stashes.isEmpty {
+ MorphMenuDivider()
+ ForEach(stashes.prefix(5)) { entry in
+ MorphMenuNote("\(entry.ref) · \(entry.message)")
+ }
+ }
+ } label: {
+ HStack(spacing: 4) {
+ toolLabel("Stash", icon: "tray", showsChevron: true)
+ if stashCount > 0 {
+ MorphCountBadge(stashCount)
+ }
+ }
+ }
+ .fixedSize()
+ .disabled(busy)
+ }
+ }
+ }
+
+ // MARK: Worktrees
+
+ private func worktreePanel(projectId: String, git: CodeGitStatus) -> some View {
+ let mainPath = activeProject?.workspacePath
+ let base = worktreeBaseBranch ?? git.baseBranch ?? git.branch
+ return groupedPanel {
+ sectionTitle("Worktree (\(git.worktrees.count))")
+ ForEach(git.worktrees) { wt in
+ worktreeRow(projectId: projectId, worktree: wt, isMain: wt.isMain ?? (wt.path == mainPath), mainBranch: git.baseBranch)
+ }
+
+ AnymorphDivider().padding(.vertical, 2)
+
+ HStack(spacing: 6) {
+ Text("새 Worktree 브랜치")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Spacer(minLength: 4)
+ MorphDropdown(placement: .belowTrailing, width: 260, name: "code-worktree-base") {
+ MorphMenuSectionHeader("기준 브랜치")
+ ForEach(git.branches, id: \.self) { br in
+ MorphMenuItem(br, isSelected: br == base, id: "wt-base-\(br)") {
+ worktreeBaseBranch = br
+ }
+ }
+ } label: {
+ branchChip(base.isEmpty ? "HEAD" : base, prefix: "기준")
+ }
+ .fixedSize()
+ }
+ HStack(spacing: 6) {
+ AnymorphTextField("feat/branch-name", text: $worktreeBranchDraft, appearance: .outlined) {
+ createWorktree(projectId: projectId, base: base)
+ }
+ Button("생성") { createWorktree(projectId: projectId, base: base) }
+ .morphPill(.primary)
+ .disabled(worktreeBranchDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ }
+
+ private func worktreeRow(projectId: String, worktree: CodeGitWorktree, isMain: Bool, mainBranch: String?) -> some View {
+ let isCurrent = worktree.path == activeWorkDir
+ let isPendingRemoval = worktreePendingRemoval == worktree.path
+ return VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ MorphLucideIcon(.gitBranch, size: 11)
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(worktree.branch.isEmpty ? String(worktree.head.prefix(7)) : worktree.branch)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ Text(URL(fileURLWithPath: worktree.path).lastPathComponent)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 4)
+ if isMain { AnymorphBadge("메인") }
+ if isCurrent { AnymorphBadge("현재") }
+ if !isMain {
+ MorphDropdown(placement: .belowTrailing, width: 250, name: "code-worktree-apply") {
+ MorphMenuSectionHeader("메인에 반영")
+ MorphMenuItem("Merge", subtitle: "병합 커밋으로 반영", id: "wt-apply-merge") {
+ applyWorktree(projectId: projectId, path: worktree.path, target: mainBranch, mode: "merge")
+ }
+ MorphMenuItem("Squash", subtitle: "한 커밋으로 합쳐 반영", id: "wt-apply-squash") {
+ applyWorktree(projectId: projectId, path: worktree.path, target: mainBranch, mode: "squash")
+ }
+ MorphMenuItem("Patch", subtitle: "커밋 없이 변경만 적용", id: "wt-apply-patch") {
+ applyWorktree(projectId: projectId, path: worktree.path, target: mainBranch, mode: "patch")
+ }
+ } label: {
+ toolLabel("메인에 반영", icon: "arrow.triangle.merge", showsChevron: true)
+ }
+ .fixedSize()
+ .disabled(state.isBusyCodeGitOp)
+
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ removeBranchToo = false
+ worktreePendingRemoval = isPendingRemoval ? nil : worktree.path
+ }
+ } label: {
+ Image(systemName: "trash")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("Worktree 삭제")
+ }
+ }
+ if isPendingRemoval {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("이 Worktree를 삭제할까요? 커밋하지 않은 변경은 사라집니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ HStack(spacing: 8) {
+ InspectorCheckbox(title: "브랜치도 삭제", isOn: $removeBranchToo)
+ Spacer(minLength: 4)
+ Button("취소") { worktreePendingRemoval = nil }
+ .morphPill(.plain, height: 24)
+ Button("삭제") {
+ let deleteBranch = removeBranchToo
+ worktreePendingRemoval = nil
+ Task {
+ _ = await state.removeCodeWorktree(
+ projectId: projectId,
+ worktreePath: worktree.path,
+ branch: worktree.branch.isEmpty ? nil : worktree.branch,
+ deleteBranch: deleteBranch
+ )
+ }
+ }
+ .morphPill(.primary, height: 24)
+ .disabled(state.isBusyCodeGitOp)
+ }
+ }
+ .padding(8)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgSubtle))
+ }
+ }
+ .padding(.vertical, 2)
+ }
+
+ private func createWorktree(projectId: String, base: String) {
+ let br = worktreeBranchDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !br.isEmpty else { return }
+ worktreeBranchDraft = ""
+ showWorktreePanel = false
+ let baseBranch = base.isEmpty ? nil : base
+ Task { await state.createCodeWorktreeThread(projectId: projectId, branch: br, baseBranch: baseBranch) }
+ }
+
+ private func applyWorktree(projectId: String, path: String, target: String?, mode: String) {
+ Task {
+ _ = await state.applyCodeWorktree(projectId: projectId, threadId: activeThread?.id, worktreePath: path, targetBranch: target, mode: mode)
+ }
+ }
+
+ // MARK: PR & CI
+
+ @ViewBuilder
+ private func prSection(projectId: String, git: CodeGitStatus) -> some View {
+ if let status = state.codeGitPR(projectId: projectId, threadId: activeThread?.id) {
+ if let pr = status.pr {
+ prCard(projectId: projectId, pr: pr)
+ } else if status.available {
+ let base = git.baseBranch ?? "main"
+ if !git.branch.isEmpty, git.branch != base, git.hasRemote != false {
+ createPRSection(projectId: projectId, git: git)
+ }
+ } else if let error = status.error, !error.isEmpty {
+ Text("PR 상태를 확인할 수 없습니다. \(error)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(2)
+ }
+ }
+ }
+
+ private func prCard(projectId: String, pr: CodeGitPullRequest) -> some View {
+ let checks = pr.checks ?? []
+ let summary = InspectorCheckSummary(checks: checks)
+ let prState = pr.state.uppercased()
+ return VStack(alignment: .leading, spacing: 8) {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text("#\(pr.number)")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgTertiary, tabular: true, monospaced: true)
+ Text(pr.title)
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(2)
+ Spacer(minLength: 4)
+ if pr.isDraft == true { AnymorphBadge("Draft") }
+ AnymorphBadge(Self.prStateLabel(prState))
+ }
+ HStack(spacing: 6) {
+ MorphLucideIcon(.gitBranch, size: 11)
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text("\(pr.headBranch) → \(pr.baseBranch)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary, monospaced: true)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ if let review = Self.reviewLabel(pr.reviewStatus) { AnymorphBadge(review) }
+ if pr.mergeable?.uppercased() == "CONFLICTING" { AnymorphBadge("충돌") }
+ }
+ if !checks.isEmpty {
+ Button {
+ withAnimation(AnymorphMotion.fast) { showAllChecks.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ InspectorCheckMark(outcome: summary.overall)
+ Text(summary.label)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ Image(systemName: showAllChecks ? "chevron.up" : "chevron.down")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel("CI 체크 \(summary.label)")
+
+ // Failed checks stay listed so their logs are one click away; the chevron shows the rest.
+ let visibleChecks = showAllChecks ? checks : checks.filter { InspectorCheckSummary.outcome($0) == .failed }
+ if !visibleChecks.isEmpty {
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(visibleChecks) { check in
+ checkRow(projectId: projectId, pr: pr, check: check)
+ }
+ }
+ .padding(.leading, 2)
+ }
+ }
+ reviewThreadsSection(projectId: projectId, pr: pr)
+ prReviewGuideSection(projectId: projectId, pr: pr)
+ HStack(spacing: 6) {
+ if let url = URL(string: pr.url) {
+ Button("GitHub에서 열기") { openURL(url) }
+ .morphPill(.secondary, height: 26)
+ }
+ if prState == "OPEN", let thread = activeThread {
+ let watchKey = "\(thread.id)#\(pr.number)"
+ let isWatched = prWatchOverrideByKey[watchKey]
+ ?? (thread.linkedPRs?.first(where: { $0.number == pr.number })?.watched == true)
+ Button {
+ togglePRWatch(thread: thread, pr: pr, currentlyWatched: isWatched)
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: isWatched ? "bell.fill" : "bell")
+ .font(.system(size: 10, weight: .medium))
+ Text(isWatched ? "알림 켬" : "자동 감시")
+ }
+ }
+ .morphPill(isWatched ? .secondary : .plain, height: 26)
+ .disabled(isUpdatingPRWatch)
+ .help(isWatched ? "PR 상태 자동 감시 끄기" : "체크 완료·병합까지 PR 자동 감시")
+ }
+ Spacer(minLength: 4)
+ if prState == "OPEN" {
+ MorphDropdown(placement: .belowTrailing, width: 240, name: "code-pr-merge") {
+ MorphMenuSectionHeader("병합 방식")
+ MorphMenuItem("Squash 병합", subtitle: "커밋을 하나로 합칩니다", id: "pr-merge-squash") {
+ pendingMerge = InspectorPendingMerge(number: pr.number, method: "squash", head: pr.headBranch, base: pr.baseBranch)
+ }
+ MorphMenuItem("Merge 커밋", subtitle: "병합 커밋을 만듭니다", id: "pr-merge-merge") {
+ pendingMerge = InspectorPendingMerge(number: pr.number, method: "merge", head: pr.headBranch, base: pr.baseBranch)
+ }
+ MorphMenuItem("Rebase 병합", subtitle: "커밋을 base 위로 옮깁니다", id: "pr-merge-rebase") {
+ pendingMerge = InspectorPendingMerge(number: pr.number, method: "rebase", head: pr.headBranch, base: pr.baseBranch)
+ }
+ } label: {
+ HStack(spacing: 5) {
+ Text("PR 병합")
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgInverse)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgInverse)
+ }
+ .padding(.horizontal, 12)
+ .frame(height: 26)
+ .background(Capsule().fill(AnymorphColor.bgInverse))
+ }
+ .fixedSize()
+ .disabled(state.isBusyCodeGitOp || pr.isDraft == true)
+ }
+ }
+ }
+ .padding(10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ }
+
+ @ViewBuilder
+ private func prReviewGuideSection(projectId: String, pr: CodeGitPullRequest) -> some View {
+ if let thread = activeThread {
+ let guide = prGuideByThread[thread.id]
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ Image(systemName: "doc.text.magnifyingglass")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text("리뷰 가이드")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Spacer(minLength: 4)
+ if isLoadingPRGuide {
+ MorphRunningDots(dotSize: 1.8, spacing: 1.8)
+ } else if guide != nil {
+ Button(showPRGuideDetails ? "접기" : "펼치기") {
+ withAnimation(AnymorphMotion.fast) { showPRGuideDetails.toggle() }
+ }
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+
+ Button("다시 생성") {
+ loadPRGuide(thread: thread, generate: true)
+ }
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ } else {
+ Button("리뷰 가이드 생성/보기") {
+ loadPRGuide(thread: thread, generate: true)
+ }
+ .morphPill(.secondary, height: 24)
+ }
+ }
+
+ if let guide, showPRGuideDetails {
+ VStack(alignment: .leading, spacing: 6) {
+ if !guide.summary.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ Text(guide.summary)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ if let why = guide.why?.trimmingCharacters(in: .whitespacesAndNewlines), !why.isEmpty {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("변경 배경")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Text(why)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ if !guide.highlights.isEmpty {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("핵심 변경 파일")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ ForEach(Array(guide.highlights.enumerated()), id: \.offset) { _, point in
+ HStack(alignment: .firstTextBaseline, spacing: 5) {
+ Text("•")
+ .anymorphText(.caption, color: AnymorphColor.fgQuaternary)
+ Text(point)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+ let risks = guide.risks ?? []
+ if !risks.isEmpty {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("확인할 점")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ ForEach(Array(risks.enumerated()), id: \.offset) { _, risk in
+ HStack(alignment: .firstTextBaseline, spacing: 5) {
+ Text("•")
+ .anymorphText(.caption, color: AnymorphColor.fgQuaternary)
+ Text(risk)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+ if let verification = guide.verification?.trimmingCharacters(in: .whitespacesAndNewlines), !verification.isEmpty {
+ Text("검증: \(verification)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ }
+ }
+ .padding(.top, 2)
+ }
+ }
+
+ private func loadPRGuide(thread: CodeThread, generate: Bool) {
+ guard !isLoadingPRGuide else { return }
+ isLoadingPRGuide = true
+ let tid = thread.id
+ let isLocal = state.isLocalCodeThread(tid)
+ Task {
+ defer { isLoadingPRGuide = false }
+ do {
+ let transport = try await state.codeTransport(local: isLocal)
+ let guide = try await transport.fetchCodePRGuide(threadId: tid, generate: generate)
+ prGuideByThread[tid] = guide
+ showPRGuideDetails = true
+ } catch {
+ state.showError("리뷰 가이드를 불러오지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+ }
+
+ private func togglePRWatch(thread: CodeThread, pr: CodeGitPullRequest, currentlyWatched: Bool) {
+ guard !isUpdatingPRWatch else { return }
+ isUpdatingPRWatch = true
+ let tid = thread.id
+ let watchKey = "\(tid)#\(pr.number)"
+ let isLocal = state.isLocalCodeThread(tid)
+ let repo = activeProject?.gitHubRepo
+ Task {
+ defer { isUpdatingPRWatch = false }
+ do {
+ let transport = try await state.codeTransport(local: isLocal)
+ if currentlyWatched {
+ _ = try await transport.unwatchCodePR(threadId: tid, url: pr.url, number: pr.number)
+ prWatchOverrideByKey[watchKey] = false
+ state.showInfo("PR #\(pr.number) 자동 감시를 껐습니다.")
+ } else {
+ _ = try await transport.watchCodePR(threadId: tid, url: pr.url, repo: repo, number: pr.number, until: "merged")
+ prWatchOverrideByKey[watchKey] = true
+ state.showInfo("PR #\(pr.number) 자동 감시를 켰습니다.")
+ }
+ } catch {
+ state.showError("PR 자동 감시 설정을 바꾸지 못했습니다. \(error.localizedDescription)")
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func createPRSection(projectId: String, git: CodeGitStatus) -> some View {
+ let base = prBaseDraft ?? git.baseBranch ?? "main"
+ if showPRForm {
+ groupedPanel {
+ HStack {
+ sectionTitle("Pull Request 만들기")
+ Spacer(minLength: 4)
+ Button {
+ withAnimation(AnymorphMotion.fast) { showPRForm = false }
+ } label: {
+ MorphLucideIcon(.x, size: 11)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ }
+ AnymorphTextField("PR 제목", text: $prTitleDraft, appearance: .outlined)
+ AnymorphTextField("설명 (선택)", text: $prBodyDraft, appearance: .outlined)
+ HStack(spacing: 8) {
+ MorphDropdown(placement: .belowLeading, width: 260, name: "code-pr-base") {
+ MorphMenuSectionHeader("Base 브랜치")
+ ForEach(git.branches.filter { $0 != git.branch }, id: \.self) { br in
+ MorphMenuItem(br, isSelected: br == base, id: "pr-base-\(br)") {
+ prBaseDraft = br
+ }
+ }
+ } label: {
+ branchChip(base, prefix: "base")
+ }
+ .fixedSize()
+ InspectorCheckbox(title: "Draft", isOn: $prIsDraft)
+ Spacer(minLength: 4)
+ Button(state.isBusyCodeGitOp ? "생성 중…" : "PR 만들기") {
+ submitPR(projectId: projectId, base: base)
+ }
+ .morphPill(.primary, height: 26)
+ .disabled(state.isBusyCodeGitOp || prTitleDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ if (git.ahead ?? 0) > 0 {
+ Text("푸시하지 않은 커밋 \(git.ahead ?? 0)개는 PR을 만들기 전에 푸시됩니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ } else {
+ HStack(spacing: 8) {
+ Image(systemName: "arrow.triangle.pull")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text("\(git.branch) → \(base)에 열린 PR이 없습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ Button("PR 만들기") {
+ if prTitleDraft.isEmpty { prTitleDraft = Self.titleFromBranch(git.branch) }
+ withAnimation(AnymorphMotion.fast) { showPRForm = true }
+ }
+ .morphPill(.secondary, height: 26)
+ }
+ }
+ }
+
+ private func submitPR(projectId: String, base: String) {
+ let title = prTitleDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !title.isEmpty else { return }
+ let body = prBodyDraft
+ let draft = prIsDraft
+ Task {
+ let ok = await state.createCodeGitPR(projectId: projectId, threadId: activeThread?.id, title: title, body: body, base: base, draft: draft)
+ if ok {
+ prTitleDraft = ""
+ prBodyDraft = ""
+ prIsDraft = false
+ showPRForm = false
+ }
+ }
+ }
+
+ static func prStateLabel(_ state: String) -> String {
+ switch state {
+ case "OPEN": return "열림"
+ case "MERGED": return "병합됨"
+ case "CLOSED": return "닫힘"
+ default: return state.capitalized
+ }
+ }
+
+ static func reviewLabel(_ status: String?) -> String? {
+ switch status?.uppercased() {
+ case "APPROVED": return "승인됨"
+ case "CHANGES_REQUESTED": return "변경 요청"
+ case "REVIEW_REQUIRED": return "리뷰 대기"
+ case .some(let raw) where !raw.isEmpty: return raw.capitalized
+ default: return nil
+ }
+ }
+
+ static func titleFromBranch(_ branch: String) -> String {
+ let last = branch.split(separator: "/").last.map(String.init) ?? branch
+ let words = last.replacingOccurrences(of: "-", with: " ").replacingOccurrences(of: "_", with: " ")
+ guard let first = words.first else { return branch }
+ return first.uppercased() + words.dropFirst()
+ }
+
+ // MARK: CI check logs
+
+ private func checkLogKey(projectId: String, number: Int, check: String) -> String {
+ "\(projectId)|\(number)|\(check)"
+ }
+
+ private func checkRow(projectId: String, pr: CodeGitPullRequest, check: CodeGitCheckRun) -> some View {
+ let key = checkLogKey(projectId: projectId, number: pr.number, check: check.name)
+ let expanded = expandedCheckLogs.contains(key)
+ let failed = InspectorCheckSummary.outcome(check) == .failed
+ return VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ Button {
+ toggleCheckLog(projectId: projectId, pr: pr, check: check)
+ } label: {
+ HStack(spacing: 6) {
+ InspectorCheckMark(outcome: InspectorCheckSummary.outcome(check))
+ Text(check.name)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ Text(InspectorCheckSummary.label(for: check))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ Image(systemName: expanded ? "chevron.up" : "text.alignleft")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(expanded ? "로그 접기" : "CI 로그 보기")
+
+ if failed {
+ Button("실패 CI 수정 지시") {
+ instructCIFix(projectId: projectId, pr: pr, check: check)
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ .help("실패한 체크 이름과 로그 끝부분을 입력창에 넣기")
+ }
+ if let link = check.url, let url = URL(string: link) {
+ Button {
+ openURL(url)
+ } label: {
+ Image(systemName: "arrow.up.right.square")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("GitHub에서 체크 열기")
+ }
+ }
+ if expanded {
+ checkLogBlock(key: key)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func checkLogBlock(key: String) -> some View {
+ if let response = state.codeGitCILogsByKey[key] {
+ let log = response.log.trimmingCharacters(in: .whitespacesAndNewlines)
+ ScrollView {
+ Text(log.isEmpty ? "로그가 비어 있습니다." : log)
+ .font(AnymorphFonts.font(.caption, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ }
+ .defaultScrollAnchor(.bottom)
+ .frame(maxHeight: 220)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ } else if loadingCheckLogs.contains(key) {
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ Text("CI 로그 불러오는 중…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else {
+ Text("CI 로그를 불러오지 못했습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+
+ private func toggleCheckLog(projectId: String, pr: CodeGitPullRequest, check: CodeGitCheckRun) {
+ let key = checkLogKey(projectId: projectId, number: pr.number, check: check.name)
+ if expandedCheckLogs.contains(key) {
+ expandedCheckLogs.remove(key)
+ return
+ }
+ expandedCheckLogs.insert(key)
+ guard state.codeGitCILogsByKey[key] == nil, !loadingCheckLogs.contains(key) else { return }
+ loadingCheckLogs.insert(key)
+ Task {
+ _ = await state.fetchCodeGitPRCILogs(projectId: projectId, threadId: activeThread?.id, number: pr.number, check: check.name)
+ loadingCheckLogs.remove(key)
+ }
+ }
+
+ /// Puts the failed check and the end of its log into the composer as a fix request.
+ private func instructCIFix(projectId: String, pr: CodeGitPullRequest, check: CodeGitCheckRun) {
+ let key = checkLogKey(projectId: projectId, number: pr.number, check: check.name)
+ Task {
+ var log = state.codeGitCILogsByKey[key]?.log
+ if log == nil {
+ log = await state.fetchCodeGitPRCILogs(projectId: projectId, threadId: activeThread?.id, number: pr.number, check: check.name)?.log
+ }
+ let tail = (log ?? "")
+ .split(separator: "\n", omittingEmptySubsequences: false)
+ .suffix(80)
+ .joined(separator: "\n")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ var parts = ["PR #\(pr.number)의 CI 체크 `\(check.name)`가 실패했습니다 (\(InspectorCheckSummary.label(for: check))). 로그를 보고 원인을 찾아 고쳐 주세요."]
+ if let url = check.url, !url.isEmpty { parts.append(url) }
+ if !tail.isEmpty { parts.append("```text\n\(tail)\n```") }
+ state.insertCodeTextIntoComposer(parts.joined(separator: "\n\n"))
+ }
+ }
+
+ // MARK: PR review threads
+
+ /// Unresolved review threads grouped by `path:line`, in the order GitHub lists them.
+ private static func groupedReviewThreads(_ threads: [CodeGitPRReviewThread]) -> [(location: String, threads: [CodeGitPRReviewThread])] {
+ var groups: [(location: String, threads: [CodeGitPRReviewThread])] = []
+ for thread in threads {
+ let location = reviewLocation(thread)
+ if let index = groups.firstIndex(where: { $0.location == location }) {
+ groups[index].threads.append(thread)
+ } else {
+ groups.append((location, [thread]))
+ }
+ }
+ return groups
+ }
+
+ private static func reviewLocation(_ thread: CodeGitPRReviewThread) -> String {
+ thread.line.map { "\(thread.path):\($0)" } ?? thread.path
+ }
+
+ private static func reviewInstruction(prNumber: Int, threads: [CodeGitPRReviewThread]) -> String {
+ let blocks = threads.map { thread -> String in
+ let comments = thread.comments.map { "- \($0.author): \($0.body.trimmingCharacters(in: .whitespacesAndNewlines))" }
+ return (["`\(reviewLocation(thread))`"] + comments).joined(separator: "\n")
+ }
+ return (["PR #\(prNumber) 리뷰 코멘트를 코드에 반영해 주세요."] + blocks).joined(separator: "\n\n")
+ }
+
+ @ViewBuilder
+ private func reviewThreadsSection(projectId: String, pr: CodeGitPullRequest) -> some View {
+ if let details = state.codeGitPRDetailsByProject[projectId], details.pr.number == pr.number, !details.reviewThreads.isEmpty {
+ let unresolved = details.reviewThreads.filter { !$0.isResolved }
+ let resolvedCount = details.reviewThreads.count - unresolved.count
+ VStack(alignment: .leading, spacing: 8) {
+ AnymorphDivider()
+ HStack(spacing: 6) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { showReviewThreads.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: showReviewThreads ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ Text("리뷰 코멘트")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ if !unresolved.isEmpty { AnymorphBadge("미해결 \(unresolved.count)") }
+ if resolvedCount > 0 {
+ Text("해결됨 \(resolvedCount)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ }
+ Spacer(minLength: 4)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ if !unresolved.isEmpty {
+ Button("미해결 리뷰 전체 반영") {
+ state.insertCodeTextIntoComposer(Self.reviewInstruction(prNumber: pr.number, threads: unresolved))
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ }
+ }
+ if showReviewThreads {
+ if unresolved.isEmpty {
+ Text("모든 리뷰 스레드가 해결됐습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ ForEach(Array(Self.groupedReviewThreads(unresolved).enumerated()), id: \.element.location) { index, group in
+ if index > 0 { AnymorphDivider() }
+ reviewThreadGroup(projectId: projectId, pr: pr, location: group.location, threads: group.threads)
+ }
+ }
+ }
+ }
+ }
+
+ private func reviewThreadGroup(projectId: String, pr: CodeGitPullRequest, location: String, threads: [CodeGitPRReviewThread]) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Button {
+ guard let first = threads.first else { return }
+ state.openCodeFileInReader(projectId: projectId, threadId: activeThread?.id, path: first.path, line: first.line)
+ } label: {
+ HStack(spacing: 5) {
+ Image(systemName: "doc.text")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(location)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("파일 열기")
+
+ ForEach(threads) { thread in
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(thread.comments) { comment in
+ VStack(alignment: .leading, spacing: 2) {
+ Text(comment.author)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgSecondary)
+ Text(comment.body.trimmingCharacters(in: .whitespacesAndNewlines))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgPrimary)
+ .lineLimit(8)
+ .textSelection(.enabled)
+ }
+ }
+ HStack(spacing: 6) {
+ Spacer(minLength: 4)
+ Button("반영 지시") {
+ state.insertCodeTextIntoComposer(Self.reviewInstruction(prNumber: pr.number, threads: [thread]))
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ Button(resolvingReviewThreads.contains(thread.id) ? "해결 중…" : "해결") {
+ resolveReviewThread(projectId: projectId, pr: pr, thread: thread)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ .disabled(resolvingReviewThreads.contains(thread.id))
+ }
+ }
+ .padding(.leading, 15)
+ }
+ }
+ }
+
+ private func resolveReviewThread(projectId: String, pr: CodeGitPullRequest, thread: CodeGitPRReviewThread) {
+ resolvingReviewThreads.insert(thread.id)
+ Task {
+ _ = await state.replyCodeGitPR(
+ projectId: projectId,
+ threadId: activeThread?.id,
+ number: pr.number,
+ reviewThreadId: thread.id,
+ body: "",
+ resolve: true
+ )
+ resolvingReviewThreads.remove(thread.id)
+ }
+ }
+
+ // MARK: Scope bar
+
+ private func scopeBar(projectId: String) -> some View {
+ HStack(spacing: 8) {
+ AnymorphSegmentControl(
+ items: InspectorDiffScope.allCases,
+ selection: $diffScope,
+ label: { $0.title }
+ )
+ .fixedSize()
+ Spacer(minLength: 4)
+ Button {
+ runReview(projectId: projectId)
+ } label: {
+ HStack(spacing: 4) {
+ if state.isRunningCodeReview {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ } else {
+ Image(systemName: "sparkles")
+ .font(.system(size: 11, weight: .medium))
+ }
+ Text("AI 리뷰")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ .disabled(state.isRunningCodeReview)
+ .help(diffScope == .branch ? "브랜치 변경을 AI로 리뷰" : "작업 트리 변경을 AI로 리뷰")
+ if isWide {
+ AnymorphSegmentControl(
+ items: InspectorDiffLayout.allCases,
+ selection: $diffLayout,
+ label: { $0.title }
+ )
+ .fixedSize()
+ }
+ }
+ }
+
+ // MARK: Working tree
+
+ @ViewBuilder
+ private func workingTreeChanges(projectId: String, git: CodeGitStatus) -> some View {
+ let stagedFiles = git.files.filter { $0.staged == true }
+ let unstagedFiles = git.files.filter { $0.unstaged == true || $0.untracked == true || ($0.staged != true && $0.unstaged != true) }
+
+ if git.files.isEmpty {
+ Text("변경된 파일이 없습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(.top, 2)
+ } else {
+ if !stagedFiles.isEmpty {
+ gitFileGroup(
+ title: "스테이징됨 (\(stagedFiles.count))",
+ files: stagedFiles,
+ mode: .staged,
+ projectId: projectId,
+ bulkLabel: "모두 해제"
+ ) {
+ Task { await state.unstageCodeGit(projectId: projectId, threadId: activeThread?.id, all: true) }
+ }
+ }
+
+ commitBox(projectId: projectId, hasStaged: !stagedFiles.isEmpty)
+
+ if !unstagedFiles.isEmpty {
+ gitFileGroup(
+ title: "변경됨 (\(unstagedFiles.count))",
+ files: unstagedFiles,
+ mode: .unstaged,
+ projectId: projectId,
+ bulkLabel: "모두 스테이징"
+ ) {
+ Task { await state.stageCodeGit(projectId: projectId, threadId: activeThread?.id, all: true) }
+ }
+ }
+ }
+ }
+
+ private func commitBox(projectId: String, hasStaged: Bool) -> some View {
+ let trimmed = commitMessage.trimmingCharacters(in: .whitespacesAndNewlines)
+ let canCommit = !isCommitting && !trimmed.isEmpty && (hasStaged || amendCommit)
+ return groupedPanel {
+ HStack(spacing: 6) {
+ AnymorphTextField(amendCommit ? "수정할 커밋 메시지…" : "커밋 메시지 입력…", text: $commitMessage, appearance: .outlined) {
+ submitCommit(projectId: projectId, hasStaged: hasStaged)
+ }
+ Button {
+ generateCommitMessage(projectId: projectId, stagedOnly: hasStaged)
+ } label: {
+ HStack(spacing: 4) {
+ if isGeneratingCommitMessage {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ } else {
+ Image(systemName: "sparkles")
+ .font(.system(size: 11, weight: .medium))
+ }
+ Text("AI 메시지")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ .disabled(isGeneratingCommitMessage)
+ .help("변경 내용으로 커밋 메시지 생성")
+ }
+ HStack(spacing: 8) {
+ InspectorCheckbox(title: "Amend (직전 커밋 수정)", isOn: $amendCommit)
+ Spacer(minLength: 4)
+ if !hasStaged && !amendCommit {
+ Text("스테이징한 파일이 없습니다")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary)
+ }
+ Button(isCommitting ? "커밋 중…" : (amendCommit ? "Amend 커밋" : "커밋")) {
+ submitCommit(projectId: projectId, hasStaged: hasStaged)
+ }
+ .morphPill(.primary)
+ .disabled(!canCommit)
+ }
+ }
+ }
+
+ private func generateCommitMessage(projectId: String, stagedOnly: Bool) {
+ guard !isGeneratingCommitMessage else { return }
+ isGeneratingCommitMessage = true
+ Task {
+ if let message = await state.generateCodeCommitMessage(projectId: projectId, threadId: activeThread?.id, stagedOnly: stagedOnly) {
+ commitMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ isGeneratingCommitMessage = false
+ }
+ }
+
+ private func submitCommit(projectId: String, hasStaged: Bool) {
+ let msg = commitMessage.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !msg.isEmpty, !isCommitting, hasStaged || amendCommit else { return }
+ isCommitting = true
+ let amend = amendCommit
+ Task {
+ let ok = await state.commitCodeGitWithOptions(projectId: projectId, threadId: activeThread?.id, message: msg, amend: amend)
+ if ok {
+ commitMessage = ""
+ amendCommit = false
+ await state.refreshCodeGitPR(projectId: projectId, threadId: activeThread?.id)
+ }
+ isCommitting = false
+ }
+ }
+
+ // MARK: Branch comparison
+
+ @ViewBuilder
+ private func branchChanges(projectId: String) -> some View {
+ let git = activeGit
+ if let diff = state.codeGitBranchDiffByProject[projectId] {
+ let base = branchDiffBase ?? diff.baseBranch
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 6) {
+ MorphDropdown(placement: .belowLeading, width: 260, name: "code-branch-diff-base") {
+ MorphMenuSectionHeader("비교할 base 브랜치")
+ ForEach((git?.branches ?? []).filter { $0 != diff.headBranch }, id: \.self) { br in
+ MorphMenuItem(br, isSelected: br == base, id: "diff-base-\(br)") {
+ branchDiffBase = br
+ }
+ }
+ } label: {
+ branchChip(base, prefix: "base")
+ }
+ .fixedSize()
+ Text("← \(diff.headBranch)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ AnymorphBadge("↑\(diff.ahead) ↓\(diff.behind)")
+ .help("base보다 앞선 커밋 \(diff.ahead)개 · 뒤처진 커밋 \(diff.behind)개")
+ }
+ if diff.files.isEmpty {
+ Text("\(base) 대비 변경된 파일이 없습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ } else {
+ gitFileGroup(
+ title: "브랜치 변경 (\(diff.files.count)) · +\(diff.files.reduce(0) { $0 + $1.additions }) −\(diff.files.reduce(0) { $0 + $1.deletions })",
+ files: diff.files,
+ mode: .branch,
+ projectId: projectId,
+ bulkLabel: nil,
+ bulkAction: nil
+ )
+ }
+ }
+ } else {
+ HStack(spacing: 8) {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ Text("브랜치 비교 불러오는 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ }
+
+ // MARK: Commit history
+
+ @ViewBuilder
+ private func commitHistory(projectId: String) -> some View {
+ let commits = state.codeGitCommitLogByProject[projectId] ?? []
+ if commits.isEmpty {
+ if state.isLoadingCodeCommitLog {
+ HStack(spacing: 8) {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ Text("커밋 기록 불러오는 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else {
+ Text("커밋 기록이 없습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ sectionTitle("최근 커밋 (\(commits.count))")
+ Spacer(minLength: 4)
+ if state.isLoadingCodeCommitLog {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ }
+ }
+ ForEach(commits) { commit in
+ commitCard(projectId: projectId, commit: commit)
+ }
+ }
+ }
+ }
+
+ private func commitCard(projectId: String, commit: CodeGitCommitEntry) -> some View {
+ let expanded = expandedCommits.contains(commit.sha)
+ return VStack(alignment: .leading, spacing: 0) {
+ Button {
+ toggleCommit(projectId: projectId, sha: commit.sha)
+ } label: {
+ HStack(alignment: .top, spacing: 6) {
+ Image(systemName: expanded ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: 10)
+ .padding(.top, 3)
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(commit.shortSha)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgTertiary, monospaced: true)
+ Text(commit.subject)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(expanded ? nil : 1)
+ }
+ HStack(spacing: 6) {
+ Text("\(commit.author) · \(commit.relativeDate)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ if let additions = commit.additions, let deletions = commit.deletions {
+ Text("+\(additions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffAddFg, tabular: true)
+ Text("−\(deletions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffRemoveFg, tabular: true)
+ }
+ }
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(commit.sha)
+
+ if expanded {
+ AnymorphDivider()
+ commitFiles(projectId: projectId, sha: commit.sha)
+ }
+ }
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+
+ @ViewBuilder
+ private func commitFiles(projectId: String, sha: String) -> some View {
+ if let diff = state.codeGitCommitDiffByKey["\(projectId)|\(sha)"], let hunksByPath = commitHunks[sha] {
+ if diff.files.isEmpty {
+ Text("이 커밋에서 바뀐 파일이 없습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(10)
+ } else {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(diff.files.enumerated()), id: \.element.path) { index, file in
+ if index > 0 { AnymorphDivider() }
+ commitFileRow(projectId: projectId, sha: sha, file: file, hunks: hunksByPath[file.path] ?? [])
+ }
+ }
+ }
+ } else {
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ Text("커밋 diff 불러오는 중…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .padding(10)
+ }
+ }
+
+ private func commitFileRow(projectId: String, sha: String, file: CodeGitFileChange, hunks: [InspectorDiffHunk]) -> some View {
+ let key = "C:\(sha):\(file.path)"
+ let expanded = expandedFileKeys.contains(key)
+ return VStack(alignment: .leading, spacing: 0) {
+ Button {
+ if expanded {
+ expandedFileKeys.remove(key)
+ } else {
+ expandedFileKeys.insert(key)
+ }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: expanded ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: 10)
+ Text(file.status)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgTertiary, monospaced: true)
+ .frame(width: 14, alignment: .leading)
+ Text(file.path)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.head)
+ Spacer(minLength: 4)
+ Text("+\(file.additions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffAddFg, tabular: true)
+ Text("−\(file.deletions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffRemoveFg, tabular: true)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(file.path)
+
+ if expanded {
+ AnymorphDivider()
+ if hunks.isEmpty {
+ Text("표시할 텍스트 diff가 없습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(10)
+ } else {
+ hunkList(path: file.path, hunks: hunks) { _ in [] }
+ }
+ }
+ }
+ }
+
+ private func toggleCommit(projectId: String, sha: String) {
+ if expandedCommits.contains(sha) {
+ expandedCommits.remove(sha)
+ return
+ }
+ expandedCommits.insert(sha)
+ guard commitHunks[sha] == nil else { return }
+ Task {
+ if let diff = await state.loadCodeGitCommitDiff(projectId: projectId, threadId: activeThread?.id, sha: sha) {
+ commitHunks[sha] = InspectorDiffParser.parseFiles(diff: diff.diff)
+ } else {
+ expandedCommits.remove(sha)
+ }
+ }
+ }
+
+ // MARK: AI code review
+
+ private func runReview(projectId: String) {
+ let scope = diffScope == .branch ? "branch" : "working"
+ let base = branchDiffBase
+ showReviewResult = true
+ Task {
+ _ = await state.runCodeGitReview(projectId: projectId, threadId: activeThread?.id, scope: scope, baseBranch: base)
+ }
+ }
+
+ @ViewBuilder
+ private func reviewResultSection(projectId: String) -> some View {
+ if let result = state.codeReviewResultByProject[projectId] {
+ reviewCard(projectId: projectId, result: result)
+ } else if state.isRunningCodeReview {
+ HStack(spacing: 8) {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ Text("AI가 변경 내용을 리뷰하는 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ }
+
+ private func reviewCard(projectId: String, result: CodeReviewResponse) -> some View {
+ let findings = result.findings.sorted { Self.severityRank($0.severity) < Self.severityRank($1.severity) }
+ return VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 6) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { showReviewResult.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: showReviewResult ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ Image(systemName: "sparkles")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text("AI 리뷰")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ AnymorphBadge(result.scope == "branch" ? "브랜치" : "작업 트리")
+ AnymorphBadge(findings.isEmpty ? "지적 없음" : "\(findings.count)개 항목")
+ if state.isRunningCodeReview {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ }
+ Spacer(minLength: 4)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ if !findings.isEmpty {
+ Button("전체 수정 지시") {
+ state.insertCodeTextIntoComposer(Self.reviewFixInstruction(findings))
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ }
+ Button {
+ state.codeReviewResultByProject[projectId] = nil
+ } label: {
+ MorphLucideIcon(.x, size: 11)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("리뷰 결과 닫기")
+ }
+
+ if showReviewResult {
+ let summary = result.summary.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !summary.isEmpty {
+ Text(summary)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .textSelection(.enabled)
+ }
+ ForEach(findings) { finding in
+ AnymorphDivider()
+ reviewFindingRow(projectId: projectId, finding: finding)
+ }
+ }
+ }
+ .padding(10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ }
+
+ private func reviewFindingRow(projectId: String, finding: CodeReviewFinding) -> some View {
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ AnymorphBadge(Self.severityLabel(finding.severity))
+ Text(finding.title)
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(3)
+ Spacer(minLength: 0)
+ }
+ if !finding.file.isEmpty {
+ Button {
+ state.openCodeFileInReader(projectId: projectId, threadId: activeThread?.id, path: finding.file, line: finding.line)
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "doc.text")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(Self.findingLocation(finding))
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.head)
+ .underline()
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("파일 열기")
+ }
+ if !finding.detail.isEmpty {
+ Text(finding.detail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .textSelection(.enabled)
+ }
+ if let suggestion = finding.suggestion?.trimmingCharacters(in: .whitespacesAndNewlines), !suggestion.isEmpty {
+ Text(suggestion)
+ .font(AnymorphFonts.font(.caption, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .textSelection(.enabled)
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+ HStack {
+ Spacer(minLength: 4)
+ Button("수정 지시") {
+ state.insertCodeTextIntoComposer(Self.reviewFixInstruction([finding]))
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ }
+ }
+ }
+
+ static func severityRank(_ severity: String) -> Int {
+ switch severity.lowercased() {
+ case "critical", "blocker": return 0
+ case "high", "major", "error": return 1
+ case "medium", "moderate", "warning": return 2
+ default: return 3
+ }
+ }
+
+ static func severityLabel(_ severity: String) -> String {
+ switch severityRank(severity) {
+ case 0: return "치명"
+ case 1: return "높음"
+ case 2: return "보통"
+ default: return "낮음"
+ }
+ }
+
+ static func findingLocation(_ finding: CodeReviewFinding) -> String {
+ finding.line.map { "\(finding.file):\($0)" } ?? finding.file
+ }
+
+ static func reviewFixInstruction(_ findings: [CodeReviewFinding]) -> String {
+ let blocks = findings.map { finding -> String in
+ var lines = ["[\(severityLabel(finding.severity))] \(finding.title)"]
+ if !finding.file.isEmpty { lines.append("- 위치: `\(findingLocation(finding))`") }
+ if !finding.detail.isEmpty { lines.append("- 내용: \(finding.detail)") }
+ if let suggestion = finding.suggestion?.trimmingCharacters(in: .whitespacesAndNewlines), !suggestion.isEmpty {
+ lines.append("- 제안: \(suggestion)")
+ }
+ return lines.joined(separator: "\n")
+ }
+ return (["AI 코드 리뷰에서 나온 아래 항목을 수정해 주세요."] + blocks).joined(separator: "\n\n")
+ }
+
+ // MARK: File groups & diffs
+
+ enum FileGroupMode {
+ case staged, unstaged, branch
+
+ var keyPrefix: String {
+ switch self {
+ case .staged: return "S"
+ case .unstaged: return "U"
+ case .branch: return "B"
+ }
+ }
+ }
+
+ private func gitFileGroup(
+ title: String,
+ files: [CodeGitFileChange],
+ mode: FileGroupMode,
+ projectId: String,
+ bulkLabel: String?,
+ bulkAction: (() -> Void)?
+ ) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack {
+ sectionTitle(title)
+ Spacer()
+ if let bulkLabel, let bulkAction {
+ Button(bulkLabel, action: bulkAction)
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ }
+
+ ForEach(files) { file in
+ gitFileCard(file: file, mode: mode, projectId: projectId)
+ }
+ }
+ }
+
+ private func gitFileCard(file: CodeGitFileChange, mode: FileGroupMode, projectId: String) -> some View {
+ let key = "\(mode.keyPrefix):\(file.path)"
+ let expanded = expandedFileKeys.contains(key)
+ let tid = activeThread?.id
+ return VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Button {
+ toggleFileExpand(key: key, projectId: projectId, path: file.path, mode: mode)
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: expanded ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: 10)
+ Text(file.status)
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgTertiary, monospaced: true)
+ .frame(width: 14, alignment: .leading)
+ VStack(alignment: .leading, spacing: 0) {
+ Text(URL(fileURLWithPath: file.path).lastPathComponent)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ let dir = (file.path as NSString).deletingLastPathComponent
+ if expanded, !dir.isEmpty {
+ Text(dir)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ }
+ Spacer(minLength: 4)
+ if file.additions > 0 || file.deletions > 0 {
+ HStack(spacing: 4) {
+ Text("+\(file.additions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffAddFg, tabular: true)
+ Text("−\(file.deletions)")
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffRemoveFg, tabular: true)
+ }
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(file.path)
+
+ Button {
+ state.openCodeFileInReader(projectId: projectId, threadId: tid, path: file.path, line: nil)
+ } label: {
+ Image(systemName: "doc.text.magnifyingglass")
+ .font(.system(size: 10, weight: .medium))
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("파일 열기")
+
+ switch mode {
+ case .staged:
+ Button {
+ Task { await state.unstageCodeGit(projectId: projectId, threadId: tid, path: file.path) }
+ } label: {
+ Image(systemName: "minus")
+ .font(.system(size: 10, weight: .semibold))
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("스테이징 해제")
+ case .unstaged:
+ Button {
+ Task { await state.stageCodeGit(projectId: projectId, threadId: tid, path: file.path) }
+ } label: {
+ Image(systemName: "plus")
+ .font(.system(size: 10, weight: .semibold))
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("스테이징")
+
+ Button {
+ Task { await state.revertCodeFile(projectId: projectId, threadId: tid, path: file.path) }
+ } label: {
+ MorphLucideIcon(.undo, size: 11.5)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("파일 변경 되돌리기")
+ case .branch:
+ EmptyView()
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+
+ if expanded {
+ AnymorphDivider()
+ switch mode {
+ case .staged, .unstaged:
+ workingTreeDiff(projectId: projectId, path: file.path, staged: mode == .staged)
+ case .branch:
+ branchFileDiff(path: file.path)
+ }
+ }
+ }
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+
+ @ViewBuilder
+ private func workingTreeDiff(projectId: String, path: String, staged: Bool) -> some View {
+ if let fileDiff = state.cachedCodeGitFileDiff(projectId: projectId, threadId: activeThread?.id, path: path, staged: staged) {
+ if fileDiff.hunks.isEmpty {
+ Text("표시할 텍스트 diff가 없습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(10)
+ } else {
+ let tid = activeThread?.id
+ let canAct = fileDiff.untracked != true
+ hunkList(path: path, hunks: fileDiff.hunks.map(InspectorDiffHunk.init(gitHunk:))) { hunk in
+ guard canAct else { return [] }
+ if staged {
+ return [
+ InspectorHunkAction(id: "unstage", title: "해제", isProminent: false) {
+ Task { await state.unstageCodeGit(projectId: projectId, threadId: tid, path: path, hunkIndex: hunk.index) }
+ },
+ ]
+ }
+ return [
+ InspectorHunkAction(id: "stage", title: "스테이징", isProminent: true) {
+ Task { await state.stageCodeGit(projectId: projectId, threadId: tid, path: path, hunkIndex: hunk.index) }
+ },
+ InspectorHunkAction(id: "discard", title: "되돌리기", isProminent: false) {
+ Task { await state.discardCodeGitHunk(projectId: projectId, threadId: tid, path: path, hunkIndex: hunk.index) }
+ },
+ ]
+ }
+ }
+ } else {
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ Text("Diff 불러오는 중…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .padding(10)
+ }
+ }
+
+ @ViewBuilder
+ private func branchFileDiff(path: String) -> some View {
+ if let hunks = branchHunks[path], !hunks.isEmpty {
+ hunkList(path: path, hunks: hunks) { _ in [] }
+ } else {
+ Text("표시할 텍스트 diff가 없습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(10)
+ }
+ }
+
+ private func hunkList(path: String, hunks: [InspectorDiffHunk], actions: @escaping (InspectorDiffHunk) -> [InspectorHunkAction]) -> some View {
+ let language = MorphSyntaxHighlighter.detectLanguage(hint: nil, filePath: path)
+ let layout = effectiveDiffLayout
+ return VStack(alignment: .leading, spacing: 0) {
+ ForEach(hunks) { hunk in
+ InspectorHunkView(
+ hunk: hunk,
+ path: path,
+ language: language,
+ layout: layout,
+ actions: actions(hunk)
+ ) { lineRange, snippet, instruction in
+ state.insertReviewCommentIntoComposer(path: path, lineRange: lineRange, diffSnippet: snippet, instruction: instruction)
+ }
+ if hunk.id != hunks.last?.id {
+ AnymorphDivider()
+ }
+ }
+ }
+ }
+
+ private func toggleFileExpand(key: String, projectId: String, path: String, mode: FileGroupMode) {
+ if expandedFileKeys.contains(key) {
+ expandedFileKeys.remove(key)
+ } else {
+ expandedFileKeys.insert(key)
+ guard mode != .branch else { return }
+ let staged = mode == .staged
+ Task { await state.fetchCodeGitFileDiff(projectId: projectId, threadId: activeThread?.id, path: path, staged: staged) }
+ }
+ }
+}
+
+// MARK: - 2. Files (Workspace Tree + Artifacts)
+
+extension MorphCodeInspectorView {
+ private struct TreeRow: Identifiable {
+ let id: String
+ let entry: CodeWorkspaceTreeEntry?
+ let depth: Int
+ var loadingPath: String? = nil
+ }
+
+ private var filesPane: some View {
+ let activeMode: InspectorFilesMode = showDeveloperInspector ? filesMode : .artifacts
+ return VStack(spacing: 0) {
+ if showDeveloperInspector {
+ HStack(spacing: 8) {
+ AnymorphSegmentControl(
+ items: InspectorFilesMode.allCases,
+ selection: $filesMode,
+ label: { $0.title }
+ )
+ .fixedSize()
+ Spacer(minLength: 4)
+ if activeMode == .tree, let pid = activeProject?.id {
+ if state.isLoadingCodeTree {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ }
+ Button {
+ reloadTree(projectId: pid)
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("파일 목록 새로고침")
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ }
+
+ ScrollView {
+ Group {
+ switch activeMode {
+ case .tree:
+ fileTree
+ case .artifacts:
+ artifactsPane
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.top, showDeveloperInspector ? 0 : 12)
+ .padding(.bottom, 14)
+ }
+ .id("\(activeProject?.id ?? "")|\(activeThread?.id ?? "")|\(activeMode.rawValue)")
+ .scrollIndicators(.never)
+ }
+ .task(id: "\(activeProject?.id ?? "")|\(activeThread?.id ?? "")|\(activeMode.rawValue)|\(state.localBridgeOnline)") {
+ guard activeMode == .tree, let pid = activeProject?.id else { return }
+ let tid = activeThread?.id
+ let rootKey = state.workspaceTreeKey(projectId: pid, threadId: tid, path: "")
+ if state.codeWorkspaceTreeByKey[rootKey] == nil,
+ !state.codeWorkspaceTreeLoadingKeys.contains(rootKey) {
+ await state.loadCodeWorkspaceTree(projectId: pid, threadId: tid, path: "")
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var fileTree: some View {
+ if let pid = activeProject?.id {
+ let tid = activeThread?.id
+ let rootKey = state.workspaceTreeKey(projectId: pid, threadId: tid, path: "")
+ let rootState = CodeWorkspaceTreeNodeState.resolve(
+ hasEntries: state.codeWorkspaceTreeByKey[rootKey] != nil,
+ isLoading: state.codeWorkspaceTreeLoadingKeys.contains(rootKey),
+ loadError: state.codeWorkspaceTreeErrorByKey[rootKey]
+ )
+ switch rootState {
+ case .loading:
+ HStack(spacing: 8) {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ Text("파일 목록 불러오는 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ case .failed(let message):
+ VStack(alignment: .leading, spacing: 8) {
+ Text("파일 목록을 불러오지 못했습니다.")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ if let message, !message.isEmpty {
+ Text(message)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(2)
+ }
+ Button("다시 시도") {
+ Task { await state.loadCodeWorkspaceTree(projectId: pid, threadId: tid, path: "") }
+ }
+ .morphPill(.secondary, height: 24)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ case .loaded:
+ let rows = visibleTreeRows(projectId: pid, threadId: tid)
+ if rows.isEmpty {
+ Text("이 폴더에 파일이 없습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ } else {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(rows) { row in
+ treeRow(row, projectId: pid, threadId: tid)
+ }
+ }
+ }
+ }
+ } else {
+ Text("프로젝트를 선택하면 파일이 표시됩니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+
+ private func visibleTreeRows(projectId: String, threadId: String?) -> [TreeRow] {
+ var out: [TreeRow] = []
+ func append(path: String, depth: Int) {
+ let key = state.workspaceTreeKey(projectId: projectId, threadId: threadId, path: path)
+ guard let entries = state.codeWorkspaceTreeByKey[key] else {
+ out.append(TreeRow(id: "loading:\(key)", entry: nil, depth: depth, loadingPath: path))
+ return
+ }
+ let sorted = entries.sorted { lhs, rhs in
+ if lhs.isDir != rhs.isDir { return lhs.isDir }
+ return lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending
+ }
+ for entry in sorted {
+ out.append(TreeRow(id: entry.path, entry: entry, depth: depth))
+ if entry.isDir, expandedTreeKeys.contains(state.workspaceTreeKey(projectId: projectId, threadId: threadId, path: entry.path)) {
+ append(path: entry.path, depth: depth + 1)
+ }
+ }
+ }
+ append(path: "", depth: 0)
+ return out
+ }
+
+ @ViewBuilder
+ private func treeRow(_ row: TreeRow, projectId: String, threadId: String?) -> some View {
+ let indent = CGFloat(row.depth) * 14
+ if let entry = row.entry {
+ let key = state.workspaceTreeKey(projectId: projectId, threadId: threadId, path: entry.path)
+ let expanded = entry.isDir && expandedTreeKeys.contains(key)
+ HStack(spacing: 6) {
+ Button {
+ if entry.isDir {
+ toggleDirectory(entry, projectId: projectId, threadId: threadId)
+ } else {
+ state.openCodeFileInReader(projectId: projectId, threadId: threadId, path: entry.path, line: nil)
+ }
+ } label: {
+ HStack(spacing: 6) {
+ Group {
+ if entry.isDir {
+ Image(systemName: expanded ? "chevron.down" : "chevron.right")
+ .font(.system(size: 8.5, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ } else {
+ Color.clear
+ }
+ }
+ .frame(width: 10, height: 10)
+ Image(systemName: Self.fileIcon(for: entry, expanded: expanded))
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(entry.isDir ? AnymorphColor.fgSecondary : AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(entry.name)
+ .anymorphText(.footnote, weight: entry.isDir ? .emphasis : .base, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 4)
+ if !entry.isDir, let size = entry.sizeBytes {
+ Text(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ .lineLimit(1)
+ }
+ }
+ .padding(.leading, indent)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(entry.path)
+
+ Button {
+ insertMention(entry.path)
+ } label: {
+ Text("@")
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgSecondary, monospaced: true)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("입력창에 @\(entry.path) 추가")
+ }
+ .padding(.vertical, 2)
+ .padding(.horizontal, 4)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous).fill(Color.clear))
+ .contextMenu {
+ if !entry.isDir {
+ Button("파일 열기") {
+ state.openCodeFileInReader(projectId: projectId, threadId: threadId, path: entry.path, line: nil)
+ }
+ #if os(macOS)
+ if let localURL = state.resolveLocalCodeFileURL(
+ source: entry.path,
+ projectId: projectId,
+ threadId: threadId,
+ isLocal: state.isLocalCodeProject(projectId)
+ ) {
+ Button("Finder에서 보기") {
+ NSWorkspace.shared.activateFileViewerSelecting([localURL])
+ }
+ }
+ #endif
+ }
+ Button("입력창에 @멘션 추가") { insertMention(entry.path) }
+ }
+ } else {
+ let path = row.loadingPath ?? ""
+ let key = state.workspaceTreeKey(projectId: projectId, threadId: threadId, path: path)
+ let nodeState = CodeWorkspaceTreeNodeState.resolve(
+ hasEntries: false,
+ isLoading: state.codeWorkspaceTreeLoadingKeys.contains(key),
+ loadError: state.codeWorkspaceTreeErrorByKey[key]
+ )
+ HStack(spacing: 6) {
+ switch nodeState {
+ case .loading, .loaded:
+ MorphRunningDots(dotSize: 1.8, spacing: 1.8)
+ Text("불러오는 중…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ case .failed:
+ Text("폴더를 불러오지 못했습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ Button("다시 시도") {
+ Task { await state.loadCodeWorkspaceTree(projectId: projectId, threadId: threadId, path: path) }
+ }
+ .morphPill(.secondary, height: 20)
+ }
+ }
+ .padding(.leading, indent + 20)
+ .padding(.vertical, 3)
+ }
+ }
+
+ private func toggleDirectory(_ entry: CodeWorkspaceTreeEntry, projectId: String, threadId: String?) {
+ let key = state.workspaceTreeKey(projectId: projectId, threadId: threadId, path: entry.path)
+ if expandedTreeKeys.contains(key) {
+ expandedTreeKeys.remove(key)
+ return
+ }
+ expandedTreeKeys.insert(key)
+ if state.codeWorkspaceTreeByKey[key] == nil {
+ Task { await state.loadCodeWorkspaceTree(projectId: projectId, threadId: threadId, path: entry.path) }
+ }
+ }
+
+ private func reloadTree(projectId: String) {
+ let tid = activeThread?.id
+ let prefix = state.workspaceTreeKey(projectId: projectId, threadId: tid, path: "")
+ let expandedPaths = expandedTreeKeys
+ .filter { $0.hasPrefix(prefix) }
+ .map { String($0.dropFirst(prefix.count)) }
+ Task {
+ await state.loadCodeWorkspaceTree(projectId: projectId, threadId: tid, path: "")
+ for path in expandedPaths where !path.isEmpty {
+ await state.loadCodeWorkspaceTree(projectId: projectId, threadId: tid, path: path)
+ }
+ }
+ }
+
+ private func insertMention(_ path: String) {
+ let mention = "@\(path) "
+ if state.codeComposerText.isEmpty || state.codeComposerText.hasSuffix(" ") || state.codeComposerText.hasSuffix("\n") {
+ state.codeComposerText += mention
+ } else {
+ state.codeComposerText += " " + mention
+ }
+ }
+
+ static func fileIcon(for entry: CodeWorkspaceTreeEntry, expanded: Bool) -> String {
+ if entry.isDir { return expanded ? "folder.fill" : "folder" }
+ let ext = (entry.ext ?? (entry.name as NSString).pathExtension).lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "."))
+ switch ext {
+ case "swift": return "swift"
+ case "png", "jpg", "jpeg", "gif", "webp", "heic", "svg", "ico": return "photo"
+ case "md", "mdx", "markdown", "txt", "rtf": return "doc.plaintext"
+ case "json", "yaml", "yml", "toml", "plist", "xml": return "curlybraces"
+ case "pdf": return "doc.richtext"
+ case "zip", "gz", "tar": return "archivebox"
+ case "sh", "zsh", "bash": return "terminal"
+ default: return "doc.text"
+ }
+ }
+
+ private var artifactsPane: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Documents & Artifacts")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+
+ let items = state.codeArtifacts.filter { art in
+ guard let pid = activeProject?.id else { return true }
+ return art.projectId == pid
+ }
+
+ if items.isEmpty {
+ Text("No artifacts created in this project yet.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ } else {
+ ForEach(items) { art in
+ let isImage = art.kind == "image" || art.mimeType.lowercased().hasPrefix("image/")
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ Image(systemName: isImage ? "photo" : "doc.text")
+ .font(.system(size: 14, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 20)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(art.name)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(art.filePath)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ }
+ Spacer()
+ if !isImage {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ }
+ if isImage {
+ let src = art.contentUrl ?? "/v1/code/artifacts/\(art.id)/content"
+ MorphInlineImageView(
+ source: src,
+ alt: "",
+ maxHeight: 180,
+ loader: { s in
+ await state.loadCodeFileData(
+ source: s,
+ projectId: art.projectId,
+ threadId: art.threadId,
+ isLocal: state.isLocalCodeProject(art.projectId)
+ )
+ },
+ onTap: { _, data in
+ lightboxImage = MorphLightboxImageItem(title: art.name, data: data)
+ }
+ )
+ } else if let preview = art.previewText, !preview.isEmpty {
+ Text(preview)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(5)
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+ }
+ .padding(10)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous))
+ .morphPointerCursor(!isImage)
+ .onTapGesture {
+ guard !isImage else { return }
+ openArtifact(art)
+ }
+ .accessibilityElement(children: isImage ? .contain : .combine)
+ .accessibilityAddTraits(isImage ? [] : .isButton)
+ }
+ }
+ }
+ }
+
+ private func openArtifact(_ art: CodeArtifact) {
+ let localURL: URL?
+ if let pid = activeProject?.id, !art.filePath.isEmpty {
+ localURL = state.resolveLocalCodeFileURL(
+ source: art.filePath,
+ projectId: pid,
+ threadId: activeThread?.id,
+ isLocal: state.isLocalCodeProject(pid)
+ )
+ } else {
+ localURL = nil
+ }
+ openedFile = MorphFileItem(
+ id: art.id,
+ name: art.name,
+ path: art.filePath,
+ mimeType: art.mimeType,
+ text: art.previewText,
+ source: art.contentUrl ?? "/v1/code/artifacts/\(art.id)/content",
+ localURL: localURL
+ )
+ }
+}
+
+// MARK: - 3. Multi-Tab Interactive Terminal
+
+extension MorphCodeInspectorView {
+ private var terminalPane: some View {
+ let pid = activeProject?.id ?? ""
+ let threadId = activeThread?.id
+ let tabs = pid.isEmpty ? [] : state.terminalTabs(projectId: pid, threadId: threadId)
+ let activeKey = pid.isEmpty ? "" : state.activeTerminalSessionKey(projectId: pid, threadId: threadId)
+ let activeTabId = tabs.first(where: { $0.sessionKey == activeKey })?.id
+ let session = state.codeTerminalSessions[activeKey]
+
+ return VStack(spacing: 0) {
+ terminalTabBar(tabs: tabs, activeTabId: activeTabId, activeKey: activeKey, projectId: pid, threadId: threadId)
+ terminalActionBar(session: session, sessionKey: activeKey, projectId: pid, threadId: threadId)
+
+ if pid.isEmpty {
+ Text("프로젝트를 선택하면 터미널을 열 수 있습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .padding(14)
+ } else {
+ InspectorTerminalArea(
+ state: state,
+ primaryKey: activeKey,
+ splitKey: state.codeTerminalSplitKeyByPrimary[activeKey],
+ projectId: pid,
+ threadId: threadId,
+ isWide: isWide,
+ isSearchVisible: $showTerminalSearch,
+ query: $terminalSearchQuery,
+ activeIndex: $terminalSearchIndex,
+ onOpenURL: { url in openTerminalURL(url, projectId: pid, threadId: threadId) },
+ onOpenFileLink: { path, line in openTerminalFile(path: path, line: line, projectId: pid, threadId: threadId) }
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ agentLogSection
+ }
+ .task(id: "terminal|\(pid)|\(threadId ?? "")|\(activeKey)") {
+ guard !pid.isEmpty, !activeKey.isEmpty else { return }
+ let cursor = state.codeTerminalCursorByKey[activeKey]
+ await state.ensureCodeTerminalSession(
+ sessionKey: activeKey,
+ projectId: pid,
+ threadId: threadId,
+ cols: cursor?.columns ?? 100,
+ rows: cursor?.rows ?? 28
+ )
+ }
+ #if DEBUG
+ .onChange(of: MorphInspectorQA.shared.terminalSearch) { _, query in
+ guard let query else { return }
+ MorphInspectorQA.shared.terminalSearch = nil
+ terminalSearchQuery = query
+ showTerminalSearch = true
+ }
+ #endif
+ }
+
+ /// Opens a link clicked in the terminal: local dev servers in the preview tab, web pages in the browser, files in the
+ /// code reader.
+ private func openTerminalURL(_ url: URL, projectId: String, threadId: String?) {
+ if url.isFileURL {
+ openTerminalFile(path: url.path, line: nil, projectId: projectId, threadId: threadId)
+ return
+ }
+ let host = (url.host() ?? "").lowercased()
+ if ["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"].contains(host) {
+ state.codePreviewURLByProject[projectId] = MorphWebPreviewView.normalizedURL(url.absoluteString)?.absoluteString ?? url.absoluteString
+ state.codeInspectorSection = .preview
+ return
+ }
+ openURL(url)
+ }
+
+ private func openTerminalFile(path: String, line: Int?, projectId: String, threadId: String?) {
+ var relative = path
+ if let root = activeWorkDir, relative.hasPrefix(root + "/") {
+ relative = String(relative.dropFirst(root.count + 1))
+ }
+ if relative.hasPrefix("./") {
+ relative = String(relative.dropFirst(2))
+ }
+ state.openCodeFileInReader(projectId: projectId, threadId: threadId, path: relative, line: line)
+ }
+
+ private func terminalTabBar(tabs: [CodeTerminalTab], activeTabId: String?, activeKey: String, projectId: String, threadId: String?) -> some View {
+ let isSplit = state.codeTerminalSplitKeyByPrimary[activeKey] != nil
+ return HStack(spacing: 4) {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 4) {
+ ForEach(tabs) { tab in
+ terminalTabChip(tab, isActive: tab.id == activeTabId, canClose: tabs.count > 1, projectId: projectId, threadId: threadId)
+ }
+ }
+ }
+ Button {
+ withAnimation(AnymorphMotion.fast) { showTerminalSearch.toggle() }
+ if !showTerminalSearch { terminalSearchQuery = "" }
+ } label: {
+ Image(systemName: "magnifyingglass")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(showTerminalSearch ? AnymorphColor.fgPrimary : AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(projectId.isEmpty)
+ #if os(iOS)
+ .keyboardShortcut("f", modifiers: .command)
+ #endif
+ .help("터미널 검색 (⌘F)")
+
+ Button {
+ guard !projectId.isEmpty, !activeKey.isEmpty else { return }
+ Task {
+ if isSplit {
+ await state.closeCodeTerminalSplit(primaryKey: activeKey, projectId: projectId)
+ } else {
+ await state.openCodeTerminalSplit(primaryKey: activeKey, projectId: projectId, threadId: threadId)
+ }
+ }
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: isWide ? "rectangle.split.2x1" : "rectangle.split.1x2")
+ .font(.system(size: 10.5, weight: .medium))
+ Text("Split")
+ }
+ }
+ .anymorphButton(size: .inline, appearance: isSplit ? .secondary : .ghost)
+ .disabled(projectId.isEmpty)
+ .help(isSplit ? "분할 닫기" : "터미널을 두 개로 나누기")
+ .accessibilityAddTraits(isSplit ? .isSelected : [])
+
+ Button {
+ guard !projectId.isEmpty else { return }
+ Task { await state.createAdditionalTerminalTab(projectId: projectId, threadId: threadId) }
+ } label: {
+ Image(systemName: "plus")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(projectId.isEmpty)
+ .help("새 터미널 탭")
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .overlay(alignment: .bottom) { AnymorphDivider() }
+ }
+
+ private func terminalTabChip(_ tab: CodeTerminalTab, isActive: Bool, canClose: Bool, projectId: String, threadId: String?) -> some View {
+ let running = state.codeTerminalSessions[tab.sessionKey]?.running == true
+ return HStack(spacing: 5) {
+ Button {
+ state.selectTerminalTab(tab.id, projectId: projectId, threadId: threadId)
+ } label: {
+ HStack(spacing: 5) {
+ Circle()
+ .fill(running ? AnymorphColor.fgPrimary : AnymorphColor.fgQuaternary)
+ .frame(width: 5, height: 5)
+ Text(tab.title)
+ .anymorphText(.caption, weight: isActive ? .strong : .emphasis, color: isActive ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ if canClose {
+ Button {
+ Task {
+ await state.closeCodeTerminalSplit(primaryKey: tab.sessionKey, projectId: projectId)
+ await state.closeTerminalTab(tab.id, projectId: projectId, threadId: threadId)
+ }
+ } label: {
+ Image(systemName: "xmark")
+ .font(.system(size: 8, weight: .bold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: 14, height: 14)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("탭 닫기")
+ }
+ }
+ .padding(.horizontal, 8)
+ .frame(height: 24)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(isActive ? AnymorphColor.bgSelected : Color.clear)
+ )
+ }
+
+ private func terminalActionBar(session: CodeTerminalSession?, sessionKey: String, projectId: String, threadId: String?) -> some View {
+ let scripts = state.codeProjectScriptsByProject[projectId] ?? []
+ let running = session?.running == true
+ return ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ Text(session.map { URL(fileURLWithPath: $0.shell).lastPathComponent } ?? "shell")
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .fixedSize()
+ if let cwd = session?.cwd ?? activeWorkDir {
+ Text(URL(fileURLWithPath: cwd).lastPathComponent)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ .fixedSize()
+ }
+ if let code = session?.exitCode, !running {
+ AnymorphBadge("exit \(code)")
+ .fixedSize()
+ }
+
+ if !scripts.isEmpty {
+ MorphDropdown(placement: .belowTrailing, width: 280, name: "code-terminal-scripts") {
+ MorphMenuSectionHeader("프로젝트 스크립트")
+ ForEach(scripts) { script in
+ MorphMenuItem(script.name, subtitle: script.command, icon: .symbol("play"), isEnabled: running, id: "script-\(script.id)") {
+ Task { await state.sendCodeTerminalInput(sessionKey: sessionKey, projectId: projectId, data: script.command + "\r") }
+ }
+ }
+ } label: {
+ toolLabel("스크립트", icon: "play", showsChevron: true)
+ }
+ .fixedSize()
+ .disabled(projectId.isEmpty)
+ }
+
+ Button {
+ state.sendTerminalOutputToAgent(sessionKey: sessionKey)
+ } label: {
+ toolLabel("Send to agent", icon: "paperplane")
+ }
+ .buttonStyle(.morphPlain)
+ .fixedSize()
+ .disabled(sessionKey.isEmpty)
+ .help("최근 터미널 출력을 입력창에 넣기")
+
+ Button {
+ guard !sessionKey.isEmpty else { return }
+ state.clearCodeTerminalOutput(sessionKey: sessionKey)
+ if running {
+ Task { await state.sendCodeTerminalInput(sessionKey: sessionKey, projectId: projectId, data: "\u{0C}") }
+ }
+ } label: {
+ Image(systemName: "eraser")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("지우기 (⌘K)")
+
+ Button {
+ guard !projectId.isEmpty else { return }
+ let cursor = state.codeTerminalCursorByKey[sessionKey]
+ Task {
+ await state.restartCodeTerminalSession(
+ sessionKey: sessionKey,
+ projectId: projectId,
+ threadId: threadId,
+ cols: cursor?.columns ?? 100,
+ rows: cursor?.rows ?? 28
+ )
+ }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("터미널 세션 재시작")
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ }
+ .overlay(alignment: .bottom) { AnymorphDivider() }
+ }
+
+ @ViewBuilder
+ private var agentLogSection: some View {
+ let termBlocks = Array(
+ (activeThread.flatMap { state.codeMessagesByThread[$0.id] } ?? [])
+ .flatMap { $0.blocks ?? [] }
+ .filter { $0.kind == "terminal" }
+ .suffix(6)
+ )
+ if !termBlocks.isEmpty {
+ VStack(alignment: .leading, spacing: 0) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { showAgentLog.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: showAgentLog ? "chevron.down" : "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ Text("Agent command history (\(termBlocks.count))")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Spacer()
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 7)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+
+ if showAgentLog {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(termBlocks) { blk in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 6) {
+ Text("$ \(blk.command ?? blk.title ?? "")")
+ .anymorphText(.caption, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(2)
+ Spacer()
+ if let code = blk.exitCode, code != 0 {
+ Text("exit \(code)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary, monospaced: true)
+ }
+ }
+ if let out = blk.stdout, !out.isEmpty {
+ Text(out)
+ .font(AnymorphFonts.font(.caption, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .textSelection(.enabled)
+ }
+ if let errOut = blk.stderr, !errOut.isEmpty {
+ Text(errOut)
+ .font(AnymorphFonts.font(.caption, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .textSelection(.enabled)
+ }
+ }
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.bottom, 10)
+ }
+ .frame(maxHeight: 220)
+ }
+ }
+ .overlay(alignment: .top) { AnymorphDivider() }
+ }
+ }
+}
+
+// MARK: - Terminal Area
+
+/// The terminal under the tab bar: an optional search bar and one pane, or two live panes when the tab is split.
+/// It reads the terminal snapshot itself so search results and links follow new output.
+struct InspectorTerminalArea: View {
+ @Bindable var state: MorphAppState
+ let primaryKey: String
+ let splitKey: String?
+ let projectId: String
+ let threadId: String?
+ let isWide: Bool
+ @Binding var isSearchVisible: Bool
+ @Binding var query: String
+ @Binding var activeIndex: Int
+ let onOpenURL: (URL) -> Void
+ let onOpenFileLink: (String, Int?) -> Void
+
+ var body: some View {
+ let _ = state.codeTerminalStyledLines[primaryKey]
+ let matches = isSearchVisible && !query.isEmpty ? state.searchCodeTerminal(sessionKey: primaryKey, query: query) : []
+ let index = matches.isEmpty ? 0 : min(max(activeIndex, 0), matches.count - 1)
+ VStack(spacing: 0) {
+ if isSearchVisible {
+ searchBar(matchCount: matches.count, index: index)
+ }
+ if let splitKey {
+ let layout = isWide ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0))
+ layout {
+ pane(sessionKey: primaryKey, matches: matches, activeIndex: index)
+ Rectangle()
+ .fill(AnymorphColor.strokeLight)
+ .frame(width: isWide ? 1 : nil, height: isWide ? nil : 1)
+ pane(sessionKey: splitKey, matches: [], activeIndex: 0)
+ .task(id: splitKey) {
+ await state.ensureCodeTerminalSession(sessionKey: splitKey, projectId: projectId, threadId: threadId, cols: 80, rows: 24)
+ }
+ }
+ } else {
+ pane(sessionKey: primaryKey, matches: matches, activeIndex: index)
+ }
+ }
+ .onChange(of: query) { _, _ in
+ // A new query starts at the newest match, at the bottom.
+ activeIndex = Int.max
+ }
+ }
+
+ private func pane(sessionKey: String, matches: [TerminalSearchMatch], activeIndex: Int) -> some View {
+ let _ = state.codeTerminalStyledLines[sessionKey]
+ return MorphTerminalView(
+ state: state,
+ sessionKey: sessionKey,
+ projectId: projectId,
+ searchMatches: matches,
+ activeSearchMatchIndex: activeIndex,
+ links: state.detectCodeTerminalLinks(sessionKey: sessionKey),
+ mouseTrackingMode: state.codeTerminalMouseModeByKey[sessionKey] ?? .none,
+ sgrMouseMode: state.codeTerminalSGRMouseByKey[sessionKey] ?? false,
+ onOpenURL: onOpenURL,
+ onOpenFileLink: onOpenFileLink,
+ onFindShortcut: { isSearchVisible = true }
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ private func searchBar(matchCount: Int, index: Int) -> some View {
+ HStack(spacing: 6) {
+ AnymorphTextField("터미널에서 찾기", text: $query, leadingSystemImage: "magnifyingglass", appearance: .filled, focusOnAppear: true) {
+ step(1, count: matchCount, from: index)
+ }
+ .onKeyPress(.escape) {
+ close()
+ return .handled
+ }
+ Text(matchCount == 0 ? (query.isEmpty ? "" : "0/0") : "\(index + 1)/\(matchCount)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true, monospaced: true)
+ .frame(minWidth: 36, alignment: .trailing)
+ Button {
+ step(-1, count: matchCount, from: index)
+ } label: {
+ Image(systemName: "chevron.up")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(matchCount == 0)
+ .help("이전 결과")
+ Button {
+ step(1, count: matchCount, from: index)
+ } label: {
+ Image(systemName: "chevron.down")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(matchCount == 0)
+ .help("다음 결과")
+ Button {
+ close()
+ } label: {
+ MorphLucideIcon(.x, size: 11)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("검색 닫기 (Esc)")
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .overlay(alignment: .bottom) { AnymorphDivider() }
+ }
+
+ private func step(_ delta: Int, count: Int, from index: Int) {
+ guard count > 0 else { return }
+ activeIndex = (index + delta + count) % count
+ }
+
+ private func close() {
+ isSearchVisible = false
+ query = ""
+ }
+}
+
+// MARK: - Checkbox
+
+/// Small ink checkbox in Morph's one-tone style (no system accent color).
+struct InspectorCheckbox: View {
+ let title: String
+ @Binding var isOn: Bool
+
+ var body: some View {
+ Button {
+ isOn.toggle()
+ } label: {
+ HStack(spacing: 6) {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous)
+ .fill(isOn ? AnymorphColor.bgInverse : Color.clear)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous)
+ .strokeBorder(isOn ? AnymorphColor.bgInverse : AnymorphColor.strokeStrongHairline, lineWidth: 1)
+ )
+ .overlay {
+ if isOn {
+ Image(systemName: "checkmark")
+ .font(.system(size: 8, weight: .bold))
+ .foregroundStyle(AnymorphColor.fgInverse)
+ }
+ }
+ .frame(width: 14, height: 14)
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel(title)
+ .accessibilityValue(isOn ? "켬" : "끔")
+ }
+}
+
+// MARK: - CI Checks
+
+struct InspectorCheckSummary {
+ let passed: Int
+ let failed: Int
+ let running: Int
+
+ init(checks: [CodeGitCheckRun]) {
+ var p = 0, f = 0, r = 0
+ for check in checks {
+ switch Self.outcome(check) {
+ case .passed: p += 1
+ case .failed: f += 1
+ case .running: r += 1
+ }
+ }
+ passed = p
+ failed = f
+ running = r
+ }
+
+ var label: String {
+ var parts: [String] = []
+ if passed > 0 { parts.append("통과 \(passed)") }
+ if failed > 0 { parts.append("실패 \(failed)") }
+ if running > 0 { parts.append("진행 \(running)") }
+ return parts.isEmpty ? "체크 없음" : parts.joined(separator: " · ")
+ }
+
+ /// The checks as one state: failed when any failed, running while any runs, passed otherwise.
+ var overall: Outcome {
+ if failed > 0 { return .failed }
+ if running > 0 { return .running }
+ return .passed
+ }
+
+ enum Outcome { case passed, failed, running }
+
+ static func outcome(_ check: CodeGitCheckRun) -> Outcome {
+ let conclusion = check.conclusion.lowercased()
+ let status = check.status.lowercased()
+ switch conclusion {
+ case "success", "neutral", "skipped": return .passed
+ case "failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale": return .failed
+ default: break
+ }
+ if status == "completed" && conclusion.isEmpty { return .passed }
+ return .running
+ }
+
+ static func label(for check: CodeGitCheckRun) -> String {
+ switch outcome(check) {
+ case .passed: return check.conclusion.lowercased() == "skipped" ? "건너뜀" : "통과"
+ case .failed: return "실패"
+ case .running: return check.status.lowercased() == "queued" ? "대기" : "진행 중"
+ }
+ }
+}
+
+/// A check's state as a mark in ink, since Morph tells states apart by mark and word: a quiet check when it
+/// passed, a filled cross when it failed and a dotted ring while it runs.
+struct InspectorCheckMark: View {
+ let outcome: InspectorCheckSummary.Outcome
+
+ var body: some View {
+ Image(systemName: symbol)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(color)
+ .accessibilityHidden(true)
+ }
+
+ private var symbol: String {
+ switch outcome {
+ case .passed: return "checkmark.circle"
+ case .failed: return "xmark.circle.fill"
+ case .running: return "circle.dotted"
+ }
+ }
+
+ private var color: Color {
+ switch outcome {
+ case .passed: return AnymorphColor.fgTertiary
+ case .failed: return AnymorphColor.fgPrimary
+ case .running: return AnymorphColor.fgQuaternary
+ }
+ }
+}
+
+// MARK: - Diff Model & Parser
+
+struct InspectorDiffHunk: Identifiable, Equatable {
+ let index: Int
+ let header: String
+ let oldStart: Int
+ let newStart: Int
+ /// Hunk body lines, each starting with " ", "+", "-" or "\".
+ let body: [String]
+
+ var id: Int { index }
+ var patchText: String { ([header] + body).joined(separator: "\n") }
+
+ init(index: Int, header: String, oldStart: Int, newStart: Int, body: [String]) {
+ self.index = index
+ self.header = header
+ self.oldStart = oldStart
+ self.newStart = newStart
+ self.body = body
+ }
+
+ init(gitHunk: CodeGitDiffHunk) {
+ let lines = gitHunk.lines.first?.hasPrefix("@@") == true ? Array(gitHunk.lines.dropFirst()) : gitHunk.lines
+ self.init(index: gitHunk.index, header: gitHunk.header, oldStart: gitHunk.oldStart, newStart: gitHunk.newStart, body: lines)
+ }
+}
+
+struct InspectorDiffRow: Identifiable, Equatable {
+ enum Kind { case context, add, remove, meta }
+
+ let id: Int
+ let kind: Kind
+ let text: String
+ let oldLine: Int?
+ let newLine: Int?
+
+ var marker: String {
+ switch kind {
+ case .add: return "+"
+ case .remove: return "−"
+ case .context, .meta: return " "
+ }
+ }
+
+ var rawLine: String {
+ switch kind {
+ case .add: return "+" + text
+ case .remove: return "-" + text
+ case .context: return " " + text
+ case .meta: return text
+ }
+ }
+
+ var lineLabel: String? { (newLine ?? oldLine).map(String.init) }
+}
+
+struct InspectorSplitRow: Identifiable {
+ let id: Int
+ let left: InspectorDiffRow?
+ let right: InspectorDiffRow?
+
+ var anchor: InspectorDiffRow? { right ?? left }
+}
+
+enum InspectorDiffParser {
+ static func rows(for hunk: InspectorDiffHunk) -> [InspectorDiffRow] {
+ var out: [InspectorDiffRow] = []
+ out.reserveCapacity(hunk.body.count)
+ var old = hunk.oldStart
+ var new = hunk.newStart
+ for (index, line) in hunk.body.enumerated() {
+ let first = line.first
+ let rest = String(line.dropFirst())
+ switch first {
+ case "+":
+ out.append(InspectorDiffRow(id: index, kind: .add, text: rest, oldLine: nil, newLine: new))
+ new += 1
+ case "-":
+ out.append(InspectorDiffRow(id: index, kind: .remove, text: rest, oldLine: old, newLine: nil))
+ old += 1
+ case "\\":
+ out.append(InspectorDiffRow(id: index, kind: .meta, text: line, oldLine: nil, newLine: nil))
+ default:
+ out.append(InspectorDiffRow(id: index, kind: .context, text: rest, oldLine: old, newLine: new))
+ old += 1
+ new += 1
+ }
+ }
+ return out
+ }
+
+ /// Pairs removed and added runs side by side; context lines appear on both sides.
+ static func splitRows(_ rows: [InspectorDiffRow]) -> [InspectorSplitRow] {
+ var out: [InspectorSplitRow] = []
+ var removed: [InspectorDiffRow] = []
+ var added: [InspectorDiffRow] = []
+ var nextId = 0
+
+ func flush() {
+ let count = max(removed.count, added.count)
+ for i in 0.. CGFloat {
+ let maxLine = rows.reduce(0) { max($0, $1.oldLine ?? 0, $1.newLine ?? 0) }
+ let digits = max(2, String(maxLine).count)
+ return CGFloat(digits) * 7 + 8
+ }
+
+ /// Splits a unified `git diff` into hunks per file path.
+ static func parseFiles(diff: String) -> [String: [InspectorDiffHunk]] {
+ guard !diff.isEmpty else { return [:] }
+ var result: [String: [InspectorDiffHunk]] = [:]
+ var currentPath: String?
+ var hunks: [InspectorDiffHunk] = []
+ var header: String?
+ var oldStart = 0
+ var newStart = 0
+ var body: [String] = []
+
+ func flushHunk() {
+ if let h = header {
+ hunks.append(InspectorDiffHunk(index: hunks.count, header: h, oldStart: oldStart, newStart: newStart, body: body))
+ }
+ header = nil
+ body = []
+ }
+ func flushFile() {
+ flushHunk()
+ if let path = currentPath, !hunks.isEmpty {
+ result[path, default: []] += hunks
+ }
+ hunks = []
+ }
+
+ for sub in diff.split(separator: "\n", omittingEmptySubsequences: false) {
+ let line = String(sub)
+ if line.hasPrefix("diff --git ") {
+ flushFile()
+ if let range = line.range(of: " b/", options: .backwards) {
+ currentPath = String(line[range.upperBound...])
+ } else {
+ currentPath = nil
+ }
+ continue
+ }
+ if header != nil, let first = line.first, first == " " || first == "+" || first == "-" || first == "\\" {
+ body.append(line)
+ continue
+ }
+ if line.hasPrefix("@@") {
+ flushHunk()
+ let parsed = parseHunkHeader(line)
+ header = line
+ oldStart = parsed.old
+ newStart = parsed.new
+ continue
+ }
+ if line.hasPrefix("+++ ") {
+ let p = String(line.dropFirst(4))
+ if p != "/dev/null" {
+ currentPath = p.hasPrefix("b/") ? String(p.dropFirst(2)) : p
+ }
+ }
+ }
+ flushFile()
+ return result
+ }
+
+ static func parseHunkHeader(_ line: String) -> (old: Int, new: Int) {
+ let parts = line.split(separator: " ")
+ func start(_ token: Substring?) -> Int {
+ guard let token else { return 1 }
+ let numbers = token.dropFirst().split(separator: ",")
+ return numbers.first.flatMap { Int($0) } ?? 1
+ }
+ let oldToken = parts.first(where: { $0.hasPrefix("-") })
+ let newToken = parts.first(where: { $0.hasPrefix("+") })
+ return (start(oldToken), start(newToken))
+ }
+}
+
+// MARK: - Hunk View (syntax-highlighted unified / side-by-side diff with inline review)
+
+struct InspectorHunkAction: Identifiable {
+ let id: String
+ let title: String
+ let isProminent: Bool
+ let perform: () -> Void
+}
+
+/// Bounded MainActor cache for parsed diff rows, split pairs, and syntax-highlighted lines in `InspectorHunkView`
+/// so mouse hover never re-parses or re-tokenizes diff lines.
+@MainActor
+private final class InspectorHunkRenderCache {
+ static let shared = InspectorHunkRenderCache()
+
+ struct CachedHunk {
+ let rows: [InspectorDiffRow]
+ let splitRows: [InspectorSplitRow]
+ let gutter: CGFloat
+ let attributedByRowId: [Int: AttributedString]
+ }
+
+ private struct Key: Hashable {
+ let header: String
+ let oldStart: Int
+ let newStart: Int
+ let bodyHash: Int
+ let bodyCount: Int
+ let exactBody: String?
+ let language: String
+ }
+
+ private struct Entry {
+ let value: CachedHunk
+ var lastUsed: UInt64
+ }
+
+ private var entries: [Key: Entry] = [:]
+ private var tick: UInt64 = 0
+ private let maxEntries = 128
+
+ func cached(for hunk: InspectorDiffHunk, language: String, fontSize: CGFloat) -> CachedHunk {
+ var hasher = Hasher()
+ var totalUTF8 = 0
+ for line in hunk.body {
+ hasher.combine(line)
+ totalUTF8 += line.utf8.count + 1
+ }
+ let exactBody: String? = totalUTF8 <= 32_768 ? hunk.body.joined(separator: "\n") : nil
+ let key = Key(
+ header: hunk.header,
+ oldStart: hunk.oldStart,
+ newStart: hunk.newStart,
+ bodyHash: hasher.finalize(),
+ bodyCount: hunk.body.count,
+ exactBody: exactBody,
+ language: language
+ )
+ tick &+= 1
+ if var hit = entries[key] {
+ hit.lastUsed = tick
+ entries[key] = hit
+ return hit.value
+ }
+
+ let rows = InspectorDiffParser.rows(for: hunk)
+ let splitRows = InspectorDiffParser.splitRows(rows)
+ let gutter = InspectorDiffParser.gutterWidth(for: rows)
+ var attributedByRowId: [Int: AttributedString] = [:]
+ attributedByRowId.reserveCapacity(rows.count)
+ for row in rows where row.kind != .meta && !row.text.isEmpty {
+ let tokens = MorphSyntaxHighlighter.tokenize(row.text, language: language).first ?? [SyntaxToken(text: row.text, kind: .plain)]
+ attributedByRowId[row.id] = MorphSyntaxPalette.attributedLine(tokens, fontSize: fontSize)
+ }
+
+ let value = CachedHunk(rows: rows, splitRows: splitRows, gutter: gutter, attributedByRowId: attributedByRowId)
+ if entries.count >= maxEntries {
+ let removeCount = max(1, maxEntries / 4)
+ let oldest = entries.sorted { $0.value.lastUsed < $1.value.lastUsed }.prefix(removeCount)
+ for (k, _) in oldest {
+ entries.removeValue(forKey: k)
+ }
+ }
+ entries[key] = Entry(value: value, lastUsed: tick)
+ return value
+ }
+}
+
+struct InspectorHunkView: View {
+ let hunk: InspectorDiffHunk
+ let path: String
+ let language: String
+ let layout: InspectorDiffLayout
+ let actions: [InspectorHunkAction]
+ let onReview: (_ lineRange: String?, _ snippet: String, _ instruction: String) -> Void
+
+ /// -1 for the whole hunk, otherwise the row id the review box opens under.
+ @State private var reviewAnchor: Int?
+ @State private var reviewDraft = ""
+ @State private var hoveredRow: Int?
+
+ private static let codeFontSize: CGFloat = 11.5
+ private static let hunkAnchor = -1
+
+ var body: some View {
+ let cached = InspectorHunkRenderCache.shared.cached(for: hunk, language: language, fontSize: Self.codeFontSize)
+ let rows = cached.rows
+ let gutter = cached.gutter
+ VStack(alignment: .leading, spacing: 0) {
+ header
+ if reviewAnchor == Self.hunkAnchor {
+ reviewBox(lineRange: hunkRange(rows), snippet: hunk.patchText)
+ }
+ if layout == .split {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(cached.splitRows) { pair in
+ splitRow(pair, gutter: gutter, attributed: cached.attributedByRowId)
+ if let anchor = pair.anchor, reviewAnchor == anchor.id {
+ reviewBox(lineRange: anchor.lineLabel, snippet: [pair.left?.rawLine, pair.right?.rawLine].compactMap { $0 }.uniqued().joined(separator: "\n"))
+ }
+ }
+ }
+ } else {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(rows) { row in
+ unifiedRow(row, gutter: gutter, attributed: cached.attributedByRowId)
+ if reviewAnchor == row.id {
+ reviewBox(lineRange: row.lineLabel, snippet: row.rawLine)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private var header: some View {
+ HStack(spacing: 6) {
+ Text(hunk.header)
+ .anymorphText(.caption, weight: .emphasis, color: MorphSyntaxPalette.diffHeaderFg, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ Spacer(minLength: 4)
+ Button {
+ openReview(Self.hunkAnchor)
+ } label: {
+ HStack(spacing: 3) {
+ Image(systemName: "text.bubble")
+ .font(.system(size: 10, weight: .medium))
+ Text("수정 요청")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("이 hunk에 대한 수정 요청을 입력창에 추가")
+ ForEach(actions) { action in
+ Button(action.title, action: action.perform)
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .emphasis, color: action.isProminent ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .background(MorphSyntaxPalette.diffHeaderBg)
+ }
+
+ private func lineNumber(_ value: Int?, width: CGFloat) -> some View {
+ Text(value.map(String.init) ?? "")
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: width, alignment: .trailing)
+ .padding(.trailing, 4)
+ }
+
+ private func code(_ row: InspectorDiffRow, attributed: [Int: AttributedString]) -> Text {
+ if row.kind == .meta {
+ return Text(row.text)
+ .font(.system(size: Self.codeFontSize, design: .monospaced).italic())
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ if row.text.isEmpty {
+ return Text(" ").font(.system(size: Self.codeFontSize, design: .monospaced))
+ }
+ if let cached = attributed[row.id] {
+ return Text(cached)
+ }
+ let tokens = MorphSyntaxHighlighter.tokenize(row.text, language: language).first ?? [SyntaxToken(text: row.text, kind: .plain)]
+ return Text(MorphSyntaxPalette.attributedLine(tokens, fontSize: Self.codeFontSize))
+ }
+
+ private static func background(_ kind: InspectorDiffRow.Kind) -> Color {
+ switch kind {
+ case .add: return MorphSyntaxPalette.diffAddBg
+ case .remove: return MorphSyntaxPalette.diffRemoveBg
+ case .context, .meta: return Color.clear
+ }
+ }
+
+ private static func markerColor(_ kind: InspectorDiffRow.Kind) -> Color {
+ switch kind {
+ case .add: return MorphSyntaxPalette.diffAddFg
+ case .remove: return MorphSyntaxPalette.diffRemoveFg
+ case .context, .meta: return AnymorphColor.fgQuaternary
+ }
+ }
+
+ private func unifiedRow(_ row: InspectorDiffRow, gutter: CGFloat, attributed: [Int: AttributedString]) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 0) {
+ lineNumber(row.oldLine, width: gutter)
+ lineNumber(row.newLine, width: gutter)
+ Text(row.marker)
+ .font(.system(size: Self.codeFontSize, weight: .semibold, design: .monospaced))
+ .foregroundStyle(Self.markerColor(row.kind))
+ .frame(width: 14, alignment: .center)
+ code(row, attributed: attributed)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(.vertical, 1)
+ .padding(.trailing, 6)
+ .background(Self.background(row.kind))
+ .overlay(alignment: .topTrailing) {
+ if hoveredRow == row.id, reviewAnchor != row.id, row.kind != .meta {
+ lineReviewButton(row.id)
+ }
+ }
+ .onHover { inside in
+ if inside {
+ hoveredRow = row.id
+ } else if hoveredRow == row.id {
+ hoveredRow = nil
+ }
+ }
+ .contextMenu {
+ if row.kind != .meta {
+ Button("이 줄 수정 요청") { openReview(row.id) }
+ }
+ }
+ }
+
+ private func splitHalf(_ row: InspectorDiffRow?, isOld: Bool, gutter: CGFloat, attributed: [Int: AttributedString]) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 0) {
+ if let row {
+ lineNumber(isOld ? row.oldLine : row.newLine, width: gutter)
+ code(row, attributed: attributed)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ Color.clear.frame(width: gutter + 4, height: 1)
+ Spacer(minLength: 0)
+ }
+ }
+ .padding(.vertical, 1)
+ .padding(.trailing, 6)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .background(row.map { Self.background($0.kind) } ?? AnymorphColor.bgSubtle)
+ }
+
+ private func splitRow(_ pair: InspectorSplitRow, gutter: CGFloat, attributed: [Int: AttributedString]) -> some View {
+ HStack(alignment: .top, spacing: 0) {
+ splitHalf(pair.left, isOld: true, gutter: gutter, attributed: attributed)
+ Rectangle().fill(AnymorphColor.strokeLight).frame(width: 1)
+ splitHalf(pair.right, isOld: false, gutter: gutter, attributed: attributed)
+ }
+ .fixedSize(horizontal: false, vertical: true)
+ .overlay(alignment: .topTrailing) {
+ if let anchor = pair.anchor, hoveredRow == anchor.id, reviewAnchor != anchor.id, anchor.kind != .meta {
+ lineReviewButton(anchor.id)
+ }
+ }
+ .onHover { inside in
+ guard let anchor = pair.anchor else { return }
+ if inside {
+ hoveredRow = anchor.id
+ } else if hoveredRow == anchor.id {
+ hoveredRow = nil
+ }
+ }
+ .contextMenu {
+ if let anchor = pair.anchor, anchor.kind != .meta {
+ Button("이 줄 수정 요청") { openReview(anchor.id) }
+ }
+ }
+ }
+
+ private func lineReviewButton(_ rowId: Int) -> some View {
+ Button {
+ openReview(rowId)
+ } label: {
+ Image(systemName: "text.bubble")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 20, height: 16)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ )
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.trailing, 4)
+ .help("이 줄 수정 요청")
+ }
+
+ private func reviewBox(lineRange: String?, snippet: String) -> some View {
+ let fileName = URL(fileURLWithPath: path).lastPathComponent
+ let trimmed = reviewDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ return VStack(alignment: .leading, spacing: 6) {
+ Text(lineRange.map { "\(fileName):\($0) 수정 요청" } ?? "\(fileName) 수정 요청")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary, monospaced: true)
+ HStack(spacing: 6) {
+ AnymorphTextField("에이전트에게 요청할 수정 내용…", text: $reviewDraft, appearance: .outlined, focusOnAppear: true) {
+ submitReview(lineRange: lineRange, snippet: snippet)
+ }
+ Button("추가") { submitReview(lineRange: lineRange, snippet: snippet) }
+ .morphPill(.primary)
+ .disabled(trimmed.isEmpty)
+ Button {
+ reviewAnchor = nil
+ reviewDraft = ""
+ } label: {
+ MorphLucideIcon(.x, size: 11)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("취소")
+ }
+ }
+ .padding(8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(AnymorphColor.bgSubtle)
+ }
+
+ private func openReview(_ anchor: Int) {
+ withAnimation(AnymorphMotion.fast) {
+ if reviewAnchor != anchor { reviewDraft = "" }
+ reviewAnchor = anchor
+ }
+ }
+
+ private func submitReview(lineRange: String?, snippet: String) {
+ let instruction = reviewDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !instruction.isEmpty else { return }
+ onReview(lineRange, snippet, instruction)
+ reviewDraft = ""
+ reviewAnchor = nil
+ }
+
+ private func hunkRange(_ rows: [InspectorDiffRow]) -> String? {
+ let lines = rows.compactMap(\.newLine)
+ let source = lines.isEmpty ? rows.compactMap(\.oldLine) : lines
+ guard let lo = source.min(), let hi = source.max() else { return nil }
+ return lo == hi ? "\(lo)" : "\(lo)-\(hi)"
+ }
+}
+
+private extension Array where Element: Hashable {
+ func uniqued() -> [Element] {
+ var seen = Set()
+ return filter { seen.insert($0).inserted }
+ }
+}
+
+#if DEBUG
+/// QA screenshots only: opens the terminal's search bar with a query.
+@MainActor
+@Observable
+final class MorphInspectorQA {
+ static let shared = MorphInspectorQA()
+ var terminalSearch: String?
+}
+#endif
diff --git a/apple/Apps/Shared/MorphCodeQueueTray.swift b/apple/Apps/Shared/MorphCodeQueueTray.swift
new file mode 100644
index 000000000..c449a37bf
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeQueueTray.swift
@@ -0,0 +1,192 @@
+import MorphCore
+import SwiftUI
+
+/// What a queue row asks the workspace to do with its request.
+struct MorphCodeQueueActions {
+ var move: (_ itemId: String, _ by: Int) -> Void
+ var beginEdit: (CodeQueuedPrompt) -> Void
+ var saveEdit: (CodeQueuedPrompt) -> Void
+ var cancelEdit: () -> Void
+ var sendNow: (CodeQueuedPrompt) -> Void
+ var delete: (CodeQueuedPrompt) -> Void
+}
+
+/// Requests waiting for the running turn, in the order they will run. The composer draws it on the shelf plate
+/// tucked behind its card, one line per request, as Codex does.
+struct MorphCodeQueueTray: View {
+ let queue: [CodeQueuedPrompt]
+ let editingItemId: String?
+ @Binding var editingText: String
+ /// A phone's narrow composer, where moving a request lives in the row's long-press menu.
+ let compact: Bool
+ let actions: MorphCodeQueueActions
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(queue.enumerated()), id: \.element.id) { index, item in
+ if editingItemId == item.id {
+ MorphCodeQueueEditRow(text: $editingText, onSave: { actions.saveEdit(item) }, onCancel: actions.cancelEdit)
+ } else {
+ MorphCodeQueueRow(
+ item: item,
+ canMoveUp: index > 0,
+ canMoveDown: index < queue.count - 1,
+ compact: compact,
+ actions: actions
+ )
+ }
+ }
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("대기 중인 요청 \(queue.count)개")
+ }
+}
+
+/// One waiting request: a clock, the request on one line, its image count and the controls.
+private struct MorphCodeQueueRow: View {
+ let item: CodeQueuedPrompt
+ let canMoveUp: Bool
+ let canMoveDown: Bool
+ let compact: Bool
+ let actions: MorphCodeQueueActions
+ @State private var hovered = false
+
+ private var showsReorder: Bool {
+ (canMoveUp || canMoveDown) && !compact
+ }
+
+ /// The Mac shows the controls on hover only; touch has no hover, so they always show there.
+ private var showsControls: Bool {
+ #if os(macOS)
+ hovered
+ #else
+ true
+ #endif
+ }
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "clock")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(item.previewLine)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if let images = item.images, !images.isEmpty {
+ Text("이미지 \(images.count)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .monospacedDigit()
+ .fixedSize()
+ }
+ if showsControls {
+ controls
+ .transition(.opacity)
+ }
+ }
+ .padding(.leading, 8)
+ .padding(.trailing, 2)
+ .frame(minHeight: 30)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(hovered ? AnymorphColor.bgHover : Color.clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous))
+ .onHover { hovered = $0 }
+ .animation(AnymorphMotion.fast, value: hovered)
+ .contextMenu { menu }
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("대기 중: \(item.previewLine)")
+ .accessibilityAction(named: "지금 보내기") { actions.sendNow(item) }
+ .accessibilityAction(named: "수정") { actions.beginEdit(item) }
+ .accessibilityAction(named: "삭제") { actions.delete(item) }
+ }
+
+ private var controls: some View {
+ HStack(spacing: 0) {
+ if showsReorder {
+ iconButton(.arrowUp, label: "위로", disabled: !canMoveUp) { actions.move(item.id, -1) }
+ iconButton(.arrowDown, label: "아래로", disabled: !canMoveDown) { actions.move(item.id, 1) }
+ }
+ iconButton(.pencil, label: "수정") { actions.beginEdit(item) }
+ iconButton(.cornerDownRight, label: "지금 보내기") { actions.sendNow(item) }
+ iconButton(.x, label: "삭제") { actions.delete(item) }
+ }
+ }
+
+ @ViewBuilder
+ private var menu: some View {
+ Button("지금 보내기") { actions.sendNow(item) }
+ Button("수정") { actions.beginEdit(item) }
+ if canMoveUp {
+ Button("위로") { actions.move(item.id, -1) }
+ }
+ if canMoveDown {
+ Button("아래로") { actions.move(item.id, 1) }
+ }
+ Divider()
+ Button("삭제") { actions.delete(item) }
+ }
+
+ private func iconButton(_ kind: MorphLucideKind, label: String, disabled: Bool = false, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ MorphLucideIcon(kind, size: 13)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(disabled)
+ .help(label)
+ .accessibilityLabel(label)
+ }
+}
+
+/// A waiting request open for editing, in place of its row. Return saves, Esc cancels.
+private struct MorphCodeQueueEditRow: View {
+ @Binding var text: String
+ let onSave: () -> Void
+ let onCancel: () -> Void
+ @FocusState private var focused: Bool
+
+ private var canSave: Bool {
+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ var body: some View {
+ HStack(alignment: .bottom, spacing: 8) {
+ Image(systemName: "clock")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 14, height: 24)
+ TextField("요청", text: $text, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .lineLimit(1...6)
+ .focused($focused)
+ .onSubmit { if canSave { onSave() } }
+ #if os(macOS)
+ .onExitCommand(perform: onCancel)
+ #endif
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Button("취소", action: onCancel)
+ .anymorphButton(size: .inline, appearance: .ghost)
+ Button("저장", action: onSave)
+ .anymorphButton(size: .inline, appearance: .solid)
+ .disabled(!canSave)
+ }
+ .padding(.leading, 8)
+ .padding(.trailing, 3)
+ .padding(.vertical, 3)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.composerCard)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+ .onAppear { focused = true }
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodeScheduledView.swift b/apple/Apps/Shared/MorphCodeScheduledView.swift
new file mode 100644
index 000000000..977908093
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeScheduledView.swift
@@ -0,0 +1,686 @@
+import SwiftUI
+import MorphCore
+
+/// 예약됨's main area: the task picked in the sidebar, the way ChatGPT shows a scheduled task's conversation. Its
+/// prompt sits as the member's request, then when it runs next, a card to edit it, and the runs it made.
+struct MorphCodeScheduledView: View {
+ @Bindable var state: MorphAppState
+ var topInset: CGFloat = 0
+
+ var body: some View {
+ Group {
+ if let schedule = state.selectedCodeSchedule {
+ CodeScheduleDetail(state: state, schedule: schedule, topInset: topInset)
+ .id(schedule.id)
+ } else {
+ emptyState
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+ }
+
+ private var emptyState: some View {
+ VStack(spacing: 12) {
+ MorphTileIcon("clock", size: 44)
+ Text("예약한 작업이 없습니다")
+ .anymorphText(.headline, weight: .strong, color: AnymorphColor.fgPrimary)
+ Text("매일 아침 점검이나 주간 정리처럼 반복할 지시를 맡기면 정해 둔 시간에 에이전트가 실행합니다.")
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 380)
+ Button {
+ state.editCodeSchedule()
+ } label: {
+ Label("새 작업", systemImage: "plus")
+ }
+ .morphPill(.primary)
+ .padding(.top, 4)
+ }
+ .padding(.top, topInset)
+ .padding(.horizontal, 24)
+ }
+
+ /// "오늘 09:00", "내일 09:00", "어제 18:00" or "12월 3일 (목) 09:00", in this device's time zone.
+ static func runTime(_ iso: String?) -> String? {
+ MorphPalette.scheduledRunTime(iso)
+ }
+
+ /// When a task runs next, for the 예약됨 list: today and tomorrow with the time, a later day by its date alone,
+ /// such as "12월 4일 (금)".
+ static func runDay(_ iso: String?) -> String? {
+ MorphPalette.scheduledRunDay(iso)
+ }
+}
+
+/// One task as a conversation: the day it was made, its prompt, when it runs next, its card, then its runs.
+private struct CodeScheduleDetail: View {
+ @Bindable var state: MorphAppState
+ let schedule: CodeSchedule
+ let topInset: CGFloat
+ @State private var showsFullPrompt = false
+ @State private var showsAllRuns = false
+ /// The task waiting for the member to confirm its deletion.
+ @State private var schedulePendingDelete: CodeSchedule?
+ @State private var isStartingRun = false
+
+ /// Runs the list shows before 더 보기.
+ private static let shownRuns = 5
+
+ /// A run as the list shows it. Only the newest run in a thread carries the thread's live status and unread dot.
+ private struct RunRow: Identifiable {
+ let run: CodeScheduleRun
+ let thread: CodeThread?
+ let isNewestInThread: Bool
+
+ var id: String { run.id }
+ }
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ if let made = MorphCodeScheduledView.runTime(schedule.createdAt) {
+ Text(made)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity)
+ }
+ prompt
+ Text(nextRunLine)
+ .anymorphText(.reading, weight: .base, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ card
+ runs
+ }
+ .frame(maxWidth: MorphCodeWorkspaceView.columnWidth, alignment: .leading)
+ .padding(.horizontal, MorphCodeWorkspaceView.horizontalPadding)
+ .padding(.top, 24 + topInset)
+ .padding(.bottom, 28)
+ .frame(maxWidth: .infinity)
+ }
+ .morphDialog(item: $schedulePendingDelete) { schedule in
+ MorphDialogContent(
+ title: "예약을 삭제할까요?",
+ message: "‘\(schedule.title)’ 예약을 더 실행하지 않습니다. 지난 실행의 스레드는 프로젝트 목록에 남습니다.",
+ confirmTitle: "삭제",
+ isDestructive: true
+ ) { _ in
+ await state.deleteCodeSchedule(schedule)
+ }
+ }
+ }
+
+ /// The task's prompt as the member's request, folded after ten lines.
+ private var prompt: some View {
+ let isLong = schedule.prompt.count > 400 || schedule.prompt.split(separator: "\n").count > 10
+ return VStack(alignment: .trailing, spacing: 6) {
+ CodeRequestBubble(text: schedule.prompt)
+ .lineLimit(isLong && !showsFullPrompt ? 10 : nil)
+ if isLong {
+ Button(showsFullPrompt ? "접기" : "더 보기") {
+ withAnimation(AnymorphMotion.fast) {
+ showsFullPrompt.toggle()
+ }
+ }
+ .morphPill(.plain)
+ }
+ }
+ .frame(maxWidth: 660, alignment: .trailing)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, 60)
+ }
+
+ /// When the task runs next, worded the way ChatGPT confirms a scheduled task.
+ private var nextRunLine: String {
+ guard schedule.enabled else { return "꺼 둔 작업입니다. 다시 켜면 다음 실행 시각을 잡습니다." }
+ guard let next = MorphCodeScheduledView.runTime(schedule.nextRunAt) else { return "다음 실행 시각이 없습니다." }
+ return "예약했습니다. 다음 실행은 \(next)입니다."
+ }
+
+ /// The task's card, as ChatGPT ends a scheduled task's reply: its name, how often and where it runs, 편집, and a
+ /// menu to run it now, turn it off or on, or delete it.
+ private var card: some View {
+ AnymorphCard(.chat) {
+ HStack(spacing: 12) {
+ Image(systemName: "clock")
+ .font(.system(size: 16, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 20)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(schedule.title)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(cardDetail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Button("편집") {
+ state.editCodeSchedule(schedule)
+ }
+ .morphPill(.secondary)
+ MorphDropdown(placement: .belowTrailing, width: 180) {
+ MorphMenuItem("지금 실행", icon: .symbol("play"), isEnabled: !isStartingRun) {
+ isStartingRun = true
+ Task {
+ await state.runCodeScheduleNow(schedule)
+ isStartingRun = false
+ }
+ }
+ MorphMenuItem(schedule.enabled ? "끄기" : "켜기", icon: .symbol(schedule.enabled ? "pause" : "play.circle")) {
+ Task { await state.setCodeScheduleEnabled(schedule, !schedule.enabled) }
+ }
+ MorphMenuDivider()
+ MorphMenuItem("삭제", icon: .symbol("trash")) {
+ schedulePendingDelete = schedule
+ }
+ } label: {
+ Image(systemName: "ellipsis")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 28, height: 28)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxl))
+ }
+ .accessibilityLabel("작업 메뉴")
+ }
+ .padding(14)
+ }
+ }
+
+ /// How often the task runs and where its runs go: its project or the thread it runs in.
+ private var cardDetail: String {
+ let when = CodeScheduleCadence.label(for: schedule.rrule, timezone: schedule.timezone)
+ let place = schedule.threadId.flatMap { id in state.codeThreads.first { $0.id == id }?.title }.map { "스레드 \($0)" }
+ ?? state.codeProjects.first { $0.id == schedule.projectId }?.name
+ let local = state.isLocalCodeSchedule(schedule.id) ? state.localDeviceDisplayName : nil
+ return [when, place, local].compactMap { $0 }.joined(separator: " · ")
+ }
+
+ /// The task's runs, newest first. A started run whose thread was archived or deleted stays out.
+ private var runRows: [RunRow] {
+ var seenThreads = Set()
+ return schedule.runs.compactMap { run in
+ let thread = run.threadId.flatMap { id in state.codeThreads.first { $0.id == id } }
+ guard run.status == "started" else {
+ return RunRow(run: run, thread: thread, isNewestInThread: false)
+ }
+ guard let thread, !thread.isEffectivelyArchived else { return nil }
+ return RunRow(run: run, thread: thread, isNewestInThread: seenThreads.insert(thread.id).inserted)
+ }
+ }
+
+ @ViewBuilder
+ private var runs: some View {
+ let rows = runRows
+ if !rows.isEmpty {
+ MorphSettingsGroup("실행 기록") {
+ ForEach(showsAllRuns ? rows : Array(rows.prefix(Self.shownRuns))) { row in
+ if let thread = row.thread, row.run.status == "started" {
+ startedRow(row.run, thread: thread, isNewest: row.isNewestInThread)
+ } else {
+ missedRow(row.run)
+ }
+ }
+ if rows.count > Self.shownRuns {
+ moreRow(hidden: rows.count - Self.shownRuns)
+ }
+ }
+ }
+ }
+
+ /// A run that started, by its time and what its thread is doing. It opens the thread.
+ private func startedRow(_ run: CodeScheduleRun, thread: CodeThread, isNewest: Bool) -> some View {
+ let status = isNewest ? threadStatus(thread) : (icon: "checkmark.circle", text: "완료")
+ let unseen = isNewest && thread.unreadCount > 0
+ let time = MorphCodeScheduledView.runTime(run.startedAt)
+ return Button {
+ Task { await state.selectCodeThread(thread) }
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: status.icon)
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 16)
+ if let time {
+ Text(time)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ }
+ Text(status.text)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ if unseen {
+ Circle()
+ .fill(AnymorphColor.fgPrimary)
+ .frame(width: 7, height: 7)
+ .accessibilityHidden(true)
+ }
+ Image(systemName: "chevron.right")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ .padding(.horizontal, 16)
+ .frame(minHeight: 40)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel([time, status.text, unseen ? "안 읽음" : nil].compactMap { $0 }.joined(separator: ", "))
+ }
+
+ /// A run that did not start: skipped while the thread was still busy, or refused by the server. It reads like a
+ /// started run, with the time first and the reason after the status.
+ private func missedRow(_ run: CodeScheduleRun) -> some View {
+ let skipped = run.status == "skipped"
+ let time = MorphCodeScheduledView.runTime(run.startedAt)
+ let status = [skipped ? "건너뜀" : "시작하지 못함", run.note].compactMap { $0 }.joined(separator: " · ")
+ return HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Image(systemName: skipped ? "forward.end" : "exclamationmark.triangle")
+ .font(.system(size: 12, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 16)
+ if let time {
+ Text(time)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ .fixedSize()
+ }
+ Text(status)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 11)
+ }
+
+ private func moreRow(hidden: Int) -> some View {
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ showsAllRuns.toggle()
+ }
+ } label: {
+ HStack {
+ Text(showsAllRuns ? "접기" : "실행 \(hidden)개 더 보기")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Spacer()
+ }
+ .padding(.horizontal, 16)
+ .frame(minHeight: 36)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+
+ /// What a run's thread is doing now.
+ private func threadStatus(_ thread: CodeThread) -> (icon: String, text: String) {
+ if state.codeLiveRuns[thread.id] != nil || thread.status == "running" { return ("play.circle", "Running") }
+ if thread.status == "awaiting_approval" { return ("hand.raised", "승인 필요") }
+ if thread.status == "error" { return ("exclamationmark.triangle", "작업 실패") }
+ return ("checkmark.circle", "완료")
+ }
+}
+
+/// The scheduled task editor, the way Codex edits an automation: what the agent runs, where the runs go, when, and the
+/// model, effort and access it runs with.
+struct CodeScheduleEditorSheet: View {
+ @Bindable var state: MorphAppState
+ let draft: CodeScheduleDraft
+ @Environment(\.dismiss) private var dismiss
+ @State private var title: String
+ @State private var prompt: String
+ @State private var projectId: String
+ @State private var runsInThread: Bool
+ @State private var cadence: CodeScheduleCadence
+ @State private var model: String
+ @State private var effort: CodeReasoningEffort
+ @State private var accessMode: CodeAccessMode
+ @State private var isSaving = false
+
+ init(state: MorphAppState, draft: CodeScheduleDraft) {
+ self.state = state
+ self.draft = draft
+ let schedule = draft.schedule
+ let threadId = schedule?.threadId ?? draft.threadId
+ let thread = state.codeThreads.first { $0.id == threadId }
+ _title = State(initialValue: schedule?.title ?? "")
+ _prompt = State(initialValue: schedule?.prompt ?? "")
+ _projectId = State(initialValue: schedule?.projectId ?? thread?.projectId ?? state.selectedCodeThread?.projectId ?? state.codeFolderProjects.first?.id ?? "")
+ _runsInThread = State(initialValue: threadId != nil)
+ _cadence = State(initialValue: schedule.map { CodeScheduleCadence(rrule: $0.rrule) } ?? CodeScheduleCadence())
+ _model = State(initialValue: schedule?.model ?? thread?.model ?? state.selectedCodeModel)
+ _effort = State(initialValue: schedule?.reasoningEffort.flatMap(CodeReasoningEffort.init(rawValue:)) ?? thread?.reasoningEffort ?? state.selectedCodeEffort)
+ _accessMode = State(initialValue: schedule?.accessMode.flatMap(CodeAccessMode.init(rawValue:)) ?? thread?.accessMode ?? .defaultPermissions)
+ }
+
+ /// The thread the task runs in, or was made from.
+ private var thread: CodeThread? {
+ state.codeThreads.first { $0.id == (draft.schedule?.threadId ?? draft.threadId) }
+ }
+
+ private var isLocalProject: Bool {
+ state.isLocalCodeProject(projectId)
+ }
+
+ private var projectName: String {
+ state.codeProjects.first { $0.id == projectId }?.name ?? "프로젝트 없음"
+ }
+
+ /// A new task runs on this device's wall clock; a saved one keeps its own.
+ private var timezone: String {
+ draft.schedule?.timezone ?? TimeZone.current.identifier
+ }
+
+ private var canSave: Bool {
+ !isSaving && !projectId.isEmpty && !cadence.rrule.isEmpty
+ && !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+ Text(draft.schedule == nil ? "새 작업" : "예약 편집")
+ .anymorphText(.headline, weight: .strong, color: AnymorphColor.fgPrimary)
+ taskFields
+ placeGroup
+ cadenceGroup
+ agentGroup
+ }
+ .padding(20)
+ }
+ AnymorphDivider()
+ HStack(spacing: 6) {
+ Spacer()
+ Button("취소") { dismiss() }
+ .morphPill(.plain)
+ .keyboardShortcut(.cancelAction)
+ Button(draft.schedule == nil ? "예약 만들기" : "저장", action: save)
+ .morphPill(.primary)
+ .disabled(!canSave)
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 14)
+ }
+ #if os(macOS)
+ .frame(width: 560, height: 680)
+ #endif
+ .background(AnymorphColor.bgBase)
+ }
+
+ private var taskFields: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ AnymorphTextField("이름 (비우면 지시에서 만듭니다)", text: $title)
+ ZStack(alignment: .topLeading) {
+ TextEditor(text: $prompt)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .scrollContentBackground(.hidden)
+ .padding(8)
+ .accessibilityLabel("지시")
+ if prompt.isEmpty {
+ Text("예: main에서 실패한 테스트를 확인하고 원인을 정리해 줘")
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgQuaternary)
+ .padding(.horizontal, 13)
+ .padding(.vertical, 8)
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+ }
+ .frame(minHeight: 120)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+ }
+
+ private var placeGroup: some View {
+ MorphSettingsGroup("실행 위치", footnote: isLocalProject ? "이 Mac의 로컬 브리지가 켜져 있을 때만 실행됩니다." : nil) {
+ MorphSettingsRow("프로젝트") {
+ EmptyView()
+ } trailing: {
+ if draft.schedule == nil && !runsInThread {
+ MorphPopupButton(projectName, menuWidth: 240) {
+ ForEach(state.codeFolderProjects) { project in
+ MorphMenuItem(project.name, isSelected: project.id == projectId, id: project.id) {
+ projectId = project.id
+ }
+ }
+ }
+ } else {
+ Text(projectName)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ }
+ }
+ if let thread {
+ MorphSettingsRow(
+ "결과",
+ detail: runsInThread ? "실행할 때마다 '\(thread.title)' 스레드에 이어서 씁니다." : "실행할 때마다 새 스레드를 만듭니다."
+ ) {
+ EmptyView()
+ } trailing: {
+ if draft.schedule == nil {
+ AnymorphSegmentControl(items: RunPlace.allCases, selection: runPlace, label: \.label)
+ }
+ }
+ }
+ }
+ }
+
+ private var cadenceGroup: some View {
+ MorphSettingsGroup("반복", footnote: "\(CodeScheduleCadence.label(for: cadence.rrule, timezone: timezone))에 실행합니다.") {
+ MorphSettingsRow("주기") {
+ EmptyView()
+ } trailing: {
+ MorphPopupButton(cadence.kind.label, menuWidth: 180) {
+ ForEach(CodeScheduleCadence.Kind.allCases) { kind in
+ MorphMenuItem(kind.label, isSelected: kind == cadence.kind, id: kind.id) {
+ pickCadence(kind)
+ }
+ }
+ }
+ }
+ switch cadence.kind {
+ case .everyMinutes:
+ MorphSettingsRow("간격") {
+ EmptyView()
+ } trailing: {
+ numberStepper("\(cadence.minuteInterval)분마다", value: $cadence.minuteInterval, in: CodeScheduleCadence.minMinuteInterval...720, step: 1)
+ }
+ case .hourly:
+ MorphSettingsRow("분") {
+ EmptyView()
+ } trailing: {
+ numberStepper("매시 \(cadence.minute)분", value: $cadence.minute, in: 0...59, step: 5)
+ }
+ case .daily, .weekdays:
+ timeRow
+ case .weekly:
+ weekdayRow
+ timeRow
+ case .monthly:
+ MorphSettingsRow("날짜", detail: cadence.monthDay > 28 ? "그 날짜가 없는 달은 건너뜁니다." : nil) {
+ EmptyView()
+ } trailing: {
+ numberStepper("매월 \(cadence.monthDay)일", value: $cadence.monthDay, in: 1...31)
+ }
+ timeRow
+ case .custom:
+ MorphSettingsRow("규칙", detail: "RRULE의 FREQ, INTERVAL, BYDAY, BYHOUR, BYMINUTE, BYMONTHDAY를 씁니다.") {
+ EmptyView()
+ } trailing: {
+ TextField("FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=0", text: $cadence.customRule)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.footnote, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .padding(.horizontal, 10)
+ .frame(width: 260, height: 30)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgBase))
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .accessibilityLabel("반복 규칙")
+ }
+ }
+ }
+ }
+
+ /// Picks the task's model, moving an effort the model does not run at to its nearest level.
+ private func selectModel(_ id: String) {
+ model = id
+ effort = effort.nearest(in: CodeModelMenu.efforts(of: id, in: state.availableCodeModels))
+ }
+
+ private var agentGroup: some View {
+ MorphSettingsGroup("에이전트") {
+ MorphSettingsRow("모델") {
+ EmptyView()
+ } trailing: {
+ let options = state.availableCodeModels
+ let sections = CodeModelMenu.sections(options, selection: model)
+ MorphPopupButton(
+ CodeModelMenu.name(of: model, in: options),
+ brand: CodeModelMenu.current(model, in: options).flatMap(MorphBrand.init(codeModel:)),
+ menuWidth: 300,
+ name: "schedule-model"
+ ) {
+ MorphCodeModelRows(sections: sections, selection: model) { id in
+ selectModel(id)
+ }
+ MorphCodeMoreModels(groups: sections.more, selection: model) { id in
+ selectModel(id)
+ }
+ }
+ }
+ let efforts = CodeModelMenu.efforts(of: model, in: state.availableCodeModels)
+ if !efforts.isEmpty {
+ MorphSettingsRow("추론") {
+ EmptyView()
+ } trailing: {
+ MorphPopupButton(effort.label, menuWidth: 268) {
+ MorphEffortRows(selection: effort, levels: efforts) { option in
+ effort = option
+ }
+ }
+ }
+ }
+ MorphSettingsRow("권한", detail: accessMode.detail) {
+ EmptyView()
+ } trailing: {
+ MorphPopupButton(accessMode.label, menuWidth: 304) {
+ MorphAccessModeRows(selection: accessMode) { option in
+ accessMode = option
+ }
+ }
+ }
+ }
+ }
+
+ private var timeRow: some View {
+ MorphSettingsRow("시각") {
+ EmptyView()
+ } trailing: {
+ DatePicker("시각", selection: timeOfDay, displayedComponents: .hourAndMinute)
+ .labelsHidden()
+ .fixedSize()
+ .tint(AnymorphColor.fgPrimary)
+ }
+ }
+
+ private var weekdayRow: some View {
+ MorphSettingsRow("요일") {
+ EmptyView()
+ } trailing: {
+ HStack(spacing: 4) {
+ ForEach(1...7, id: \.self) { day in
+ let isOn = cadence.weekdays.contains(day)
+ let name = CodeScheduleCadence.dayNames[day - 1]
+ Button {
+ // A weekly task keeps at least one day.
+ if !isOn {
+ cadence.weekdays.insert(day)
+ } else if cadence.weekdays.count > 1 {
+ cadence.weekdays.remove(day)
+ }
+ } label: {
+ Text(name)
+ .anymorphText(.footnote, weight: .emphasis, color: isOn ? AnymorphColor.fgInverse : AnymorphColor.fgSecondary)
+ .frame(width: 28, height: 28)
+ .background(Circle().fill(isOn ? AnymorphColor.bgInverse : AnymorphColor.bgSelected))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel("\(name)요일")
+ .accessibilityAddTraits(isOn ? .isSelected : [])
+ }
+ }
+ }
+ }
+
+ /// The task's hour and minute as a time today, for the time picker.
+ private var timeOfDay: Binding {
+ Binding {
+ Calendar.current.date(bySettingHour: cadence.hour, minute: cadence.minute, second: 0, of: Date()) ?? Date()
+ } set: { date in
+ let parts = Calendar.current.dateComponents([.hour, .minute], from: date)
+ cadence.hour = parts.hour ?? cadence.hour
+ cadence.minute = parts.minute ?? cadence.minute
+ }
+ }
+
+ private enum RunPlace: String, CaseIterable, Identifiable {
+ case thread
+ case newThread
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .thread: return "이 스레드"
+ case .newThread: return "새 스레드"
+ }
+ }
+ }
+
+ private var runPlace: Binding {
+ Binding {
+ runsInThread ? .thread : .newThread
+ } set: { place in
+ runsInThread = place == .thread
+ if runsInThread, let thread {
+ projectId = thread.projectId
+ }
+ }
+ }
+
+ /// Switches the preset. A rule typed by hand starts from the one the presets made.
+ private func pickCadence(_ kind: CodeScheduleCadence.Kind) {
+ let current = cadence.rrule
+ cadence.kind = kind
+ if kind == .custom {
+ cadence.customRule = current
+ }
+ }
+
+ private func numberStepper(_ label: String, value: Binding, in range: ClosedRange, step: Int = 1) -> some View {
+ AnymorphStepper(label, value: value, in: range, step: step)
+ }
+
+ private func save() {
+ var input = CodeScheduleInput(
+ title: title.trimmingCharacters(in: .whitespacesAndNewlines),
+ prompt: prompt.trimmingCharacters(in: .whitespacesAndNewlines),
+ rrule: cadence.rrule,
+ model: model,
+ reasoningEffort: effort,
+ accessMode: accessMode
+ )
+ if draft.schedule == nil {
+ input.projectId = projectId
+ input.threadId = runsInThread ? thread?.id : nil
+ input.timezone = timezone
+ }
+ isSaving = true
+ Task {
+ let saved = await state.saveCodeSchedule(input, editing: draft.schedule)
+ isSaving = false
+ if saved {
+ dismiss()
+ }
+ }
+ }
+}
+
diff --git a/apple/Apps/Shared/MorphCodeSidebarView.swift b/apple/Apps/Shared/MorphCodeSidebarView.swift
new file mode 100644
index 000000000..61b6f70ae
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeSidebarView.swift
@@ -0,0 +1,1392 @@
+import SwiftUI
+import MorphCore
+
+/// Morph Code sidebar (macOS, iPad) and home list (iPhone): threads grouped by fixed user-ordered folder projects
+/// (drag-and-drop reorderable), sorted inside each folder by triage priority (awaiting action → failed → completed →
+/// running → calm idle), with folder update indicators, darker 2×2 running spinners, semantic status dots, and
+/// 보관함 tucked inside the profile menu directly under 설정.
+public struct MorphCodeSidebarView: View {
+ @Bindable var state: MorphAppState
+ var onOpen: () -> Void
+ @Environment(\.openWindow) private var openWindow
+ @State private var query = ""
+ @State private var projectPendingDelete: CodeProject?
+ /// Project id currently highlighted as a drag-and-drop reorder target.
+ @State private var dropTargetProjectId: String?
+ /// The thread picked in the archive, opened once the archive has closed.
+ @State private var archivedThreadToOpen: CodeThread?
+
+ public init(state: MorphAppState, onOpen: @escaping () -> Void = {}) {
+ self.state = state
+ self.onOpen = onOpen
+ }
+
+ private var projects: [CodeProject] {
+ state.codeFolderProjects
+ }
+
+ private var trimmedQuery: String {
+ query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ }
+
+ /// Threads that runs of a scheduled task made. They live in 예약됨; once their task is deleted they go back to
+ /// their project.
+ private var scheduledRunThreads: [CodeThread] {
+ let scheduleIds = Set(state.codeSchedules.map(\.id))
+ return state.listedCodeThreads.filter { thread in
+ thread.scheduleId.map(scheduleIds.contains) ?? false
+ }
+ }
+
+ /// The text around the first match in each thread's messages, from the local FTS5 index, while searching.
+ private var messageSnippets: [String: String] {
+ guard !trimmedQuery.isEmpty else { return [:] }
+ var snippets: [String: String] = [:]
+ for hit in state.codeSearchHits where hit.kind == "message" && snippets[hit.threadId] == nil {
+ let clean = hit.snippet
+ .replacingOccurrences(of: "\n", with: " ")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if !clean.isEmpty {
+ snippets[hit.threadId] = clean
+ }
+ }
+ return snippets
+ }
+
+ /// Active (non-archived, non-snoozed) threads under a folder project for summary indicators.
+ private func activeProjectThreads(for project: CodeProject, listedUnder: [String: String], hiding hidden: Set, now: Date) -> [CodeThread] {
+ state.listedCodeThreads.filter {
+ listedUnder[$0.projectId] == project.id
+ && !hidden.contains($0.id)
+ && $0.isActiveForTriage(now: now)
+ }
+ }
+
+ /// A project's threads sorted by triage priority (awaiting action → failed → completed → running → calm idle),
+ /// with delegated child threads nested under their parent.
+ private func threads(for project: CodeProject, listedUnder: [String: String], hiding hidden: Set, snippets: [String: String], now: Date) -> [CodeThreadListEntry] {
+ let base: [CodeThread]
+ if trimmedQuery.isEmpty {
+ base = activeProjectThreads(for: project, listedUnder: listedUnder, hiding: hidden, now: now)
+ } else {
+ let all = state.listedCodeThreads.filter {
+ listedUnder[$0.projectId] == project.id && !hidden.contains($0.id)
+ }
+ base = matchingQuery(all, groupName: project.name, snippets: snippets)
+ }
+ return CodeThread.nestedByTriage(
+ base,
+ signals: { state.codeThreadSignals(for: $0) },
+ stickyThreadId: state.stickyTriageThreadId,
+ stickyStatus: state.stickyTriageStatus
+ )
+ }
+
+ /// Pinned threads from every project, listed together above the projects in triage priority order.
+ private func pinnedThreads(_ pinnedSection: Set, hiding runIds: Set, snippets: [String: String], now: Date) -> [CodeThreadListEntry] {
+ let pinned = state.listedCodeThreads.filter {
+ pinnedSection.contains($0.id)
+ && !runIds.contains($0.id)
+ && (!trimmedQuery.isEmpty || $0.isActiveForTriage(now: now))
+ }
+ let names = Dictionary(state.codeProjects.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first })
+ let trimmed = trimmedQuery
+ let matched = trimmed.isEmpty ? pinned : pinned.filter { thread in
+ !matchingQuery([thread], groupName: names[thread.projectId] ?? "", snippets: snippets).isEmpty
+ }
+ return CodeThread.nestedByTriage(
+ matched,
+ signals: { state.codeThreadSignals(for: $0) },
+ stickyThreadId: state.stickyTriageThreadId,
+ stickyStatus: state.stickyTriageStatus
+ )
+ }
+
+ private func matchingQuery(_ threads: [CodeThread], groupName: String, snippets: [String: String]) -> [CodeThread] {
+ let trimmed = trimmedQuery
+ guard !trimmed.isEmpty else { return threads }
+ return threads.filter {
+ $0.title.lowercased().contains(trimmed)
+ || groupName.lowercased().contains(trimmed)
+ || $0.model.lowercased().contains(trimmed)
+ || snippets[$0.id] != nil
+ }
+ }
+
+ /// Count of archived threads matching the current sidebar search query (shown as a subtle link while searching).
+ private func matchingArchivedCount(snippets: [String: String]) -> Int {
+ guard !trimmedQuery.isEmpty else { return 0 }
+ let names = Dictionary(state.codeProjects.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first })
+ return state.archivedCodeThreads.filter { thread in
+ !matchingQuery([thread], groupName: names[thread.projectId] ?? "", snippets: snippets).isEmpty
+ }.count
+ }
+
+ private var archiveMenuBadgeCount: Int {
+ state.archivedCodeThreads.count + state.snoozedCodeThreads.count
+ }
+
+ public var body: some View {
+ VStack(spacing: 0) {
+ if state.isCodeScheduledOpen {
+ scheduledHeader
+ scheduledList
+ .morphListTextSize()
+ } else {
+ HStack(spacing: 6) {
+ AnymorphTextField("Search threads…", text: $query, leadingSystemImage: "magnifyingglass", appearance: .filled)
+ newThreadMenu
+ }
+ .padding(.horizontal, 12)
+ .padding(.top, 4)
+ .padding(.bottom, 8)
+
+ threadList
+ .morphListTextSize()
+ }
+
+ footer
+ .morphListTextSize()
+ }
+ .background(AnymorphColor.bgSidebar.ignoresSafeArea())
+ .onChange(of: query) { _, newValue in
+ // Matches message bodies too, through the local FTS5 index, not only titles.
+ state.runCodeFullTextSearch(query: newValue)
+ }
+ .onChange(of: state.isCommandPalettePresented) { _, isOpen in
+ // ⌘K shares the search results; its own query is gone once it closes.
+ if !isOpen {
+ state.runCodeFullTextSearch(query: query)
+ }
+ }
+ .morphDialog(item: $projectPendingDelete) { project in
+ MorphDialogContent(
+ title: "이 프로젝트를 삭제할까요?",
+ message: "‘\(project.name)’의 스레드가 모두 지워집니다. 폴더의 파일은 그대로 남습니다.",
+ confirmTitle: "프로젝트 삭제",
+ isDestructive: true
+ ) { _ in
+ await state.deleteCodeProject(id: project.id)
+ }
+ }
+ .sheet(isPresented: $state.isCodeArchivePresented, onDismiss: openArchivedThread) {
+ MorphCodeArchiveView(state: state) { thread in
+ archivedThreadToOpen = thread
+ state.isCodeArchivePresented = false
+ }
+ }
+ .sheet(isPresented: $state.isCLISessionImportSheetPresented) {
+ MorphCLISessionImportSheet(state: state)
+ }
+ }
+
+ /// The new-thread button: a menu of the folder projects and 폴더 추가…, the way T3 Code's New thread in… lists
+ /// them, then 로컬 CLI 세션 가져오기 for a Claude Code or Codex session already on this Mac. The new-thread screen
+ /// opens in the project picked.
+ private var newThreadMenu: some View {
+ MorphDropdown(placement: .belowTrailing, width: 256, name: "code-new-thread") {
+ MorphCodeProjectRows(state: state) { projectId in
+ state.startNewCodeThread(projectId: projectId)
+ onOpen()
+ }
+ MorphMenuDivider()
+ MorphMenuItem("Import local CLI session", subtitle: "Claude Code · Codex", icon: .symbol("square.and.arrow.down"), id: "import-cli-session") {
+ state.isCLISessionImportSheetPresented = true
+ }
+ } label: {
+ Image(systemName: "square.and.pencil")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .frame(width: 32, height: 32)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxxl))
+ }
+ .help("New Thread")
+ .accessibilityLabel("New Thread")
+ }
+
+ /// A list, so rows take swipe actions and the phone's list pulls to refresh: the folder projects in fixed user
+ /// order with triage-sorted threads inside each folder, less the runs 예약됨 keeps.
+ private var threadList: some View {
+ let _ = state.snoozeClockTick
+ let now = Date()
+ let runIds = Set(scheduledRunThreads.map(\.id))
+ let listedUnder = state.codeListedProjectIds
+ let snippets = messageSnippets
+ let projectNames = Dictionary(state.codeProjects.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first })
+ let pinnedSection = CodeThread.pinnedSectionIds(in: state.listedCodeThreads)
+ let pinned = pinnedThreads(pinnedSection, hiding: runIds, snippets: snippets, now: now)
+ let archivedSearchMatches = matchingArchivedCount(snippets: snippets)
+ return List {
+ if !pinned.isEmpty {
+ sectionCaption("Pinned")
+ .sidebarListRow(top: 6)
+ ForEach(pinned) { entry in
+ if entry.startsCalmGroup {
+ calmGroupDivider
+ .sidebarListRow(leading: 16, top: 4)
+ }
+ threadRow(
+ entry,
+ inMacProject: state.isLocalCodeProject(entry.thread.projectId),
+ snippets: snippets,
+ inPinnedSection: true,
+ projectName: projectNames[entry.thread.projectId]
+ )
+ .sidebarListRow(leading: 8)
+ }
+ }
+ if projects.isEmpty {
+ MorphSidebarRow("Add Folder", action: { state.pickCodeFolder() }) {
+ Image(systemName: "folder.badge.plus")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ }
+ .sidebarListRow(top: 6)
+ } else {
+ ForEach(projects) { project in
+ projectRows(
+ project,
+ listedUnder: listedUnder,
+ hiding: runIds.union(pinnedSection),
+ snippets: snippets,
+ now: now
+ )
+ }
+ }
+ if archivedSearchMatches > 0 {
+ Button {
+ state.isCodeArchivePresented = true
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "archivebox")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text("Show \(archivedSearchMatches) archived match\(archivedSearchMatches == 1 ? "" : "es")")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Spacer(minLength: 4)
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 28)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .sidebarListRow(top: 8)
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .scrollIndicators(.never)
+ #if os(iOS)
+ .scrollDismissesKeyboard(.immediately)
+ #endif
+ .contentMargins(.bottom, 16, for: .scrollContent)
+ .environment(\.defaultMinListRowHeight, 0)
+ .animation(AnymorphMotion.base, value: state.listedCodeThreads.map(\.id))
+ .animation(AnymorphMotion.fast, value: projects.map(\.id))
+ .refreshable {
+ await state.refreshCodeState()
+ }
+ }
+
+ private var calmGroupDivider: some View {
+ Rectangle()
+ .fill(AnymorphColor.strokeLight)
+ .frame(height: 1)
+ .padding(.trailing, 8)
+ .padding(.vertical, 3)
+ .accessibilityHidden(true)
+ }
+
+ // MARK: - 예약됨
+
+ /// 예약됨 above the account, where ChatGPT keeps Scheduled in its rail. It reads as open while a task or one of
+ /// its runs is. Shows the highest-priority status indicator among its active runs.
+ private var scheduledEntry: some View {
+ let summary = CodeProjectFolderSummary.summarize(
+ scheduledRunThreads,
+ signals: { state.codeThreadSignals(for: $0) }
+ )
+ let status = summary.headerStatus(isExpanded: false)
+ return MorphSidebarRow(
+ "Scheduled",
+ isSelected: state.isCodeScheduledOpen,
+ action: { state.openCodeScheduled() },
+ leading: {
+ Image(systemName: "clock")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ },
+ trailing: {
+ if let status {
+ if status == .running {
+ CodeThreadRow.spinner
+ } else {
+ CodeThreadRow.statusDot(status)
+ }
+ }
+ }
+ )
+ }
+
+ /// 예약됨's title over its list, with the way back to the projects.
+ private var scheduledHeader: some View {
+ HStack(spacing: 4) {
+ Button {
+ Task { await state.closeCodeScheduled() }
+ } label: {
+ Image(systemName: "chevron.left")
+ }
+ .morphRound(diameter: 28)
+ .help("프로젝트로 돌아가기")
+ .accessibilityLabel("프로젝트로 돌아가기")
+ Text("Scheduled")
+ .anymorphText(.headline, weight: .strong, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 32)
+ .padding(.top, 4)
+ .padding(.bottom, 8)
+ }
+
+ /// 예약됨's list, the way ChatGPT lists scheduled tasks: 새 작업, then the tasks that are on and the ones turned
+ /// off.
+ private var scheduledList: some View {
+ let schedules = state.codeSchedules
+ let active = schedules.filter(\.enabled)
+ let paused = schedules.filter { !$0.enabled }
+ return List {
+ MorphSidebarRow("새 작업", action: { state.editCodeSchedule() }) {
+ Image(systemName: "plus")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ } trailing: {
+ EmptyView()
+ }
+ .sidebarListRow()
+ if !active.isEmpty {
+ sectionCaption("활성")
+ .sidebarListRow(top: 10)
+ ForEach(active) { schedule in
+ scheduleRow(schedule)
+ .sidebarListRow()
+ }
+ }
+ if !paused.isEmpty {
+ sectionCaption("꺼짐")
+ .sidebarListRow(top: 10)
+ ForEach(paused) { schedule in
+ scheduleRow(schedule)
+ .sidebarListRow()
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .scrollIndicators(.never)
+ #if os(iOS)
+ .scrollDismissesKeyboard(.immediately)
+ #endif
+ .contentMargins(.bottom, 16, for: .scrollContent)
+ .environment(\.defaultMinListRowHeight, 0)
+ .refreshable {
+ await state.refreshCodeState()
+ }
+ }
+
+ /// A task by its name, with when it runs next and how often, or its full rule once turned off. Shows the
+ /// highest-priority status indicator among its runs.
+ private func scheduleRow(_ schedule: CodeSchedule) -> some View {
+ let runs = state.codeRunThreads(of: schedule)
+ let summary = CodeProjectFolderSummary.summarize(
+ runs,
+ signals: { state.codeThreadSignals(for: $0) }
+ )
+ let status = summary.headerStatus(isExpanded: false)
+ let isOpen = state.codeDestination == .scheduled
+ ? state.selectedCodeSchedule?.id == schedule.id
+ : state.selectedCodeThread?.scheduleId == schedule.id
+ let when: [String?] = schedule.enabled
+ ? [MorphCodeScheduledView.runDay(schedule.nextRunAt), CodeScheduleCadence.shortLabel(for: schedule.rrule)]
+ : [CodeScheduleCadence.label(for: schedule.rrule, timezone: schedule.timezone)]
+ return MorphSidebarRow(
+ schedule.title,
+ subtitle: when.compactMap { $0 }.joined(separator: " · "),
+ isSelected: isOpen,
+ action: {
+ state.openCodeScheduled(schedule.id)
+ onOpen()
+ },
+ leading: { EmptyView() },
+ trailing: {
+ if let status {
+ if status == .running {
+ CodeThreadRow.spinner
+ } else {
+ CodeThreadRow.statusDot(status)
+ }
+ }
+ }
+ )
+ }
+
+ private func sectionCaption(_ title: String) -> some View {
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ .padding(.horizontal, 10)
+ .frame(height: 24)
+ }
+
+ @ViewBuilder
+ private func projectRows(_ project: CodeProject, listedUnder: [String: String], hiding hidden: Set, snippets: [String: String], now: Date) -> some View {
+ let activeForSummary = activeProjectThreads(for: project, listedUnder: listedUnder, hiding: hidden, now: now)
+ let summary = CodeProjectFolderSummary.summarize(
+ activeForSummary,
+ signals: { state.codeThreadSignals(for: $0) }
+ )
+ let items = threads(for: project, listedUnder: listedUnder, hiding: hidden, snippets: snippets, now: now)
+ let onMac = state.isLocalCodeProject(project.id)
+ let expanded = !trimmedQuery.isEmpty || !state.collapsedCodeProjectIds.contains(project.id)
+ // While searching, show only projects with matching threads.
+ if trimmedQuery.isEmpty || !items.isEmpty {
+ projectHeader(project, expanded: expanded, summary: summary)
+ .sidebarListRow(top: 6)
+ if expanded {
+ if items.isEmpty {
+ Text("스레드 없음")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary)
+ // In line with the threads' titles.
+ .padding(.leading, 10)
+ .padding(.vertical, 3)
+ .sidebarListRow(leading: 16)
+ } else {
+ ForEach(items) { entry in
+ if entry.startsCalmGroup {
+ calmGroupDivider
+ .sidebarListRow(leading: 24, top: 4)
+ }
+ threadRow(entry, inMacProject: onMac, snippets: snippets, inPinnedSection: false, projectName: nil)
+ .sidebarListRow(leading: 16)
+ }
+ }
+ }
+ }
+ }
+
+ /// A project's folding row: its arrow, where its threads run, its name, a live folder update indicator,
+ /// drag-and-drop reorder handle, and the button that opens a new thread in it.
+ private func projectHeader(_ project: CodeProject, expanded: Bool, summary: CodeProjectFolderSummary) -> some View {
+ let target = project.defaultTarget.running(onLocalBridge: state.isLocalCodeProject(project.id))
+ let headerStatus = summary.headerStatus(isExpanded: expanded)
+ let headerCount = summary.headerCount(isExpanded: expanded)
+ let isDropTarget = dropTargetProjectId == project.id
+ let projectIndex = projects.firstIndex(where: { $0.id == project.id })
+ return HStack(spacing: 6) {
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ state.toggleCodeProjectCollapsed(project.id)
+ }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .rotationEffect(.degrees(expanded ? 90 : 0))
+ .frame(width: 10)
+ Image(systemName: target.systemImage)
+ .symbolRenderingMode(.monochrome)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ // One width for the laptop and the cloud keeps project names in line.
+ .frame(width: 18)
+ .accessibilityLabel(state.codeTargetLabel(target))
+ Text(project.name)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ if let headerStatus {
+ folderStatusIndicator(status: headerStatus, count: headerCount)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+
+ Button {
+ startThread(in: project)
+ } label: {
+ Image(systemName: "square.and.pencil")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 24, height: 24)
+ .contentShape(Circle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("\(project.name)에 새 스레드")
+ .accessibilityLabel("\(project.name)에 새 스레드")
+ }
+ .padding(.horizontal, 8)
+ .frame(height: 30)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(isDropTarget ? AnymorphColor.bgHover : Color.clear)
+ )
+ .overlay(alignment: .top) {
+ if isDropTarget {
+ Rectangle()
+ .fill(AnymorphColor.fgPrimary)
+ .frame(height: 2)
+ .padding(.horizontal, 8)
+ }
+ }
+ .draggable(project.id) {
+ HStack(spacing: 6) {
+ Image(systemName: target.systemImage)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text(project.name)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.menuSurface)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .strokeBorder(AnymorphColor.menuStroke, lineWidth: 1)
+ )
+ )
+ }
+ .dropDestination(for: String.self) { items, _ in
+ guard let sourceId = items.first,
+ sourceId != project.id,
+ projects.contains(where: { $0.id == sourceId }) else {
+ dropTargetProjectId = nil
+ return false
+ }
+ withAnimation(AnymorphMotion.fast) {
+ state.reorderCodeProject(moving: sourceId, to: project.id)
+ }
+ dropTargetProjectId = nil
+ return true
+ } isTargeted: { targeted in
+ if targeted {
+ dropTargetProjectId = project.id
+ } else if dropTargetProjectId == project.id {
+ dropTargetProjectId = nil
+ }
+ }
+ .contextMenu {
+ Button {
+ startThread(in: project)
+ } label: {
+ Label("새 스레드", systemImage: "square.and.pencil")
+ }
+ if let idx = projectIndex, projects.count > 1 {
+ Divider()
+ if idx > 0 {
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ state.reorderCodeProject(moving: project.id, to: projects[idx - 1].id)
+ }
+ } label: {
+ Label("위로 이동", systemImage: "arrow.up")
+ }
+ }
+ if idx + 1 < projects.count {
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ state.reorderCodeProject(moving: project.id, to: projects[idx + 1].id)
+ }
+ } label: {
+ Label("아래로 이동", systemImage: "arrow.down")
+ }
+ }
+ }
+ Divider()
+ Button(role: .destructive) {
+ projectPendingDelete = project
+ } label: {
+ Label("프로젝트 삭제", systemImage: "trash")
+ }
+ }
+ .swipeActions(edge: .trailing, allowsFullSwipe: false) {
+ Button {
+ projectPendingDelete = project
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ .tint(AnymorphColor.swipeSecondary)
+ }
+ }
+
+ @ViewBuilder
+ private func folderStatusIndicator(status: CodeThreadVisualStatus, count: Int) -> some View {
+ HStack(spacing: 4) {
+ if status == .running {
+ MorphRunningDots(dotSize: 2.2, spacing: 1.8)
+ .frame(width: 12, height: 12)
+ } else {
+ MorphCodeStatusDot(status, size: 7)
+ }
+ if count > 1 {
+ Text("\(count)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary, tabular: true)
+ }
+ }
+ .accessibilityLabel(folderStatusAccessibilityLabel(status: status, count: count))
+ }
+
+ private func folderStatusAccessibilityLabel(status: CodeThreadVisualStatus, count: Int) -> String {
+ let kind: String
+ switch status {
+ case .awaitingAction: kind = "확인 필요"
+ case .failed: kind = "작업 실패"
+ case .completedUnread: kind = "완료됨"
+ case .running: kind = "실행 중"
+ case .idle: kind = ""
+ }
+ return count > 1 ? "\(kind) \(count)개" : kind
+ }
+
+ private func startThread(in project: CodeProject) {
+ state.startNewCodeThread(projectId: project.id)
+ onOpen()
+ }
+
+ /// A thread's row. Always a single clean line inside project folders (status reads from the colored dot or
+ /// 4-dot spinner, with full status detail in the tooltip and VoiceOver). Shows a second line only for the
+ /// project name inside 고정됨 or a matched message snippet while searching.
+ private func threadRow(_ entry: CodeThreadListEntry, inMacProject: Bool, snippets: [String: String], inPinnedSection: Bool, projectName: String?) -> some View {
+ let thread = entry.thread
+ let run = state.codeLiveRuns[thread.id]
+ let unread = thread.unreadCount > 0
+ let target = state.codeTarget(of: thread)
+ let detailParts = [
+ CodeModelOption.displayName(for: thread.model, dynamic: state.availableCodeModels),
+ thread.branch,
+ state.codeTargetLabel(target),
+ MorphPalette.listTimeLabel(thread.updatedAt),
+ ].compactMap { $0 }.filter { !$0.isEmpty }
+ let snippet: String? = trimmedQuery.isEmpty || thread.title.lowercased().contains(trimmedQuery)
+ ? nil
+ : snippets[thread.id]
+
+ return CodeThreadRow(
+ thread: thread,
+ run: run,
+ visualStatus: state.codeVisualStatus(of: thread),
+ hasPendingQuestion: run?.question != nil || !(state.pendingCodeQuestionsByThread[thread.id] ?? []).isEmpty,
+ detailParts: detailParts,
+ isSelected: state.codeDestination == .threads && state.selectedCodeThreadId == thread.id,
+ showsCloud: inMacProject && target == .cloud,
+ showsPin: inPinnedSection && thread.isPinned,
+ isNested: entry.depth > 0,
+ projectName: inPinnedSection ? projectName : nil,
+ searchSnippet: snippet,
+ onArchive: { archive(thread) }
+ ) {
+ // Prepare selection & hydrate cached messages synchronously before onOpen() to eliminate blank flashes.
+ state.prepareSelectCodeThread(thread)
+ onOpen()
+ Task { await state.selectCodeThread(thread) }
+ }
+ .padding(.leading, CGFloat(entry.depth) * 14)
+ .contextMenu {
+ if run != nil {
+ Button {
+ Task { await state.cancelCodeTurn(threadId: thread.id) }
+ } label: {
+ Label("실행 중지", systemImage: "stop.circle")
+ }
+ }
+ Button {
+ Task { await state.toggleCodeThreadPinned(id: thread.id) }
+ } label: {
+ Label(thread.isPinned ? "고정 해제" : "고정", systemImage: thread.isPinned ? "pin.slash" : "pin")
+ }
+ Menu {
+ Button("1시간 후") {
+ Task { await state.snoozeCodeThread(id: thread.id, until: MorphAppState.snoozeOneHourISO()) }
+ }
+ Button("내일 오전 9시") {
+ Task { await state.snoozeCodeThread(id: thread.id, until: MorphAppState.snoozeTomorrowMorningISO()) }
+ }
+ if thread.isSnoozed {
+ Divider()
+ Button("보류 해제") {
+ Task { await state.snoozeCodeThread(id: thread.id, until: nil) }
+ }
+ }
+ } label: {
+ Label("나중에 보기", systemImage: "moon.zzz")
+ }
+ #if os(macOS)
+ Button {
+ openWindow(id: "code-thread", value: thread.id)
+ } label: {
+ Label("새 창에서 열기", systemImage: "macwindow.badge.plus")
+ }
+ #endif
+ Divider()
+ Button {
+ state.codeThreadPendingRename = thread
+ } label: {
+ Label("이름 변경…", systemImage: "pencil")
+ }
+ Button {
+ Task { await state.regenerateCodeThreadTitle(id: thread.id) }
+ } label: {
+ Label("제목 다시 짓기", systemImage: "sparkles")
+ }
+ Button {
+ state.codeThreadPendingDelegate = thread
+ } label: {
+ Label("위임 작업 시작…", systemImage: "arrow.triangle.branch")
+ }
+ Button {
+ Task { await state.setCodeThreadUnread(id: thread.id, unread: !unread) }
+ } label: {
+ Label(unread ? "읽음으로 표시" : "안 읽음으로 표시", systemImage: unread ? "envelope.open" : "envelope.badge")
+ }
+ Button {
+ state.editCodeSchedule(threadId: thread.id)
+ } label: {
+ Label("이 스레드에서 예약…", systemImage: "clock")
+ }
+ Button {
+ archive(thread)
+ } label: {
+ Label(thread.isEffectivelyArchived ? "목록으로 되돌리기" : "보관", systemImage: thread.isEffectivelyArchived ? "tray.and.arrow.up" : "archivebox")
+ }
+ Divider()
+ Button(role: .destructive) {
+ state.codeThreadPendingDelete = thread
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ }
+ // Mail's swipes: a full swipe to the left archives, and delete asks first. A swipe to the right marks it read.
+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {
+ Button {
+ archive(thread)
+ } label: {
+ Label("보관", systemImage: "archivebox")
+ }
+ .tint(AnymorphColor.swipePrimary)
+ Button {
+ state.codeThreadPendingDelete = thread
+ } label: {
+ Label("삭제", systemImage: "trash")
+ }
+ .tint(AnymorphColor.swipeSecondary)
+ }
+ .swipeActions(edge: .leading, allowsFullSwipe: true) {
+ Button {
+ Task { await state.setCodeThreadUnread(id: thread.id, unread: !unread) }
+ } label: {
+ Label(unread ? "읽음" : "안 읽음", systemImage: unread ? "envelope.open" : "envelope.badge")
+ }
+ .tint(AnymorphColor.swipeSecondary)
+ Button {
+ Task { await state.toggleCodeThreadPinned(id: thread.id) }
+ } label: {
+ Label(thread.isPinned ? "고정 해제" : "고정", systemImage: thread.isPinned ? "pin.slash" : "pin")
+ }
+ .tint(AnymorphColor.swipePrimary)
+ }
+ }
+
+ private func archive(_ thread: CodeThread) {
+ Task { await state.archiveCodeThread(id: thread.id, archived: !thread.isEffectivelyArchived) }
+ }
+
+ private func openArchivedThread() {
+ guard let thread = archivedThreadToOpen else { return }
+ archivedThreadToOpen = nil
+ state.prepareSelectCodeThread(thread)
+ onOpen()
+ Task { await state.selectCodeThread(thread) }
+ }
+
+ private var footer: some View {
+ VStack(spacing: 2) {
+ AnymorphDivider()
+ .padding(.bottom, 4)
+
+ scheduledEntry
+
+ MorphDropdown(placement: .aboveLeading, width: 236, name: "code-settings") {
+ MorphMenuItem("Settings", icon: .symbol("gearshape"), trailing: "⌘,") {
+ state.openSettings(.general)
+ }
+ MorphMenuItem(
+ "Archive",
+ icon: .symbol("archivebox"),
+ trailing: archiveMenuBadgeCount > 0 ? "\(archiveMenuBadgeCount)" : nil
+ ) {
+ state.isCodeArchivePresented = true
+ }
+ MorphMenuItem("Providers & Keys", icon: .symbol("key")) {
+ state.openSettings(.providers)
+ }
+ MorphMenuItem("Harness & MCP", icon: .symbol("wrench.and.screwdriver")) {
+ state.openSettings(.harness)
+ }
+ MorphMenuItem("Refresh", icon: .symbol("arrow.triangle.2.circlepath"), trailing: "⌘R") {
+ Task { await state.syncNow(userInitiated: true) }
+ }
+ MorphMenuDivider()
+ MorphMenuSubmenu("Theme", value: state.themeMode.label, width: 180, id: "theme-mode") {
+ ForEach(MorphThemeMode.allCases) { mode in
+ MorphMenuItem(mode.label, isSelected: state.themeMode == mode, id: "theme-\(mode.rawValue)") {
+ state.themeMode = mode
+ }
+ }
+ }
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: "gearshape")
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 24, height: 24)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Settings & Daemon")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(state.localBridgeOnline ? "\(MacBridgeAgent.activeListenAddress) · Online" : "Local daemon offline")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 4)
+ Circle()
+ .fill(state.localBridgeOnline ? AnymorphColor.statusDone : AnymorphColor.fgQuaternary)
+ .frame(width: 6, height: 6)
+ }
+ .padding(.horizontal, 8)
+ .frame(height: 40)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.lg))
+ }
+ .accessibilityLabel("Settings and local daemon")
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 8)
+ }
+}
+
+/// A thread in the sidebar by its title, under a project row that shows where its threads run.
+/// Keeps rows single-line with semantic status dots (amber = awaiting action, red = failed unread, green = completed
+/// unread) or the darker 2×2 animated dot matrix (`MorphRunningDots`) while running; status words live in tooltips
+/// and accessibility labels rather than bloating row height.
+private struct CodeThreadRow: View {
+ let thread: CodeThread
+ /// The thread's running turn. The row reads its activity itself, so a step of the turn redraws this row alone.
+ let run: CodeLiveRun?
+ let visualStatus: CodeThreadVisualStatus
+ let hasPendingQuestion: Bool
+ /// What the tooltip lists after the status: model, branch, where it runs and when it last changed.
+ let detailParts: [String]
+ let isSelected: Bool
+ let showsCloud: Bool
+ /// A pin before the trailing marks, on a pinned thread in the 고정됨 section.
+ var showsPin: Bool = false
+ /// An arrow before the title, for a delegated thread listed under the thread it was delegated from.
+ var isNested: Bool = false
+ /// Project name shown in subtitle when the row lives in the top 고정됨 section.
+ var projectName: String? = nil
+ /// The matching text from the thread's messages while the sidebar search found it there.
+ var searchSnippet: String? = nil
+ let onArchive: () -> Void
+ let action: () -> Void
+ #if os(macOS)
+ @State private var isHovered = false
+ #endif
+
+ private var subtitle: String? {
+ let parts = [projectName, searchSnippet].compactMap { $0 }.filter { !$0.isEmpty }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ /// The status the tooltip and VoiceOver read, such as the running turn's current step.
+ private var statusDescription: String? {
+ if let run {
+ if run.isCancelling { return "중지하는 중" }
+ if hasPendingQuestion { return "응답 필요" }
+ if run.approval != nil || visualStatus == .awaitingAction {
+ return "Approval required"
+ }
+ let activity = run.activity.trimmingCharacters(in: .whitespacesAndNewlines)
+ let queueCount = thread.queue?.count ?? 0
+ let base = activity.isEmpty ? "실행 중" : activity
+ return queueCount > 0 ? "\(base) · 대기 \(queueCount)" : base
+ }
+ switch visualStatus {
+ case .awaitingAction:
+ if hasPendingQuestion { return "Input required" }
+ return "Approval required"
+ case .failed:
+ return "작업 실패"
+ case .completedUnread:
+ return "완료됨"
+ case .running:
+ return "실행 중"
+ case .idle:
+ return thread.status == "error" ? "이전 작업 실패" : nil
+ }
+ }
+
+ var body: some View {
+ let isRunning = run != nil
+ let status = statusDescription
+ #if os(macOS)
+ let trailingAccessory = CodeThreadTrailingAccessory.resolve(
+ visualStatus: visualStatus,
+ isRunning: isRunning,
+ isHovered: isHovered,
+ allowsQuickArchive: true
+ )
+ #else
+ let trailingAccessory = CodeThreadTrailingAccessory.resolve(
+ visualStatus: visualStatus,
+ isRunning: isRunning,
+ isHovered: false,
+ allowsQuickArchive: false
+ )
+ #endif
+ MorphSidebarRow(
+ thread.title,
+ subtitle: subtitle,
+ meta: nil,
+ isSelected: isSelected,
+ action: action,
+ leading: {
+ if isNested {
+ Image(systemName: "arrow.turn.down.right")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ },
+ trailing: {
+ if let pr = thread.primaryLinkedPR {
+ CodeLinkedPRBadge(pr: pr, compact: true)
+ }
+ if thread.isSnoozed {
+ Image(systemName: "moon.zzz")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ .accessibilityLabel("보류됨")
+ }
+ if showsPin {
+ Self.pinMark
+ }
+ if showsCloud {
+ Self.cloudMark
+ }
+ switch trailingAccessory {
+ case .quickArchive:
+ Self.quickArchiveButton(action: onArchive)
+ case .statusDot(let status):
+ Self.statusDot(status)
+ case .spinner:
+ Self.spinner
+ case .none:
+ EmptyView()
+ }
+ }
+ )
+ .accessibilityValue(status ?? "")
+ .help(([status].compactMap { $0 } + detailParts).joined(separator: " · "))
+ #if os(macOS)
+ .onHover { isHovered = $0 }
+ #endif
+ }
+
+ /// Hover-only quick archive button kept inside a 12pt-tall layout slot so showing it never grows the
+ /// single-line row height or shifts sibling rows, while its overlay keeps a generous 20×20pt hit target.
+ static func quickArchiveButton(action: @escaping () -> Void) -> some View {
+ Color.clear
+ .frame(width: 14, height: 12)
+ .overlay {
+ QuickArchiveButton(action: action)
+ }
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ }
+
+ private struct QuickArchiveButton: View {
+ let action: () -> Void
+ @State private var hovered = false
+
+ var body: some View {
+ Button(action: action) {
+ Image(systemName: "archivebox")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(hovered ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ .frame(width: 20, height: 20)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous)
+ .fill(hovered ? AnymorphColor.bgSelected : Color.clear)
+ )
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { hovered = $0 }
+ .help("보관 (⌘E)")
+ .accessibilityLabel("보관")
+ }
+ }
+
+ /// The pin on the title's line of a pinned thread.
+ static var pinMark: some View {
+ Image(systemName: "pin.fill")
+ .symbolRenderingMode(.monochrome)
+ .font(.system(size: 9, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .rotationEffect(.degrees(45))
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ .accessibilityLabel("고정됨")
+ }
+
+ /// The cloud on the title's line of a cloud thread listed under a Mac project.
+ static var cloudMark: some View {
+ Image(systemName: "cloud")
+ .symbolRenderingMode(.monochrome)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ .accessibilityLabel("Cloud")
+ }
+
+ /// 2×2 pulsing dot matrix on the title's line while a turn runs.
+ static var spinner: some View {
+ MorphRunningDots(dotSize: 2.5, spacing: 2.2)
+ .frame(width: 14, height: 14)
+ // Centers it on the title's capitals, which stand about 9 points above the line it shares.
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ }
+
+ /// Semantic status dot on the title's line (amber = awaiting action, red = failed, green = completed).
+ static func statusDot(_ status: CodeThreadVisualStatus) -> some View {
+ MorphCodeStatusDot(status, size: 7)
+ .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4.5 }
+ }
+}
+
+private extension View {
+ /// A row of the sidebar's list as the sidebar draws it: its own insets, no separator and no system background. A
+ /// Mac list pads each row 8 points on both sides by itself, so the insets there leave those points out.
+ func sidebarListRow(leading: CGFloat = 8, top: CGFloat = 1) -> some View {
+ #if os(macOS)
+ let listPadding: CGFloat = 8
+ #else
+ let listPadding: CGFloat = 0
+ #endif
+ return listRowInsets(EdgeInsets(top: top, leading: leading - listPadding, bottom: 1, trailing: 8 - listPadding))
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ }
+}
+
+extension View {
+ /// The rename and delete dialogs any part of Morph Code can ask for through the app state. Deleting a thread that
+ /// works in its own Git worktree asks in a sheet that can also clean up the worktree and its branch.
+ func morphCodeThreadDialogs(_ state: MorphAppState) -> some View {
+ @Bindable var state = state
+ let plainDelete = Binding(
+ get: { state.codeThreadPendingDelete.flatMap { $0.hasLinkedWorktree ? nil : $0 } },
+ set: { newValue in
+ if let newValue {
+ state.codeThreadPendingDelete = newValue
+ } else if state.codeThreadPendingDelete?.hasLinkedWorktree != true {
+ state.codeThreadPendingDelete = nil
+ }
+ }
+ )
+ let worktreeDelete = Binding(
+ get: { state.codeThreadPendingDelete.flatMap { $0.hasLinkedWorktree ? $0 : nil } },
+ set: { newValue in
+ if let newValue {
+ state.codeThreadPendingDelete = newValue
+ } else if state.codeThreadPendingDelete?.hasLinkedWorktree == true {
+ state.codeThreadPendingDelete = nil
+ }
+ }
+ )
+ return self
+ .morphDialog(item: $state.codeThreadPendingRename) { thread in
+ MorphDialogContent.renameCodeThread(thread, state: state)
+ }
+ .morphDialog(item: plainDelete) { thread in
+ MorphDialogContent.deleteCodeThread(thread, state: state)
+ }
+ .sheet(item: worktreeDelete) { thread in
+ CodeThreadWorktreeDeleteSheet(state: state, thread: thread)
+ #if os(iOS)
+ .presentationDetents([.medium])
+ .presentationDragIndicator(.visible)
+ #endif
+ }
+ .sheet(item: $state.codeThreadPendingDelegate) { thread in
+ CodeThreadDelegateSheet(state: state, parentThread: thread)
+ #if os(iOS)
+ .presentationDetents([.medium])
+ .presentationDragIndicator(.visible)
+ #endif
+ }
+ }
+}
+
+/// Monochrome PR & CI status pill shared between sidebar thread rows and thread headers.
+struct CodeLinkedPRBadge: View {
+ let pr: CodeLinkedPR
+ var compact: Bool = false
+
+ private var statusText: String {
+ switch (pr.state ?? "open").lowercased() {
+ case "merged": return "머지됨"
+ case "closed": return "닫힘"
+ default:
+ switch pr.checksState?.lowercased() {
+ case "success", "passing", "passed": return "통과"
+ case "failure", "failed", "error": return "실패"
+ case "pending", "in_progress", "queued": return "진행 중"
+ default: return "열림"
+ }
+ }
+ }
+
+ private var iconName: String {
+ switch (pr.state ?? "open").lowercased() {
+ case "merged": return "checkmark.circle.fill"
+ case "closed": return "xmark.circle"
+ default:
+ switch pr.checksState?.lowercased() {
+ case "success", "passing", "passed": return "checkmark"
+ case "failure", "failed", "error": return "exclamationmark.triangle"
+ case "pending", "in_progress", "queued": return "clock"
+ default: return "arrow.triangle.pull"
+ }
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 3) {
+ Image(systemName: iconName)
+ .font(.system(size: compact ? 8 : 9, weight: .semibold))
+ Text(compact ? "#\(pr.number)" : "#\(pr.number) · \(statusText)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary, monospaced: true)
+ .lineLimit(1)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .padding(.horizontal, compact ? 5 : 7)
+ .padding(.vertical, 2)
+ .background(
+ Capsule()
+ .fill(AnymorphColor.bgSurface)
+ .overlay(Capsule().strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ .help("PR #\(pr.number) · \(statusText)")
+ }
+}
+
+/// Sheet to delegate a focused sub-task to a child thread under `parentThread`.
+private struct CodeThreadDelegateSheet: View {
+ @Bindable var state: MorphAppState
+ let parentThread: CodeThread
+ @Environment(\.dismiss) private var dismiss
+ @State private var prompt = ""
+ @State private var useWorktree = false
+ @State private var isSubmitting = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("위임 작업 시작")
+ .anymorphText(.headline, weight: .strong, color: AnymorphColor.fgPrimary)
+ Text("‘\(parentThread.title)’ 아래에 하위 스레드를 만들어 독립된 작업을 맡깁니다.")
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ TextEditor(text: $prompt)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .scrollContentBackground(.hidden)
+ .frame(minHeight: 96, maxHeight: 160)
+ .padding(10)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSurface)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ )
+
+ Toggle("별도 Git Worktree에서 실행", isOn: $useWorktree)
+ .toggleStyle(AnymorphSwitchStyle())
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgPrimary)
+
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("취소") { dismiss() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .keyboardShortcut(.cancelAction)
+ Button(isSubmitting ? "시작하는 중…" : "위임 시작") {
+ guard !isSubmitting else { return }
+ let trimmed = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+ isSubmitting = true
+ Task {
+ await state.delegateCodeTask(
+ parentThreadId: parentThread.id,
+ prompt: trimmed,
+ worktree: useWorktree,
+ model: state.selectedCodeModel,
+ effort: state.selectedCodeEffort.rawValue,
+ accessMode: state.selectedCodeAccessMode.rawValue
+ )
+ isSubmitting = false
+ dismiss()
+ }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSubmitting)
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(24)
+ #if os(macOS)
+ .frame(width: 440)
+ #endif
+ .background(AnymorphColor.bgBase)
+ }
+}
+
+private extension CodeThread {
+ /// The thread works in a Git worktree of its own rather than the project's checkout.
+ var hasLinkedWorktree: Bool {
+ !(worktreePath ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+}
+
+/// Asks before deleting a thread that works in its own Git worktree, with the option to remove that worktree and
+/// its branch too. Cleaning up is off by default: the worktree may hold changes that were never committed.
+private struct CodeThreadWorktreeDeleteSheet: View {
+ @Bindable var state: MorphAppState
+ let thread: CodeThread
+ @Environment(\.dismiss) private var dismiss
+ @State private var cleansWorktree = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("이 스레드를 삭제할까요?")
+ .anymorphText(.headline, weight: .strong, color: AnymorphColor.fgPrimary)
+ Text(state.codeLiveRuns[thread.id] == nil
+ ? "‘\(thread.title)’의 대화와 실행 기록이 지워집니다. 되돌릴 수 없습니다."
+ : "‘\(thread.title)’의 대화와 실행 기록이 지워지고, 실행 중인 작업도 멈춥니다. 되돌릴 수 없습니다.")
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ HStack(alignment: .center, spacing: 12) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("연결된 Git Worktree 및 브랜치도 함께 정리")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Text([thread.branch, thread.worktreePath].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(2)
+ .truncationMode(.middle)
+ Text("커밋하지 않은 변경이 있으면 정리하지 않고 알려 드립니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ Spacer(minLength: 8)
+ Toggle("연결된 Git Worktree 및 브랜치도 함께 정리", isOn: $cleansWorktree)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ }
+ .padding(14)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).fill(AnymorphColor.bgGrouped))
+
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("취소") { dismiss() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .keyboardShortcut(.cancelAction)
+ Button(cleansWorktree ? "삭제 및 정리" : "삭제") {
+ confirm()
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(24)
+ #if os(macOS)
+ .frame(width: 440)
+ #endif
+ .background(AnymorphColor.bgBase)
+ }
+
+ private func confirm() {
+ let threadId = thread.id
+ let projectId = thread.projectId
+ let worktreePath = thread.worktreePath
+ let branch = thread.branch
+ let cleans = cleansWorktree
+ dismiss()
+ Task {
+ await state.deleteCodeThread(id: threadId)
+ if cleans, let worktreePath, !worktreePath.isEmpty {
+ _ = await state.removeCodeWorktree(
+ projectId: projectId,
+ worktreePath: worktreePath,
+ branch: branch,
+ deleteBranch: !(branch ?? "").isEmpty
+ )
+ }
+ }
+ }
+}
+
+extension MorphDialogContent {
+ /// Codex's rename dialog for a thread: the title selected in the field, saved on the thread's server, and the
+ /// server's refusal under the field.
+ @MainActor
+ static func renameCodeThread(_ thread: CodeThread, state: MorphAppState) -> MorphDialogContent {
+ MorphDialogContent(
+ title: "스레드 이름 변경",
+ message: "짧고 알아보기 쉽게 작성하세요",
+ field: Field(text: thread.title, placeholder: "제목 추가…", accessibilityLabel: "스레드 제목"),
+ confirmTitle: "저장",
+ waitsForCompletion: true,
+ failureMessage: "저장하지 못했습니다.",
+ perform: { title in
+ guard title != thread.title else { return }
+ try await state.renameCodeThread(id: thread.id, title: title)
+ },
+ reportFailure: { error in
+ state.showError("스레드 이름을 바꾸지 못했습니다. \(error.localizedDescription)")
+ }
+ )
+ }
+
+ /// Asks before a thread's conversation and runs are deleted, and says when a running turn stops with it.
+ @MainActor
+ static func deleteCodeThread(_ thread: CodeThread, state: MorphAppState) -> MorphDialogContent {
+ MorphDialogContent(
+ title: "이 스레드를 삭제할까요?",
+ message: state.codeLiveRuns[thread.id] == nil
+ ? "‘\(thread.title)’의 대화와 실행 기록이 지워집니다. 되돌릴 수 없습니다."
+ : "‘\(thread.title)’의 대화와 실행 기록이 지워지고, 실행 중인 작업도 멈춥니다. 되돌릴 수 없습니다.",
+ confirmTitle: "삭제",
+ isDestructive: true
+ ) { _ in
+ await state.deleteCodeThread(id: thread.id)
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodeTurnViews.swift b/apple/Apps/Shared/MorphCodeTurnViews.swift
new file mode 100644
index 000000000..b49d99601
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeTurnViews.swift
@@ -0,0 +1,1846 @@
+import SwiftUI
+import MorphCore
+
+// Morph Code turns in Codex's manner: what the agent did folds into short lines, and the answer reads in full.
+
+/// A turn's work log: tool steps, approvals, Q&A records, and intermediate notes along a clean timeline.
+/// Verbose raw chain-of-thought (`thinking`) is intentionally omitted, matching Claude/Codex UI.
+struct CodeWorkLogView: View {
+ let items: [CodeWorkItem]
+ /// When true (inside an opened finished-turn summary), expands step groups directly onto one rail
+ /// instead of nesting a second disclosure chevron.
+ var flattenSteps = false
+
+ var body: some View {
+ let subagents = CodeSubagentTree(items: items)
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(items) { item in
+ switch item {
+ case .note(let block):
+ CodeNoteText(text: block.content ?? "")
+ .equatable()
+ case .thinking:
+ EmptyView()
+ case .steps(let steps):
+ ForEach(subagents.segments(steps)) { segment in
+ switch segment {
+ case .subagent(let parent):
+ CodeSubagentCard(parent: parent, tree: subagents)
+ case .run(let run):
+ if flattenSteps {
+ ForEach(run) { step in
+ CodeStepRow(step: step)
+ }
+ } else {
+ CodeStepGroupRow(steps: run)
+ }
+ }
+ }
+ case .approval(let block):
+ CodeApprovalLine(block: block)
+ case .question(let block):
+ CodeQuestionLine(block: block)
+ case .userInput(let block):
+ CodeUserInputLine(block: block)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// Quiet centered hairline divider marking where context was compacted (matching Codex, Claude Code, and
+/// Clean document-flow turn presentation. Never dumps internal fallback summaries or revert icons into the chat stream.
+struct CodeCompactionDividerView: View {
+ let meta: CodeCompactionMeta?
+
+ private var label: String {
+ CodeTurnSummary.compactionLabel(for: meta)
+ }
+
+ var body: some View {
+ CodeTranscriptDivider(systemImage: "arrow.down.right.and.arrow.up.left", label: label)
+ }
+}
+
+/// The divider where a thread changed model or effort, "Gemini 4 Neon High → Claude Opus 5.5 High", drawn as the
+/// compaction divider is, with each engine's logo before its model as the composer's model button shows it.
+struct CodeModelSwitchDividerView: View {
+ let change: CodeModelSwitch
+
+ var body: some View {
+ CodeTranscriptDividerLine {
+ HStack(spacing: 6) {
+ side(change.from, model: change.fromModel)
+ Text("→")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary)
+ side(change.to, model: change.toModel)
+ }
+ }
+ .accessibilityLabel("모델 변경, \(change.from)에서 \(change.to)로")
+ }
+
+ private func side(_ name: String, model: String) -> some View {
+ HStack(spacing: 4) {
+ if let brand = MorphBrand(codeModelId: model) {
+ MorphBrandMark(brand, size: 11, color: AnymorphColor.fgTertiary)
+ } else {
+ Image(systemName: "sparkles")
+ .font(.system(size: 10, weight: .regular))
+ }
+ Text(name)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ }
+}
+
+/// A quiet centered hairline with an icon and a short label, marking a boundary in the conversation.
+struct CodeTranscriptDivider: View {
+ let systemImage: String
+ let label: String
+
+ var body: some View {
+ CodeTranscriptDividerLine {
+ HStack(spacing: 5) {
+ Image(systemName: systemImage)
+ .font(.system(size: 10, weight: .regular))
+ Text(label)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ }
+ .accessibilityLabel(label)
+ }
+}
+
+/// Hairlines on both sides of a divider's center. A center too long for a phone takes the room from the lines first,
+/// then shortens.
+struct CodeTranscriptDividerLine: View {
+ @ViewBuilder let center: Center
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Rectangle()
+ .fill(AnymorphColor.strokeBase)
+ .frame(height: 1)
+ .frame(minWidth: 12)
+ center
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ .layoutPriority(1)
+ Rectangle()
+ .fill(AnymorphColor.strokeBase)
+ .frame(height: 1)
+ .frame(minWidth: 12)
+ }
+ .padding(.vertical, 6)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// Content with quiet icon actions under it, as Codex puts copy and edit under a request and copy and the time under
+/// an answer. On a Mac they show while the pointer is over the content, or all the time when alwaysVisible is set, and
+/// keep their room when hidden so nothing moves. A phone shows them when showsOnTouch is set, and otherwise reaches
+/// them by holding the content.
+struct CodeHoverActions: View {
+ var alignment: HorizontalAlignment = .trailing
+ /// Keeps the actions in view without the pointer, as Codex does under the latest answer.
+ var alwaysVisible = false
+ var showsOnTouch = false
+ @ViewBuilder let content: Content
+ /// The actions, told whether the pointer is over the content so a part such as the time can wait for it.
+ @ViewBuilder let actions: (_ hovered: Bool) -> Actions
+ @State private var hovered = false
+
+ var body: some View {
+ VStack(alignment: alignment, spacing: 4) {
+ content
+ #if os(macOS)
+ HStack(spacing: 2) {
+ actions(hovered)
+ }
+ .opacity(alwaysVisible || hovered ? 1 : 0)
+ .allowsHitTesting(alwaysVisible || hovered)
+ .animation(AnymorphMotion.fast, value: hovered)
+ #else
+ if showsOnTouch {
+ HStack(spacing: 2) {
+ actions(false)
+ }
+ }
+ #endif
+ }
+ .contentShape(Rectangle())
+ .onHover { hovered = $0 }
+ }
+}
+
+/// Codex-style completed work header above an answer:
+/// - Simple replies (no tools/approvals/questions): quiet muted "Worked for 7s" with no raw thinking dump.
+/// - Coding turns with real actions: "Worked for 14s · Read 3 files · Ran 1 command >" opening a single clean rail.
+struct CodeWorkedRow: View {
+ let seconds: Int?
+ let items: [CodeWorkItem]
+ @State private var expanded = false
+ @State private var hovered = false
+
+ /// Real work entries (tools, approvals, Q&A, intermediate notes) excluding raw thinking dumps.
+ private var visibleItems: [CodeWorkItem] {
+ items.filter {
+ if case .thinking = $0 { return false }
+ return true
+ }
+ }
+
+ private var allSteps: [CodeTurnBlock] {
+ visibleItems.flatMap { item -> [CodeTurnBlock] in
+ if case .steps(let s) = item { return s }
+ return []
+ }
+ }
+
+ private var summaryTitle: String {
+ if let seconds, seconds > 0 {
+ return "Worked for \(CodeTurnSummary.durationLabel(seconds: seconds))"
+ }
+ let allSteps = self.allSteps
+ if !allSteps.isEmpty {
+ return CodeTurnSummary.groupedSummary(allSteps)
+ }
+ return "Work log"
+ }
+
+ var body: some View {
+ if visibleItems.isEmpty {
+ if let seconds, seconds > 0 {
+ Text("Worked for \(CodeTurnSummary.durationLabel(seconds: seconds))")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+ } else {
+ VStack(alignment: .leading, spacing: 8) {
+ Button {
+ withAnimation(AnymorphMotion.base) { expanded.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Text(summaryTitle)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ CodeProviderMarks(providers: CodeTurnSummary.providers(allSteps))
+ CodeDisclosureChevron(expanded: expanded)
+ }
+ .padding(.horizontal, 6)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(hovered ? AnymorphColor.bgSubtle : .clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.horizontal, -6)
+ .onHover { hovered = $0 }
+
+ if expanded {
+ CodeScrollableRail(verticalPadding: 2, railInset: 6) {
+ CodeWorkLogView(items: visibleItems, flattenSteps: false)
+ }
+ .transition(.opacity)
+ }
+ }
+ }
+ }
+}
+
+/// Chronological live progress feed shown while a turn runs (Codex-style): intermediate commentary notes stay
+/// visible while each consecutive run of tool steps collapses into one compact expandable summary line
+/// (`CodeStepGroupRow`), avoiding a noisy per-tool dump. Once the turn finishes, everything folds into
+/// `CodeWorkedRow`.
+private struct CodeLiveWorkFeedView: View {
+ let items: [CodeWorkItem]
+ /// The text block still being written, drawn without the raw markers of its unfinished last line.
+ var streamingBlockId: String?
+ @ViewBuilder let userInput: (CodeTurnBlock) -> UserInput
+
+ var body: some View {
+ let subagents = CodeSubagentTree(items: items)
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(items) { item in
+ switch item {
+ case .note(let block):
+ CodeNoteText(text: block.content ?? "", isStreaming: block.id == streamingBlockId)
+ .equatable()
+ case .thinking:
+ EmptyView()
+ case .steps(let steps):
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(subagents.segments(steps)) { segment in
+ switch segment {
+ case .subagent(let parent):
+ CodeSubagentCard(parent: parent, tree: subagents)
+ case .run(let run):
+ CodeStepGroupRow(steps: run)
+ }
+ }
+ }
+ case .approval(let block):
+ CodeApprovalLine(block: block)
+ case .question(let block):
+ CodeQuestionLine(block: block)
+ case .userInput(let block):
+ userInput(block)
+ .morphSubmitRise(distance: 14, initialScale: 1.0)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// A running turn in Codex's manner:
+/// - Commentary notes, tool calls, commands, subagents, approvals, Q&A, and steered messages appear live in
+/// chronological order as the agent works. Text the agent is still writing streams in as a secondary note too, so
+/// it keeps its look and place when the next step arrives.
+/// - The shimmering live status line (`Working..`, `Reading · File.swift`, or the current reasoning title) anchors
+/// the active edge when tools or thinking run, and writing dots sit under text that is streaming.
+/// - On completion, `CodeWorkedRow` cleanly folds all intermediate work into a single collapsed summary row above
+/// the final answer, the only text in the answer's primary style.
+struct CodeLiveTurnView: View {
+ let run: CodeLiveRun
+ let onStop: () -> Void
+ var onSubmitSecret: ((CodeTurnBlock, String) async -> Bool)? = nil
+ var onDeclineSecret: ((CodeTurnBlock) async -> Void)? = nil
+ var macSyncLabelForSecret: ((CodeTurnBlock) -> String?)? = nil
+ var onSyncSecretFromMac: ((CodeTurnBlock) async -> String?)? = nil
+ /// A message the member sent into the turn, with its images.
+ @ViewBuilder let userInput: (CodeTurnBlock) -> UserInput
+ @ViewBuilder let approvalCard: (CodeApproval) -> ApprovalCard
+ @ViewBuilder let questionCard: (CodeUserQuestion) -> QuestionCard
+ @State private var showWorkLog = true
+ @State private var hoveredStatus = false
+
+ var body: some View {
+ let layout = CodeTurnSummary.liveLayout(run.entries)
+ let compactions = run.entries.filter { $0.kind == "compaction" && !$0.isRunning }
+ let hasLiveFeed = !layout.feedItems.isEmpty
+ let needsAttentionStatus = run.isCancelling
+ || run.approval != nil
+ || run.question != nil
+ || layout.hasPendingSecret
+ || layout.hasRunningPreview
+ // Keep the shimmer status footer anchored throughout tool execution and reasoning so it never blinks off
+ // while tools run; omit it only while prose text streams (where writing dots sit underneath instead) unless
+ // an approval/question/cancel needs attention.
+ let showsStatusFooter = layout.showsStatusFooter(needsAttention: needsAttentionStatus)
+
+ // The turn, then the row the finished answer's actions take, spaced as CodeHoverActions spaces them.
+ VStack(alignment: .leading, spacing: 4) {
+ VStack(alignment: .leading, spacing: 12) {
+ if hasLiveFeed {
+ if showWorkLog {
+ CodeLiveWorkFeedView(
+ items: layout.feedItems,
+ streamingBlockId: layout.isStreamingText ? run.entries.last(where: { $0.kind == "text" })?.id : nil,
+ userInput: userInput
+ )
+ .transition(.opacity)
+ } else {
+ // Even when the user manually folds live work, keep steered user messages visible.
+ ForEach(layout.feedItems) { item in
+ if case .userInput(let block) = item {
+ userInput(block)
+ .morphSubmitRise(distance: 14, initialScale: 1.0)
+ }
+ }
+ if !showsStatusFooter {
+ collapsedLiveWorkHeader(feedItems: layout.feedItems)
+ }
+ }
+ }
+ ForEach(compactions) { block in
+ CodeCompactionDividerView(meta: block.compaction)
+ }
+
+ ForEach(layout.htmlPreviews) { previewBlock in
+ CodeHTMLPreviewBlockView(block: previewBlock)
+ }
+
+ ForEach(layout.secretRequests) { secretBlock in
+ CodeSecretRequestCard(
+ block: secretBlock,
+ macSyncLabel: macSyncLabelForSecret?(secretBlock),
+ onSyncFromMac: onSyncSecretFromMac.map { handler in { await handler(secretBlock) } },
+ onSubmit: onSubmitSecret.map { handler in { value in await handler(secretBlock, value) } },
+ onDecline: onDeclineSecret.map { handler in { await handler(secretBlock) } }
+ )
+ }
+
+ if let approval = run.approval {
+ approvalCard(approval)
+ }
+ if let question = run.question {
+ questionCard(question)
+ }
+
+ if showsStatusFooter {
+ liveStatusSection(hasWorkLog: hasLiveFeed)
+ }
+ }
+
+ HStack(spacing: 10) {
+ if layout.isStreamingText && !showsStatusFooter {
+ MorphRunningDots(dotSize: 2.4, spacing: 2.2)
+ }
+ }
+ .frame(height: AnymorphButtonSize.inline.height)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ /// Single-line live status anchored at the active edge: "Working..", active step detail, or reasoning heading.
+ private var liveStatusText: String {
+ CodeTurnSummary.liveStatus(
+ entries: run.entries,
+ approval: run.approval,
+ question: run.question,
+ isCancelling: run.isCancelling
+ )
+ }
+
+ private var liveProvider: String? {
+ CodeTurnSummary.liveProvider(
+ entries: run.entries,
+ approval: run.approval,
+ question: run.question,
+ isCancelling: run.isCancelling
+ )
+ }
+
+ private var liveStatusLabel: some View {
+ HStack(spacing: 6) {
+ if let provider = liveProvider {
+ CodeProviderMarks(providers: [provider])
+ }
+ MorphShimmerText(liveStatusText, scale: .footnote, weight: .base)
+ }
+ }
+
+ private func collapsedLiveWorkHeader(feedItems: [CodeWorkItem]) -> some View {
+ let allSteps = feedItems.flatMap { item -> [CodeTurnBlock] in
+ if case .steps(let s) = item { return s }
+ return []
+ }
+ let summary = allSteps.isEmpty ? "Work log" : CodeTurnSummary.groupedSummary(allSteps)
+ return Button {
+ withAnimation(AnymorphMotion.base) { showWorkLog = true }
+ } label: {
+ HStack(spacing: 6) {
+ Text(summary)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ CodeProviderMarks(providers: CodeTurnSummary.providers(allSteps))
+ CodeDisclosureChevron(expanded: false)
+ }
+ .padding(.horizontal, 6)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(hoveredStatus ? AnymorphColor.bgSubtle : .clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.horizontal, -6)
+ .onHover { hoveredStatus = $0 }
+ }
+
+ @ViewBuilder
+ private func liveStatusSection(hasWorkLog: Bool) -> some View {
+ HStack(spacing: 10) {
+ if !hasWorkLog {
+ liveStatusLabel
+ } else {
+ Button {
+ withAnimation(AnymorphMotion.base) { showWorkLog.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ liveStatusLabel
+ if !showWorkLog || hoveredStatus {
+ Image(systemName: showWorkLog ? "chevron.up" : "chevron.right")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ }
+ .padding(.horizontal, 6)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(hoveredStatus ? AnymorphColor.bgSubtle : .clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.horizontal, -6)
+ .onHover { hoveredStatus = $0 }
+ }
+ Spacer(minLength: 8)
+ }
+ }
+}
+
+/// A hairline work-log container that hugs short content and caps long tool bursts at `maxHeight` with an
+/// internal vertical scrollbar so toggling open a busy group never pushes the conversation off screen.
+private struct CodeScrollableRail: View {
+ #if os(macOS)
+ static var defaultMaxHeight: CGFloat { 280 }
+ #else
+ static var defaultMaxHeight: CGFloat { 240 }
+ #endif
+
+ var maxHeight: CGFloat = defaultMaxHeight
+ var verticalPadding: CGFloat = 2
+ var railInset: CGFloat = 7
+ var anchorBottom: Bool = false
+ @ViewBuilder let content: Content
+ @State private var contentHeight: CGFloat = 0
+
+ private var isOverflowing: Bool {
+ contentHeight > maxHeight
+ }
+
+ private var resolvedHeight: CGFloat? {
+ guard contentHeight > 0 else { return nil }
+ return min(contentHeight, maxHeight)
+ }
+
+ var body: some View {
+ ScrollView(.vertical) {
+ content
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.vertical, verticalPadding)
+ .padding(.trailing, 8)
+ .onGeometryChange(for: CGFloat.self) { proxy in
+ ceil(proxy.size.height)
+ } action: { newHeight in
+ if abs(newHeight - contentHeight) > 0.5 {
+ contentHeight = newHeight
+ }
+ }
+ }
+ .defaultScrollAnchor(anchorBottom ? .bottom : .top, for: .initialOffset)
+ .scrollIndicators(isOverflowing ? .visible : .hidden, axes: .vertical)
+ .scrollBounceBehavior(.basedOnSize)
+ .scrollDisabled(!isOverflowing)
+ .frame(height: resolvedHeight)
+ .frame(maxHeight: maxHeight)
+ .padding(.leading, 14)
+ .overlay(alignment: .leading) {
+ Rectangle().fill(AnymorphColor.strokeBase).frame(width: 1)
+ }
+ .padding(.leading, railInset)
+ }
+}
+
+/// One quiet T3-style summary line for a run of consecutive tool steps (no left status icon), opening into
+/// individual cleaned steps only when tapped. Services the steps reached trail as logos.
+struct CodeStepGroupRow: View {
+ let steps: [CodeTurnBlock]
+ @State private var expanded = false
+ @State private var hovered = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Button {
+ withAnimation(AnymorphMotion.base) { expanded.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Text(CodeTurnSummary.groupedSummary(steps))
+ .anymorphText(
+ .footnote,
+ weight: .base,
+ color: hovered ? AnymorphColor.fgSecondary : AnymorphColor.fgTertiary,
+ tabular: true
+ )
+ .lineLimit(2)
+ .multilineTextAlignment(.leading)
+ CodeProviderMarks(providers: CodeTurnSummary.providers(steps))
+ if steps.contains(where: \.isRunning) {
+ MorphRunningDots(dotSize: 1.8, spacing: 1.6)
+ } else if hovered || expanded {
+ CodeDisclosureChevron(expanded: expanded)
+ }
+ }
+ .padding(.horizontal, 6)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(hovered ? AnymorphColor.bgSubtle : .clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.horizontal, -6)
+ .onHover { hovered = $0 }
+
+ if expanded {
+ CodeScrollableRail(
+ verticalPadding: 4,
+ railInset: 6,
+ anchorBottom: steps.contains(where: \.isRunning)
+ ) {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(steps) { step in
+ CodeStepRow(step: step)
+ }
+ }
+ }
+ .transition(.opacity)
+ }
+ }
+ }
+}
+
+/// One step in an opened group, showing its concise summary without raw shell noise. A step that reached a
+/// service leads with its logo and name, as in "Linear Search issues", in place of "Tool" or "Web". Tapping a
+/// step with command/output opens the full command and output tail.
+private struct CodeStepRow: View {
+ let step: CodeTurnBlock
+ @State private var expanded = false
+ @State private var pathHovered = false
+ @Environment(\.morphOpenFileLocation) private var openFileLocation
+
+ /// The full raw command (when summarized) plus the end of the step's output.
+ private var output: String {
+ var sections: [String] = []
+ if CodeStepKind(block: step) == .execute,
+ let rawCmd = step.command?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !rawCmd.isEmpty,
+ rawCmd != step.conciseStepDetail {
+ sections.append("$ \(rawCmd)")
+ }
+ let text = [step.stdout, step.stderr, step.content]
+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ .joined(separator: "\n")
+ if !text.isEmpty {
+ sections.append(String(text.suffix(2000)))
+ }
+ return sections.joined(separator: "\n\n")
+ }
+
+ var body: some View {
+ let kind = CodeStepKind(block: step)
+ let rowDetail = step.stepRowDetail
+ let detail = rowDetail.isEmpty && step.serviceName == nil ? kind.fallbackDetail : rowDetail
+ let output = self.output
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ if let brand = step.provider.flatMap(MorphBrand.init(provider:)) {
+ MorphBrandMark(brand, size: 12, color: AnymorphColor.fgTertiary)
+ .alignmentGuide(.firstTextBaseline) { $0.height * 0.88 }
+ .padding(.trailing, -4)
+ .help(brand.displayName)
+ }
+ Text(step.stepVerb)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize()
+ if let path = step.filePath, !path.isEmpty, let openFileLocation {
+ Button {
+ openFileLocation(path: path)
+ } label: {
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .underline(pathHovered)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { pathHovered = $0 }
+ .help("Open \(path)")
+ } else {
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ if step.isRunning {
+ MorphRunningDots(dotSize: 1.8, spacing: 1.6)
+ } else if step.isFailed {
+ Text("Failed")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ .fixedSize()
+ }
+ if !output.isEmpty {
+ CodeDisclosureChevron(expanded: expanded)
+ }
+ }
+ .contentShape(Rectangle())
+ .morphPointerCursor(!output.isEmpty)
+ .onTapGesture {
+ guard !output.isEmpty else { return }
+ withAnimation(AnymorphMotion.fast) { expanded.toggle() }
+ }
+ .accessibilityAddTraits(output.isEmpty ? [] : .isButton)
+
+ if expanded {
+ Text(output)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary, monospaced: true)
+ .textSelection(.enabled)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ )
+ .transition(.opacity)
+ }
+ }
+ }
+}
+
+/// Which steps of a turn a subagent ran: the steps whose parent is an agent step of the same turn.
+struct CodeSubagentTree {
+ /// A run of ordinary steps, or an agent step drawn as its card.
+ enum Segment: Identifiable {
+ case run([CodeTurnBlock])
+ case subagent(CodeTurnBlock)
+
+ var id: String {
+ switch self {
+ case .run(let steps): return "run-" + (steps.first?.id ?? "")
+ case .subagent(let parent): return "agent-" + parent.id
+ }
+ }
+ }
+
+ private let childrenByParent: [String: [CodeTurnBlock]]
+
+ init(items: [CodeWorkItem]) {
+ let steps = items.flatMap { item -> [CodeTurnBlock] in
+ if case .steps(let steps) = item { return steps }
+ return []
+ }
+ let parentIds = Set(steps.filter(Self.isSubagent).compactMap(\.toolCallId))
+ let children = steps.filter { step in
+ guard let parentId = step.parentToolCallId else { return false }
+ return parentIds.contains(parentId)
+ }
+ childrenByParent = Dictionary(grouping: children) { $0.parentToolCallId ?? "" }
+ }
+
+ /// An agent step: the server marks it agent, or it names the subagent's role.
+ static func isSubagent(_ step: CodeTurnBlock) -> Bool {
+ step.toolCallId != nil && (step.toolKind == "agent" || step.subagentRole != nil)
+ }
+
+ func children(of parent: CodeTurnBlock) -> [CodeTurnBlock] {
+ parent.toolCallId.flatMap { childrenByParent[$0] } ?? []
+ }
+
+ /// The steps drawn at this level, in order: a subagent's own steps go inside its card.
+ func segments(_ steps: [CodeTurnBlock]) -> [Segment] {
+ var segments: [Segment] = []
+ var run: [CodeTurnBlock] = []
+ for step in steps {
+ if let parentId = step.parentToolCallId, childrenByParent[parentId] != nil {
+ continue
+ }
+ if Self.isSubagent(step) {
+ if !run.isEmpty {
+ segments.append(.run(run))
+ run = []
+ }
+ segments.append(.subagent(step))
+ } else {
+ run.append(step)
+ }
+ }
+ if !run.isEmpty {
+ segments.append(.run(run))
+ }
+ return segments
+ }
+}
+
+/// A subagent's work as one card in the work log: its role and task, whether it still runs, how many steps it took
+/// and its summary, opening to the steps themselves.
+struct CodeSubagentCard: View {
+ let parent: CodeTurnBlock
+ let tree: CodeSubagentTree
+ @State private var expanded = false
+ @State private var hovered = false
+
+ var body: some View {
+ let children = tree.children(of: parent)
+ let isRunning = parent.isRunning || parent.subagentStatus == "running" || children.contains(where: \.isRunning)
+ let isFailed = parent.isFailed || parent.subagentStatus == "failed" || parent.subagentStatus == "error"
+ let summary = parent.subagentSummary?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ VStack(alignment: .leading, spacing: 8) {
+ Button {
+ withAnimation(AnymorphMotion.base) { expanded.toggle() }
+ } label: {
+ HStack(spacing: 8) {
+ Group {
+ if isRunning {
+ MorphRunningDots(dotSize: 2.2, spacing: 2.0)
+ } else {
+ Image(systemName: isFailed ? "exclamationmark.circle" : "person.2")
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ }
+ .frame(width: 14)
+ Text(roleLabel)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .fixedSize()
+ Text(taskLabel)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ Spacer(minLength: 6)
+ Text(statusLabel(isRunning: isRunning, isFailed: isFailed, steps: children.count))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .fixedSize()
+ CodeDisclosureChevron(expanded: expanded)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { hovered = $0 }
+
+ if !summary.isEmpty {
+ Text(summary)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(expanded ? nil : 2)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ .padding(.leading, 22)
+ }
+
+ if expanded, !children.isEmpty {
+ CodeScrollableRail(
+ verticalPadding: 2,
+ railInset: 7,
+ anchorBottom: isRunning
+ ) {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(tree.segments(children)) { segment in
+ switch segment {
+ case .subagent(let nested):
+ CodeSubagentCard(parent: nested, tree: tree)
+ case .run(let run):
+ ForEach(run) { step in
+ CodeStepRow(step: step)
+ }
+ }
+ }
+ }
+ }
+ .transition(.opacity)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(hovered ? AnymorphColor.bgHover : AnymorphColor.bgSubtle)
+ )
+ .animation(AnymorphMotion.fast, value: hovered)
+ }
+
+ private var roleLabel: String {
+ let role = parent.subagentRole?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return role.isEmpty ? "Subagent" : role
+ }
+
+ private var taskLabel: String {
+ let title = parent.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return title.isEmpty ? parent.stepDetail : title
+ }
+
+ private func statusLabel(isRunning: Bool, isFailed: Bool, steps: Int) -> String {
+ let state = isRunning ? "Running" : (isFailed ? "Failed" : "Done")
+ let stepCount = steps == 1 ? "1 step" : "\(steps) steps"
+ return steps > 0 ? "\(state) · \(stepCount)" : state
+ }
+}
+
+/// The logos of the services a turn reached, shown inline beside the activity summary.
+/// it used. The agent's own tools have no logo and show nothing.
+private struct CodeProviderMarks: View {
+ let providers: [String]
+
+ var body: some View {
+ let brands = providers.compactMap(MorphBrand.init(provider:))
+ if !brands.isEmpty {
+ HStack(spacing: 4) {
+ ForEach(brands, id: \.self) { brand in
+ MorphBrandMark(brand, size: 12, color: AnymorphColor.fgTertiary)
+ .help(brand.displayName)
+ }
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(brands.map(\.displayName).joined(separator: ", "))
+ }
+ }
+}
+
+/// A step the member decided on, as one line in the work log.
+private struct CodeApprovalLine: View {
+ let block: CodeTurnBlock
+
+ var body: some View {
+ HStack(spacing: 8) {
+ CodeApprovalIcon(actionKind: block.actionKind, size: 11, weight: .regular, color: AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(CodeApprovalStatus.label(block.status))
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize()
+ Text(block.title ?? "")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+ }
+}
+
+/// An answered or skipped Ask/Answer card folded cleanly into the turn's work log.
+private struct CodeQuestionLine: View {
+ let block: CodeTurnBlock
+
+ private var summary: String {
+ if block.status == "declined" {
+ return "Skipped question"
+ }
+ guard let answers = block.questionAnswers, !answers.isEmpty else {
+ return block.title ?? "Answered question"
+ }
+ let questions = block.questions ?? []
+ let rendered: [String] = questions.compactMap { item in
+ guard let vals = answers[item.id], !vals.isEmpty else { return nil }
+ if item.isSecret == true {
+ return "••••••••"
+ }
+ let labels = vals.map { val -> String in
+ if val.hasPrefix("other:") { return String(val.dropFirst(6)) }
+ return item.options?.first(where: { $0.value == val })?.label ?? val
+ }
+ return labels.joined(separator: ", ")
+ }
+ if !rendered.isEmpty {
+ return rendered.joined(separator: " · ")
+ }
+ if questions.contains(where: { $0.isSecret == true }) {
+ return "••••••••"
+ }
+ return answers.values.flatMap { $0 }.joined(separator: ", ")
+ }
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "questionmark.circle")
+ .font(.system(size: 11, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(block.status == "declined" ? "Skipped" : "Answered")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize()
+ Text(summary)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+ }
+}
+
+/// Renders a `CodeTurnBlock` with `kind == "html_preview"` inline using `MorphInlineHTMLCardView`.
+public struct CodeHTMLPreviewBlockView: View {
+ public let block: CodeTurnBlock
+
+ public init(block: CodeTurnBlock) {
+ self.block = block
+ }
+
+ public var body: some View {
+ let htmlPayload = (block.html ?? block.content ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if !htmlPayload.isEmpty {
+ MorphInlineHTMLCardView(
+ html: htmlPayload,
+ title: block.previewTitle ?? block.title,
+ requestedHeight: block.previewHeight.map { CGFloat($0) }
+ )
+ }
+ }
+}
+
+/// Dedicated monochrome private secret request card for `CodeTurnBlock` with `kind == "secret_request"`.
+/// Keeps values masked (`••••••••`) with an optional show/hide eye toggle and never echoes plaintext into history.
+public struct CodeSecretRequestCard: View {
+ public let block: CodeTurnBlock
+ public var macSyncLabel: String?
+ public var onSyncFromMac: (() async -> String?)?
+ public var onSubmit: ((_ secretValue: String) async -> Bool)?
+ public var onDecline: (() async -> Void)?
+
+ @State private var secretDraft = ""
+ @State private var isRevealed = false
+ @State private var isSubmitting = false
+ @State private var isSyncingFromMac = false
+ @State private var syncErrorText: String?
+ @State private var localState: LocalState = .none
+
+ private enum LocalState {
+ case none
+ case submitted
+ case syncedFromMac
+ case declined
+ }
+
+ public init(
+ block: CodeTurnBlock,
+ macSyncLabel: String? = nil,
+ onSyncFromMac: (() async -> String?)? = nil,
+ onSubmit: ((_ secretValue: String) async -> Bool)? = nil,
+ onDecline: (() async -> Void)? = nil
+ ) {
+ self.block = block
+ self.macSyncLabel = macSyncLabel
+ self.onSyncFromMac = onSyncFromMac
+ self.onSubmit = onSubmit
+ self.onDecline = onDecline
+ }
+
+ private var primaryQuestion: CodeQuestionItem? {
+ block.questions?.first
+ }
+
+ private var isCLIAuthSyncOnly: Bool {
+ let preset = (primaryQuestion?.cliPreset ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let envKey = (primaryQuestion?.envKey ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return !preset.isEmpty && envKey.isEmpty
+ }
+
+ private var labelText: String {
+ let raw = (block.secretLabel ?? block.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return raw.isEmpty ? "비공개 값 입력" : raw
+ }
+
+ private var reasonText: String {
+ (block.secretReason ?? block.content ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ private var isResolved: Bool {
+ if localState != .none { return true }
+ let s = (block.status ?? "").lowercased()
+ return s == "answered" || s == "completed" || s == "done" || s == "submitted" || s == "accepted" || s == "declined" || s == "cancelled"
+ }
+
+ private var isDeclined: Bool {
+ if localState == .declined { return true }
+ let s = (block.status ?? "").lowercased()
+ return s == "declined" || s == "cancelled"
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 8) {
+ Image(systemName: isCLIAuthSyncOnly ? "terminal" : "lock")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ Text(labelText)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ AnymorphBadge(isResolved ? (isDeclined ? "건너뜀" : (localState == .syncedFromMac ? "Mac 동기화됨" : "전달됨")) : (isCLIAuthSyncOnly ? "인증 동기화" : "암호화 입력"))
+ }
+
+ if !reasonText.isEmpty {
+ Text(reasonText)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ if isResolved {
+ HStack(spacing: 6) {
+ Image(systemName: isDeclined ? "minus.circle" : "checkmark.shield")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(
+ isDeclined
+ ? "입력을 건너뛰었습니다."
+ : (localState == .syncedFromMac
+ ? "Mac에서 클라우드 환경으로 안전하게 동기화되었습니다."
+ : "비공개 값이 안전하게 전달되었습니다 · ••••••••")
+ )
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else {
+ if let onSyncFromMac, let syncLabel = macSyncLabel, !syncLabel.isEmpty {
+ HStack(spacing: 8) {
+ Button {
+ guard !isSyncingFromMac, !isSubmitting else { return }
+ isSyncingFromMac = true
+ syncErrorText = nil
+ Task {
+ let err = await onSyncFromMac()
+ if let err, !err.isEmpty {
+ syncErrorText = err
+ } else {
+ secretDraft = ""
+ isRevealed = false
+ localState = .syncedFromMac
+ }
+ isSyncingFromMac = false
+ }
+ } label: {
+ HStack(spacing: 6) {
+ if isSyncingFromMac {
+ ProgressView()
+ .controlSize(.mini)
+ } else {
+ Image(systemName: "laptopcomputer.and.arrow.down")
+ .font(.system(size: 11, weight: .medium))
+ }
+ Text(isSyncingFromMac ? "Mac에서 동기화 중..." : syncLabel)
+ }
+ }
+ .morphPill(isCLIAuthSyncOnly ? .primary : .plain)
+ .disabled(isSyncingFromMac || isSubmitting)
+
+ if isCLIAuthSyncOnly, let onDecline {
+ Spacer()
+ Button("건너뛰기") {
+ guard !isSubmitting, !isSyncingFromMac else { return }
+ isSubmitting = true
+ Task {
+ await onDecline()
+ localState = .declined
+ isSubmitting = false
+ }
+ }
+ .morphPill(.plain)
+ .disabled(isSubmitting || isSyncingFromMac)
+ }
+ }
+ } else if isCLIAuthSyncOnly {
+ HStack(spacing: 8) {
+ Text("Mac 앱에서 한 번 클릭해 클라우드 인증을 동기화할 수 있습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 8)
+ if let onDecline {
+ Button("건너뛰기") {
+ guard !isSubmitting else { return }
+ isSubmitting = true
+ Task {
+ await onDecline()
+ localState = .declined
+ isSubmitting = false
+ }
+ }
+ .morphPill(.plain)
+ .disabled(isSubmitting)
+ }
+ }
+ }
+
+ if let syncErrorText, !syncErrorText.isEmpty {
+ Text(syncErrorText)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ if !isCLIAuthSyncOnly {
+ HStack(spacing: 6) {
+ Group {
+ if isRevealed {
+ TextField("비공개 값을 입력하세요", text: $secretDraft)
+ } else {
+ SecureField("••••••••", text: $secretDraft)
+ }
+ }
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+
+ Button {
+ isRevealed.toggle()
+ } label: {
+ Image(systemName: isRevealed ? "eye.slash" : "eye")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help(isRevealed ? "값 숨기기" : "값 보기")
+ .accessibilityLabel(isRevealed ? "값 숨기기" : "값 보기")
+ }
+
+ if onSubmit != nil || onDecline != nil {
+ HStack(spacing: 8) {
+ if let onDecline {
+ Button("건너뛰기") {
+ guard !isSubmitting, !isSyncingFromMac else { return }
+ isSubmitting = true
+ Task {
+ await onDecline()
+ secretDraft = ""
+ localState = .declined
+ isSubmitting = false
+ }
+ }
+ .morphPill(.plain)
+ .disabled(isSubmitting || isSyncingFromMac)
+ }
+ Spacer()
+ if let onSubmit {
+ Button("안전하게 전달") {
+ let trimmed = secretDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty, !isSubmitting, !isSyncingFromMac else { return }
+ isSubmitting = true
+ Task {
+ let ok = await onSubmit(trimmed)
+ if ok {
+ secretDraft = ""
+ isRevealed = false
+ localState = .submitted
+ }
+ isSubmitting = false
+ }
+ }
+ .morphPill(.primary)
+ .disabled(isSubmitting || isSyncingFromMac || secretDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ } else {
+ Text("입력값은 대화 기록에 평문으로 남지 않습니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ }
+ }
+ .padding(14)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+ }
+}
+
+/// Interactive Ask/Answer card for agent-raised questions (tool elicitation & requestUserInput).
+/// Strictly follows the monochrome Anymorph design system (`AnymorphCard`, `MorphPillButtonStyle`).
+struct CodeQuestionCard: View {
+ let question: CodeUserQuestion
+ let onSubmit: (_ action: String, _ answers: [String: [String]]) -> Void
+ let onSubmitAsync: ((_ action: String, _ answers: [String: [String]]) async -> Bool)?
+
+ @State private var selections: [String: Set] = [:]
+ @State private var otherText: [String: String] = [:]
+ @State private var isSubmitting = false
+ @FocusState private var isOtherFieldFocused: Bool
+
+ init(
+ question: CodeUserQuestion,
+ onSubmit: @escaping (_ action: String, _ answers: [String: [String]]) -> Void
+ ) {
+ self.question = question
+ self.onSubmit = onSubmit
+ self.onSubmitAsync = nil
+ }
+
+ init(
+ question: CodeUserQuestion,
+ onSubmitAsync: @escaping (_ action: String, _ answers: [String: [String]]) async -> Bool
+ ) {
+ self.question = question
+ self.onSubmit = { _, _ in }
+ self.onSubmitAsync = onSubmitAsync
+ }
+
+ private var canSubmit: Bool {
+ guard !isSubmitting else { return false }
+ return question.questions.contains { item in
+ let picked = selections[item.id] ?? []
+ let typed = (otherText[item.id] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return !picked.isEmpty || !typed.isEmpty
+ }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 8) {
+ Image(systemName: "questionmark.circle")
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ Text(question.title?.isEmpty == false ? question.title! : "확인이 필요합니다")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 8)
+ Text("\(question.questions.count)개 질문")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+
+ if let msg = question.message?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !msg.isEmpty,
+ msg != "The agent has a question." {
+ Text(msg)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ }
+
+ ForEach(Array(question.questions.enumerated()), id: \.element.id) { idx, item in
+ VStack(alignment: .leading, spacing: 8) {
+ if idx > 0 {
+ AnymorphDivider()
+ .padding(.vertical, 2)
+ }
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ if let header = item.header?.trimmingCharacters(in: .whitespacesAndNewlines), !header.isEmpty {
+ AnymorphBadge(header)
+ }
+ Text(item.question)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ if let options = item.options, !options.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(Array(options.enumerated()), id: \.element.id) { optIdx, opt in
+ let isSelected = (selections[item.id] ?? []).contains(opt.value)
+ optionRow(item: item, option: opt, questionIndex: idx, optionIndex: optIdx, isSelected: isSelected)
+ }
+ }
+ }
+
+ if item.allowOther == true || (item.options?.isEmpty ?? true) {
+ let binding = Binding(
+ get: { otherText[item.id] ?? "" },
+ set: { otherText[item.id] = $0 }
+ )
+ AnymorphTextField(
+ (item.options?.isEmpty ?? true) ? "답변을 입력하세요…" : "기타 직접 입력…",
+ text: binding,
+ appearance: .outlined,
+ isSecure: item.isSecret == true
+ )
+ .focused($isOtherFieldFocused)
+ }
+ }
+ }
+
+ HStack(spacing: 8) {
+ declineButton
+ Spacer()
+ submitButton
+ }
+ }
+ .padding(14)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+ }
+
+ @ViewBuilder
+ private func optionRow(
+ item: CodeQuestionItem,
+ option opt: CodeQuestionOption,
+ questionIndex: Int,
+ optionIndex: Int,
+ isSelected: Bool
+ ) -> some View {
+ let btn = Button {
+ toggleOption(item: item, value: opt.value)
+ } label: {
+ HStack(alignment: .top, spacing: 10) {
+ Text("\(optionIndex + 1)")
+ .anymorphText(
+ .caption,
+ weight: .emphasis,
+ color: isSelected ? AnymorphColor.fgInverse : AnymorphColor.fgTertiary,
+ tabular: true
+ )
+ .frame(width: 20, height: 20)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgInverse : AnymorphColor.bgSurface)
+ )
+ VStack(alignment: .leading, spacing: 2) {
+ Text(opt.label)
+ .anymorphText(.callout, weight: isSelected ? .strong : .base, color: AnymorphColor.fgPrimary)
+ .multilineTextAlignment(.leading)
+ if let desc = opt.description?.trimmingCharacters(in: .whitespacesAndNewlines), !desc.isEmpty {
+ Text(desc)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.leading)
+ }
+ }
+ Spacer(minLength: 4)
+ if isSelected {
+ MorphLucideIcon(.check, size: 13)
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .padding(.top, 3)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgSelected : AnymorphColor.bgSubtle)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(isSelected ? AnymorphColor.strokeStrong : AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ )
+ }
+ .buttonStyle(.morphPlain)
+
+ #if os(macOS)
+ if questionIndex == 0 && optionIndex < 9 && !isOtherFieldFocused {
+ btn.keyboardShortcut(KeyEquivalent(Character("\(optionIndex + 1)")), modifiers: [])
+ } else {
+ btn
+ }
+ #else
+ btn
+ #endif
+ }
+
+ @ViewBuilder
+ private var declineButton: some View {
+ let btn = Button("건너뛰기") {
+ submitAction("decline", answers: [:])
+ }
+ .morphPill(.plain)
+ .disabled(isSubmitting)
+ #if os(macOS)
+ btn.keyboardShortcut(.escape, modifiers: [])
+ #else
+ btn
+ #endif
+ }
+
+ @ViewBuilder
+ private var submitButton: some View {
+ let btn = Button {
+ guard canSubmit else { return }
+ submitAction("accept", answers: buildAnswers())
+ } label: {
+ if isSubmitting {
+ HStack(spacing: 6) {
+ ProgressView()
+ .controlSize(.mini)
+ Text("보내는 중…")
+ }
+ } else {
+ Text("답변 보내기")
+ }
+ }
+ .morphPill(.primary)
+ .disabled(!canSubmit)
+ #if os(macOS)
+ btn.keyboardShortcut(.return, modifiers: .command)
+ #else
+ btn
+ #endif
+ }
+
+ private func submitAction(_ action: String, answers: [String: [String]]) {
+ guard !isSubmitting else { return }
+ isSubmitting = true
+ if let onSubmitAsync {
+ Task { @MainActor in
+ let ok = await onSubmitAsync(action, answers)
+ if !ok {
+ isSubmitting = false
+ }
+ }
+ } else {
+ onSubmit(action, answers)
+ // Prevent permanent lockout if the async caller fails and leaves the card on screen.
+ Task { @MainActor in
+ try? await Task.sleep(for: .seconds(3.5))
+ isSubmitting = false
+ }
+ }
+ }
+
+ private func toggleOption(item: CodeQuestionItem, value: String) {
+ var current = selections[item.id] ?? []
+ if item.multiSelect == true {
+ if current.contains(value) {
+ current.remove(value)
+ } else {
+ current.insert(value)
+ }
+ } else {
+ current = current.contains(value) ? [] : [value]
+ }
+ selections[item.id] = current
+ }
+
+ private func buildAnswers() -> [String: [String]] {
+ var out: [String: [String]] = [:]
+ for item in question.questions {
+ var vals: [String] = []
+ let picked = selections[item.id] ?? []
+ if let opts = item.options {
+ for opt in opts where picked.contains(opt.value) {
+ vals.append(opt.value)
+ }
+ }
+ let typed = (otherText[item.id] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if !typed.isEmpty {
+ vals.append((item.options?.isEmpty ?? true) ? typed : "other:\(typed)")
+ }
+ if !vals.isEmpty {
+ out[item.id] = vals
+ }
+ }
+ return out
+ }
+}
+
+/// The mark in front of an approval: the logo of the service the action reaches (a GitHub pull request, a Linear
+/// issue, a KakaoTalk message), a clock for a scheduled task, or a shield for the actions Morph runs on the member's
+/// Mac.
+struct CodeApprovalIcon: View {
+ let actionKind: String?
+ let size: CGFloat
+ let weight: Font.Weight
+ let color: Color
+
+ var body: some View {
+ if let brand = Self.brand(for: actionKind) {
+ MorphBrandMark(brand, size: size + 1, color: color)
+ } else {
+ Image(systemName: Self.symbol(for: actionKind))
+ .font(.system(size: size, weight: weight))
+ .foregroundStyle(color)
+ }
+ }
+
+ static func brand(for actionKind: String?) -> MorphBrand? {
+ switch actionKind {
+ case "open_git_pr", "merge_git_pr", "push_git_branch": return .github
+ case "update_linear_issue": return .linear
+ case "local_kakao_send": return .kakaotalk
+ default: return nil
+ }
+ }
+
+ static func symbol(for actionKind: String?) -> String {
+ switch actionKind {
+ case "schedule_task": return "clock"
+ case "plan_approval": return "list.bullet.clipboard"
+ default: return "checkmark.shield"
+ }
+ }
+}
+
+// MARK: - Plan approval
+
+/// What the member chose on a plan approval card.
+enum CodePlanDecision: Equatable {
+ /// Approve the plan and implement it in this access mode, optionally from a compacted, fresh context.
+ case implement(accessMode: CodeAccessMode, clearContext: Bool)
+ /// Send the plan back with what to change.
+ case revise(String)
+}
+
+/// A plan the agent wrote in Plan mode, waiting for the member, as Claude's ExitPlanMode asks: the plan in full
+/// Markdown, then 구현 시작 under default permissions, Full access or a fresh context, or a revision request.
+struct CodePlanApprovalCard: View {
+ let approval: CodeApproval
+ var imageLoader: ((String) async -> Data?)? = nil
+ let onDecide: (CodePlanDecision) -> Void
+
+ @State private var isRevising = false
+ @State private var revisionDraft = ""
+ @State private var isSubmitting = false
+ @FocusState private var isRevisionFocused: Bool
+
+ private var plan: String {
+ let content = approval.planContent?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if !content.isEmpty { return content }
+ let summary = approval.summary.trimmingCharacters(in: .whitespacesAndNewlines)
+ return summary.isEmpty ? approval.payload : summary
+ }
+
+ private var isPending: Bool { approval.status == "pending" }
+
+ private var trimmedRevision: String {
+ revisionDraft.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ header
+ planPreview
+ if isPending {
+ actions
+ if isRevising {
+ revisionField
+ .transition(.opacity.combined(with: .move(edge: .top)))
+ }
+ } else if let reason = approval.decisionReason?.trimmingCharacters(in: .whitespacesAndNewlines), !reason.isEmpty {
+ Text(reason)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ .padding(12)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ )
+ .animation(AnymorphMotion.fast, value: isRevising)
+ }
+
+ /// The same head as a command's approval card: the plan mark, the title and where the decision stands.
+ private var header: some View {
+ HStack(alignment: .center, spacing: 8) {
+ CodeApprovalIcon(actionKind: "plan_approval", size: 13, weight: .semibold, color: AnymorphColor.fgPrimary)
+ Text(approval.title.isEmpty ? "구현 계획" : approval.title)
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ Spacer(minLength: 8)
+ AnymorphBadge(Self.statusLabel(approval))
+ }
+ }
+
+ /// The plan in a quiet inset well that scrolls past 360 points, so long plans keep the actions in reach.
+ private var planPreview: some View {
+ ScrollView(.vertical, showsIndicators: true) {
+ MorphMarkdownText(plan, scale: .callout, preserveLineBreaks: false, imageLoader: imageLoader)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 14)
+ .padding(.vertical, 12)
+ }
+ .frame(maxWidth: .infinity, maxHeight: 360, alignment: .topLeading)
+ .fixedSize(horizontal: false, vertical: true)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+
+ private var actions: some View {
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 8) {
+ implementButtons
+ Spacer(minLength: 8)
+ reviseToggle
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ primaryButton
+ reviseToggle
+ }
+ HStack(spacing: 8) {
+ fullAccessButton
+ freshContextButton
+ }
+ }
+ }
+ .disabled(isSubmitting)
+ }
+
+ @ViewBuilder
+ private var implementButtons: some View {
+ primaryButton
+ fullAccessButton
+ freshContextButton
+ }
+
+ private var primaryButton: some View {
+ Button("Start implementing") {
+ decide(.implement(accessMode: .defaultPermissions, clearContext: false))
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .help("Approve the plan and implement with default permissions")
+ }
+
+ private var fullAccessButton: some View {
+ Button {
+ decide(.implement(accessMode: .fullAccess, clearContext: false))
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "bolt")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.accessFull)
+ Text("Full access")
+ }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .help("Approve the plan and implement with full workspace access")
+ }
+
+ private var freshContextButton: some View {
+ Button("Fresh context") {
+ decide(.implement(accessMode: .defaultPermissions, clearContext: true))
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .help("Compact conversation and implement this plan in a fresh context")
+ }
+
+ private var reviseToggle: some View {
+ Button(isRevising ? "Cancel" : "Request changes") {
+ isRevising.toggle()
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ }
+
+ private var revisionField: some View {
+ HStack(alignment: .bottom, spacing: 8) {
+ TextField("Describe what to change in the plan", text: $revisionDraft, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .lineLimit(1...6)
+ .focused($isRevisionFocused)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .onSubmit(sendRevision)
+ .onAppear { isRevisionFocused = true }
+ Button("Send revision", action: sendRevision)
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(trimmedRevision.isEmpty || isSubmitting)
+ }
+ }
+
+ private func sendRevision() {
+ let reason = trimmedRevision
+ guard !reason.isEmpty else { return }
+ decide(.revise(reason))
+ }
+
+ private func decide(_ decision: CodePlanDecision) {
+ guard !isSubmitting else { return }
+ isSubmitting = true
+ onDecide(decision)
+ // A failed decision leaves the plan pending; the buttons come back once the request has had its time.
+ Task {
+ try? await Task.sleep(for: .seconds(4))
+ isSubmitting = false
+ }
+ }
+
+ static func statusLabel(_ approval: CodeApproval) -> String {
+ switch approval.status {
+ case "denied":
+ return "Changes requested"
+ case "allow_once", "allow_thread", "approved":
+ if approval.clearContext == true { return "Implemented in fresh context" }
+ return approval.targetAccessMode == .fullAccess ? "Implemented (Full access)" : "Plan approved"
+ default:
+ return CodeApprovalStatus.label(approval.status)
+ }
+ }
+}
+
+/// An approval's state in words, for approval cards and the work log.
+enum CodeApprovalStatus {
+ static func label(_ status: String?) -> String {
+ switch status {
+ case "allow_once": return "Allowed"
+ case "allow_thread": return "Allowed in thread"
+ case "denied": return "Denied"
+ default: return "Pending approval"
+ }
+ }
+}
+
+/// A message the member sent into the turn while it ran, as a request where it arrived in the work.
+private struct CodeUserInputLine: View {
+ let block: CodeTurnBlock
+
+ var body: some View {
+ CodeRequestBubble(text: block.content ?? "")
+ .frame(maxWidth: 660, alignment: .trailing)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, 60)
+ }
+}
+
+/// A request's text on the surface every request in a conversation uses.
+struct CodeRequestBubble: View {
+ let text: String
+
+ var body: some View {
+ Text(text)
+ .anymorphText(.reading, weight: .base, color: AnymorphColor.fgPrimary)
+ .lineSpacing(2)
+ .textSelection(.enabled)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 15)
+ .padding(.vertical, 10)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ )
+ }
+}
+
+/// A note the model wrote on its way to the answer: the same Markdown, size and block rhythm as the final answer,
+/// in a dimmer ink. The last note of a turn becomes its answer, so finishing only brightens the ink and nothing
+/// reflows. While a note streams, its unfinished last line drops raw markers (`**`, a lone `#`, a table header
+/// waiting for its separator) so it never shows syntax that turns into formatting a moment later.
+private struct CodeNoteText: View, Equatable {
+ let text: String
+ var isStreaming = false
+
+ /// Brings the answer's reading ink (0.82 to 0.88 alpha) down to about the secondary ink (0.72).
+ private static let noteOpacity = 0.84
+
+ var body: some View {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ MorphMarkdownText(
+ isStreaming ? MorphStreamingMarkdown.stabilize(trimmed) : trimmed,
+ scale: .reading,
+ preserveLineBreaks: false
+ )
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .opacity(Self.noteOpacity)
+ }
+}
+
+/// The small chevron after a disclosure row's label, pointing down while the row is open.
+struct CodeDisclosureChevron: View {
+ let expanded: Bool
+
+ var body: some View {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 8, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .rotationEffect(.degrees(expanded ? 90 : 0))
+ }
+}
+
diff --git a/apple/Apps/Shared/MorphCodeWorkspaceView.swift b/apple/Apps/Shared/MorphCodeWorkspaceView.swift
new file mode 100644
index 000000000..eb0e38899
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodeWorkspaceView.swift
@@ -0,0 +1,3521 @@
+import SwiftUI
+import UniformTypeIdentifiers
+import WebKit
+import MorphCore
+#if os(macOS)
+import AppKit
+#elseif os(iOS)
+import UIKit
+import PhotosUI
+#endif
+
+/// Morph Code's main area: the open thread or 예약됨, as the sidebar picked.
+/// Keeps both layers warm once visited so hopping to 예약됨 and back to a thread never recreates the workspace.
+struct MorphCodeMainArea: View {
+ @Bindable var state: MorphAppState
+ var topInset: CGFloat = 0
+
+ var body: some View {
+ MorphKeepAliveStack(
+ active: state.codeDestination,
+ items: [CodeDestination.threads, .scheduled]
+ ) { destination in
+ switch destination {
+ case .threads:
+ MorphCodeWorkspaceView(state: state, topInset: topInset)
+ case .scheduled:
+ MorphCodeScheduledView(state: state, topInset: topInset)
+ }
+ }
+ }
+}
+
+/// Codex-style workspace for Morph Code: each turn's work folds into short lines above its full Markdown answer,
+/// a running turn shows what it is doing now, and cards carry images, documents, browser live views and approvals.
+/// The composer takes `@file` mentions and images: pasted, dropped anywhere on the workspace, or picked from the +
+/// menu, waiting as tiles inside the composer card until they go with the request.
+public struct MorphCodeWorkspaceView: View {
+ @Bindable var state: MorphAppState
+ var topInset: CGFloat
+ @State private var composerFocused = false
+ #if os(iOS)
+ /// The bottom safe area under the composer: the home indicator's strip, or the keyboard while it is up.
+ @State private var bottomSafeArea: CGFloat = 0
+ @Environment(\.morphComposerRestingGap) private var composerRestingGap
+ #endif
+ @Environment(\.openURL) private var openURL
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ #if os(iOS)
+ @Environment(\.horizontalSizeClass) private var horizontalSizeClass
+ #endif
+ @State private var copiedMessageId: String?
+ @State private var openedFile: MorphFileItem?
+ @State private var lightboxImage: MorphLightboxImageItem?
+ @State private var showFileImporter = false
+ #if os(iOS)
+ @State private var showPhotoPicker = false
+ @State private var showCameraPicker = false
+ @State private var photoSelection: [PhotosPickerItem] = []
+ #endif
+ /// Approval cards whose raw command/diff preview disclosure is expanded.
+ @State private var expandedApprovalDetailIds: Set = []
+ /// A drag carrying images is over the workspace, or over the composer's field, which takes drops itself.
+ @State private var isWorkspaceDropTargeted = false
+ @State private var isFieldDropTargeted = false
+ /// The `@` mention at the caret, while its popover is open.
+ @State private var activeMention: MorphComposerMention?
+ /// Set while the composer's text changes because a mention was completed, so the completion opens no popover.
+ @State private var isApplyingMention = false
+ @State private var popoverHighlightedIndex = 0
+ /// Increments on each prompt submission so the scroll view glides upward smoothly instead of snapping.
+ @State private var submitScrollTrigger = 0
+ /// Anchors the scroll position to the previously-oldest message after prepending an older history page.
+ @State private var olderAnchorRequest: MorphCodeOlderAnchorRequest?
+ /// The request open for editing in place, its text and whether sending it puts the files back first.
+ @State private var editingMessageId: String?
+ @State private var editingText = ""
+ @State private var editRestoresFiles = false
+ /// The queued request open for editing and its text.
+ @State private var editingQueueItemId: String?
+ @State private var editingQueueText = ""
+ /// The reply whose file changes wait for the member to confirm the revert.
+ @State private var revertCandidate: CodeMessage?
+ /// The match the ⌘F find bar is on, an index into the matching messages.
+ @State private var findMatchIndex = 0
+ @FocusState private var isFindFieldFocused: Bool
+ /// The approval whose rejection reason field is open, its text, and whether the field has focus.
+ @State private var feedbackApprovalId: String?
+ @State private var approvalFeedback = ""
+ @FocusState private var isRejectionFieldFocused: Bool
+ /// Where ↑ ↓ stand in the sent-request history (0 is the latest), and the unsent text ↑ first stepped away from.
+ @State private var promptHistoryIndex: Int? = nil
+ @State private var promptHistorySavedDraft: String = ""
+ /// Set while the composer's text changes because history filled it, so the change keeps the history position.
+ @State private var isApplyingHistory = false
+ @State private var voiceDictator = MorphVoiceDictator()
+ /// A window bound to one thread keeps its own composer, mirrored into that thread's saved draft.
+ @State private var boundComposerText = ""
+ @State private var boundAttachments: [CodeImageAttachment] = []
+ @State private var boundProcessingImages = 0
+ /// It picks its own model, effort and permission mode too, starting from the thread's.
+ @State private var boundModel = "auto"
+ @State private var boundEffort: CodeReasoningEffort = .medium
+ @State private var boundAccessMode: CodeAccessMode = .defaultPermissions
+
+ /// The thread a secondary window shows regardless of the sidebar's selection; nil for the main window.
+ public let boundThreadId: String?
+
+ static let columnWidth: CGFloat = 920
+
+ #if os(macOS)
+ static let horizontalPadding: CGFloat = 28
+ #else
+ static let horizontalPadding: CGFloat = 14
+ #endif
+
+ /// - Parameter boundThreadId: Binds the view to one thread, as a secondary window does: it shows that thread
+ /// whatever the sidebar selects, keeps its own composer, model, effort and permission mode, and sends straight
+ /// to it. Nil follows the selection.
+ public init(state: MorphAppState, topInset: CGFloat = 0, boundThreadId: String? = nil) {
+ self.state = state
+ self.topInset = topInset
+ self.boundThreadId = boundThreadId
+ }
+
+ private var activeThread: CodeThread? {
+ if let boundThreadId {
+ return state.codeThreads.first { $0.id == boundThreadId }
+ }
+ return state.selectedCodeThread
+ }
+
+ /// The open thread's project, or on the new-thread screen the folder project picked there.
+ private var activeProject: CodeProject? {
+ let projectId = activeThread?.projectId ?? (boundThreadId == nil ? state.codeNewThreadDraft?.projectId : nil)
+ return state.codeProjects.first { $0.id == projectId }
+ }
+
+ private var activeRun: CodeLiveRun? {
+ if let thread = activeThread {
+ return state.codeLiveRuns[thread.id]
+ }
+ return boundThreadId == nil ? state.pendingDraftCodeRun : nil
+ }
+
+ private var isActiveThreadLocal: Bool {
+ true
+ }
+
+ private var messages: [CodeMessage] {
+ guard let id = activeThread?.id else { return [] }
+ return state.codeMessagesByThread[id] ?? []
+ }
+
+ /// Stored messages currently shown, excluding the duplicate server copy while the optimistic prompt finishes rising.
+ private var shownMessages: [CodeMessage] {
+ let hidingMessageId = activeRun?.pendingPrompt != nil ? activeRun?.submittedMessageId : nil
+ return hidingMessageId == nil ? messages : messages.filter { $0.id != hidingMessageId }
+ }
+
+ /// Sync state for the open thread: centered canvas sync while empty, quiet header/composer sync indicator while
+ /// refreshing or hydrating history behind a live turn, or centered error retry when an uncached fetch fails.
+ private var syncPresentation: CodeThreadSyncPresentation {
+ guard let threadId = activeThread?.id else { return .none }
+ return CodeThreadSyncPresentation.resolve(
+ hasMessages: !shownMessages.isEmpty,
+ hasActiveRun: activeRun != nil,
+ isLoading: state.codeLoadingMessageThreadIds.contains(threadId),
+ hasSyncedOnce: state.codeSyncedMessageThreadIds.contains(threadId),
+ loadError: state.codeMessageLoadErrorByThread[threadId],
+ source: state.codeThreadSyncSource(for: threadId)
+ )
+ }
+
+ /// No thread opened yet.
+ private var isConversationEmpty: Bool {
+ activeThread == nil && activeRun == nil
+ }
+
+ /// Loads an image or a file of the open thread, from this Mac or the server.
+ private var activeFileLoader: (String) async -> Data? {
+ let projectId = activeProject?.id
+ let threadId = activeThread?.id
+ let isLocal = isActiveThreadLocal
+ return { source in
+ await state.loadCodeFileData(source: source, projectId: projectId, threadId: threadId, isLocal: isLocal)
+ }
+ }
+
+ /// A phone leaves the file path out of an image card's header so the title keeps the room.
+ private var showsImagePath: Bool {
+ #if os(iOS)
+ horizontalSizeClass != .compact
+ #else
+ true
+ #endif
+ }
+
+ /// Opens `path:line` from answers and steps in the reader, for the open thread's project. A path inside the
+ /// thread's worktree or the project's folder becomes relative to it, the way the reader loads files.
+ private var openFileLocationAction: MorphOpenFileLocationAction? {
+ guard let projectId = activeProject?.id else { return nil }
+ let threadId = activeThread?.id
+ let roots = [activeThread?.worktreePath, activeProject?.workspacePath]
+ .compactMap { $0 }
+ .filter { !$0.isEmpty }
+ let state = state
+ return MorphOpenFileLocationAction { path, line in
+ state.openCodeFileInReader(
+ projectId: projectId,
+ threadId: threadId,
+ path: Self.workspaceRelativePath(path, roots: roots),
+ line: line
+ )
+ }
+ }
+
+ static func workspaceRelativePath(_ path: String, roots: [String]) -> String {
+ for root in roots {
+ let folder = root.hasSuffix("/") ? root : root + "/"
+ if path.hasPrefix(folder) {
+ return String(path.dropFirst(folder.count))
+ }
+ }
+ return path.hasPrefix("./") ? String(path.dropFirst(2)) : path
+ }
+
+ /// The files the + menu, the file panel and Files offer: images and the documents and code a request can carry.
+ static let attachableTypes: [UTType] = [.image, .pdf, .commaSeparatedText, .json, .text, .sourceCode, .zip, .data]
+
+ public var body: some View {
+ workspaceLifecycle(workspaceChrome)
+ }
+
+ /// The conversation or the new-task home, with the find bar, the thread menu and the composer dock.
+ private var workspaceChrome: some View {
+ // `safeAreaInset(edge: .bottom)` asks its primary view for its minimum size on layout updates, which would
+ // otherwise descend into the ScrollView's content and re-measure streaming text multiple times per delta.
+ // An overlay over `Color.clear` takes the final bounds directly while still receiving the bottom safe-area inset.
+ Color.clear
+ .overlay {
+ ZStack {
+ if isConversationEmpty {
+ emptyState
+ .transition(.asymmetric(
+ insertion: .opacity,
+ removal: reduceMotion ? .opacity : .opacity.combined(with: .offset(y: -14))
+ ))
+ } else {
+ conversation
+ .transition(.asymmetric(
+ insertion: reduceMotion ? .opacity : .opacity.combined(with: .offset(y: 14)),
+ removal: .opacity
+ ))
+ }
+ }
+ .animation(reduceMotion ? AnymorphMotion.fast : AnymorphMotion.submit, value: isConversationEmpty)
+ .withoutAnimationOnThreadSwitch(activeThread?.id)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+ .overlay(alignment: .top) {
+ VStack(spacing: 6) {
+ if let thread = activeThread, thread.isEffectivelyArchived || thread.isSnoozed {
+ threadStateBanner(thread)
+ .transition(.opacity.combined(with: .move(edge: .top)))
+ }
+ if boundThreadId == nil, state.isCodeThreadFindPresented, activeThread != nil {
+ findBar
+ .transition(.opacity.combined(with: .move(edge: .top)))
+ }
+ }
+ .padding(.top, topInset + 10)
+ .padding(.horizontal, Self.horizontalPadding)
+ .withoutAnimationOnThreadSwitch(activeThread?.id)
+ }
+ .animation(AnymorphMotion.fast, value: state.isCodeThreadFindPresented)
+ .animation(AnymorphMotion.fast, value: activeThread?.isEffectivelyArchived == true || activeThread?.isSnoozed == true)
+ .onChange(of: state.isCodeThreadFindPresented) { _, presented in
+ if presented {
+ isFindFieldFocused = true
+ }
+ }
+ .safeAreaInset(edge: .bottom, spacing: 0) {
+ MorphCodeObservationBoundary {
+ composerDock()
+ .onChange(of: composerText) { oldValue, newValue in
+ if isApplyingHistory {
+ isApplyingHistory = false
+ } else {
+ promptHistoryIndex = nil
+ }
+ updateMention(old: oldValue, new: newValue)
+ }
+ .modifier(BoundDraftSync(
+ isBound: boundThreadId != nil,
+ text: boundComposerText,
+ attachments: boundAttachments,
+ revision: boundDraftRevision,
+ persist: persistBoundDraft,
+ reload: loadBoundDraft
+ ))
+ }
+ }
+ #if os(iOS)
+ .onGeometryChange(for: CGFloat.self) { $0.safeAreaInsets.bottom } action: { bottomSafeArea = $0 }
+ #endif
+ .environment(\.morphOpenFileLocation, openFileLocationAction)
+ }
+
+ private var isCodeWorkspaceVisible: Bool {
+ state.appMode == .code && state.codeDestination == .threads
+ }
+
+ private func syncWorkspaceVisibility(_ isVisible: Bool) {
+ guard boundThreadId == nil else { return }
+ state.isCodeThreadOnScreen = isVisible
+ if isVisible {
+ if let threadId = activeThread?.id {
+ state.markCodeThreadReadIfViewing(threadId)
+ }
+ } else {
+ voiceDictator.stop()
+ composerFocused = false
+ }
+ }
+
+ private func workspaceLifecycle(_ content: some View) -> some View {
+ content
+ // The open thread is on screen while this view is: beside the sidebar on a Mac.
+ // A window bound to one thread leaves the main window's flag alone.
+ .onAppear {
+ if boundThreadId == nil {
+ state.isCodeThreadOnScreen = isCodeWorkspaceVisible
+ }
+ }
+ .onDisappear {
+ if boundThreadId == nil { state.isCodeThreadOnScreen = false }
+ voiceDictator.stop()
+ }
+ .onChange(of: state.appMode) { _, _ in
+ syncWorkspaceVisibility(isCodeWorkspaceVisible)
+ }
+ .onChange(of: state.codeDestination) { _, _ in
+ syncWorkspaceVisibility(isCodeWorkspaceVisible)
+ }
+ .task(id: boundThreadId == nil ? "\(activeThread?.id ?? "")|\(state.localBridgeOnline)" : nil) {
+ guard boundThreadId == nil, let threadId = activeThread?.id else { return }
+ state.markCodeThreadReadIfViewing(threadId)
+ let needsFetch = CodeThreadSyncPresentation.shouldFetchOnOpen(
+ hasMessages: !(state.codeMessagesByThread[threadId]?.isEmpty ?? true),
+ hasSyncedOnce: state.codeSyncedMessageThreadIds.contains(threadId),
+ hasLoadError: state.codeMessageLoadErrorByThread[threadId] != nil,
+ isLoading: state.codeLoadingMessageThreadIds.contains(threadId)
+ )
+ if needsFetch {
+ await state.hydrateAndLoadCodeMessages(threadId: threadId)
+ }
+ }
+ .task(id: boundThreadId.map { "\($0)|\(state.localBridgeOnline)" }) {
+ guard let boundThreadId else { return }
+ loadBoundSettings()
+ loadBoundDraft()
+ state.markCodeThreadReadIfViewing(boundThreadId, allowBoundWindow: true)
+ let needsFetch = CodeThreadSyncPresentation.shouldFetchOnOpen(
+ hasMessages: !(state.codeMessagesByThread[boundThreadId]?.isEmpty ?? true),
+ hasSyncedOnce: state.codeSyncedMessageThreadIds.contains(boundThreadId),
+ hasLoadError: state.codeMessageLoadErrorByThread[boundThreadId] != nil,
+ isLoading: state.codeLoadingMessageThreadIds.contains(boundThreadId)
+ )
+ if needsFetch {
+ await state.hydrateAndLoadCodeMessages(threadId: boundThreadId)
+ }
+ }
+ .onChange(of: activeThread?.unreadCount ?? 0) { _, unread in
+ if let boundThreadId, unread > 0 {
+ state.markCodeThreadReadIfViewing(boundThreadId, allowBoundWindow: true)
+ }
+ }
+ // Skills become / commands; a project brings its own.
+ .task(id: activeProject?.id) {
+ await state.refreshCodeSkills(projectId: activeProject?.id)
+ }
+ .morphFilePreview($openedFile, load: activeFileLoader) { message in
+ state.showError(message)
+ }
+ .morphImagePreview($lightboxImage)
+ .sheet(item: boundThreadId == nil ? $state.codePendingFileViewer : .constant(nil)) { request in
+ fileReader(request)
+ }
+ #if os(iOS)
+ .fullScreenCover(isPresented: $showCameraPicker) {
+ MorphCameraPicker { data in
+ if let data {
+ attachImages([.data(data, name: "camera-\(Int(Date().timeIntervalSince1970)).jpg")])
+ }
+ }
+ .ignoresSafeArea()
+ }
+ #endif
+ #if os(macOS)
+ .onKeyPress(characters: CharacterSet(charactersIn: "yYnN")) { press in
+ guard !composerFocused, !isFindFieldFocused, feedbackApprovalId == nil,
+ let threadId = activeThread?.id,
+ let pending = activePendingApproval(for: threadId) else {
+ return .ignored
+ }
+ let ch = press.characters.lowercased()
+ if ch == "y" {
+ Task { await state.decideCodeApproval(id: pending.id, decision: "allow_once", threadId: threadId) }
+ return .handled
+ } else if ch == "n" {
+ Task { await state.decideCodeApproval(id: pending.id, decision: "denied", threadId: threadId) }
+ return .handled
+ }
+ return .ignored
+ }
+ #endif
+ .fileImporter(
+ isPresented: $showFileImporter,
+ allowedContentTypes: Self.attachableTypes,
+ allowsMultipleSelection: true
+ ) { result in
+ if case .success(let urls) = result {
+ attachFiles(urls)
+ }
+ }
+ #if os(iOS)
+ .photosPicker(isPresented: $showPhotoPicker, selection: $photoSelection, matching: .images)
+ .onChange(of: photoSelection) { _, items in
+ guard !items.isEmpty else { return }
+ photoSelection = []
+ attachPhotos(items)
+ }
+ #endif
+ .onDrop(
+ of: MorphImageDropDelegate.acceptedTypes,
+ delegate: MorphImageDropDelegate(isTargeted: $isWorkspaceDropTargeted) { picked in
+ attachPicked(picked)
+ }
+ )
+ .onChange(of: activeThread?.id) { _, _ in
+ voiceDictator.stop()
+ promptHistoryIndex = nil
+ }
+ .onChange(of: voiceDictator.errorMessage) { _, message in
+ guard let message else { return }
+ voiceDictator.errorMessage = nil
+ state.showError(message)
+ }
+ }
+
+ /// A file the conversation named, opened in the viewer (PDF, image, Quick Look, Markdown, HTML/SVG, or code).
+ private func fileReader(_ request: CodeFileOpenRequest) -> some View {
+ let name = (request.path as NSString).lastPathComponent
+ let state = state
+ let localURL = state.resolveLocalCodeFileURL(
+ source: request.path,
+ projectId: request.projectId,
+ threadId: request.threadId,
+ isLocal: request.isLocal
+ )
+ return MorphFileReader(
+ file: MorphFileItem(
+ id: request.id.uuidString,
+ name: name.isEmpty ? request.path : name,
+ path: request.path,
+ mimeType: nil,
+ text: nil,
+ source: request.path,
+ localURL: localURL
+ ),
+ load: { source in
+ await state.loadCodeFileData(
+ source: source,
+ projectId: request.projectId,
+ threadId: request.threadId,
+ isLocal: request.isLocal
+ )
+ },
+ initialLine: request.line
+ )
+ }
+
+ // MARK: - ⌘F Find
+
+ /// The messages holding the find bar's text, oldest first.
+ private var findMatchIds: [String] {
+ guard state.isCodeThreadFindPresented else { return [] }
+ let query = state.codeThreadFindQuery.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !query.isEmpty else { return [] }
+ return messages.filter { $0.content.localizedCaseInsensitiveContains(query) }.map(\.id)
+ }
+
+ private var activeFindMatchId: String? {
+ let ids = findMatchIds
+ guard !ids.isEmpty else { return nil }
+ return ids[min(max(0, findMatchIndex), ids.count - 1)]
+ }
+
+ /// Slim banner shown at the top of an archived or snoozed thread with a 1-click restore / unsnooze action.
+ private func threadStateBanner(_ thread: CodeThread) -> some View {
+ let isArchived = thread.isEffectivelyArchived
+ return HStack(spacing: 10) {
+ Image(systemName: isArchived ? "archivebox" : "moon.zzz")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text(isArchived ? "보관된 스레드입니다. 메시지를 보내면 목록으로 자동 복원됩니다." : "나중에 보기로 보류 중인 스레드입니다.")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ Button(isArchived ? "목록으로 되돌리기" : "보류 해제") {
+ Task {
+ if isArchived {
+ await state.archiveCodeThread(id: thread.id, archived: false)
+ } else {
+ await state.snoozeCodeThread(id: thread.id, until: nil)
+ }
+ }
+ }
+ .morphPill(.secondary)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .frame(maxWidth: Self.columnWidth)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+ }
+
+ private var findBar: some View {
+ let ids = findMatchIds
+ let hasQuery = !state.codeThreadFindQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let position = ids.isEmpty ? 0 : min(max(0, findMatchIndex), ids.count - 1) + 1
+ return HStack(spacing: 6) {
+ Image(systemName: "magnifyingglass")
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ TextField("대화에서 찾기", text: $state.codeThreadFindQuery)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .focused($isFindFieldFocused)
+ .frame(minWidth: 150)
+ .onSubmit { moveFindMatch(by: 1) }
+ .onKeyPress(.escape) {
+ closeFind()
+ return .handled
+ }
+ .onKeyPress(.upArrow) {
+ moveFindMatch(by: -1)
+ return .handled
+ }
+ .onKeyPress(.downArrow) {
+ moveFindMatch(by: 1)
+ return .handled
+ }
+ if hasQuery {
+ Text("\(position)/\(ids.count)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .fixedSize()
+ }
+ findBarButton("chevron.up", label: "이전 결과", disabled: ids.isEmpty) { moveFindMatch(by: -1) }
+ findBarButton("chevron.down", label: "다음 결과", disabled: ids.isEmpty) { moveFindMatch(by: 1) }
+ findBarButton("xmark", label: "닫기 · Esc", disabled: false) { closeFind() }
+ }
+ .padding(.leading, 12)
+ .padding(.trailing, 4)
+ .frame(height: 34)
+ .frame(maxWidth: 420)
+ .background(Capsule().fill(AnymorphColor.menuSurface))
+ .overlay(Capsule().strokeBorder(AnymorphColor.menuStroke, lineWidth: 1))
+ .shadow(color: AnymorphColor.composerShadow, radius: 10, y: 3)
+ .onAppear { isFindFieldFocused = true }
+ .onChange(of: state.codeThreadFindQuery) { _, _ in
+ // A new search starts at the latest match, nearest to where the conversation is read.
+ findMatchIndex = max(0, findMatchIds.count - 1)
+ }
+ }
+
+ private func findBarButton(_ symbol: String, label: String, disabled: Bool, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Image(systemName: symbol)
+ .font(.system(size: 10.5, weight: .semibold))
+ .foregroundStyle(disabled ? AnymorphColor.fgDisabled : AnymorphColor.fgSecondary)
+ .frame(width: 24, height: 24)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxl))
+ }
+ .buttonStyle(.morphPlain)
+ .disabled(disabled)
+ .help(label)
+ .accessibilityLabel(label)
+ }
+
+ private func moveFindMatch(by delta: Int) {
+ let count = findMatchIds.count
+ guard count > 0 else { return }
+ findMatchIndex = (min(max(0, findMatchIndex), count - 1) + delta + count) % count
+ }
+
+ private func closeFind() {
+ state.isCodeThreadFindPresented = false
+ isFindFieldFocused = false
+ composerFocused = true
+ }
+
+ /// The quiet plate behind a message the find bar matched; the current match also gets a hairline.
+ @ViewBuilder
+ private func findHighlight(isMatch: Bool, isActive: Bool) -> some View {
+ if isMatch {
+ let shape = RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ shape
+ .fill(isActive ? AnymorphColor.bgSelected : AnymorphColor.bgSubtle)
+ .overlay(shape.strokeBorder(isActive ? AnymorphColor.strokeStrong : Color.clear, lineWidth: 1))
+ .padding(-8)
+ }
+ }
+
+ // MARK: - Conversation (Document Flow)
+
+ private var conversation: some View {
+ let findMatches = Set(findMatchIds)
+ let activeFindMatch = activeFindMatchId
+ let shown = shownMessages
+ // Codex keeps the actions under the latest answer in view while no turn runs.
+ let latestReplyId = activeRun == nil ? shown.last(where: { $0.role == "assistant" })?.id : nil
+ let threadId = activeThread?.id
+ let hasMore = threadId.map { state.codeThreadHasMoreByThread[$0] == true } ?? false
+ let approvalStates = threadId.map { tid in
+ (state.codeApprovalsByThread[tid] ?? []).map { "\($0.id):\($0.status)" }
+ } ?? []
+ let canEdit = activeRun == nil
+ let isPlanMode = activeThread?.accessMode == .plan
+ let hasPendingPlan = threadId.map { hasPendingPlanApproval(threadId: $0) } ?? false
+ let revertTargets = shown.compactMap(\.revertOf)
+ let modelSwitches = CodeModelSwitch.switches(in: shown, options: state.availableCodeModels)
+ let presentation = syncPresentation
+ let hasLiveTail = activeRun != nil
+ || (activeThread != nil && !(state.pendingCodeQuestionsByThread[activeThread!.id] ?? []).isEmpty)
+ let hasTopBanner = activeThread.map { $0.isEffectivelyArchived || $0.isSnoozed } ?? false
+ return MorphCodeThreadScrollView(
+ threadId: threadId ?? "",
+ submitScrollTrigger: submitScrollTrigger,
+ activeFindMatch: activeFindMatch,
+ olderAnchorRequest: olderAnchorRequest
+ ) {
+ // Use an eager `VStack` rather than `LazyVStack` for the paginated conversation page (<= 80 messages
+ // per fetch). Bottom-anchored `ScrollView` + `LazyVStack` with variable-height Markdown/table replies
+ // and a growing live-turn sibling repeatedly leaves upper rows unmaterialized, clipped, or jumping
+ // when `position.scrollTo(edge: .bottom)` runs on macOS and iOS. Per-row `.equatable()` keeps
+ // unchanged historical rows from re-evaluating while live turns stream.
+ VStack(alignment: .leading, spacing: 0) {
+ if let thread = activeThread, hasMore {
+ olderMessagesButton(threadId: thread.id, firstMessageId: shown.first?.id)
+ .padding(.bottom, shown.isEmpty && !hasLiveTail ? 0 : 22)
+ }
+ ForEach(Array(shown.enumerated()), id: \.element.id) { index, msg in
+ let previous = index > 0 ? shown[index - 1] : nil
+ let isEditing = editingMessageId == msg.id
+ let isMatch = findMatches.contains(msg.id)
+ let isActiveMatch = msg.id == activeFindMatch
+ let scheduleTitle = msg.scheduleId.map { id in
+ state.codeSchedules.first { $0.id == id }?.title ?? "예약 작업"
+ }
+ let rowKey = MorphCodeMessageRowKey(
+ message: msg,
+ previousCreatedAt: previous?.createdAt,
+ isLatestReply: msg.id == latestReplyId,
+ isEditing: isEditing,
+ editingText: isEditing ? editingText : "",
+ editRestoresFiles: isEditing ? editRestoresFiles : false,
+ isCopied: copiedMessageId == msg.id,
+ isFindMatch: isMatch,
+ isActiveFindMatch: isActiveMatch,
+ canEdit: canEdit,
+ isPlanMode: isPlanMode,
+ hasPendingPlanApproval: hasPendingPlan,
+ isCompactWidth: isCompactWidth,
+ expandedApprovalDetailIds: expandedApprovalDetailIds,
+ feedbackApprovalId: feedbackApprovalId,
+ approvalFeedback: feedbackApprovalId == nil ? "" : approvalFeedback,
+ approvalStates: approvalStates,
+ revertTargets: revertTargets,
+ scheduleTitle: scheduleTitle
+ )
+ VStack(alignment: .leading, spacing: 22) {
+ if let change = modelSwitches[msg.id] {
+ CodeModelSwitchDividerView(change: change)
+ }
+ MorphCodeMessageRowView(key: rowKey) {
+ messageRow(msg, previous: previous, isLatestReply: msg.id == latestReplyId)
+ .background(findHighlight(isMatch: isMatch, isActive: isActiveMatch))
+ }
+ .equatable()
+ }
+ .padding(.top, index == 0 ? 0 : 22)
+ .id(msg.id)
+ }
+
+ // Keep the live-turn container mounted (with zero spacing when idle) so
+ // `.transition(.morphSubmitRise)` animates cleanly when `activeRun?.launchId` appears.
+ VStack(alignment: .leading, spacing: 22) {
+ if let run = activeRun {
+ if let prompt = run.pendingPrompt {
+ if let model = run.pendingModel, let effort = run.pendingEffort,
+ let change = CodeModelSwitch.pending(after: shown, model: model, effort: effort, options: state.availableCodeModels) {
+ CodeModelSwitchDividerView(change: change)
+ .transition(.opacity)
+ }
+ CodeHoverActions {
+ userPromptCard(prompt, attachedImages: run.pendingImages)
+ } actions: { _ in
+ lucideActionButton(.copy, label: "복사") {
+ copyText(prompt)
+ }
+ }
+ .transition(.morphSubmitRise(distance: reduceMotion ? 0 : 16))
+ .id("pending-\(run.launchId)")
+ }
+ CodeLiveTurnView(
+ run: run
+ ) {
+ Task { await state.cancelCodeTurn(threadId: run.threadId) }
+ } onSubmitSecret: { block, value in
+ await submitSecretRequest(block: block, value: value, threadId: run.threadId)
+ } onDeclineSecret: { block in
+ await declineSecretRequest(block: block, threadId: run.threadId)
+ } macSyncLabelForSecret: { block in
+ macSyncLabel(for: block, threadId: run.threadId)
+ } onSyncSecretFromMac: { block in
+ await syncSecretRequestFromMac(block: block, threadId: run.threadId)
+ } userInput: { block in
+ userPromptCard(block.content ?? "", imageBlocks: block.images ?? [])
+ } approvalCard: { approval in
+ liveApprovalCard(approval)
+ } questionCard: { question in
+ CodeQuestionCard(question: question) { action, answers in
+ await state.answerCodeQuestion(
+ id: question.id,
+ action: action,
+ answers: answers,
+ threadId: run.threadId
+ )
+ }
+ }
+ .transition(.morphSubmitRise(distance: reduceMotion ? 0 : 12))
+ .id("live-\(run.launchId)")
+ } else if let thread = activeThread {
+ if let question = state.pendingCodeQuestionsByThread[thread.id]?.first {
+ CodeQuestionCard(question: question) { action, answers in
+ await state.answerCodeQuestion(
+ id: question.id,
+ action: action,
+ answers: answers,
+ threadId: thread.id
+ )
+ }
+ }
+ }
+ }
+ .padding(.top, shown.isEmpty || !hasLiveTail ? 0 : 22)
+ .animation(reduceMotion ? AnymorphMotion.fast : AnymorphMotion.submit, value: activeRun?.launchId)
+ }
+ .frame(maxWidth: Self.columnWidth, alignment: .leading)
+ .padding(.horizontal, Self.horizontalPadding)
+ .padding(.top, (hasTopBanner ? 60 : 18) + topInset)
+ .padding(.bottom, 22)
+ .frame(maxWidth: .infinity)
+ }
+ .id(threadId ?? "")
+ .withoutAnimationOnThreadSwitch(threadId)
+ .morphDialog(item: $revertCandidate) { reply in
+ MorphDialogContent(
+ title: "이 작업의 파일 변경을 되돌릴까요?",
+ message: "이 작업이 바꾼 파일을 작업 전으로 돌립니다. 그 뒤에 다시 바뀐 파일은 그대로 둡니다.",
+ confirmTitle: "파일 \(reply.fileChanges?.count ?? 0)개 되돌리기",
+ isDestructive: true
+ ) { _ in
+ await state.revertCodeTurn(threadId: reply.threadId, messageId: reply.id)
+ }
+ }
+ .overlay {
+ Group {
+ switch presentation {
+ case .emptySyncing(let source):
+ threadEmptySyncState(source)
+ .transition(.opacity)
+ case .emptyError(let source, let message):
+ if let thread = activeThread {
+ threadEmptyErrorState(source: source, message: message, thread: thread)
+ .transition(.opacity)
+ }
+ case .none, .inlineSyncing:
+ EmptyView()
+ }
+ }
+ .animation(AnymorphMotion.fast, value: presentation)
+ .withoutAnimationOnThreadSwitch(threadId)
+ }
+ }
+
+ /// Centered sync state shown in an empty thread canvas so opening an uncached remote thread never shows a blank screen.
+ private func threadEmptySyncState(_ source: CodeThreadSyncSource) -> some View {
+ VStack(spacing: 8) {
+ HStack(spacing: 8) {
+ MorphSyncIcon(size: 13, color: AnymorphColor.fgSecondary)
+ MorphShimmerText(source.emptySyncTitle, scale: .callout, weight: .emphasis)
+ }
+ Text(source.emptySyncSubtitle)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ }
+ .padding(.horizontal, 24)
+ .padding(.top, topInset)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .allowsHitTesting(false)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel("\(source.emptySyncTitle) \(source.emptySyncSubtitle)")
+ }
+
+ /// Centered retry state shown when an uncached thread fails to sync.
+ private func threadEmptyErrorState(source: CodeThreadSyncSource, message: String, thread: CodeThread) -> some View {
+ VStack(spacing: 10) {
+ Image(systemName: source == .cloud ? "icloud.slash" : "exclamationmark.triangle")
+ .font(.system(size: 18, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(source.emptyErrorTitle)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Text(message)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ .lineLimit(3)
+ .frame(maxWidth: 360)
+ Button("다시 시도") {
+ Task { await state.hydrateAndLoadCodeMessages(threadId: thread.id) }
+ }
+ .morphPill(.secondary)
+ .padding(.top, 2)
+ }
+ .padding(.horizontal, 24)
+ .padding(.top, topInset)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ /// Loads the page of messages before the oldest one shown, anchoring the scroll position to the prior top row.
+ private func olderMessagesButton(threadId: String, firstMessageId: String?) -> some View {
+ HStack {
+ Spacer()
+ if state.isLoadingOlderCodeMessages {
+ ProgressView().controlSize(.small)
+ } else {
+ Button("이전 메시지 더 보기") {
+ Task {
+ await state.loadOlderCodeMessages(threadId: threadId)
+ if let firstMessageId {
+ olderAnchorRequest = MorphCodeOlderAnchorRequest(
+ threadId: threadId,
+ messageId: firstMessageId,
+ seq: (olderAnchorRequest?.seq ?? 0) + 1
+ )
+ }
+ }
+ }
+ .morphPill(.secondary)
+ }
+ Spacer()
+ }
+ .frame(height: 30)
+ }
+
+ @ViewBuilder
+ private func liveApprovalCard(_ apr: CodeApproval) -> some View {
+ if apr.actionKind == "plan_approval" {
+ planApprovalCard(apr)
+ } else {
+ let block = CodeTurnBlock(
+ id: "live-apr-\(apr.id)",
+ kind: "local_approval",
+ title: apr.title,
+ content: apr.summary.isEmpty ? apr.payload : apr.summary,
+ status: apr.status,
+ approvalId: apr.id,
+ actionKind: apr.actionKind,
+ allowThreadAllowed: apr.allowThreadAllowed
+ )
+ toolApprovalCard(block, approval: apr)
+ }
+ }
+
+ /// Whether the thread has a plan from Plan mode waiting for approval, which then owns the plan's actions.
+ private func hasPendingPlanApproval(threadId: String) -> Bool {
+ if state.codeLiveRuns[threadId]?.approval?.actionKind == "plan_approval" {
+ return true
+ }
+ return state.codeApprovals.contains {
+ $0.threadId == threadId && $0.actionKind == "plan_approval" && $0.status == "pending"
+ }
+ }
+
+ /// A plan waiting for approval: its Markdown, then implementing it in the chosen way or asking for changes.
+ private func planApprovalCard(_ apr: CodeApproval) -> some View {
+ CodePlanApprovalCard(approval: apr, imageLoader: activeFileLoader) { decision in
+ Task {
+ switch decision {
+ case .implement(let accessMode, let clearContext):
+ submitScrollTrigger += 1
+ boundAccessMode = accessMode
+ await state.decideCodePlanApproval(
+ id: apr.id,
+ threadId: apr.threadId,
+ approve: true,
+ targetAccessMode: accessMode,
+ clearContext: clearContext
+ )
+ case .revise(let reason):
+ await state.decideCodePlanApproval(
+ id: apr.id,
+ threadId: apr.threadId,
+ approve: false,
+ revisionReason: reason
+ )
+ }
+ }
+ }
+ .id("plan-apr-\(apr.id)-\(apr.status)")
+ }
+
+ /// Active pending tool approval for keyboard Y/N approval shortcuts on macOS.
+ private func activePendingApproval(for threadId: String) -> CodeApproval? {
+ if let liveApr = activeRun?.approval, liveApr.status == "pending", liveApr.actionKind != "plan_approval" {
+ return liveApr
+ }
+ return state.codeApprovalsByThread[threadId]?.first(where: { $0.status == "pending" && $0.actionKind != "plan_approval" })
+ }
+
+ /// Codex-style empty state hero; shares the persistent composer dock on the outer container so
+ /// submitting the first prompt never remounts or flashes the composer.
+ private var emptyState: some View {
+ #if os(iOS)
+ GeometryReader { proxy in
+ ScrollView {
+ emptyStateContent
+ .frame(maxWidth: .infinity, minHeight: proxy.size.height)
+ .contentShape(Rectangle())
+ .onTapGesture {
+ dismissComposerKeyboard()
+ }
+ }
+ .scrollIndicators(.hidden)
+ .scrollDismissesKeyboard(.immediately)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ #else
+ emptyStateContent
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ #endif
+ }
+
+ private var emptyStateContent: some View {
+ VStack(spacing: 0) {
+ Spacer(minLength: 24)
+ VStack(spacing: 18) {
+ MorphAssistantMark(width: 52)
+ Text("What shall we build?")
+ .anymorphText(.title, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .multilineTextAlignment(.center)
+ if boundThreadId == nil,
+ state.codeNewThread == nil,
+ state.codeThreads.isEmpty,
+ state.isSyncingRemoteCodeWorkspace {
+ HStack(spacing: 6) {
+ MorphSyncIcon(size: 11.5, color: AnymorphColor.fgSecondary)
+ MorphShimmerText("원격 스레드 동기화 중…", scale: .footnote, weight: .emphasis)
+ }
+ .transition(.opacity)
+ }
+ }
+ .animation(AnymorphMotion.fast, value: state.isSyncingRemoteCodeWorkspace)
+ .padding(.top, topInset)
+ .padding(.horizontal, 24)
+ Spacer(minLength: 24)
+ }
+ }
+
+ #if os(iOS)
+ private func dismissComposerKeyboard() {
+ composerFocused = false
+ UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
+ }
+ #endif
+
+ // MARK: - Turn Rows
+
+ @ViewBuilder
+ private func messageRow(_ msg: CodeMessage, previous: CodeMessage?, isLatestReply: Bool) -> some View {
+ switch msg.role {
+ case "user":
+ if editingMessageId == msg.id {
+ promptEditor(msg)
+ } else {
+ userMessageRow(msg)
+ }
+ case "system":
+ if msg.isCompactionMarker {
+ CodeCompactionDividerView(meta: msg.compaction)
+ } else {
+ systemNoteRow(msg)
+ }
+ default:
+ assistantTurn(msg, previous: previous, isLatest: isLatestReply)
+ }
+ }
+
+ /// A stored request with Codex's quiet icons under it: copy, and edit while no turn runs. A phone reaches
+ /// them by holding the request.
+ private func userMessageRow(_ msg: CodeMessage) -> some View {
+ let userImages = (msg.blocks ?? []).filter { $0.kind == "image" || $0.artifactKind == "image" }
+ // A scheduled task posts its prompt as the member would; the line above it names the task.
+ let scheduledBy = msg.scheduleId.map { id in state.codeSchedules.first { $0.id == id }?.title ?? "예약 작업" }
+ let canEdit = activeRun == nil
+ return CodeHoverActions {
+ userPromptCard(msg.content, imageBlocks: userImages, scheduledBy: scheduledBy)
+ } actions: { _ in
+ copyButton(msg)
+ if canEdit {
+ lucideActionButton(.pencil, label: "수정") {
+ startEditing(msg)
+ }
+ }
+ }
+ .contextMenu {
+ Button("복사") { copyText(msg.content) }
+ if canEdit {
+ Button("수정") { startEditing(msg) }
+ }
+ }
+ }
+
+ private func startEditing(_ msg: CodeMessage) {
+ editingText = msg.content
+ editRestoresFiles = false
+ editingMessageId = msg.id
+ }
+
+ /// A request opened for editing in place. Sending it again drops the conversation from here on and runs the
+ /// edited request, after putting the files back when asked.
+ private func promptEditor(_ msg: CodeMessage) -> some View {
+ let changedFiles = filesChanged(from: msg)
+ let edited = editingText.trimmingCharacters(in: .whitespacesAndNewlines)
+ return VStack(alignment: .trailing, spacing: 10) {
+ TextField("요청", text: $editingText, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.reading, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .lineLimit(1...12)
+ .padding(.horizontal, 15)
+ .padding(.vertical, 10)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeStrongHairline, lineWidth: 1)
+ )
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 8) {
+ if changedFiles > 0 {
+ Toggle("파일도 되돌리기", isOn: $editRestoresFiles)
+ .toggleStyle(AnymorphSwitchStyle())
+ Text("파일 \(changedFiles)개도 이 요청 전으로 되돌리기")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Button("취소") { editingMessageId = nil }
+ .anymorphButton(size: .md, appearance: .ghost)
+ Button("다시 보내기") {
+ let restore = editRestoresFiles && changedFiles > 0
+ editingMessageId = nil
+ Task { await state.editCodeMessage(threadId: msg.threadId, messageId: msg.id, prompt: edited, restoreFiles: restore) }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(edited.isEmpty || activeRun != nil)
+ }
+ VStack(alignment: .trailing, spacing: 8) {
+ if changedFiles > 0 {
+ HStack(spacing: 8) {
+ Toggle("파일도 되돌리기", isOn: $editRestoresFiles)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ Text("파일 \(changedFiles)개도 이 요청 전으로 되돌리기")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ Spacer(minLength: 0)
+ }
+ }
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("취소") { editingMessageId = nil }
+ .anymorphButton(size: .md, appearance: .ghost)
+ Button("다시 보내기") {
+ let restore = editRestoresFiles && changedFiles > 0
+ editingMessageId = nil
+ Task { await state.editCodeMessage(threadId: msg.threadId, messageId: msg.id, prompt: edited, restoreFiles: restore) }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(edited.isEmpty || activeRun != nil)
+ }
+ }
+ }
+ Text("이 요청 뒤의 대화는 지우고 고친 요청부터 다시 실행합니다.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .frame(maxWidth: 660, alignment: .trailing)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, isCompactWidth ? 16 : 60)
+ }
+
+ /// How many files the turns after a request changed, which editing it can put back.
+ private func filesChanged(from request: CodeMessage) -> Int {
+ guard let start = messages.firstIndex(where: { $0.id == request.id }) else { return 0 }
+ let paths = messages[start...].filter { $0.role == "assistant" }.flatMap { $0.fileChanges ?? [] }.map(\.path)
+ return Set(paths).count
+ }
+
+ /// A revert's note: a quiet line in the conversation, with the way back while the revert stands.
+ private func systemNoteRow(_ note: CodeMessage) -> some View {
+ HStack(spacing: 8) {
+ MorphLucideIcon(.undo, size: 12.5)
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(note.content)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ if activeRun == nil, revertStands(note) {
+ Button {
+ Task { await state.revertCodeTurn(threadId: note.threadId, messageId: note.id) }
+ } label: {
+ HStack(spacing: 4) {
+ MorphLucideIcon(.redo, size: 11.5)
+ Text("다시 적용")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary)
+ }
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+ Spacer(minLength: 0)
+ }
+ }
+
+ /// Whether a note records a revert that still stands: it put back a reply's files and was not undone since.
+ private func revertStands(_ note: CodeMessage) -> Bool {
+ guard note.checkpointId != nil, let target = note.revertOf,
+ messages.first(where: { $0.id == target })?.role != "system" else { return false }
+ return !messages.contains { $0.revertOf == note.id }
+ }
+
+ /// Whether a reply's file changes are in place: no revert of them stands.
+ private func changesInPlace(_ reply: CodeMessage) -> Bool {
+ !messages.contains { $0.revertOf == reply.id && revertStands($0) }
+ }
+
+ /// The member's prompt: a subtle rounded surface on the right, as in Codex. A scheduled run's prompt carries its
+ /// task's name above it.
+ private func userPromptCard(
+ _ text: String,
+ attachedImages: [CodeImageAttachment] = [],
+ imageBlocks: [CodeTurnBlock] = [],
+ scheduledBy: String? = nil
+ ) -> some View {
+ VStack(alignment: .trailing, spacing: 8) {
+ if let scheduledBy {
+ HStack(spacing: 5) {
+ Image(systemName: "clock")
+ .font(.system(size: 10, weight: .regular))
+ Text("예약 실행 · \(scheduledBy)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ if !attachedImages.isEmpty {
+ MorphFlowLayout(spacing: 8, lineSpacing: 8, alignment: .trailing) {
+ ForEach(attachedImages) { img in
+ if let b64 = img.dataBase64, let data = Data(base64Encoded: b64) {
+ MorphInlineImageView(
+ source: img.name,
+ alt: "",
+ maxHeight: 140,
+ maxWidth: 200,
+ preloadedData: data,
+ onTap: { title, d in lightboxImage = MorphLightboxImageItem(title: title, data: d) }
+ )
+ }
+ }
+ }
+ } else if !imageBlocks.isEmpty {
+ MorphFlowLayout(spacing: 8, lineSpacing: 8, alignment: .trailing) {
+ ForEach(imageBlocks) { blk in
+ if let src = blk.imageUrl ?? blk.filePath {
+ MorphInlineImageView(
+ source: src,
+ alt: "",
+ maxHeight: 140,
+ maxWidth: 200,
+ loader: activeFileLoader,
+ onTap: { title, d in lightboxImage = MorphLightboxImageItem(title: title, data: d) }
+ )
+ }
+ }
+ }
+ }
+ // A picture sent on its own has no words to put in a bubble.
+ if !text.isEmpty {
+ CodeRequestBubble(text: text)
+ }
+ }
+ .frame(maxWidth: 660, alignment: .trailing)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ .padding(.leading, 60)
+ }
+
+ /// A finished turn in Codex's order: the messages the member sent while it ran, the folded work log, the
+ /// Markdown answer with its inline images, cards for images, documents, browser live views and approvals
+ /// still waiting, then Codex's quiet row of actions, in view under the latest answer and under the others while
+ /// the pointer is over them.
+ private func assistantTurn(_ msg: CodeMessage, previous: CodeMessage?, isLatest: Bool) -> some View {
+ let blocks = msg.blocks ?? []
+ // Messages sent into the turn stay in the conversation, so folding the work log never hides them.
+ let sentWhileRunning = blocks.filter { block in
+ block.kind == "user_input" && block.isUserInputShown
+ }
+ let compactions = blocks.filter { block in
+ block.kind == "compaction" && !block.isRunning
+ }
+ let workItems = CodeTurnSummary.workItems(blocks.filter { $0.kind != "user_input" && $0.kind != "compaction" }, answer: msg.content)
+ let cardBlocks = blocks.filter { blk in
+ if blk.kind == "local_approval" {
+ // Decided approvals are part of the work log.
+ return blk.status == "pending"
+ }
+ guard blk.kind == "artifact"
+ || blk.kind == "image"
+ || blk.kind == "browser_live_view"
+ || blk.kind == "html_preview"
+ || blk.kind == "secret_request" else {
+ return false
+ }
+ // Avoid rendering the same workspace image twice if Markdown already embeds it via .
+ let isImage = blk.kind == "image"
+ || blk.artifactKind == "image"
+ || (blk.mimeType?.lowercased().hasPrefix("image/") ?? false)
+ if isImage, let path = blk.filePath, !path.isEmpty {
+ let base = URL(fileURLWithPath: path).lastPathComponent
+ if msg.content.contains("](\(path)") || msg.content.contains("](\(base)") || msg.content.contains("(\(path))") || msg.content.contains("(\(base))") {
+ return false
+ }
+ }
+ return true
+ }
+
+ let turn = VStack(alignment: .leading, spacing: 12) {
+ ForEach(sentWhileRunning) { block in
+ userPromptCard(block.content ?? "", imageBlocks: block.images ?? [])
+ }
+
+ ForEach(compactions) { block in
+ CodeCompactionDividerView(meta: block.compaction)
+ }
+
+ let elapsedSeconds = turnSeconds(msg, previous: previous)
+ let isStoppedOrFailed = msg.content == "작업을 중지했습니다." || msg.content.hasPrefix("작업이 실패했습니다.")
+ let hasActionWork = workItems.contains {
+ if case .thinking = $0 { return false }
+ return true
+ }
+ let showsWorkedRow = hasActionWork || (!isStoppedOrFailed && (elapsedSeconds ?? 0) > 0)
+ let hasAnswerText = !msg.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ if showsWorkedRow {
+ CodeWorkedRow(seconds: elapsedSeconds, items: workItems)
+ if hasAnswerText {
+ Rectangle()
+ .fill(AnymorphColor.strokeLight)
+ .frame(height: 1)
+ }
+ }
+
+ if hasAnswerText {
+ answerText(msg.content)
+ }
+
+ if isLatest,
+ activeRun == nil,
+ let thread = activeThread,
+ thread.accessMode == .plan || msg.accessMode == .plan,
+ !msg.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ msg.content != "작업을 중지했습니다.",
+ !msg.content.hasPrefix("작업이 실패했습니다."),
+ !hasPendingPlanApproval(threadId: thread.id) {
+ planReviewBar(msg, thread: thread)
+ }
+
+ if !cardBlocks.isEmpty {
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(cardBlocks) { block in
+ switch block.kind {
+ case "artifact", "image":
+ artifactRow(block)
+ case "browser_live_view":
+ browserLiveViewCard(block)
+ case "local_approval":
+ localApprovalCard(block)
+ case "html_preview":
+ CodeHTMLPreviewBlockView(block: block)
+ case "secret_request":
+ CodeSecretRequestCard(
+ block: block,
+ macSyncLabel: macSyncLabel(for: block, threadId: msg.threadId),
+ onSyncFromMac: {
+ await syncSecretRequestFromMac(block: block, threadId: msg.threadId)
+ },
+ onSubmit: { value in
+ await submitSecretRequest(block: block, value: value, threadId: msg.threadId)
+ },
+ onDecline: {
+ await declineSecretRequest(block: block, threadId: msg.threadId)
+ }
+ )
+ default:
+ EmptyView()
+ }
+ }
+ }
+ .padding(.top, 2)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ return CodeHoverActions(alignment: .leading, alwaysVisible: isLatest, showsOnTouch: true) {
+ turn
+ } actions: { hovered in
+ turnActions(msg, hovered: hovered)
+ }
+ }
+
+ private func submitSecretRequest(block: CodeTurnBlock, value: String, threadId: String) async -> Bool {
+ let requestId = block.questionId ?? block.id
+ let fieldKey = block.questions?.first?.id ?? "value"
+ return await state.answerCodeQuestion(
+ id: requestId,
+ action: "accept",
+ answers: [fieldKey: [value]],
+ threadId: threadId
+ )
+ }
+
+ private func declineSecretRequest(block: CodeTurnBlock, threadId: String) async {
+ let requestId = block.questionId ?? block.id
+ _ = await state.answerCodeQuestion(
+ id: requestId,
+ action: "decline",
+ answers: [:],
+ threadId: threadId
+ )
+ }
+
+ private func macSyncLabel(for block: CodeTurnBlock, threadId: String) -> String? {
+ #if os(macOS)
+ guard !state.isLocalCodeThread(threadId) else { return nil }
+ guard let item = block.questions?.first else { return nil }
+ if let preset = item.cliPreset?.trimmingCharacters(in: .whitespacesAndNewlines), !preset.isEmpty {
+ return "Mac \(preset) 인증 동기화"
+ }
+ if let key = item.envKey?.trimmingCharacters(in: .whitespacesAndNewlines), !key.isEmpty {
+ return "Mac에서 \(key) 가져오기"
+ }
+ return nil
+ #else
+ return nil
+ #endif
+ }
+
+ private func syncSecretRequestFromMac(block: CodeTurnBlock, threadId: String) async -> String? {
+ return nil
+ }
+
+ /// How long a turn ran: from the request to the stored reply.
+ private func turnSeconds(_ reply: CodeMessage, previous: CodeMessage?) -> Int? {
+ guard let previous, previous.role == "user",
+ let start = MorphPalette.parseDate(previous.createdAt),
+ let end = MorphPalette.parseDate(reply.createdAt) else { return nil }
+ return Int(end.timeIntervalSince(start))
+ }
+
+ private func answerText(_ markdown: String) -> some View {
+ MorphMarkdownText(
+ markdown,
+ scale: .reading,
+ preserveLineBreaks: false,
+ imageLoader: activeFileLoader,
+ onTapImage: { title, data in
+ lightboxImage = MorphLightboxImageItem(title: title, data: data)
+ }
+ )
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ @ViewBuilder
+ private func artifactRow(_ block: CodeTurnBlock) -> some View {
+ let isImage = block.kind == "image"
+ || block.artifactKind == "image"
+ || (block.mimeType?.lowercased().hasPrefix("image/") ?? false)
+ let imageSource = block.imageUrl
+ ?? block.artifactId.map { "/v1/code/artifacts/\($0)/content" }
+ ?? block.filePath
+
+ if isImage, let src = imageSource, !src.isEmpty {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ Image(systemName: "photo")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(block.title ?? block.filePath ?? "생성된 이미지")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer()
+ if showsImagePath, let path = block.filePath {
+ Text(path)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ }
+ }
+ MorphInlineImageView(
+ source: src,
+ alt: "",
+ maxHeight: 380,
+ loader: activeFileLoader,
+ onTap: { title, data in
+ lightboxImage = MorphLightboxImageItem(title: block.title ?? title, data: data)
+ }
+ )
+ }
+ .padding(12)
+ .background(flatCardChrome)
+ } else {
+ Button {
+ let localURL: URL? = block.filePath.flatMap { path in
+ guard let pid = activeProject?.id else { return nil }
+ return state.resolveLocalCodeFileURL(
+ source: path,
+ projectId: pid,
+ threadId: activeThread?.id,
+ isLocal: state.isLocalCodeProject(pid)
+ )
+ }
+ openedFile = MorphFileItem(
+ id: block.id,
+ name: block.title ?? block.filePath.map { ($0 as NSString).lastPathComponent } ?? "문서",
+ path: block.filePath,
+ mimeType: block.mimeType,
+ text: block.content,
+ source: block.artifactId.map { "/v1/code/artifacts/\($0)/content" } ?? block.filePath,
+ localURL: localURL
+ )
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: isImage ? "photo" : "doc.text")
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 26, height: 26)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(block.title ?? "문서 산출물")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(block.filePath ?? block.mimeType ?? "미리보기 열기")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ }
+ Spacer()
+ Text("미리보기")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .padding(.horizontal, 9)
+ .padding(.vertical, 4)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(AnymorphColor.bgGrouped))
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 9)
+ .background(flatCardChrome)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+ }
+
+ private func browserLiveViewCard(_ block: CodeTurnBlock) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 10) {
+ MorphServiceIcon("safari")
+ VStack(alignment: .leading, spacing: 1) {
+ Text(block.title ?? "Browser Session")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ if let profile = block.browserProfile {
+ Text("Profile \(profile)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ }
+ }
+ Spacer()
+ if let fallbackURL = block.liveViewUrl.flatMap(URL.init(string:)) {
+ Button("Open Live View") {
+ openURL(fallbackURL)
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ }
+ }
+ if let desc = block.content, !desc.isEmpty {
+ Text(desc)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ }
+ }
+ .padding(12)
+ .background(flatCardChrome)
+ }
+
+ /// An approval stored on a reply: a plan from Plan mode gets the plan card, anything else the tool card.
+ @ViewBuilder
+ private func localApprovalCard(_ block: CodeTurnBlock, approval: CodeApproval? = nil) -> some View {
+ let apr = approval ?? block.approvalId.flatMap { id in state.codeApprovals.first { $0.id == id } }
+ if (apr?.actionKind ?? block.actionKind) == "plan_approval", let plan = apr ?? planApproval(from: block) {
+ planApprovalCard(plan)
+ } else {
+ toolApprovalCard(block, approval: apr)
+ }
+ }
+
+ /// A plan approval rebuilt from its block when the approval list has not loaded it yet.
+ private func planApproval(from block: CodeTurnBlock) -> CodeApproval? {
+ guard let approvalId = block.approvalId else { return nil }
+ let thread = activeThread
+ return CodeApproval(
+ id: approvalId,
+ threadId: thread?.id ?? "",
+ projectId: thread?.projectId ?? "",
+ memberId: thread?.memberId ?? "",
+ target: thread?.executionTarget ?? .local,
+ actionKind: "plan_approval",
+ title: block.title ?? "구현 계획",
+ summary: block.content ?? "",
+ payload: block.content ?? "",
+ allowThreadAllowed: false,
+ status: block.status ?? "pending",
+ createdAt: ""
+ )
+ }
+
+ /// Natural-language intent-first approval card: leads with plain-language intent + affected target summary,
+ /// placing raw command/diff preview inside a collapsible "세부 내용 보기" disclosure. 거절 swaps the buttons
+ /// for a field where the member may say why.
+ private func toolApprovalCard(_ block: CodeTurnBlock, approval: CodeApproval? = nil) -> some View {
+ let apr = approval ?? block.approvalId.flatMap { id in state.codeApprovals.first { $0.id == id } }
+ let status = apr?.status ?? block.status ?? "pending"
+ let isPending = status == "pending"
+ let allowThread = apr?.allowThreadAllowed ?? block.allowThreadAllowed ?? false
+ let prefix = apr?.commandPrefix?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let allowsPrefix = allowThread && apr?.allowPrefixAllowed == true && !prefix.isEmpty
+ let command = apr?.commandPreview?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let diff = apr?.diffPreview?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let summary = apr?.summary.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let fallback = summary.isEmpty ? (apr?.payload ?? block.content ?? "") : summary
+ let threadId = apr?.threadId ?? activeThread?.id
+ let cardKey = block.approvalId ?? block.id
+ let hasTechnicalDetails = !command.isEmpty || !diff.isEmpty
+ let detailsExpanded = expandedApprovalDetailIds.contains(cardKey)
+ let intentSummary: String = {
+ if !summary.isEmpty { return summary }
+ if !command.isEmpty {
+ let firstLine = command.split(separator: "\n", maxSplits: 1).first.map(String.init) ?? command
+ return "터미널 명령을 실행합니다: \(firstLine.prefix(80))"
+ }
+ if !diff.isEmpty {
+ return "워크스페이스 파일 변경을 적용합니다."
+ }
+ return fallback
+ }()
+
+ return VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 8) {
+ // The approval's own kind first, so a block saved without one still shows the service's logo.
+ CodeApprovalIcon(
+ actionKind: apr?.actionKind ?? block.actionKind,
+ size: 13,
+ weight: .semibold,
+ color: AnymorphColor.fgPrimary
+ )
+ Text(block.title ?? "실행 승인 요청")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ Spacer()
+ #if os(macOS)
+ if isPending {
+ Text("Y 허용 · N 거절")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, monospaced: true)
+ }
+ #endif
+ // The buttons show that the card waits, so the badge only names the decision.
+ if !isPending {
+ AnymorphBadge(CodeApprovalStatus.label(status))
+ }
+ }
+
+ if !intentSummary.isEmpty {
+ Text(intentSummary)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ }
+
+ if hasTechnicalDetails {
+ Button {
+ withAnimation(AnymorphMotion.base) {
+ if detailsExpanded {
+ expandedApprovalDetailIds.remove(cardKey)
+ } else {
+ expandedApprovalDetailIds.insert(cardKey)
+ }
+ }
+ } label: {
+ HStack(spacing: 6) {
+ Text("세부 내용 보기")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ CodeDisclosureChevron(expanded: detailsExpanded)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+
+ if detailsExpanded {
+ VStack(alignment: .leading, spacing: 8) {
+ if !command.isEmpty {
+ approvalPreview(command, language: "shell", maxHeight: 160)
+ }
+ if !diff.isEmpty {
+ approvalPreview(diff, language: "diff", maxHeight: 260)
+ }
+ }
+ }
+ }
+
+ if isPending, let aprId = block.approvalId {
+ if feedbackApprovalId == aprId {
+ rejectionField(aprId: aprId, threadId: threadId)
+ .transition(.opacity)
+ } else {
+ // The buttons span the card, and wrap to a second line where they do not fit side by side.
+ MorphFlowLayout(fillsLines: true) {
+ approvalButtons(aprId: aprId, threadId: threadId, allowThread: allowThread, prefix: allowsPrefix ? prefix : nil)
+ }
+ .transition(.opacity)
+ }
+ }
+ }
+ .padding(12)
+ .background(flatCardChrome)
+ .animation(AnymorphMotion.fast, value: feedbackApprovalId)
+ }
+
+ @ViewBuilder
+ private func approvalButtons(aprId: String, threadId: String?, allowThread: Bool, prefix: String?) -> some View {
+ Button {
+ MorphHaptics.success()
+ Task { await state.decideCodeApproval(id: aprId, decision: "allow_once", threadId: threadId) }
+ } label: {
+ Text("한 번 허용")
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+
+ if allowThread {
+ Button {
+ MorphHaptics.success()
+ Task { await state.decideCodeApproval(id: aprId, decision: "allow_thread", threadId: threadId) }
+ } label: {
+ Text("이번 스레드 허용")
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+
+ if let prefix {
+ Button {
+ MorphHaptics.success()
+ Task {
+ await state.decideCodeApprovalWithFeedback(
+ id: aprId,
+ decision: "allow_prefix",
+ prefix: prefix,
+ scope: "project",
+ threadId: threadId
+ )
+ }
+ } label: {
+ // As wide as the prefix up to 220 points, then truncated in the middle.
+ Text("항상 허용: \(prefix)")
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .frame(maxWidth: 220)
+ .fixedSize(horizontal: true, vertical: false)
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .help("이 프로젝트에서 \(prefix)로 시작하는 명령은 묻지 않고 실행합니다")
+ }
+
+ Button {
+ approvalFeedback = ""
+ feedbackApprovalId = aprId
+ } label: {
+ Text("거절")
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+
+ /// The optional reason field that 거절 opens in place of the buttons, with 거절 and 취소 under it.
+ private func rejectionField(aprId: String, threadId: String?) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ TextField("거절 이유나 다른 방법 (선택)", text: $approvalFeedback, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .lineLimit(1...4)
+ .focused($isRejectionFieldFocused)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .onSubmit { sendRejection(aprId: aprId, threadId: threadId) }
+ .onAppear { isRejectionFieldFocused = true }
+ HStack(spacing: 8) {
+ Button {
+ sendRejection(aprId: aprId, threadId: threadId)
+ } label: {
+ Text("거절")
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ Button {
+ feedbackApprovalId = nil
+ approvalFeedback = ""
+ } label: {
+ Text("취소")
+ .frame(maxWidth: .infinity)
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+ }
+ }
+
+ /// Rejects with the reason in the field, or with none when the member left it empty.
+ private func sendRejection(aprId: String, threadId: String?) {
+ let reason = approvalFeedback.trimmingCharacters(in: .whitespacesAndNewlines)
+ MorphHaptics.light()
+ feedbackApprovalId = nil
+ approvalFeedback = ""
+ Task {
+ await state.decideCodeApprovalWithFeedback(id: aprId, decision: "denied", reason: reason, threadId: threadId)
+ }
+ }
+
+ /// A command or diff an approval would run or apply, with syntax colors and diff line tints.
+ private func approvalPreview(_ text: String, language: String, maxHeight: CGFloat) -> some View {
+ let lines = Array(MorphSyntaxHighlighter.tokenize(text, language: language).prefix(400))
+ let isDiff = language == "diff"
+ // A command wraps at the card's width so all of it shows, and a diff keeps its columns and scrolls sideways.
+ let axes: Axis.Set = isDiff ? [.vertical, .horizontal] : .vertical
+ return ScrollView(axes, showsIndicators: true) {
+ MorphCodeLines(lines: lines, showsLineNumbers: false, wraps: !isDiff, tintsDiffLines: isDiff)
+ .padding(.vertical, 8)
+ .textSelection(.enabled)
+ }
+ .frame(maxWidth: .infinity, maxHeight: maxHeight, alignment: .topLeading)
+ .fixedSize(horizontal: false, vertical: true)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+
+ /// Plan mode's answer, reviewed: one click implements it under default permissions, Full access or a fresh
+ /// context, as Claude Code offers after a plan. Request changes keeps Plan mode and returns to the composer.
+ private func planReviewBar(_ msg: CodeMessage, thread: CodeThread) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 8) {
+ CodeApprovalIcon(actionKind: "plan_approval", size: 13, weight: .semibold, color: AnymorphColor.fgPrimary)
+ Text("Review plan · Ready to implement")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ }
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 8) {
+ planImplementButtons(msg, thread: thread)
+ Spacer(minLength: 8)
+ planRevisionButton
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ planImplementButtons(msg, thread: thread)
+ planRevisionButton
+ }
+ }
+ }
+ .padding(12)
+ .background(flatCardChrome)
+ }
+
+ @ViewBuilder
+ private func planImplementButtons(_ msg: CodeMessage, thread: CodeThread) -> some View {
+ Button("Implement (Ask first)") {
+ implementPlan(msg, thread: thread, accessMode: .defaultPermissions, clearContext: false)
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .help("Implement with default permissions, asking before risky actions")
+ Button {
+ implementPlan(msg, thread: thread, accessMode: .fullAccess, clearContext: false)
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "bolt")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(AnymorphColor.accessFull)
+ Text("Full access")
+ }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .help("Implement with full workspace access without prompting")
+ Button("Fresh context") {
+ implementPlan(msg, thread: thread, accessMode: .defaultPermissions, clearContext: true)
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .help("Compact conversation and implement this plan in a fresh context")
+ }
+
+ private var planRevisionButton: some View {
+ Button("Request changes") {
+ accessModeBinding.wrappedValue = .plan
+ composerFocused = true
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ .help("Stay in Plan mode and focus the composer to request plan changes")
+ }
+
+ private func implementPlan(_ msg: CodeMessage, thread: CodeThread, accessMode: CodeAccessMode, clearContext: Bool) {
+ submitScrollTrigger += 1
+ boundAccessMode = accessMode
+ Task {
+ await state.startImplementingPlanMessage(
+ thread: thread,
+ planMarkdown: msg.content,
+ targetAccessMode: accessMode,
+ clearContext: clearContext
+ )
+ }
+ }
+
+ /// Unified action row under an answer: Lucide copy, fork, revert when files changed, and quiet timestamp.
+ @ViewBuilder
+ private func turnActions(_ msg: CodeMessage, hovered: Bool) -> some View {
+ if !msg.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ copyButton(msg)
+ }
+ if activeRun == nil {
+ lucideActionButton(.gitBranch, label: "여기서 대화 분기") {
+ Task { await state.forkCodeThread(threadId: msg.threadId, messageId: msg.id) }
+ }
+ }
+ if let changes = msg.fileChanges, !changes.isEmpty {
+ if msg.checkpointId != nil, activeRun == nil, changesInPlace(msg) {
+ lucideActionButton(.undo, label: "파일 되돌리기") {
+ revertCandidate = msg
+ }
+ }
+ Text(fileChangeSummary(changes))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ .lineLimit(1)
+ .padding(.horizontal, 4)
+ }
+ #if os(macOS)
+ Text(MorphPalette.timeLabel(msg.createdAt))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ .padding(.horizontal, 4)
+ #endif
+ }
+
+ /// Lucide copy icon, which turns into a check for a moment after copying.
+ private func copyButton(_ msg: CodeMessage) -> some View {
+ let copied = copiedMessageId == msg.id
+ return lucideActionButton(copied ? .check : .copy, label: copied ? "복사됨" : "복사") {
+ copyMessage(msg)
+ }
+ }
+
+ /// "파일 2개 변경 +12 −3", as Codex sums up a turn's edits.
+ private func fileChangeSummary(_ changes: [CodeGitFileChange]) -> String {
+ let added = changes.reduce(0) { $0 + $1.additions }
+ let removed = changes.reduce(0) { $0 + $1.deletions }
+ return "파일 \(changes.count)개 변경 +\(added) −\(removed)"
+ }
+
+ private func copyMessage(_ msg: CodeMessage) {
+ copyText(msg.content)
+ copiedMessageId = msg.id
+ Task {
+ try? await Task.sleep(for: .seconds(1.4))
+ if copiedMessageId == msg.id { copiedMessageId = nil }
+ }
+ }
+
+ private var flatCardChrome: some View {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ }
+
+ // MARK: - Codex Composer (context shelf + attachments + @mentions + card)
+
+ /// Submits the composer prompt and kicks off the Codex-style smooth upward scroll transition. A window bound to
+ /// one thread sends straight to it; the main window sends to the selection or the new-thread screen.
+ private func submitPrompt(mode: CodeFollowUpMode? = nil) {
+ MorphHaptics.light()
+ voiceDictator.stop()
+ promptHistoryIndex = nil
+ promptHistorySavedDraft = ""
+ if let loopCmd = CodeLoopCommand.parse(composerText) {
+ composerText = ""
+ Task {
+ await state.handleCodeLoopCommand(
+ loopCmd,
+ thread: activeThread,
+ project: activeProject,
+ model: modelBinding.wrappedValue,
+ effort: effortBinding.wrappedValue,
+ accessMode: accessModeBinding.wrappedValue
+ )
+ }
+ return
+ }
+ guard let boundThreadId else {
+ guard let submission = state.beginCodePromptSubmit(mode: mode) else { return }
+ submitScrollTrigger += 1
+ Task { await state.finishCodePromptSubmit(submission) }
+ return
+ }
+ let text = boundComposerText
+ let attachments = boundAttachments
+ guard boundProcessingImages == 0,
+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty else { return }
+ guard let submission = state.beginCodePromptForThread(
+ threadId: boundThreadId,
+ rawPrompt: text,
+ attachments: attachments,
+ model: boundModel,
+ effort: boundEffort,
+ accessMode: boundAccessMode,
+ followUpMode: mode
+ ) else { return }
+ submitScrollTrigger += 1
+ boundComposerText = ""
+ boundAttachments = []
+ Task {
+ let sent = await state.finishCodePromptForThread(submission)
+ // A request that did not go out comes back into an untouched composer.
+ if !sent, boundComposerText.isEmpty, boundAttachments.isEmpty {
+ boundComposerText = text
+ boundAttachments = attachments
+ }
+ }
+ }
+
+ // MARK: - Composer Text, Attachments & Bound-Window Drafts
+
+ /// The composer's text: the shared composer for the main window, the window's own for a bound one.
+ private var composerText: String {
+ get { boundThreadId == nil ? state.codeComposerText : boundComposerText }
+ nonmutating set {
+ if boundThreadId == nil {
+ state.codeComposerText = newValue
+ } else {
+ boundComposerText = newValue
+ }
+ }
+ }
+
+ private var composerTextBinding: Binding {
+ boundThreadId == nil ? $state.codeComposerText : $boundComposerText
+ }
+
+ private var composerAttachments: [CodeImageAttachment] {
+ boundThreadId == nil ? state.codeComposerAttachments : boundAttachments
+ }
+
+ private var composerProcessingImages: Int {
+ boundThreadId == nil ? state.codeComposerProcessingImages : boundProcessingImages
+ }
+
+ /// The model, effort and permission mode the composer sends with: the main window's, or a bound window's own.
+ private var modelBinding: Binding {
+ boundThreadId == nil ? $state.selectedCodeModel : $boundModel
+ }
+
+ private var effortBinding: Binding {
+ boundThreadId == nil ? $state.selectedCodeEffort : $boundEffort
+ }
+
+ private var accessModeBinding: Binding {
+ boundThreadId == nil ? $state.selectedCodeAccessMode : $boundAccessMode
+ }
+
+ /// Starts a bound window on its thread's model, effort and permission mode, or the composer's where the thread
+ /// has none.
+ private func loadBoundSettings() {
+ boundModel = activeThread?.model ?? state.selectedCodeModel
+ boundEffort = activeThread?.reasoningEffort ?? state.selectedCodeEffort
+ boundAccessMode = activeThread?.accessMode ?? state.selectedCodeAccessMode
+ }
+
+ private var boundDraftKey: String? {
+ boundThreadId.map { "thread:\($0)" }
+ }
+
+ /// Bumped when something outside this window, such as a preview snapshot, adds to the bound thread's draft.
+ private var boundDraftRevision: Int {
+ boundThreadId.flatMap { state.codeDraftRevisionByThread[$0] } ?? 0
+ }
+
+ /// Writes the bound window's composer into the thread's saved draft, so the main window finds it there.
+ private func persistBoundDraft() {
+ guard let key = boundDraftKey else { return }
+ let draft = CodeComposerDraft(text: boundComposerText, attachments: boundAttachments)
+ guard state.codeDraftsByKey[key] != (draft.isEmpty ? nil : draft) else { return }
+ if draft.isEmpty {
+ state.codeDraftsByKey.removeValue(forKey: key)
+ } else {
+ state.codeDraftsByKey[key] = draft
+ }
+ }
+
+ /// Reads the thread's saved draft into the bound window's composer.
+ private func loadBoundDraft() {
+ guard let key = boundDraftKey else { return }
+ let draft = state.codeDraftsByKey[key] ?? CodeComposerDraft()
+ if draft.text != boundComposerText {
+ boundComposerText = draft.text
+ }
+ if draft.attachments != boundAttachments {
+ boundAttachments = draft.attachments
+ }
+ }
+
+ private func attachImages(_ picked: [MorphPickedImage]) {
+ guard boundThreadId != nil else {
+ state.attachCodeImages(picked)
+ return
+ }
+ guard !picked.isEmpty else { return }
+ boundProcessingImages += picked.count
+ Task {
+ var unreadable: [String] = []
+ for item in picked {
+ let result = await Task.detached(priority: .userInitiated) { MorphAppState.readCodeImage(item) }.value
+ boundProcessingImages -= 1
+ switch result {
+ case .success(let attachment):
+ boundAttachments.append(attachment)
+ case .failure(let failure):
+ unreadable.append(failure.name)
+ }
+ }
+ if !unreadable.isEmpty {
+ let names = unreadable.map { "‘\($0)’" }.joined(separator: ", ")
+ state.showError("이미지를 첨부하지 못했습니다: \(names). PNG, JPEG, HEIC 같은 이미지 파일인지 확인해 주세요.")
+ }
+ }
+ }
+
+ private func attachFiles(_ urls: [URL]) {
+ guard boundThreadId != nil else {
+ state.attachCodeFiles(urls)
+ return
+ }
+ let images = urls.filter { CodeImagePasteDecision.isImageFile($0) }
+ let documents = urls.filter { !CodeImagePasteDecision.isImageFile($0) }
+ attachImages(images.map { .file($0) })
+ guard !documents.isEmpty else { return }
+ boundProcessingImages += documents.count
+ Task {
+ var failed: [String] = []
+ for url in documents {
+ let attachment = await Task.detached(priority: .userInitiated) { Self.readDocumentAttachment(url) }.value
+ boundProcessingImages -= 1
+ if let attachment {
+ boundAttachments.append(attachment)
+ } else {
+ failed.append(url.lastPathComponent)
+ }
+ }
+ if !failed.isEmpty {
+ let names = failed.map { "‘\($0)’" }.joined(separator: ", ")
+ state.showError("파일을 첨부하지 못했습니다: \(names) (15MB 이하 파일만 지원합니다).")
+ }
+ }
+ }
+
+ /// A document or code file as an attachment, up to 15 MB, as the shared composer reads one.
+ private nonisolated static func readDocumentAttachment(_ url: URL) -> CodeImageAttachment? {
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ guard let data = try? Data(contentsOf: url), !data.isEmpty, data.count <= 15 * 1024 * 1024 else { return nil }
+ let ext = url.pathExtension.lowercased()
+ let mime = UTType(filenameExtension: ext)?.preferredMIMEType
+ ?? (ext == "md" || ext == "markdown" ? "text/markdown" : "application/octet-stream")
+ return CodeImageAttachment(
+ id: UUID().uuidString,
+ path: url.path,
+ name: url.lastPathComponent,
+ mimeType: mime,
+ sizeBytes: Int64(data.count),
+ dataBase64: data.base64EncodedString()
+ )
+ }
+
+ private func removeAttachment(id: String) {
+ if boundThreadId == nil {
+ state.removeCodeAttachment(id: id)
+ } else {
+ boundAttachments.removeAll { $0.id == id }
+ }
+ }
+
+ // MARK: - Prompt History (↑ / ↓)
+
+ /// Steps through sent requests: -1 goes to an older one, +1 back toward the unsent draft. The field asks only
+ /// with the caret on its first line (↑) or last line (↓), and only while no popover takes the arrows.
+ private func navigatePromptHistory(_ delta: Int) -> Bool {
+ let history = state.codePromptHistory
+ if delta < 0 {
+ guard !history.isEmpty else { return false }
+ let next: Int
+ if let index = promptHistoryIndex {
+ next = index + 1
+ } else {
+ promptHistorySavedDraft = composerText
+ next = 0
+ }
+ // At the oldest request ↑ stays put rather than moving the caret.
+ guard next < history.count else { return promptHistoryIndex != nil }
+ applyHistoryText(history[next], index: next)
+ return true
+ }
+ guard let index = promptHistoryIndex else { return false }
+ if index <= 0 || index - 1 >= history.count {
+ applyHistoryText(promptHistorySavedDraft, index: nil)
+ promptHistorySavedDraft = ""
+ } else {
+ applyHistoryText(history[index - 1], index: index - 1)
+ }
+ return true
+ }
+
+ private func applyHistoryText(_ text: String, index: Int?) {
+ promptHistoryIndex = index
+ guard text != composerText else { return }
+ // The change below keeps the history position and opens no mention popover.
+ isApplyingHistory = true
+ isApplyingMention = true
+ composerText = text
+ }
+
+ // MARK: - Voice Dictation
+
+ private var isDictating: Bool {
+ voiceDictator.isActive
+ }
+
+ private var composerDictation: MorphComposerDictation {
+ #if DEBUG
+ if let preview = MorphVoiceDictationQA.shared.overrideState {
+ return preview
+ }
+ #endif
+ let mappedPhase: MorphComposerDictation.Phase
+ switch voiceDictator.phase {
+ case .idle: mappedPhase = .idle
+ case .connecting: mappedPhase = .connecting
+ case .recording: mappedPhase = .recording
+ case .finalizing: mappedPhase = .finalizing
+ }
+ return MorphComposerDictation(
+ phase: mappedPhase,
+ audioLevels: voiceDictator.audioLevels,
+ elapsedSeconds: voiceDictator.elapsedSeconds,
+ onStart: { startDictation() },
+ onConfirm: {
+ MorphHaptics.light()
+ voiceDictator.confirm()
+ composerFocused = true
+ },
+ onCancel: {
+ MorphHaptics.light()
+ voiceDictator.cancel()
+ composerFocused = true
+ }
+ )
+ }
+
+ /// Starts Azure realtime dictation (`gpt-live-transcribe`) into the composer, appending after existing text.
+ private func startDictation() {
+ guard !isDictating else {
+ voiceDictator.confirm()
+ return
+ }
+ MorphHaptics.light()
+ let base = composerText
+ let contextKeywords = [
+ activeProject?.name,
+ activeThread?.branch,
+ activeThread?.title,
+ ].compactMap { value -> String? in
+ let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return trimmed.isEmpty ? nil : trimmed
+ } + ["Morph Code"]
+ let appState = state
+ voiceDictator.start(
+ baseText: base,
+ keywords: contextKeywords,
+ prompt: "",
+ requestSession: { _ in
+ try await appState.requestVoiceTranscriptionSession()
+ },
+ onText: { composed in
+ composerText = composed
+ }
+ )
+ composerFocused = true
+ }
+
+ private func composerDock() -> some View {
+ let slashMatches = MorphCodeSlashCommand.matching(composerText, skills: state.codeSkills)
+ let mentionMatches = activeMention.map {
+ MorphComposerMentionItem.items(for: $0, files: state.codeFileSearchResults)
+ } ?? []
+ let hasSlash = !slashMatches.isEmpty
+ let hasMention = !hasSlash && !mentionMatches.isEmpty
+
+ return VStack(alignment: .leading, spacing: 8) {
+ if let recovery = activeRecoveryBanner {
+ poolRecoveryBanner(recovery)
+ }
+
+ if hasSlash {
+ slashCommandPopover(commands: slashMatches)
+ } else if hasMention, let mention = activeMention {
+ fileMentionPopover(mention: mention, items: mentionMatches)
+ }
+
+ if let thread = activeThread, !state.activeCodeLoops(for: thread.id).isEmpty {
+ activeLoopBanner(loops: state.activeCodeLoops(for: thread.id))
+ }
+
+ let alternate = state.codeFollowUpMode.alternate
+ MorphCodexComposer(
+ placeholder: composerPlaceholder,
+ text: composerTextBinding,
+ isBusy: activeRun != nil,
+ hasAttachments: !composerAttachments.isEmpty,
+ isSendBlocked: composerProcessingImages > 0,
+ focused: $composerFocused,
+ sendsWhileBusy: true,
+ onStop: {
+ MorphHaptics.light()
+ guard let threadId = activeRun?.threadId else { return }
+ Task { await state.cancelCodeTurn(threadId: threadId) }
+ },
+ alternateSend: MorphComposerAlternateSend(title: alternate == .queue ? "Add to Queue" : "Steer Now") {
+ submitPrompt(mode: alternate)
+ },
+ onCycleMode: {
+ let mode = accessModeBinding
+ mode.wrappedValue = mode.wrappedValue.next
+ state.showInfo("권한 모드: \(mode.wrappedValue.label)")
+ },
+ onMoveSelection: { delta in
+ let count = hasSlash ? slashMatches.count : (hasMention ? mentionMatches.count : 0)
+ guard count > 0 else { return false }
+ popoverHighlightedIndex = (popoverHighlightedIndex + delta + count) % count
+ return true
+ },
+ onAcceptSelection: {
+ if hasSlash {
+ let idx = min(max(0, popoverHighlightedIndex), slashMatches.count - 1)
+ executeSlashCommand(slashMatches[idx])
+ return true
+ }
+ if hasMention {
+ let idx = min(max(0, popoverHighlightedIndex), mentionMatches.count - 1)
+ applyMention(mentionMatches[idx])
+ return true
+ }
+ return false
+ },
+ onDismissPopover: {
+ if isDictating {
+ voiceDictator.cancel()
+ return true
+ }
+ if hasSlash {
+ composerText = ""
+ popoverHighlightedIndex = 0
+ return true
+ }
+ if hasMention {
+ activeMention = nil
+ popoverHighlightedIndex = 0
+ return true
+ }
+ return false
+ },
+ attachmentTray: composerAttachmentTray,
+ imageIntake: MorphComposerImageIntake(
+ attach: { attachPicked($0) },
+ onDropTargetChange: { isFieldDropTargeted = $0 }
+ ),
+ isDropTargeted: isWorkspaceDropTargeted || isFieldDropTargeted,
+ dropLabel: "파일을 놓아 첨부하세요",
+ showsShelf: activeThread == nil && activeRun == nil,
+ queueTray: composerQueueTray,
+ onHistory: { delta in
+ // The popovers own the arrows while they are open.
+ guard !hasSlash, !hasMention else { return false }
+ return navigatePromptHistory(delta)
+ },
+ dictation: composerDictation,
+ onSubmit: { submitPrompt() }
+ ) {
+ codeShelf
+ } leading: {
+ toolsMenu
+ MorphCodeAccessModeMenu(mode: accessModeBinding)
+ } trailing: {
+ MorphCodeModelMenu(state: state, model: modelBinding, effort: effortBinding)
+ MorphCodeEffortMenu(state: state, model: modelBinding.wrappedValue, effort: effortBinding)
+ .padding(.leading, 2)
+ }
+ }
+ .animation(AnymorphMotion.submit, value: activeThread?.queue?.map(\.id) ?? [])
+ .withoutAnimationOnThreadSwitch(activeThread?.id)
+ .frame(maxWidth: Self.columnWidth)
+ .padding(.horizontal, Self.horizontalPadding)
+ .padding(.top, 8)
+ #if os(macOS)
+ .padding(.bottom, 16)
+ #else
+ .padding(.bottom, MorphComposerDock.bottomPadding(
+ focused: composerFocused,
+ safeArea: bottomSafeArea,
+ restingGap: composerRestingGap
+ ))
+ #endif
+ .frame(maxWidth: .infinity)
+ .background {
+ LinearGradient(
+ stops: [
+ .init(color: AnymorphColor.bgBase.opacity(0), location: 0),
+ .init(color: AnymorphColor.bgBase.opacity(0.8), location: 0.25),
+ .init(color: AnymorphColor.bgBase, location: 0.45),
+ ],
+ startPoint: .top,
+ endPoint: .bottom
+ )
+ .padding(.top, -20)
+ .ignoresSafeArea(edges: .bottom)
+ .allowsHitTesting(false)
+ }
+ }
+
+ /// Requests waiting for the running turn, drawn on the composer's shelf plate with Codex's controls for each:
+ /// move, edit, send now and delete.
+ private var composerQueueTray: AnyView? {
+ guard let thread = activeThread, let queue = thread.queue, !queue.isEmpty else { return nil }
+ let threadId = thread.id
+ return AnyView(MorphCodeQueueTray(
+ queue: queue,
+ editingItemId: editingQueueItemId,
+ editingText: $editingQueueText,
+ compact: isCompactWidth,
+ actions: MorphCodeQueueActions(
+ move: { itemId, delta in
+ Task { await state.moveCodeQueueItem(threadId: threadId, itemId: itemId, by: delta) }
+ },
+ beginEdit: { item in
+ editingQueueText = item.prompt
+ editingQueueItemId = item.id
+ },
+ saveEdit: { item in saveQueueEdit(item, threadId: threadId) },
+ cancelEdit: { editingQueueItemId = nil },
+ sendNow: { item in
+ MorphHaptics.light()
+ Task { await state.sendCodeQueueItemNow(threadId: threadId, itemId: item.id) }
+ },
+ delete: { item in
+ Task { await state.deleteCodeQueueItem(threadId: threadId, itemId: item.id) }
+ }
+ )
+ ))
+ }
+
+ /// Lucide icon button for quiet message & queue actions.
+ private func lucideActionButton(_ kind: MorphLucideKind, label: String, disabled: Bool = false, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ MorphLucideIcon(kind, size: 13.5)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(disabled)
+ .help(label)
+ .accessibilityLabel(label)
+ }
+
+ private func saveQueueEdit(_ item: CodeQueuedPrompt, threadId: String) {
+ let text = editingQueueText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { return }
+ editingQueueItemId = nil
+ Task { await state.editCodeQueueItem(threadId: threadId, itemId: item.id, prompt: text) }
+ }
+
+ private var isCompactWidth: Bool {
+ #if os(iOS)
+ horizontalSizeClass == .compact
+ #else
+ false
+ #endif
+ }
+
+ /// The attachments waiting in the composer card; a click opens one, the remove button takes it out.
+ private var composerAttachmentTray: AnyView? {
+ let attachments = composerAttachments
+ let processing = composerProcessingImages
+ guard !attachments.isEmpty || processing > 0 else { return nil }
+ return AnyView(
+ MorphComposerAttachmentTray(
+ attachments: attachments,
+ processingCount: processing,
+ onOpen: { attachment in
+ guard let base64 = attachment.dataBase64, let data = Data(base64Encoded: base64) else { return }
+ if attachment.isImage {
+ lightboxImage = MorphLightboxImageItem(title: attachment.name, data: data)
+ } else {
+ openedFile = MorphFileItem(
+ id: attachment.id,
+ name: attachment.name,
+ path: attachment.path,
+ mimeType: attachment.mimeType,
+ text: nil,
+ source: nil,
+ data: data
+ )
+ }
+ },
+ onRemove: { attachment in
+ removeAttachment(id: attachment.id)
+ }
+ )
+ )
+ }
+
+ private struct RecoveryBannerModel {
+ let message: String
+ let fallback: CodeModelOption?
+ let isError: Bool
+ }
+
+ private var activeRecoveryBanner: RecoveryBannerModel? {
+ let model = modelBinding.wrappedValue
+ if let issue = state.codeModelIssue(for: model) {
+ return RecoveryBannerModel(
+ message: "\(issue.modelName) · \(issue.reason)",
+ fallback: issue.fallback,
+ isError: false
+ )
+ }
+ if let err = state.codeTurnErrorBanner, err.threadId == activeThread?.id {
+ let healthyFallback = state.availableCodeModels.first {
+ $0.id != "auto" && $0.id != "orchestrator" && $0.id != model && $0.available == true
+ }
+ return RecoveryBannerModel(
+ message: err.message,
+ fallback: healthyFallback,
+ isError: true
+ )
+ }
+ return nil
+ }
+
+ private func poolRecoveryBanner(_ banner: RecoveryBannerModel) -> some View {
+ let actionButtons = HStack(spacing: 6) {
+ if let fallback = banner.fallback {
+ Button("Switch to \(CodeModelMenu.name(fallback))") {
+ modelBinding.wrappedValue = fallback.id
+ effortBinding.wrappedValue = effortBinding.wrappedValue.nearest(
+ in: CodeModelMenu.efforts(of: fallback.id, in: state.availableCodeModels)
+ )
+ state.codeTurnErrorBanner = nil
+ }
+ .morphPill(.primary)
+ }
+ Button("Providers") {
+ state.openSettings(.providers)
+ }
+ .morphPill(.secondary)
+ if banner.isError {
+ Button {
+ state.codeTurnErrorBanner = nil
+ } label: {
+ MorphLucideIcon(.x, size: 11)
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ .buttonStyle(.morphPlain)
+ }
+ }
+ return ViewThatFits(in: .horizontal) {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.circle")
+ .font(.system(size: 12.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text(banner.message)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(2)
+ Spacer(minLength: 6)
+ actionButtons
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.circle")
+ .font(.system(size: 12.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text(banner.message)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 0)
+ }
+ actionButtons
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(flatCardChrome)
+ }
+
+ private func slashCommandPopover(commands: [MorphCodeSlashCommand]) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack {
+ #if os(macOS)
+ Text("빠른 명령어 (↑↓ 선택 · Enter 실행)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ #else
+ Text("빠른 명령어")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ #endif
+ Spacer()
+ Button("닫기") {
+ composerText = ""
+ popoverHighlightedIndex = 0
+ }
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .padding(.horizontal, 10)
+ .padding(.top, 6)
+ .padding(.bottom, 2)
+
+ ForEach(Array(commands.enumerated()), id: \.element.id) { idx, cmd in
+ let isSelected = idx == min(popoverHighlightedIndex, max(0, commands.count - 1))
+ Button {
+ executeSlashCommand(cmd)
+ } label: {
+ HStack(spacing: 8) {
+ Image(systemName: cmd.icon)
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 16)
+ Text(cmd.command)
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ Text(cmd.title)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(cmd.detail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ Spacer()
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgSelected : .clear)
+ )
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { inside in
+ if inside { popoverHighlightedIndex = idx }
+ }
+ }
+ }
+ .padding(.horizontal, 4)
+ .padding(.bottom, 6)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .shadow(color: AnymorphColor.composerShadow, radius: 10, y: 3)
+ )
+ }
+
+ private func executeSlashCommand(_ cmd: MorphCodeSlashCommand) {
+ composerText = ""
+ popoverHighlightedIndex = 0
+ switch cmd.action {
+ case .accessMode(let mode):
+ accessModeBinding.wrappedValue = mode
+ state.showInfo("\(mode.label) 모드로 전환했습니다.")
+ case .effort(let effort):
+ // A level the model does not run at moves to its nearest level, as the Effort menu offers.
+ let picked = effort.nearest(in: CodeModelMenu.efforts(of: modelBinding.wrappedValue, in: state.availableCodeModels))
+ effortBinding.wrappedValue = picked
+ state.showInfo("추론 강도: \(picked.label)")
+ case .compact:
+ if let threadId = activeThread?.id {
+ Task { await state.compactCodeThread(threadId: threadId) }
+ } else {
+ state.showInfo("압축할 대화가 없습니다.")
+ }
+ case .loop:
+ composerText = "/loop 5m "
+ case .review:
+ composerText = MorphCodeSlashCommand.reviewPrompt
+ case .skill(let skill):
+ composerText = MorphCodeSlashCommand.skillPrompt(skill)
+ case .diff:
+ state.codeInspectorSection = .changes
+ state.isCodeInspectorPresented = true
+ case .terminal:
+ state.codeInspectorSection = .terminal
+ state.isCodeInspectorPresented = true
+ case .fork:
+ if let tid = activeThread?.id {
+ Task { await state.forkCodeThread(threadId: tid) }
+ }
+ case .clear, .newThread:
+ state.startNewCodeThreadHere()
+ }
+ composerFocused = true
+ }
+
+ private func activeLoopBanner(loops: [CodeSchedule]) -> some View {
+ HStack(spacing: 8) {
+ Image(systemName: "repeat")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ if let first = loops.first {
+ Text(loops.count == 1 ? "반복 루프 · \(first.title)" : "반복 루프 \(loops.count)개 활성 · \(first.title)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ }
+ Spacer(minLength: 6)
+ Button("중지") {
+ Task {
+ await state.handleCodeLoopCommand(
+ .stop,
+ thread: activeThread,
+ project: activeProject,
+ model: modelBinding.wrappedValue,
+ effort: effortBinding.wrappedValue,
+ accessMode: accessModeBinding.wrappedValue
+ )
+ }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ )
+ }
+
+ private func fileMentionPopover(mention: MorphComposerMention, items: [MorphComposerMentionItem]) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack {
+ Text(mention.isFolderSearch ? "폴더 멘션 @\(mention.searchText)" : "멘션 @\(mention.query)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Spacer()
+ Button("닫기") {
+ activeMention = nil
+ popoverHighlightedIndex = 0
+ }
+ .buttonStyle(.morphPlain)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ .padding(.horizontal, 10)
+ .padding(.top, 6)
+ .padding(.bottom, 2)
+
+ ForEach(Array(items.enumerated()), id: \.element.id) { idx, item in
+ let isSelected = idx == min(popoverHighlightedIndex, max(0, items.count - 1))
+ Button {
+ applyMention(item)
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: item.icon)
+ .font(.system(size: 11))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 14)
+ Text(item.label)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if let detail = item.detail {
+ Text(detail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ Spacer()
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgSelected : .clear)
+ )
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { inside in
+ if inside { popoverHighlightedIndex = idx }
+ }
+ }
+ }
+ .padding(.horizontal, 4)
+ .padding(.bottom, 6)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .shadow(color: AnymorphColor.composerShadow, radius: 10, y: 3)
+ )
+ }
+
+ /// The project and the way of working of a new thread, chosen on the new-task home. The way of working waits
+ /// for a project.
+ @ViewBuilder
+ private var codeShelf: some View {
+ MorphCodeProjectMenu(state: state, project: activeProject)
+ if let project = activeProject {
+ MorphCodeRunModeMenu(state: state)
+ if state.codeNewThreadDraft?.mode == .worktree {
+ MorphCodeBaseBranchMenu(state: state, projectId: project.id)
+ }
+ }
+ }
+
+ private var toolsMenu: some View {
+ MorphCodeToolsMenu(state: state, attachActions: attachActions)
+ }
+
+ /// The + menu's ways to attach images and files: the file panel and the clipboard on a Mac; the photo library,
+ /// Files and the clipboard on iPhone and iPad. Pasting and dropping work without the menu.
+ private var attachActions: [MorphComposerAttachAction] {
+ #if os(macOS)
+ [
+ MorphComposerAttachAction(id: "file", title: "파일·이미지 첨부…", icon: "paperclip", perform: pickFilesOnMac),
+ MorphComposerAttachAction(id: "paste", title: "클립보드에서 첨부", icon: "doc.on.clipboard", shortcut: "⌘V", perform: pasteAttachmentsFromClipboard),
+ ]
+ #else
+ var items: [MorphComposerAttachAction] = [
+ MorphComposerAttachAction(id: "photos", title: "사진 보관함", icon: "photo.on.rectangle", perform: { presentAfterMenu { showPhotoPicker = true } }),
+ ]
+ if UIImagePickerController.isSourceTypeAvailable(.camera) {
+ items.append(MorphComposerAttachAction(id: "camera", title: "카메라 촬영", icon: "camera", perform: { presentAfterMenu { showCameraPicker = true } }))
+ }
+ items.append(MorphComposerAttachAction(id: "files", title: "파일 선택", icon: "folder", perform: { presentAfterMenu { showFileImporter = true } }))
+ items.append(MorphComposerAttachAction(id: "paste", title: "클립보드 이미지 붙여넣기", icon: "doc.on.clipboard", perform: pasteAttachmentsFromClipboard))
+ return items
+ #endif
+ }
+
+ private var composerPlaceholder: String {
+ if activeRun != nil {
+ return state.codeFollowUpMode == .steer ? "진행 중인 작업에 지시하세요" : "다음에 할 작업을 추가하세요"
+ }
+ return accessModeBinding.wrappedValue == .plan ? "Ask Morph Code to analyze and plan…" : "Ask Morph Code to build, fix, or explain…"
+ }
+
+ private func copyText(_ text: String) {
+ #if os(macOS)
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ #elseif os(iOS)
+ UIPasteboard.general.string = text
+ #endif
+ }
+
+ // MARK: - Attachments & @ Mentions
+
+ /// Sends picked images through image normalization and every other file as a general attachment.
+ private func attachPicked(_ picked: [MorphPickedImage]) {
+ var images: [MorphPickedImage] = []
+ var files: [URL] = []
+ for item in picked {
+ if case .file(let url) = item, !CodeImagePasteDecision.isImageFile(url) {
+ files.append(url)
+ } else {
+ images.append(item)
+ }
+ }
+ if !images.isEmpty {
+ attachImages(images)
+ }
+ if !files.isEmpty {
+ attachFiles(files)
+ }
+ }
+
+ /// Opens or closes the `@` popover for the word being typed, wherever it is in the text, and searches the
+ /// workspace for it.
+ private func updateMention(old: String, new: String) {
+ popoverHighlightedIndex = 0
+ if isApplyingMention {
+ isApplyingMention = false
+ activeMention = nil
+ return
+ }
+ guard let projectId = activeProject?.id,
+ let mention = MorphComposerMention.active(in: new, caret: MorphComposerMention.caret(old: old, new: new)) else {
+ activeMention = nil
+ return
+ }
+ activeMention = mention
+ let query = mention.searchText
+ let threadId = activeThread?.id
+ Task {
+ await state.searchCodeFiles(projectId: projectId, threadId: threadId, query: query)
+ }
+ }
+
+ /// Completes the mention at the caret. `@folder` turns it into a folder search and keeps the popover open.
+ private func applyMention(_ item: MorphComposerMentionItem) {
+ guard let mention = activeMention else { return }
+ popoverHighlightedIndex = 0
+ if item == .folderSearch {
+ composerText = mention.replacing(
+ in: composerText,
+ with: "@" + MorphComposerMention.folderPrefix,
+ addsSpace: false
+ )
+ composerFocused = true
+ return
+ }
+ let replacement: String
+ switch item {
+ case .diff:
+ replacement = diffMentionText
+ case .folder(let path), .file(let path):
+ replacement = "@" + path
+ case .folderSearch:
+ return
+ }
+ activeMention = nil
+ let completed = mention.replacing(in: composerText, with: replacement)
+ if completed != composerText {
+ isApplyingMention = true
+ composerText = completed
+ }
+ composerFocused = true
+ }
+
+ /// What `@diff` puts in the request: the working tree's `git diff`, with the changed files when known.
+ private var diffMentionText: String {
+ let files = activeProject.flatMap { state.codeGitStatusByProject[$0.id]?.files } ?? []
+ guard !files.isEmpty else { return "@diff(작업 트리의 현재 `git diff` 변경사항)" }
+ let names = files.prefix(5).map(\.path).joined(separator: ", ")
+ let more = files.count > 5 ? " 외 \(files.count - 5)개" : ""
+ return "@diff(현재 `git diff` 변경 파일 \(files.count)개: \(names)\(more))"
+ }
+
+ #if os(macOS)
+ /// The file panel, as a sheet on the window once the + menu has closed.
+ private func pickFilesOnMac() {
+ DispatchQueue.main.async {
+ let panel = NSOpenPanel()
+ panel.allowedContentTypes = Self.attachableTypes
+ panel.allowsMultipleSelection = true
+ panel.canChooseDirectories = false
+ panel.canChooseFiles = true
+ panel.prompt = "첨부"
+ panel.message = "요청과 함께 보낼 이미지나 파일을 고르세요."
+ let attach: (NSApplication.ModalResponse) -> Void = { response in
+ guard response == .OK, !panel.urls.isEmpty else { return }
+ attachFiles(panel.urls)
+ composerFocused = true
+ }
+ if let window = NSApp.keyWindow ?? NSApp.mainWindow {
+ panel.beginSheetModal(for: window, completionHandler: attach)
+ } else {
+ attach(panel.runModal())
+ }
+ }
+ }
+
+ /// The + menu's paste: files copied in Finder, or any image on the clipboard, even one that came with text,
+ /// which ⌘V would paste as text.
+ private func pasteAttachmentsFromClipboard() {
+ let fileURLs = NSPasteboard.general.readObjects(
+ forClasses: [NSURL.self],
+ options: [.urlReadingFileURLsOnly: true]
+ ) as? [URL] ?? []
+ if !fileURLs.isEmpty {
+ attachFiles(fileURLs)
+ composerFocused = true
+ return
+ }
+ guard let picked = MorphPasteboardImages.anyImages(.general) else {
+ state.showInfo("클립보드에 첨부할 파일이나 이미지가 없습니다.")
+ return
+ }
+ attachImages(picked)
+ composerFocused = true
+ }
+ #else
+ private func pasteAttachmentsFromClipboard() {
+ let images = UIPasteboard.general.images ?? []
+ let picked = images.compactMap { $0.pngData() }.map { MorphPickedImage.data($0, name: nil) }
+ guard !picked.isEmpty else {
+ state.showInfo("클립보드에 이미지가 없습니다.")
+ return
+ }
+ attachImages(picked)
+ }
+
+ private func attachPhotos(_ items: [PhotosPickerItem]) {
+ Task {
+ var picked: [MorphPickedImage] = []
+ for item in items {
+ if let data = try? await item.loadTransferable(type: Data.self) {
+ picked.append(.data(data, name: nil))
+ }
+ }
+ if picked.count < items.count {
+ state.showError("사진 \(items.count - picked.count)장을 불러오지 못했습니다.")
+ }
+ attachImages(picked)
+ }
+ }
+
+ /// Presents a picker on the next main-actor turn without an artificial 350 ms delay.
+ private func presentAfterMenu(_ present: @escaping () -> Void) {
+ Task { @MainActor in
+ await Task.yield()
+ present()
+ }
+ }
+ #endif
+}
+
+// MARK: - Bound-window draft mirroring
+
+/// Keeps a bound window's composer and the thread's saved draft in step: local edits are written to the draft, and a
+/// bump of the thread's draft revision, from something that inserted text elsewhere, reloads it.
+private struct BoundDraftSync: ViewModifier {
+ let isBound: Bool
+ let text: String
+ let attachments: [CodeImageAttachment]
+ let revision: Int
+ let persist: () -> Void
+ let reload: () -> Void
+
+ func body(content: Content) -> some View {
+ content
+ .onChange(of: text) { _, _ in
+ if isBound { persist() }
+ }
+ .onChange(of: attachments) { _, _ in
+ if isBound { persist() }
+ }
+ .onChange(of: revision) { _, _ in
+ if isBound { reload() }
+ }
+ }
+}
+
+// MARK: - Context, cost and composition meter
+
+/// How full the open thread's context window is, "42% · 84k/200k", amber from 75%; a crowded composer row keeps the
+/// percentage, then the ring alone. A click opens what fills it: the window in tokens, the estimated cost so far, the
+/// Compact circular context ring shown in the top thread header bar; opens breakdown, cost, and `지금 압축` below it.
+struct MorphCodeHeaderContextRing: View {
+ @Bindable var state: MorphAppState
+ let thread: CodeThread
+
+ var body: some View {
+ MorphCodeObservationBoundary {
+ if let usage = state.codeThreadUsage[thread.id], usage.contextWindow > 0 {
+ CodeContextUsageMeter(
+ state: state,
+ thread: thread,
+ usage: usage,
+ isLocal: state.isLocalCodeThread(thread.id),
+ placement: .belowTrailing
+ )
+ }
+ }
+ }
+}
+
+/// system, tool, cache and conversation shares, the auto-compact threshold, and 지금 압축 to summarize the
+/// conversation now.
+struct CodeContextUsageMeter: View {
+ @Bindable var state: MorphAppState
+ let thread: CodeThread
+ let usage: CodeTokenUsage
+ let isLocal: Bool
+ var placement: MorphDropdownPlacement = .belowTrailing
+ @Environment(\.morphComposerDensity) private var density
+
+ private struct Segment: Identifiable {
+ let id: String
+ let label: String
+ let tokens: Int64
+ let tint: Color
+ }
+
+ private var percent: Int {
+ Int((usage.contextFraction * 100).rounded())
+ }
+
+ private var tint: Color {
+ usage.contextFraction > 0.75 ? AnymorphColor.caution : AnymorphColor.fgTertiary
+ }
+
+ private var cost: Double {
+ usage.totalCostUsd ?? 0
+ }
+
+ /// The four shares in restrained ink steps, darkest for what the member wrote.
+ private var segments: [Segment] {
+ guard let breakdown = usage.breakdown else { return [] }
+ let parts = [
+ Segment(id: "system", label: "시스템", tokens: breakdown.systemTokens ?? 0, tint: AnymorphColor.fgQuaternary),
+ Segment(id: "tools", label: "도구", tokens: breakdown.toolTokens ?? 0, tint: AnymorphColor.fgTertiary),
+ Segment(id: "cache", label: "캐시", tokens: breakdown.cacheTokens ?? 0, tint: AnymorphColor.fgDisabled),
+ Segment(id: "conversation", label: "대화", tokens: breakdown.conversationTokens ?? 0, tint: AnymorphColor.fgSecondary),
+ ]
+ return parts.contains { $0.tokens > 0 } ? parts : []
+ }
+
+ static func costLabel(_ usd: Double) -> String {
+ if usd < 0.001 { return "< $0.001" }
+ if usd < 1 { return String(format: "$%.3f", usd) }
+ return String(format: "$%.2f", usd)
+ }
+
+ var body: some View {
+ MorphDropdown(placement: placement, width: 300, name: "code-context") {
+ details
+ MorphMenuDivider()
+ MorphMenuItem(
+ "지금 압축",
+ subtitle: "CLI 기본 방식으로 압축합니다",
+ icon: .symbol("arrow.down.right.and.arrow.up.left"),
+ trailing: "/compact",
+ isEnabled: !state.isCompactingCodeThread
+ ) {
+ Task { await state.compactCodeThread(threadId: thread.id) }
+ }
+ } label: {
+ label
+ }
+ .help("컨텍스트 \(percent)% · \(MorphCodeContextMeter.tokens(usage.contextTokens))/\(MorphCodeContextMeter.tokens(usage.contextWindow)) · 자세히 보기")
+ .accessibilityLabel("컨텍스트 \(percent)% 사용")
+ .accessibilityHint("구성과 비용을 엽니다")
+ }
+
+ private var label: some View {
+ ZStack {
+ if state.isCompactingCodeThread {
+ ProgressView().controlSize(.mini)
+ } else {
+ Circle().stroke(AnymorphColor.strokeBase, lineWidth: 2)
+ Circle()
+ .trim(from: 0, to: usage.contextFraction)
+ .stroke(tint, style: StrokeStyle(lineWidth: 2, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ }
+ }
+ .frame(width: 14, height: 14)
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ .modifier(MorphComposerHoverPlate())
+ }
+
+ /// The usage the menu opens on, inset to line up with the menu's rows.
+ private var details: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(alignment: .firstTextBaseline) {
+ Text("컨텍스트")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 12)
+ Text("\(percent)% 사용")
+ .anymorphText(.callout, weight: .emphasis, color: usage.contextFraction > 0.75 ? AnymorphColor.caution : AnymorphColor.fgSecondary, tabular: true)
+ }
+
+ VStack(alignment: .leading, spacing: 8) {
+ compositionBar
+ Text("\(usage.contextTokens.formatted()) / \(usage.contextWindow.formatted()) 토큰")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+
+ if !segments.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(segments) { segment in
+ legendRow(segment)
+ }
+ }
+ }
+
+ AnymorphDivider()
+
+ VStack(alignment: .leading, spacing: 6) {
+ if cost > 0 {
+ detailRow("누적 비용 (추정)", value: Self.costLabel(cost))
+ }
+ detailRow(
+ "입력 · 출력",
+ value: "\(MorphCodeContextMeter.tokens(usage.inputTokens)) · \(MorphCodeContextMeter.tokens(usage.outputTokens))"
+ )
+ if let cacheRead = usage.cacheReadTokens, cacheRead > 0 {
+ detailRow("캐시 읽기", value: MorphCodeContextMeter.tokens(cacheRead))
+ }
+ if let reasoning = usage.reasoningTokens, reasoning > 0 {
+ detailRow("사고 토큰 (컨텍스트 제외)", value: MorphCodeContextMeter.tokens(reasoning))
+ }
+ }
+
+ AnymorphDivider()
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(autoCompactTitle)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ Text(autoCompactDetail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .padding(11)
+ .task {
+ // The threshold lives in the harness settings; read them once if nothing has yet.
+ if state.codeHarnessConfig == nil, !state.isLoadingCodeHarnessConfig {
+ await state.refreshCodeHarnessConfig(projectId: thread.projectId, local: isLocal)
+ }
+ }
+ }
+
+ /// The window as one track: each share in its ink step when the agent reports them, otherwise the used part.
+ private var compositionBar: some View {
+ GeometryReader { proxy in
+ let window = max(Double(usage.contextWindow), 1)
+ HStack(spacing: 1) {
+ if segments.isEmpty {
+ Rectangle()
+ .fill(tint)
+ .frame(width: proxy.size.width * usage.contextFraction)
+ } else {
+ ForEach(segments.filter { $0.tokens > 0 }) { segment in
+ Rectangle()
+ .fill(segment.tint)
+ .frame(width: max(1, proxy.size.width * min(1, Double(segment.tokens) / window)))
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 8)
+ .background(Capsule().fill(AnymorphColor.bgSurface))
+ .clipShape(Capsule())
+ .accessibilityHidden(true)
+ }
+
+ private func legendRow(_ segment: Segment) -> some View {
+ HStack(spacing: 8) {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxs, style: .continuous)
+ .fill(segment.tint)
+ .frame(width: 8, height: 8)
+ Text(segment.label)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ Spacer(minLength: 8)
+ Text(MorphCodeContextMeter.tokens(segment.tokens))
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+ .accessibilityElement(children: .combine)
+ }
+
+ private func detailRow(_ title: String, value: String) -> some View {
+ HStack(spacing: 8) {
+ Text(title)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ Spacer(minLength: 8)
+ Text(value)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ }
+ .accessibilityElement(children: .combine)
+ }
+
+ private var autoCompactTitle: String {
+ guard let config = state.codeHarnessConfig else { return "자동 압축" }
+ guard config.autoCompactEnabled ?? true else { return "자동 압축 꺼짐" }
+ return "자동 압축 \(CodeHarnessConfig.tokenLimitLabel(config.effectiveAutoCompactTokens))"
+ }
+
+ private var autoCompactDetail: String {
+ guard let config = state.codeHarnessConfig else { return "설정을 불러오는 중입니다." }
+ guard config.autoCompactEnabled ?? true else { return "설정에서 켤 수 있습니다." }
+ return "컨텍스트가 \(CodeHarnessConfig.tokenLimitLabel(config.effectiveAutoCompactTokens)) 토큰에 이르면 자동 압축합니다. 창이 더 작은 모델은 창 크기 기준을 따릅니다."
+ }
+}
+
+// MARK: - iOS Haptic Feedback
+
+@MainActor
+enum MorphHaptics {
+ static func light() {
+ #if os(iOS)
+ let generator = UIImpactFeedbackGenerator(style: .light)
+ generator.impactOccurred()
+ #endif
+ }
+
+ static func medium() {
+ #if os(iOS)
+ let generator = UIImpactFeedbackGenerator(style: .medium)
+ generator.impactOccurred()
+ #endif
+ }
+
+ static func success() {
+ #if os(iOS)
+ let generator = UINotificationFeedbackGenerator()
+ generator.notificationOccurred(.success)
+ #endif
+ }
+
+ static func error() {
+ #if os(iOS)
+ let generator = UINotificationFeedbackGenerator()
+ generator.notificationOccurred(.error)
+ #endif
+ }
+}
+
+private struct MorphCodeOlderAnchorRequest: Equatable {
+ let threadId: String
+ let messageId: String
+ let seq: Int
+}
+
+/// Per-thread conversation scroll container keyed by `threadId`. Giving each opened thread its own `ScrollView`,
+/// `ScrollPosition`, and `MorphConversationScroll` state ensures every thread switch starts with clean bottom-anchored
+/// scroll geometry on macOS and iOS.
+private struct MorphCodeThreadScrollView: View {
+ let threadId: String
+ let submitScrollTrigger: Int
+ let activeFindMatch: String?
+ let olderAnchorRequest: MorphCodeOlderAnchorRequest?
+ @ViewBuilder let content: () -> Content
+ @State private var scrollPosition = ScrollPosition(edge: .bottom)
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ content()
+ }
+ .morphConversationScroll(
+ $scrollPosition,
+ conversationID: threadId,
+ animatedScrollTrigger: submitScrollTrigger
+ )
+ #if os(iOS)
+ // Any drag on the conversation puts the keyboard away. Following the finger (`.interactively`) only starts
+ // once the finger reaches the keyboard, below the composer, so a swipe felt stuck.
+ .scrollDismissesKeyboard(.immediately)
+ #endif
+ .onChange(of: activeFindMatch) { _, matchId in
+ guard let matchId else { return }
+ withAnimation(AnymorphMotion.base) {
+ proxy.scrollTo(matchId, anchor: .center)
+ }
+ }
+ .onChange(of: olderAnchorRequest) { _, request in
+ guard let request, request.threadId == threadId else { return }
+ proxy.scrollTo(request.messageId, anchor: .top)
+ }
+ }
+ }
+}
+
+/// Isolates `@Observable` property reads inside `content` into its own SwiftUI observation scope so composer
+/// keystrokes and attachment/popover changes do not re-evaluate the conversation scroll view.
+private struct MorphCodeObservationBoundary: View {
+ private let content: () -> Content
+
+ init(@ViewBuilder content: @escaping () -> Content) {
+ self.content = content
+ }
+
+ var body: some View {
+ content()
+ }
+}
+
+private extension View {
+ /// Shows another thread's content at once. An animation running in the same update, such as the archived banner's
+ /// or the queue's, would otherwise fade the previous thread's conversation, banner or queued requests out over the
+ /// new thread's. Animations inside, such as a live turn's, stay off for that update too.
+ func withoutAnimationOnThreadSwitch(_ threadId: String?) -> some View {
+ transaction(value: threadId) { transaction in
+ transaction.animation = nil
+ transaction.disablesAnimations = true
+ }
+ }
+}
+
+/// Value-equality key for a single stored message row inside `MorphCodeWorkspaceView`.
+private struct MorphCodeMessageRowKey: Equatable {
+ let message: CodeMessage
+ let previousCreatedAt: String?
+ let isLatestReply: Bool
+ let isEditing: Bool
+ let editingText: String
+ let editRestoresFiles: Bool
+ let isCopied: Bool
+ let isFindMatch: Bool
+ let isActiveFindMatch: Bool
+ let canEdit: Bool
+ let isPlanMode: Bool
+ let hasPendingPlanApproval: Bool
+ let isCompactWidth: Bool
+ let expandedApprovalDetailIds: Set
+ let feedbackApprovalId: String?
+ let approvalFeedback: String
+ let approvalStates: [String]
+ let revertTargets: [String]
+ let scheduleTitle: String?
+}
+
+/// Skips re-evaluating unchanged historical message rows while live-run ticks arrive.
+private struct MorphCodeMessageRowView: View, Equatable {
+ let key: MorphCodeMessageRowKey
+ let content: () -> Content
+
+ nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.key == rhs.key
+ }
+
+ var body: some View {
+ content()
+ }
+}
+
+#if os(iOS)
+private struct MorphCameraPicker: UIViewControllerRepresentable {
+ let onCapture: (Data?) -> Void
+ @Environment(\.dismiss) private var dismiss
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(onCapture: onCapture, dismiss: dismiss)
+ }
+
+ func makeUIViewController(context: Context) -> UIImagePickerController {
+ let picker = UIImagePickerController()
+ picker.sourceType = .camera
+ picker.delegate = context.coordinator
+ return picker
+ }
+
+ func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
+
+ final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
+ let onCapture: (Data?) -> Void
+ let dismiss: DismissAction
+
+ init(onCapture: @escaping (Data?) -> Void, dismiss: DismissAction) {
+ self.onCapture = onCapture
+ self.dismiss = dismiss
+ }
+
+ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
+ onCapture(nil)
+ dismiss()
+ }
+
+ func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
+ let image = (info[.editedImage] ?? info[.originalImage]) as? UIImage
+ let data = image?.jpegData(compressionQuality: 0.88)
+ onCapture(data)
+ dismiss()
+ }
+ }
+}
+#endif
+
+/// Quiet monochrome sync pill shown in header bars (macOS / iPad) or centered above the compact iPhone composer
+/// while a thread with existing messages or a live turn is syncing updates from remote.
+struct MorphCodeInlineSyncIndicator: View {
+ @Bindable var state: MorphAppState
+ var threadId: String? = nil
+ var floating: Bool = false
+ @State private var delayedVisible = false
+
+ private var resolvedThreadId: String? {
+ if let threadId { return threadId }
+ guard state.appMode == .code, state.codeDestination == .threads else { return nil }
+ return state.selectedCodeThread?.id
+ }
+
+ private var indicator: (label: String, immediate: Bool)? {
+ guard let tid = resolvedThreadId else { return nil }
+ let run = state.codeLiveRuns[tid]
+ let msgs = state.codeMessagesByThread[tid] ?? []
+ let hidingId = run?.pendingPrompt != nil ? run?.submittedMessageId : nil
+ let hasMessages = hidingId == nil ? !msgs.isEmpty : msgs.contains { $0.id != hidingId }
+ let presentation = CodeThreadSyncPresentation.resolve(
+ hasMessages: hasMessages,
+ hasActiveRun: run != nil,
+ isLoading: state.codeLoadingMessageThreadIds.contains(tid),
+ hasSyncedOnce: state.codeSyncedMessageThreadIds.contains(tid),
+ loadError: state.codeMessageLoadErrorByThread[tid],
+ source: state.codeThreadSyncSource(for: tid)
+ )
+ guard case .inlineSyncing(let source, let immediate) = presentation else { return nil }
+ return (source.inlineSyncLabel, immediate)
+ }
+
+ private var taskId: String {
+ guard let indicator else { return "idle" }
+ return "\(resolvedThreadId ?? "")|\(indicator.label)|\(indicator.immediate)"
+ }
+
+ var body: some View {
+ if let indicator {
+ ZStack {
+ if indicator.immediate || delayedVisible {
+ if floating {
+ HStack {
+ Spacer(minLength: 0)
+ pill(label: indicator.label)
+ Spacer(minLength: 0)
+ }
+ .transition(.opacity.combined(with: .move(edge: .bottom)))
+ } else {
+ pill(label: indicator.label)
+ .transition(.opacity)
+ }
+ } else {
+ Color.clear.frame(width: 0, height: 0)
+ }
+ }
+ .animation(AnymorphMotion.fast, value: indicator.immediate || delayedVisible)
+ .task(id: taskId) {
+ if indicator.immediate {
+ delayedVisible = true
+ return
+ }
+ delayedVisible = false
+ try? await Task.sleep(for: .milliseconds(180))
+ guard !Task.isCancelled else { return }
+ delayedVisible = true
+ }
+ .onDisappear {
+ delayedVisible = false
+ }
+ }
+ }
+
+ private func pill(label: String) -> some View {
+ HStack(spacing: 5) {
+ MorphSyncIcon(size: floating ? 11 : 10.5, color: AnymorphColor.fgSecondary)
+ MorphShimmerText(label, scale: floating ? .footnote : .caption, weight: .emphasis)
+ }
+ .padding(.horizontal, floating ? 11 : 9)
+ .frame(height: floating ? 26 : 24)
+ .background(Capsule().fill(floating ? AnymorphColor.menuSurface : AnymorphColor.bgSubtle))
+ .overlay(Capsule().strokeBorder(floating ? AnymorphColor.menuStroke : AnymorphColor.strokeLight, lineWidth: 1))
+ .shadow(color: floating ? AnymorphColor.composerShadow : .clear, radius: floating ? 8 : 0, y: floating ? 2 : 0)
+ .fixedSize()
+ .allowsHitTesting(false)
+ .accessibilityElement(children: .combine)
+ .accessibilityLabel(label)
+ }
+}
diff --git a/apple/Apps/Shared/MorphCodexComposer.swift b/apple/Apps/Shared/MorphCodexComposer.swift
new file mode 100644
index 000000000..816ce5112
--- /dev/null
+++ b/apple/Apps/Shared/MorphCodexComposer.swift
@@ -0,0 +1,1153 @@
+import SwiftUI
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// Puts text on the system clipboard on either platform.
+enum MorphClipboard {
+ static func copy(_ text: String) {
+ #if os(macOS)
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ #else
+ UIPasteboard.general.string = text
+ #endif
+ }
+}
+
+// MARK: - Codex-style composer shared by Morph Assistant and Morph Code
+//
+// A recessed context shelf tucked behind the top edge of a rounded card. The card holds the attached images, the
+// text field and one borderless action bar: + and the mode on the left, model controls and the round send button on
+// the right. Controls carry no pill backgrounds; a soft plate appears only on hover.
+// When the controls are wider than the composer, as on a phone, the shelf and the action bar scroll sideways
+// instead of widening the screen, and the send button stays in place.
+// A caller can leave the shelf out, as Morph Code does once a conversation has started.
+// On a Mac the field is `MorphComposerTextInput`, which takes images from a paste or a drop; on iPhone and iPad it is
+// a SwiftUI text field.
+
+/// One quick prompt shown as a single quiet line above the composer in an empty conversation.
+public struct MorphComposerSuggestion {
+ public let systemImage: String
+ public let text: String
+ public let action: () -> Void
+
+ public init(systemImage: String = "sparkle", text: String, action: @escaping () -> Void) {
+ self.systemImage = systemImage
+ self.text = text
+ self.action = action
+ }
+}
+
+/// A second way to send what the composer holds, such as queueing a request instead of adding it to the running
+/// turn: the Tab key, or the send button's menu.
+public struct MorphComposerAlternateSend {
+ public let title: String
+ public let action: () -> Void
+
+ public init(title: String, action: @escaping () -> Void) {
+ self.title = title
+ self.action = action
+ }
+}
+
+/// Live voice dictation state passed to `MorphCodexComposer` for the Codex-style recording bar.
+public struct MorphComposerDictation {
+ public enum Phase: Equatable, Sendable {
+ case idle
+ case connecting
+ case recording
+ case finalizing
+ }
+
+ public let phase: Phase
+ public let audioLevels: [Double]
+ public let elapsedSeconds: Int
+ public let onStart: () -> Void
+ public let onConfirm: () -> Void
+ public let onCancel: () -> Void
+
+ public var isActive: Bool { phase != .idle }
+
+ public init(
+ phase: Phase,
+ audioLevels: [Double] = [],
+ elapsedSeconds: Int = 0,
+ onStart: @escaping () -> Void,
+ onConfirm: @escaping () -> Void,
+ onCancel: @escaping () -> Void
+ ) {
+ self.phase = phase
+ self.audioLevels = audioLevels
+ self.elapsedSeconds = elapsedSeconds
+ self.onStart = onStart
+ self.onConfirm = onConfirm
+ self.onCancel = onCancel
+ }
+}
+
+public struct MorphCodexComposer: View {
+ public let placeholder: String
+ @Binding public var text: String
+ public let isBusy: Bool
+ public let hasAttachments: Bool
+ /// Holds the send button back, as while attached images are still being read.
+ private let isSendBlocked: Bool
+ /// Whether the field has the keyboard. Setting it to true puts the caret in the field.
+ @Binding private var isFocused: Bool
+ public let onSubmit: () -> Void
+ private let suggestion: MorphComposerSuggestion?
+ /// Whether a request can be sent while busy, into the running work.
+ private let sendsWhileBusy: Bool
+ /// Stops the running work: the send button while the composer is empty, and Esc.
+ private let onStop: (() -> Void)?
+ private let alternateSend: MorphComposerAlternateSend?
+ /// Cycles access/plan mode on Shift+Tab.
+ private let onCycleMode: (() -> Void)?
+ /// Moves highlighted popover item up (-1) or down (+1). Return true if consumed.
+ private let onMoveSelection: ((Int) -> Bool)?
+ /// Accepts the currently highlighted popover item on Return/Tab. Return true if consumed.
+ private let onAcceptSelection: (() -> Bool)?
+ /// Closes an open popover on Escape before stopping a running turn. Return true if consumed.
+ private let onDismissPopover: (() -> Bool)?
+ /// The images waiting to go with the request, drawn inside the card above the text.
+ private let attachmentTray: AnyView?
+ /// Takes images pasted or dropped on the field. Without it a paste or drop inserts text only.
+ private let imageIntake: MorphComposerImageIntake?
+ /// A drag carrying images is over the composer or the conversation it belongs to.
+ private let isDropTargeted: Bool
+ /// What the veil over the card says during that drag.
+ private let dropLabel: String
+ /// Whether the shelf shows above the card.
+ private let showsShelf: Bool
+ /// Requests waiting for the running work, drawn on the shelf plate in place of the shelf.
+ private let queueTray: AnyView?
+ /// Steps through sent requests: ↑ (-1) for an older one, ↓ (+1) back toward the draft. The field calls it only
+ /// with the caret on its first line (↑) or last line (↓). Return true if consumed.
+ private let onHistory: ((Int) -> Bool)?
+ /// Live voice dictation controls. Without it the composer shows no mic button.
+ private let dictation: MorphComposerDictation?
+ private let shelf: Shelf
+ private let leading: Leading
+ private let trailing: Trailing
+
+ static var cardRadius: CGFloat { 20 }
+ static var shelfRadius: CGFloat { 14 }
+ /// How far the card covers the shelf's bottom edge.
+ static var shelfTuck: CGFloat { 14 }
+
+ init(
+ placeholder: String,
+ text: Binding,
+ isBusy: Bool,
+ hasAttachments: Bool = false,
+ isSendBlocked: Bool = false,
+ focused: Binding,
+ suggestion: MorphComposerSuggestion? = nil,
+ sendsWhileBusy: Bool = false,
+ onStop: (() -> Void)? = nil,
+ alternateSend: MorphComposerAlternateSend? = nil,
+ onCycleMode: (() -> Void)? = nil,
+ onMoveSelection: ((Int) -> Bool)? = nil,
+ onAcceptSelection: (() -> Bool)? = nil,
+ onDismissPopover: (() -> Bool)? = nil,
+ attachmentTray: AnyView? = nil,
+ imageIntake: MorphComposerImageIntake? = nil,
+ isDropTargeted: Bool = false,
+ dropLabel: String = "이미지를 놓아 첨부하세요",
+ showsShelf: Bool = true,
+ queueTray: AnyView? = nil,
+ onHistory: ((Int) -> Bool)? = nil,
+ dictation: MorphComposerDictation? = nil,
+ onSubmit: @escaping () -> Void,
+ @ViewBuilder shelf: () -> Shelf,
+ @ViewBuilder leading: () -> Leading,
+ @ViewBuilder trailing: () -> Trailing
+ ) {
+ self.placeholder = placeholder
+ self._text = text
+ self.isBusy = isBusy
+ self.hasAttachments = hasAttachments
+ self.isSendBlocked = isSendBlocked
+ self._isFocused = focused
+ self.suggestion = suggestion
+ self.sendsWhileBusy = sendsWhileBusy
+ self.onStop = onStop
+ self.alternateSend = alternateSend
+ self.onCycleMode = onCycleMode
+ self.onMoveSelection = onMoveSelection
+ self.onAcceptSelection = onAcceptSelection
+ self.onDismissPopover = onDismissPopover
+ self.attachmentTray = attachmentTray
+ self.imageIntake = imageIntake
+ self.isDropTargeted = isDropTargeted
+ self.dropLabel = dropLabel
+ self.showsShelf = showsShelf
+ self.queueTray = queueTray
+ self.onHistory = onHistory
+ self.dictation = dictation
+ self.onSubmit = onSubmit
+ self.shelf = shelf()
+ self.leading = leading()
+ self.trailing = trailing()
+ }
+
+ private var isDictating: Bool {
+ dictation?.isActive == true
+ }
+
+ private var activePlaceholder: String {
+ switch dictation?.phase {
+ case .connecting: return "음성 인식 연결 중..."
+ case .recording: return "말씀하세요..."
+ case .finalizing: return "전사 정리 중..."
+ case .idle, nil: return placeholder
+ }
+ }
+
+ private var hasContent: Bool {
+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || hasAttachments
+ }
+
+ private var canSend: Bool {
+ (sendsWhileBusy || !isBusy) && hasContent && !isSendBlocked
+ }
+
+ /// While busy with nothing to send, the send button stops the work, as in Codex.
+ private var showsStop: Bool {
+ isBusy && onStop != nil && !hasContent
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ if let suggestion {
+ suggestionRow(suggestion)
+ .transition(.opacity.combined(with: .move(edge: .bottom)))
+ }
+ VStack(spacing: 0) {
+ if let queueTray {
+ shelfPlate {
+ queueTray
+ .padding(.horizontal, 4)
+ .padding(.top, 4)
+ }
+ .transition(.opacity.combined(with: .move(edge: .bottom)))
+ } else if showsShelf {
+ shelfRow
+ .transition(.opacity.combined(with: .move(edge: .bottom)))
+ }
+ card
+ .padding(.top, hasShelfPlate ? -Self.shelfTuck : 0)
+ }
+ }
+ .animation(AnymorphMotion.submit, value: showsShelf)
+ .animation(AnymorphMotion.submit, value: queueTray == nil)
+ .animation(AnymorphMotion.submit, value: suggestion != nil)
+ }
+
+ // MARK: Suggestion
+
+ private func suggestionRow(_ suggestion: MorphComposerSuggestion) -> some View {
+ Button(action: suggestion.action) {
+ HStack(spacing: 7) {
+ Image(systemName: suggestion.systemImage)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(suggestion.text)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ }
+ .padding(.horizontal, 8)
+ .frame(height: 28)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.md))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(.leading, 12)
+ .accessibilityHint("입력창에 채웁니다")
+ }
+
+ // MARK: Shelf
+
+ private var hasShelfPlate: Bool {
+ queueTray != nil || showsShelf
+ }
+
+ private var shelfRow: some View {
+ shelfPlate {
+ MorphComposerControlRow(spacing: 4) {
+ shelf
+ }
+ .frame(height: 30)
+ .padding(.horizontal, 8)
+ .padding(.top, 4)
+ }
+ }
+
+ /// The plate tucked behind the card's top edge, narrower than the card. It holds the shelf or the queue.
+ private func shelfPlate(@ViewBuilder _ content: () -> Content) -> some View {
+ let shape = UnevenRoundedRectangle(
+ topLeadingRadius: Self.shelfRadius,
+ bottomLeadingRadius: 0,
+ bottomTrailingRadius: 0,
+ topTrailingRadius: Self.shelfRadius,
+ style: .continuous
+ )
+ return content()
+ .padding(.bottom, Self.shelfTuck + 2)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(shape.fill(AnymorphColor.composerShelf))
+ .overlay(shape.strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ .padding(.horizontal, 14)
+ }
+
+ // MARK: Card
+
+ private var card: some View {
+ let shape = RoundedRectangle(cornerRadius: Self.cardRadius, style: .continuous)
+ return VStack(alignment: .leading, spacing: 0) {
+ if let attachmentTray {
+ attachmentTray
+ .padding(.horizontal, 12)
+ .padding(.top, 12)
+ .transition(.opacity.combined(with: .move(edge: .top)))
+ }
+
+ field
+ .frame(minHeight: 26, alignment: .topLeading)
+ .padding(.horizontal, 16)
+ .padding(.top, attachmentTray == nil ? 14 : 10)
+ .padding(.bottom, 10)
+
+ if let dictation, dictation.isActive {
+ MorphDictationControlBar(dictation: dictation)
+ .frame(height: 30)
+ .padding(.horizontal, 10)
+ .padding(.bottom, 10)
+ .transition(.opacity)
+ } else {
+ HStack(spacing: 0) {
+ MorphComposerControlRow(spacing: 1) {
+ leading
+ Spacer(minLength: 2)
+ trailing
+ }
+ .frame(height: 30)
+ if dictation != nil {
+ dictationButton
+ .padding(.leading, 10)
+ }
+ sendButton
+ .padding(.leading, dictation == nil ? 10 : 4)
+ }
+ .padding(.horizontal, 8)
+ .padding(.bottom, 10)
+ .transition(.opacity)
+ }
+ }
+ .background(shape.fill(AnymorphColor.composerCard))
+ .overlay(shape.strokeBorder((isFocused || isDictating) ? AnymorphColor.strokeStrongHairline : AnymorphColor.strokeBase, lineWidth: 1))
+ .overlay {
+ if isDropTargeted {
+ MorphComposerDropOverlay(cornerRadius: Self.cardRadius, label: dropLabel)
+ .transition(.opacity)
+ }
+ }
+ .shadow(color: AnymorphColor.composerShadow, radius: 14, x: 0, y: 4)
+ .animation(AnymorphMotion.fast, value: isFocused)
+ .animation(AnymorphMotion.fast, value: isDictating)
+ .animation(AnymorphMotion.fast, value: isDropTargeted)
+ .animation(AnymorphMotion.base, value: attachmentTray == nil)
+ }
+
+ /// The keys the field hands to the composer: Return sends (or finishes live dictation), and the popover, mode and stop keys.
+ private var keyHandlers: MorphComposerKeyHandlers {
+ MorphComposerKeyHandlers(
+ submit: {
+ if let dictation, dictation.isActive {
+ dictation.onConfirm()
+ return
+ }
+ if canSend { onSubmit() }
+ },
+ alternateSubmit: {
+ guard canSend else { return }
+ if isBusy, let alternateSend {
+ alternateSend.action()
+ } else {
+ onSubmit()
+ }
+ },
+ moveSelection: onMoveSelection,
+ acceptSelection: onAcceptSelection,
+ escape: {
+ if let dictation, dictation.isActive {
+ dictation.onCancel()
+ return true
+ }
+ if onDismissPopover?() == true { return true }
+ guard isBusy, let onStop else { return false }
+ onStop()
+ return true
+ },
+ tab: {
+ if onAcceptSelection?() == true { return true }
+ guard isBusy, canSend, let alternateSend else { return false }
+ alternateSend.action()
+ return true
+ },
+ backtab: {
+ guard let onCycleMode else { return false }
+ onCycleMode()
+ return true
+ },
+ history: onHistory
+ )
+ }
+
+ /// The mic beside the send button: a quiet monochrome glyph at rest.
+ private var dictationButton: some View {
+ Button {
+ dictation?.onStart()
+ } label: {
+ Image(systemName: "mic")
+ .font(.system(size: 15, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 28, height: 28)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxl))
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel("음성으로 입력")
+ .help("실시간 음성으로 입력")
+ }
+
+ #if os(macOS)
+ private var field: some View {
+ MorphComposerTextInput(
+ text: $text,
+ placeholder: activePlaceholder,
+ isFocused: $isFocused,
+ keys: keyHandlers,
+ images: imageIntake
+ )
+ }
+ #else
+ private var field: some View {
+ MorphComposerPhoneField(
+ placeholder: activePlaceholder,
+ text: $text,
+ isFocused: $isFocused,
+ keys: keyHandlers,
+ images: imageIntake
+ )
+ }
+ #endif
+
+ @ViewBuilder
+ private var sendButton: some View {
+ if isBusy, let onStop {
+ HStack(spacing: 6) {
+ if hasContent {
+ submitArrowButton
+ }
+ Button(action: onStop) {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxs, style: .continuous)
+ .fill(AnymorphColor.fgInverse)
+ .frame(width: 10, height: 10)
+ .frame(width: 30, height: 30)
+ .background(Circle().fill(AnymorphColor.bgInverse))
+ .contentShape(Circle())
+ }
+ .buttonStyle(MorphComposerPrimaryCircleButtonStyle())
+ .accessibilityLabel("중지")
+ .help("중지 · Esc")
+ }
+ } else {
+ submitArrowButton
+ }
+ }
+
+ private var submitArrowButton: some View {
+ Button(action: onSubmit) {
+ Image(systemName: "arrow.up")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(canSend ? AnymorphColor.fgInverse : AnymorphColor.fgQuaternary)
+ .frame(width: 30, height: 30)
+ .background(Circle().fill(canSend ? AnymorphColor.bgInverse : AnymorphColor.bgDisabled))
+ .contentShape(Circle())
+ }
+ .buttonStyle(MorphComposerPrimaryCircleButtonStyle())
+ .disabled(!canSend)
+ .accessibilityLabel("보내기")
+ .help(sendHelp)
+ .contextMenu {
+ if isBusy, canSend, let alternateSend {
+ Button(alternateSend.title, action: alternateSend.action)
+ }
+ }
+ .animation(AnymorphMotion.fast, value: canSend)
+ }
+
+ /// While busy, the send button's tooltip names the other way to send, which ⌘Return and Tab pick.
+ private var sendHelp: String {
+ guard isBusy, let alternateSend else { return "보내기" }
+ return "보내기 · ⌘↩ \(alternateSend.title)"
+ }
+}
+
+// MARK: - Composer field keys
+
+/// What the composer does with the keys a text field would handle by itself. A handler returns true if it used the key.
+struct MorphComposerKeyHandlers {
+ /// Return without a modifier.
+ var submit: () -> Void
+ /// ⌘Return: while a turn runs, sends the other way than Return (the queue when Return steers).
+ var alternateSubmit: (() -> Void)? = nil
+ /// ↑ (-1) and ↓ (+1) while a popover is open.
+ var moveSelection: ((Int) -> Bool)?
+ /// Return or Tab on the popover's highlighted row.
+ var acceptSelection: (() -> Bool)?
+ /// Esc.
+ var escape: (() -> Bool)?
+ /// Tab.
+ var tab: (() -> Bool)?
+ /// ⇧Tab.
+ var backtab: (() -> Bool)?
+ /// ↑ (-1) with the caret on the first line and ↓ (+1) with it on the last, while no popover takes the arrows:
+ /// steps through the requests sent before.
+ var history: ((Int) -> Bool)? = nil
+}
+
+/// How much a composer control shows. A control row tries its controls at each density in turn and keeps the first at
+/// which they all fit, so a model name or a mode never runs off a narrow composer.
+enum MorphComposerDensity: Comparable {
+ /// Glyph, title, detail and chevron.
+ case full
+ /// Short forms: an effort's short name, a branch without its label.
+ case short
+ /// Short forms, and the controls whose state an icon shows show only the icon.
+ case symbols
+ /// No details, and a title gives way before the row overflows.
+ case minimal
+}
+
+extension EnvironmentValues {
+ @Entry var morphComposerDensity: MorphComposerDensity = .full
+}
+
+/// Composer controls in one row, at the first `MorphComposerDensity` at which they all fit.
+private struct MorphComposerControlRow: View {
+ let spacing: CGFloat
+ let content: Content
+
+ init(spacing: CGFloat, @ViewBuilder content: () -> Content) {
+ self.spacing = spacing
+ self.content = content()
+ }
+
+ var body: some View {
+ // The row takes the width its container gives it, and `ViewThatFits` sees only that width. Containers size
+ // the composer at other widths first, and `ViewThatFits` builds the candidates it measures again for each one,
+ // many times a second while an answer streams above. An overlay is laid out at its base view's final size.
+ Color.clear
+ .overlay(alignment: .leading) {
+ ViewThatFits(in: .horizontal) {
+ row(.full)
+ row(.short)
+ row(.symbols)
+ row(.minimal)
+ }
+ }
+ }
+
+ private func row(_ density: MorphComposerDensity) -> some View {
+ HStack(spacing: spacing) {
+ content
+ }
+ .environment(\.morphComposerDensity, density)
+ }
+}
+
+/// Codex-style monochrome recording bar anchored to the composer foot while realtime dictation runs.
+/// Keeps the text field live above so transcribed words stream directly into view while the bottom bar shows
+/// status/elapsed time, a scrolling live waveform, and clean cancel (×) / confirm (✓) circle actions.
+private struct MorphDictationControlBar: View {
+ let dictation: MorphComposerDictation
+
+ var body: some View {
+ HStack(spacing: 10) {
+ statusCluster
+ .fixedSize()
+
+ MorphDictationWaveform(
+ levels: dictation.audioLevels,
+ isRecording: dictation.phase == .recording
+ )
+ .frame(maxWidth: .infinity)
+ .frame(height: 22)
+
+ HStack(spacing: 6) {
+ Button(action: dictation.onCancel) {
+ Image(systemName: "xmark")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 30, height: 30)
+ .background(Circle().fill(AnymorphColor.bgSelected))
+ .contentShape(Circle())
+ }
+ .buttonStyle(MorphComposerPrimaryCircleButtonStyle())
+ .accessibilityLabel("받아쓰기 취소")
+ .help("취소 · Esc")
+
+ Button(action: dictation.onConfirm) {
+ Group {
+ if dictation.phase == .finalizing {
+ MorphRunningDots(dotSize: 2.0, spacing: 1.8, color: AnymorphColor.fgInverse)
+ } else {
+ Image(systemName: "checkmark")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgInverse)
+ }
+ }
+ .frame(width: 30, height: 30)
+ .background(Circle().fill(AnymorphColor.bgInverse))
+ .contentShape(Circle())
+ }
+ .buttonStyle(MorphComposerPrimaryCircleButtonStyle())
+ .disabled(dictation.phase == .connecting)
+ .opacity(dictation.phase == .connecting ? 0.45 : 1.0)
+ .accessibilityLabel("받아쓰기 완료")
+ .help(dictation.phase == .finalizing ? "전사 정리 중" : "완료 · Return")
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var statusCluster: some View {
+ switch dictation.phase {
+ case .recording:
+ HStack(spacing: 6) {
+ MorphDictationLiveDot()
+ Text(formattedElapsed(dictation.elapsedSeconds))
+ .font(AnymorphFonts.font(.footnote, weight: .emphasis))
+ .monospacedDigit()
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(minWidth: 32, alignment: .leading)
+ }
+ .padding(.leading, 4)
+ case .connecting:
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 1.8)
+ Text("연결 중")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ }
+ .padding(.leading, 4)
+ case .finalizing:
+ HStack(spacing: 6) {
+ MorphRunningDots(dotSize: 2.0, spacing: 1.8)
+ Text("정리 중")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ }
+ .padding(.leading, 4)
+ case .idle:
+ EmptyView()
+ }
+ }
+
+ private func formattedElapsed(_ totalSeconds: Int) -> String {
+ let clamped = max(0, totalSeconds)
+ let minutes = clamped / 60
+ let seconds = clamped % 60
+ return String(format: "%d:%02d", minutes, seconds)
+ }
+}
+
+/// Quiet monochrome breathing dot signaling an open microphone. Holds still under Reduce Motion.
+private struct MorphDictationLiveDot: View {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var dimmed = false
+
+ var body: some View {
+ Circle()
+ .fill(AnymorphColor.fgPrimary)
+ .frame(width: 6, height: 6)
+ .opacity(reduceMotion ? 0.9 : (dimmed ? 0.3 : 0.95))
+ .onAppear {
+ guard !reduceMotion else { return }
+ withAnimation(.easeInOut(duration: 0.85).repeatForever(autoreverses: true)) {
+ dimmed = true
+ }
+ }
+ .accessibilityHidden(true)
+ }
+}
+
+/// Scrolling Codex-style monochrome vertical bar waveform driven by live microphone RMS samples.
+private struct MorphDictationWaveform: View {
+ let levels: [Double]
+ let isRecording: Bool
+
+ var body: some View {
+ Canvas { context, size in
+ guard size.width > 8, size.height > 4 else { return }
+ let barWidth: CGFloat = 2
+ let gap: CGFloat = 3
+ let step = barWidth + gap
+ let count = max(4, Int((size.width + gap) / step))
+ let totalWidth = CGFloat(count) * step - gap
+ let startX = (size.width - totalWidth) / 2
+ let centerY = size.height / 2
+ let minBarHeight: CGFloat = 2.5
+ let maxBarHeight = max(minBarHeight, size.height - 2)
+
+ for i in 0..= 0 && sampleIndex < levels.count)
+ ? levels[sampleIndex]
+ : 0
+ let clamped = min(1.0, max(0.0, rawLevel))
+ let shaped = pow(clamped, 0.85)
+ let height = minBarHeight + CGFloat(shaped) * (maxBarHeight - minBarHeight)
+ let x = startX + CGFloat(i) * step
+ let rect = CGRect(x: x, y: centerY - height / 2, width: barWidth, height: height)
+ let path = Path(roundedRect: rect, cornerRadius: barWidth / 2)
+
+ let color: Color = shaped > 0.04
+ ? AnymorphColor.fgPrimary.opacity(0.38 + 0.56 * shaped)
+ : AnymorphColor.fgQuaternary.opacity(0.75)
+ context.fill(path, with: .color(color))
+ }
+ }
+ .mask {
+ LinearGradient(
+ stops: [
+ .init(color: .clear, location: 0.0),
+ .init(color: .black, location: 0.06),
+ .init(color: .black, location: 0.94),
+ .init(color: .clear, location: 1.0),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ )
+ }
+ .accessibilityHidden(true)
+ }
+}
+
+#if os(iOS)
+/// The composer's field on iPhone and iPad: a lightweight `UITextView` wrapper that disables smart dashes/quotes
+/// (so `--flag` never corrupts to `—flag`), supports pasting images from `UIPasteboard`, and grows cleanly up to 8 lines.
+struct MorphComposerPhoneField: View {
+ let placeholder: String
+ @Binding var text: String
+ @Binding var isFocused: Bool
+ let keys: MorphComposerKeyHandlers
+ var images: MorphComposerImageIntake? = nil
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ if text.isEmpty {
+ Text(placeholder)
+ .font(AnymorphFonts.font(.reading, weight: .base))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .padding(.top, 2)
+ .allowsHitTesting(false)
+ }
+ MorphComposerUITextView(
+ text: $text,
+ isFocused: $isFocused,
+ keys: keys,
+ images: images
+ )
+ }
+ }
+}
+
+private struct MorphComposerUITextView: UIViewRepresentable {
+ @Binding var text: String
+ @Binding var isFocused: Bool
+ let keys: MorphComposerKeyHandlers
+ let images: MorphComposerImageIntake?
+
+ /// One line, and the eight lines the field grows to before it scrolls.
+ private static let minHeight: CGFloat = 24
+ private static let maxHeight: CGFloat = 176
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
+
+ func makeUIView(context: Context) -> ComposerInputTextView {
+ let tv = ComposerInputTextView()
+ tv.backgroundColor = .clear
+ tv.isScrollEnabled = false
+ tv.textContainerInset = UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0)
+ tv.textContainer.lineFragmentPadding = 0
+ tv.font = .systemFont(ofSize: 16, weight: .regular)
+ tv.textColor = UIColor(AnymorphColor.fgPrimary)
+ tv.tintColor = UIColor(AnymorphColor.fgPrimary)
+ tv.smartDashesType = .no
+ tv.smartQuotesType = .no
+ tv.autocorrectionType = .no
+ tv.autocapitalizationType = .none
+ tv.spellCheckingType = .no
+ tv.returnKeyType = .default
+ tv.delegate = context.coordinator
+ tv.keys = keys
+ tv.onPasteImages = { picked in
+ images?.attach(picked)
+ }
+ tv.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
+ tv.text = text
+ return tv
+ }
+
+ func updateUIView(_ uiView: ComposerInputTextView, context: Context) {
+ context.coordinator.parent = self
+ uiView.keys = keys
+ uiView.onPasteImages = { picked in
+ images?.attach(picked)
+ }
+ if uiView.text != text {
+ uiView.text = text
+ }
+ // The field took or gave up the keyboard itself and `isFocused` has yet to read it. An update in between
+ // still carries the old value, and acting on it would take back a keyboard the member just put away.
+ if context.coordinator.focusOnItsWay == isFocused {
+ context.coordinator.focusOnItsWay = nil
+ }
+ guard context.coordinator.focusOnItsWay == nil else { return }
+ if isFocused && !uiView.isFirstResponder {
+ DispatchQueue.main.async {
+ uiView.becomeFirstResponder()
+ }
+ } else if !isFocused && uiView.isFirstResponder {
+ DispatchQueue.main.async {
+ uiView.resignFirstResponder()
+ }
+ }
+ }
+
+ /// Sizes the field to its text within the layout pass that draws the text. Measuring afterwards and resizing on
+ /// the next turn of the run loop showed every new line for a frame inside the old height, lower than where it
+ /// settles.
+ func sizeThatFits(_ proposal: ProposedViewSize, uiView: ComposerInputTextView, context: Context) -> CGSize? {
+ let width = proposal.width ?? uiView.bounds.width
+ guard width > 0 else { return nil }
+ let fitting = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
+ let scrolls = fitting > Self.maxHeight
+ if uiView.isScrollEnabled != scrolls {
+ uiView.isScrollEnabled = scrolls
+ }
+ return CGSize(width: width, height: min(Self.maxHeight, max(Self.minHeight, ceil(fitting))))
+ }
+
+ final class Coordinator: NSObject, UITextViewDelegate {
+ var parent: MorphComposerUITextView
+ /// What the field told `isFocused` when it took or gave up the keyboard itself, until an update reads it.
+ var focusOnItsWay: Bool?
+
+ init(_ parent: MorphComposerUITextView) {
+ self.parent = parent
+ }
+
+ func textViewDidChange(_ textView: UITextView) {
+ parent.text = textView.text ?? ""
+ }
+
+ func textViewDidBeginEditing(_ textView: UITextView) {
+ if !parent.isFocused {
+ focusOnItsWay = true
+ DispatchQueue.main.async { self.parent.isFocused = true }
+ }
+ }
+
+ func textViewDidEndEditing(_ textView: UITextView) {
+ if parent.isFocused {
+ focusOnItsWay = false
+ DispatchQueue.main.async { self.parent.isFocused = false }
+ }
+ }
+ }
+}
+
+private final class ComposerInputTextView: UITextView {
+ var keys: MorphComposerKeyHandlers?
+ var onPasteImages: (([MorphPickedImage]) -> Void)?
+
+ override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) {
+ if markedTextRange == nil, let keys, let key = presses.first?.key {
+ let modifiers = key.modifierFlags.intersection([.shift, .control, .alternate, .command])
+ switch key.keyCode {
+ case .keyboardReturnOrEnter, .keypadEnter:
+ if modifiers.isEmpty {
+ if keys.acceptSelection?() == true { return }
+ keys.submit()
+ return
+ }
+ if modifiers == .command, let alternateSubmit = keys.alternateSubmit {
+ alternateSubmit()
+ return
+ }
+ case .keyboardTab:
+ if modifiers == .shift {
+ if keys.backtab?() == true { return }
+ } else if modifiers.isEmpty {
+ if keys.acceptSelection?() == true { return }
+ if keys.tab?() == true { return }
+ }
+ case .keyboardEscape:
+ if modifiers.isEmpty, keys.escape?() == true {
+ return
+ }
+ case .keyboardUpArrow:
+ if modifiers.isEmpty {
+ if keys.moveSelection?(-1) == true { return }
+ if isCaretOnFirstLine, keys.history?(-1) == true { return }
+ }
+ case .keyboardDownArrow:
+ if modifiers.isEmpty {
+ if keys.moveSelection?(1) == true { return }
+ if isCaretOnLastLine, keys.history?(1) == true { return }
+ }
+ default:
+ break
+ }
+ }
+ super.pressesBegan(presses, with: event)
+ }
+
+ private var isCaretOnFirstLine: Bool {
+ let loc = selectedRange.location
+ guard loc != NSNotFound else { return true }
+ let ns = (text ?? "") as NSString
+ let prefix = ns.substring(to: min(loc, ns.length))
+ return !prefix.contains("\n")
+ }
+
+ private var isCaretOnLastLine: Bool {
+ let end = selectedRange.location + selectedRange.length
+ guard selectedRange.location != NSNotFound else { return true }
+ let ns = (text ?? "") as NSString
+ guard end < ns.length else { return true }
+ let suffix = ns.substring(from: end)
+ return !suffix.contains("\n")
+ }
+
+ override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
+ if action == #selector(UIResponderStandardEditActions.paste(_:)),
+ let images = UIPasteboard.general.images, !images.isEmpty {
+ return true
+ }
+ return super.canPerformAction(action, withSender: sender)
+ }
+
+ override func paste(_ sender: Any?) {
+ if let images = UIPasteboard.general.images, !images.isEmpty, let onPasteImages {
+ let picked = images.compactMap { $0.pngData() }.map { MorphPickedImage.data($0, name: nil) }
+ if !picked.isEmpty {
+ onPasteImages(picked)
+ return
+ }
+ }
+ super.paste(sender)
+ }
+}
+#endif
+
+// MARK: - Borderless composer controls
+
+/// A soft plate behind a borderless composer control, shown on hover and while the control's dropdown is open.
+struct MorphComposerHoverPlate: ViewModifier {
+ var cornerRadius: CGFloat = 8
+ @State private var hovered = false
+ @Environment(\.morphDropdownIsOpen) private var isOpen
+
+ func body(content: Content) -> some View {
+ content
+ .background(
+ RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
+ .fill(hovered || isOpen ? AnymorphColor.bgHover : Color.clear)
+ )
+ .contentShape(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
+ .onHover { hovered = $0 }
+ .animation(AnymorphMotion.fast, value: hovered)
+ .animation(AnymorphMotion.fast, value: isOpen)
+ }
+}
+
+/// Tactile hover/press and pointer-cursor styling for the composer's round Send and Stop buttons.
+private struct MorphComposerPrimaryCircleButtonStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ CircleAction(configuration: configuration)
+ }
+
+ private struct CircleAction: View {
+ let configuration: Configuration
+ @State private var hovered = false
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ configuration.label
+ .opacity(isEnabled ? (configuration.isPressed ? 0.82 : (hovered ? 0.9 : 1.0)) : 1.0)
+ .scaleEffect(isEnabled && configuration.isPressed ? 0.94 : 1.0)
+ .animation(AnymorphMotion.instant, value: configuration.isPressed)
+ .animation(AnymorphMotion.fast, value: hovered)
+ .onHover { hovered = $0 }
+ .morphPointerCursor()
+ }
+ }
+}
+
+/// The icon in front of a composer control: a brand logo or an SF Symbol.
+enum MorphComposerGlyph {
+ case symbol(String)
+ case brand(MorphBrand)
+ case none
+}
+
+/// Label of a borderless composer or shelf control: glyph, title, optional quieter detail and a small chevron. In a
+/// crowded row it takes its short forms: `shortTitle` and `shortDetail` from `.short`, no detail at `.minimal`, and
+/// `collapsedSymbol` alone once the row is as crowded as `collapsesAt`.
+struct MorphComposerControlLabel: View {
+ let glyph: MorphComposerGlyph
+ let title: String
+ var detail: String? = nil
+ var shortTitle: String? = nil
+ var shortDetail: String? = nil
+ var collapsedSymbol: String? = nil
+ var collapsesAt: MorphComposerDensity = .symbols
+ var tint: Color = AnymorphColor.fgSecondary
+ var titleWeight: AnymorphFontWeight = .emphasis
+ var scale: AnymorphTypeScale = .footnote
+ var monospaced: Bool = false
+ var showsChevron: Bool = true
+ @Environment(\.morphComposerDensity) private var density
+
+ var body: some View {
+ HStack(spacing: 4) {
+ if let collapsedSymbol, density >= collapsesAt {
+ Image(systemName: collapsedSymbol)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(tint)
+ } else {
+ switch glyph {
+ case .symbol(let name):
+ Image(systemName: name)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(tint)
+ case .brand(let brand):
+ MorphBrandMark(brand, size: 12, color: tint)
+ case .none:
+ EmptyView()
+ }
+ Text(density == .full ? title : (shortTitle ?? title))
+ .anymorphText(scale, weight: titleWeight, color: tint, monospaced: monospaced)
+ .lineLimit(1)
+ if let shownDetail, !shownDetail.isEmpty {
+ Text(shownDetail)
+ .anymorphText(scale, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ if showsChevron {
+ Image(systemName: "chevron.down")
+ .font(.system(size: 7, weight: .bold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ }
+ }
+ .padding(.horizontal, 7)
+ .frame(height: 28)
+ // At the minimal density the title may truncate rather than push the row past its edge.
+ .fixedSize(horizontal: density != .minimal, vertical: true)
+ .modifier(MorphComposerHoverPlate())
+ }
+
+ private var shownDetail: String? {
+ switch density {
+ case .full: detail
+ case .short, .symbols: shortDetail ?? detail
+ case .minimal: nil
+ }
+ }
+}
+
+/// The borderless + at the start of the action bar.
+struct MorphComposerPlusLabel: View {
+ var body: some View {
+ Image(systemName: "plus")
+ .font(.system(size: 14, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 28, height: 28)
+ .modifier(MorphComposerHoverPlate(cornerRadius: AnymorphRadius.xxl))
+ }
+}
+
+/// A thin dot between shelf items.
+struct MorphShelfSeparator: View {
+ var body: some View {
+ Circle()
+ .fill(AnymorphColor.fgDisabled)
+ .frame(width: 3, height: 3)
+ .padding(.horizontal, 2)
+ }
+}
+
+// MARK: - Access mode tint
+
+extension CodeAccessMode {
+ /// Default stays muted ink; Full access reads in warm amber as Codex marks it; Plan in a quiet indigo.
+ var composerTint: Color {
+ switch self {
+ case .defaultPermissions: return AnymorphColor.fgTertiary
+ case .fullAccess: return AnymorphColor.accessFull
+ case .plan: return AnymorphColor.accessPlan
+ }
+ }
+
+ /// The mode ⇧⇥ moves to: Default permissions, Full access and Plan in turn.
+ var next: CodeAccessMode {
+ let all = Self.allCases
+ let index = all.firstIndex(of: self) ?? all.startIndex
+ return all[(index + 1) % all.count]
+ }
+}
+
+extension CodeExecutionTarget {
+ /// Short label for the composer shelf and the header: the real shared server, not a hardware SKU.
+ var shelfLabel: String {
+ switch self {
+ case .cloud: return "Cloud"
+ case .local: return "Local Mac"
+ }
+ }
+}
+
+#if os(iOS)
+/// Where the phone composer rests at the bottom of a conversation, in Morph Code, the assistant and Morph Chat.
+enum MorphComposerDock {
+ /// The composer's bottom edge sits this far above the screen's bottom while the keyboard is down,
+ /// reaching into the home indicator's strip rather than stacking a margin on top of it.
+ static let restingGap: CGFloat = 22
+ /// An unfolded iPhone Duo rests the composer lower, right on top of the home indicator, which an iPhone draws
+ /// 8 to 13 pt above the screen's bottom edge.
+ static let duoRestingGap: CGFloat = 12
+ /// The gap above the keyboard, or above the screen edge on a device without a home indicator.
+ static let keyboardGap: CGFloat = 8
+
+ /// - Parameter restingGap: How far above the screen's bottom edge the composer rests, `morphComposerRestingGap`.
+ static func bottomPadding(focused: Bool, safeArea: CGFloat, restingGap: CGFloat) -> CGFloat {
+ guard !focused, safeArea > 0 else { return keyboardGap }
+ return restingGap - safeArea
+ }
+}
+
+extension EnvironmentValues {
+ /// How far above the screen's bottom edge the composer rests while the keyboard is down: `restingGap`, or
+ /// `duoRestingGap` on an unfolded iPhone Duo.
+ @Entry var morphComposerRestingGap: CGFloat = MorphComposerDock.restingGap
+}
+#endif
diff --git a/apple/Apps/Shared/MorphComposerAttachments.swift b/apple/Apps/Shared/MorphComposerAttachments.swift
new file mode 100644
index 000000000..48dd5c24a
--- /dev/null
+++ b/apple/Apps/Shared/MorphComposerAttachments.swift
@@ -0,0 +1,372 @@
+import SwiftUI
+import UniformTypeIdentifiers
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+// MARK: - Composer attachments
+//
+// Images wait inside the composer card above the text, as Codex shows them: square tiles with rounded corners and
+// a hairline, the image filling the tile, a remove button in the corner, and a click that opens the image. Tiles
+// still being read show as quiet placeholders. A drag carrying images over the conversation or the composer lays a
+// veil over the card that says where they go.
+
+/// An image picked, pasted or dropped, before it is read and normalized.
+enum MorphPickedImage: Sendable {
+ case file(URL)
+ case data(Data, name: String?)
+}
+
+/// Where the composer sends the images a member pastes or drops on its field, and how it marks a drop on the way.
+struct MorphComposerImageIntake {
+ /// Takes the images; the field keeps nothing of them.
+ var attach: ([MorphPickedImage]) -> Void
+ /// A drag with images is over the field (true) or has left or landed (false).
+ var onDropTargetChange: (Bool) -> Void
+}
+
+/// The attachments waiting in the composer card, in the order they were added, then the images still being read.
+/// Images show as tiles, other files as chips with their kind, name and size.
+struct MorphComposerAttachmentTray: View {
+ let attachments: [CodeImageAttachment]
+ let processingCount: Int
+ let onOpen: (CodeImageAttachment) -> Void
+ let onRemove: (CodeImageAttachment) -> Void
+
+ #if os(macOS)
+ static let tileSize: CGFloat = 76
+ #else
+ static let tileSize: CGFloat = 68
+ #endif
+
+ var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 8) {
+ ForEach(attachments) { attachment in
+ Group {
+ if attachment.isImage {
+ MorphComposerImageTile(attachment: attachment, size: Self.tileSize) {
+ onOpen(attachment)
+ } onRemove: {
+ onRemove(attachment)
+ }
+ } else {
+ MorphComposerFileChip(attachment: attachment) {
+ onOpen(attachment)
+ } onRemove: {
+ onRemove(attachment)
+ }
+ }
+ }
+ .transition(.scale(scale: 0.85).combined(with: .opacity))
+ }
+ ForEach(0.. Void
+ let onRemove: () -> Void
+ @State private var thumbnail: Image?
+ @State private var hovered = false
+
+ private var shape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ }
+
+ var body: some View {
+ Button(action: onOpen) {
+ ZStack {
+ shape.fill(AnymorphColor.bgGrouped)
+ if let thumbnail {
+ thumbnail
+ .resizable()
+ .scaledToFill()
+ .frame(width: size, height: size)
+ .clipped()
+ .transition(.opacity)
+ }
+ shape.fill(hovered ? AnymorphColor.mediaTileHover : Color.clear)
+ }
+ .frame(width: size, height: size)
+ .clipShape(shape)
+ .overlay(shape.strokeBorder(hovered ? AnymorphColor.strokeStrongHairline : AnymorphColor.strokeBase, lineWidth: 1))
+ .contentShape(shape)
+ }
+ .buttonStyle(.morphPlain)
+ .overlay(alignment: .topTrailing) {
+ removeButton
+ }
+ .onHover { hovered = $0 }
+ .animation(AnymorphMotion.fast, value: hovered)
+ .help(attachment.name)
+ .accessibilityLabel("첨부한 이미지 \(attachment.name)")
+ .accessibilityHint("눌러서 크게 봅니다")
+ .accessibilityAction(named: "제거", onRemove)
+ .task(id: attachment.id) {
+ thumbnail = await MorphAttachmentThumbnails.thumbnail(for: attachment, pointSize: size)
+ }
+ }
+
+ private var removeButton: some View {
+ Button(action: onRemove) {
+ Image(systemName: "xmark")
+ .font(.system(size: 8, weight: .bold))
+ .foregroundStyle(AnymorphColor.mediaInk)
+ .frame(width: 18, height: 18)
+ .background(Circle().fill(hovered ? AnymorphColor.mediaChipFillHover : AnymorphColor.mediaChipFill))
+ .overlay(Circle().strokeBorder(AnymorphColor.mediaChipStroke, lineWidth: 0.5))
+ .contentShape(Circle().inset(by: -4))
+ }
+ .buttonStyle(.morphPlain)
+ .padding(5)
+ .help("제거")
+ .accessibilityLabel("\(attachment.name) 제거")
+ }
+}
+
+/// A file other than an image in the tray: its kind's symbol, its name and size, and a remove button.
+private struct MorphComposerFileChip: View {
+ let attachment: CodeImageAttachment
+ let onOpen: () -> Void
+ let onRemove: () -> Void
+ @State private var hovered = false
+
+ private var shape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ }
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Button(action: onOpen) {
+ HStack(spacing: 8) {
+ Image(systemName: MorphAttachmentKind.symbol(for: attachment))
+ .font(.system(size: 13, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 28, height: 28)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(attachment.name)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text(MorphAttachmentKind.detail(for: attachment))
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ .frame(maxWidth: 160, alignment: .leading)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ Button(action: onRemove) {
+ Image(systemName: "xmark")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 20, height: 20)
+ .background(Circle().fill(hovered ? AnymorphColor.bgHover : Color.clear))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.morphPlain)
+ .help("제거")
+ .accessibilityLabel("\(attachment.name) 제거")
+ }
+ .padding(.leading, 8)
+ .padding(.trailing, 6)
+ .frame(height: 46)
+ .background(shape.fill(hovered ? AnymorphColor.bgHover : AnymorphColor.bgSubtle))
+ .overlay(shape.strokeBorder(hovered ? AnymorphColor.strokeStrongHairline : AnymorphColor.strokeBase, lineWidth: 1))
+ .onHover { hovered = $0 }
+ .animation(AnymorphMotion.fast, value: hovered)
+ .help(attachment.path ?? attachment.name)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("첨부한 파일 \(attachment.name)")
+ }
+}
+
+/// How the tray names a file other than an image: a symbol for its kind and "PDF · 1.2 MB".
+enum MorphAttachmentKind {
+ private static func fileExtension(_ attachment: CodeImageAttachment) -> String {
+ (attachment.name as NSString).pathExtension.lowercased()
+ }
+
+ static func symbol(for attachment: CodeImageAttachment) -> String {
+ let ext = fileExtension(attachment)
+ let mime = attachment.mimeType.lowercased()
+ if ext == "pdf" || mime == "application/pdf" {
+ return "doc.richtext"
+ }
+ if ["csv", "tsv", "xls", "xlsx", "numbers"].contains(ext) {
+ return "tablecells"
+ }
+ if ["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar"].contains(ext) || mime.contains("zip") {
+ return "archivebox"
+ }
+ if ["md", "markdown", "txt", "log", "rtf"].contains(ext) {
+ return "doc.text"
+ }
+ if ["json", "yaml", "yml", "toml", "xml", "swift", "go", "ts", "tsx", "js", "jsx", "py", "rs", "sh", "sql",
+ "java", "kt", "c", "h", "cpp", "rb", "css", "html"].contains(ext) || mime == "application/json" {
+ return "curlybraces"
+ }
+ return "doc"
+ }
+
+ static func detail(for attachment: CodeImageAttachment) -> String {
+ let ext = fileExtension(attachment)
+ let kind = ext.isEmpty ? "파일" : ext.uppercased()
+ guard let size = attachment.sizeBytes else { return kind }
+ return "\(kind) · \(ByteCountFormatter.string(fromByteCount: size, countStyle: .file))"
+ }
+}
+
+/// A tile for an image still being read or resized.
+private struct MorphComposerImagePlaceholder: View {
+ let size: CGFloat
+
+ var body: some View {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous)
+ .fill(AnymorphColor.bgGrouped)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.xl, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ .overlay { ProgressView().controlSize(.small) }
+ .frame(width: size, height: size)
+ .accessibilityLabel("이미지 읽는 중")
+ }
+}
+
+/// Small pictures of composer attachments, made off the main thread once per attachment.
+@MainActor
+enum MorphAttachmentThumbnails {
+ private static var cache: [String: Image] = [:]
+
+ static func thumbnail(for attachment: CodeImageAttachment, pointSize: CGFloat) async -> Image? {
+ if let cached = cache[attachment.id] {
+ return cached
+ }
+ guard let base64 = attachment.dataBase64 else { return nil }
+ // Three pixels a point covers every display at the tile's size.
+ let pixels = Int(pointSize * 3)
+ let cgImage = await Task.detached(priority: .userInitiated) { () -> CGImage? in
+ guard let data = Data(base64Encoded: base64) else { return nil }
+ return CodeImageNormalizer.thumbnail(data, maxPixelSize: pixels)
+ }.value
+ guard let cgImage else { return nil }
+ let image = Image(decorative: cgImage, scale: 1)
+ if cache.count > 64 {
+ cache.removeAll()
+ }
+ cache[attachment.id] = image
+ return image
+ }
+}
+
+/// The veil over the composer card while a drag carrying images or files is over the conversation or the composer.
+struct MorphComposerDropOverlay: View {
+ let cornerRadius: CGFloat
+ var label = "이미지를 놓아 첨부하세요"
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
+ shape
+ .fill(AnymorphColor.composerCard.opacity(0.94))
+ .overlay(shape.strokeBorder(AnymorphColor.strokeStrong, lineWidth: 1.5))
+ .overlay {
+ HStack(spacing: 7) {
+ Image(systemName: "photo.badge.plus")
+ .font(.system(size: 13, weight: .medium))
+ Text(label)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ }
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .padding(.horizontal, 14)
+ .frame(height: 32)
+ .background(Capsule().fill(AnymorphColor.menuSurface))
+ .overlay(Capsule().strokeBorder(AnymorphColor.menuStroke, lineWidth: 1))
+ .shadow(color: AnymorphColor.composerShadow, radius: 10, x: 0, y: 3)
+ }
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+}
+
+/// Takes images and files dropped anywhere on the Morph Code workspace outside the composer's field, which takes its
+/// own. A file comes as `.file`, whether or not it is an image; the receiver sorts them.
+struct MorphImageDropDelegate: DropDelegate {
+ @Binding var isTargeted: Bool
+ let attach: ([MorphPickedImage]) -> Void
+
+ static let acceptedTypes: [UTType] = [.fileURL, .image]
+
+ /// Image data or any file.
+ func validateDrop(info: DropInfo) -> Bool {
+ info.hasItemsConforming(to: Self.acceptedTypes)
+ }
+
+ func dropEntered(info: DropInfo) {
+ isTargeted = validateDrop(info: info)
+ }
+
+ func dropUpdated(info: DropInfo) -> DropProposal? {
+ validateDrop(info: info) ? DropProposal(operation: .copy) : nil
+ }
+
+ func dropExited(info: DropInfo) {
+ isTargeted = false
+ }
+
+ func performDrop(info: DropInfo) -> Bool {
+ isTargeted = false
+ let providers = info.itemProviders(for: Self.acceptedTypes)
+ guard !providers.isEmpty else { return false }
+ Task { @MainActor in
+ var picked: [MorphPickedImage] = []
+ for provider in providers {
+ if let image = await Self.load(provider) {
+ picked.append(image)
+ }
+ }
+ if !picked.isEmpty {
+ attach(picked)
+ }
+ }
+ return true
+ }
+
+ /// A dropped file as is, else the image the provider writes out.
+ private static func load(_ provider: NSItemProvider) async -> MorphPickedImage? {
+ if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier),
+ let url = await loadFileURL(provider) {
+ return .file(url)
+ }
+ guard let type = provider.registeredTypeIdentifiers.compactMap(UTType.init).first(where: { $0.conforms(to: .image) }) else {
+ return nil
+ }
+ let name = provider.suggestedName
+ return await withCheckedContinuation { continuation in
+ _ = provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in
+ continuation.resume(returning: data.map { .data($0, name: name) })
+ }
+ }
+ }
+
+ private static func loadFileURL(_ provider: NSItemProvider) async -> URL? {
+ await withCheckedContinuation { continuation in
+ _ = provider.loadObject(ofClass: URL.self) { url, _ in
+ continuation.resume(returning: url?.isFileURL == true ? url : nil)
+ }
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphComposerTextInput.swift b/apple/Apps/Shared/MorphComposerTextInput.swift
new file mode 100644
index 000000000..719425b84
--- /dev/null
+++ b/apple/Apps/Shared/MorphComposerTextInput.swift
@@ -0,0 +1,637 @@
+#if os(macOS)
+import SwiftUI
+import AppKit
+import UniformTypeIdentifiers
+import MorphCore
+
+// MARK: - Composer text input on the Mac
+//
+// The composer's field is an NSTextView rather than a SwiftUI TextField, because a text field keeps pastes and drops
+// to itself: ⌘V reaches the Edit menu's Paste before any SwiftUI key handler, and a file dropped on the field turns
+// into its path. The text view takes an image from either, as Codex's composer does, and leaves text to the usual
+// paste. It also owns Return (send), ⇧Return and ⌥Return (new line), ↑ ↓ and Tab for the open popover, ↑ on the
+// first line and ↓ on the last for sent-request history, ⇧Tab and Esc.
+
+/// Reads images from a pasteboard the way `CodeImagePasteDecision` rules.
+enum MorphPasteboardImages {
+ /// Image data types in the order they are read: lossless first, TIFF (what the Mac clipboard often holds) last.
+ static let imageTypes: [NSPasteboard.PasteboardType] = [
+ .png,
+ NSPasteboard.PasteboardType(UTType.jpeg.identifier),
+ NSPasteboard.PasteboardType(UTType.heic.identifier),
+ NSPasteboard.PasteboardType(UTType.gif.identifier),
+ NSPasteboard.PasteboardType(UTType.webP.identifier),
+ .tiff,
+ ]
+
+ static func decision(_ pasteboard: NSPasteboard) -> CodeImagePasteDecision {
+ let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
+ return CodeImagePasteDecision.decide(
+ fileURLs: urls,
+ hasImageData: pasteboard.availableType(from: imageTypes) != nil,
+ plainText: pasteboard.string(forType: .string)
+ )
+ }
+
+ /// The images a paste or drop should attach, or nil when it should insert text.
+ static func images(_ pasteboard: NSPasteboard) -> [MorphPickedImage]? {
+ switch decision(pasteboard) {
+ case .text:
+ return nil
+ case .imageFiles(let urls):
+ return urls.map { .file($0) }
+ case .imageData:
+ guard let type = pasteboard.availableType(from: imageTypes), let data = pasteboard.data(forType: type) else {
+ return nil
+ }
+ return [.data(data, name: nil)]
+ }
+ }
+
+ /// Every image the pasteboard holds, text or not: what the + menu's paste attaches.
+ static func anyImages(_ pasteboard: NSPasteboard) -> [MorphPickedImage]? {
+ if case .imageFiles(let urls) = decision(pasteboard) {
+ return urls.map { .file($0) }
+ }
+ guard let type = pasteboard.availableType(from: imageTypes), let data = pasteboard.data(forType: type) else {
+ return nil
+ }
+ return [.data(data, name: nil)]
+ }
+
+ /// Files a drag promises to write (Photos, a browser's image, the screenshot thumbnail) that are images.
+ static func imagePromises(_ pasteboard: NSPasteboard) -> [NSFilePromiseReceiver] {
+ let receivers = pasteboard.readObjects(forClasses: [NSFilePromiseReceiver.self], options: nil) as? [NSFilePromiseReceiver] ?? []
+ return receivers.filter { receiver in
+ receiver.fileTypes.contains { UTType($0)?.conforms(to: .image) ?? false }
+ }
+ }
+
+ static func hasImages(_ pasteboard: NSPasteboard) -> Bool {
+ images(pasteboard) != nil || !imagePromises(pasteboard).isEmpty
+ }
+
+ /// Writes the promised images into a fresh temporary folder and hands their URLs over on the main thread.
+ static func receive(_ promises: [NSFilePromiseReceiver], then attach: @escaping @MainActor ([MorphPickedImage]) -> Void) {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("morph-drop-\(UUID().uuidString)", isDirectory: true)
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let queue = OperationQueue()
+ let group = DispatchGroup()
+ let received = ReceivedFiles()
+ for promise in promises {
+ group.enter()
+ promise.receivePromisedFiles(atDestination: folder, options: [:], operationQueue: queue) { url, error in
+ if error == nil {
+ received.append(url)
+ }
+ group.leave()
+ }
+ }
+ group.notify(queue: .main) {
+ let picked = received.urls.sorted { $0.lastPathComponent < $1.lastPathComponent }.map { MorphPickedImage.file($0) }
+ MainActor.assumeIsolated {
+ attach(picked)
+ }
+ }
+ }
+
+ /// The files a drop's promises wrote, collected from the queue they arrive on.
+ private final class ReceivedFiles: @unchecked Sendable {
+ private let lock = NSLock()
+ private var stored: [URL] = []
+
+ var urls: [URL] {
+ lock.withLock { stored }
+ }
+
+ func append(_ url: URL) {
+ lock.withLock { stored.append(url) }
+ }
+ }
+}
+
+/// The composer's text field on the Mac: an NSTextView in a scroll view that grows from one line to `maxLines`.
+struct MorphComposerTextInput: NSViewRepresentable {
+ @Binding var text: String
+ let placeholder: String
+ @Binding var isFocused: Bool
+ var maxLines: Int = 8
+ /// The field's height with one line, so a short request keeps the card's resting height.
+ var minHeight: CGFloat = 26
+ var keys: MorphComposerKeyHandlers
+ var images: MorphComposerImageIntake?
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
+
+ func makeNSView(context: Context) -> NSScrollView {
+ let storage = NSTextStorage()
+ let layout = NSLayoutManager()
+ storage.addLayoutManager(layout)
+ let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
+ container.widthTracksTextView = true
+ container.lineFragmentPadding = 0
+ layout.addTextContainer(container)
+
+ let textView = MorphComposerNSTextView(frame: .zero, textContainer: container)
+ textView.configure(font: Self.font, color: Self.textColor)
+ textView.delegate = context.coordinator
+ textView.coordinator = context.coordinator
+ textView.placeholder = placeholder
+ textView.string = text
+
+ let scroll = MorphComposerScrollView()
+ scroll.drawsBackground = false
+ scroll.contentView.drawsBackground = false
+ scroll.borderType = .noBorder
+ scroll.hasVerticalScroller = true
+ scroll.hasHorizontalScroller = false
+ scroll.autohidesScrollers = true
+ scroll.scrollerStyle = .overlay
+ scroll.horizontalScrollElasticity = .none
+ scroll.verticalScrollElasticity = .none
+ scroll.documentView = textView
+ textView.autoresizingMask = [.width]
+ return scroll
+ }
+
+ func updateNSView(_ scroll: NSScrollView, context: Context) {
+ context.coordinator.parent = self
+ guard let textView = scroll.documentView as? MorphComposerNSTextView else { return }
+ let isEnabled = context.environment.isEnabled
+ if scroll.isHidden == isEnabled {
+ scroll.isHidden = !isEnabled
+ }
+ if textView.isEditable != isEnabled {
+ textView.isEditable = isEnabled
+ }
+ if textView.isSelectable != isEnabled {
+ textView.isSelectable = isEnabled
+ }
+ if textView.string != text, !textView.hasMarkedText() {
+ // A send, a mention or an edit put new text in the field: the caret goes to its end, and the field's
+ // undo history, which refers to the text it replaced, starts over.
+ context.coordinator.undo.removeAllActions()
+ textView.string = text
+ textView.invalidateFittingHeightCache()
+ textView.setSelectedRange(NSRange(location: (text as NSString).length, length: 0))
+ textView.scrollRangeToVisible(textView.selectedRange())
+ scroll.invalidateIntrinsicContentSize()
+ }
+ if textView.placeholder != placeholder {
+ textView.placeholder = placeholder
+ }
+ if !isEnabled {
+ if let window = textView.window, window.firstResponder === textView {
+ DispatchQueue.main.async { [weak textView] in
+ guard let textView, let window = textView.window, window.firstResponder === textView else { return }
+ window.makeFirstResponder(nil)
+ }
+ }
+ } else if isFocused, let window = textView.window, window.firstResponder !== textView {
+ // Focus moves after SwiftUI's update, since changing the responder during one updates SwiftUI again.
+ DispatchQueue.main.async { [weak textView] in
+ guard let textView, textView.isEditable, let window = textView.window, window.firstResponder !== textView else { return }
+ window.makeFirstResponder(textView)
+ }
+ }
+ }
+
+ func sizeThatFits(_ proposal: ProposedViewSize, nsView scroll: NSScrollView, context: Context) -> CGSize? {
+ guard let textView = scroll.documentView as? MorphComposerNSTextView else { return nil }
+ let width = proposal.width ?? scroll.bounds.width
+ guard width.isFinite, width > 0 else { return nil }
+ return CGSize(width: width, height: textView.fittingHeight(width: width, maxLines: maxLines, minHeight: minHeight))
+ }
+
+ static var font: NSFont {
+ .systemFont(ofSize: AnymorphTypeScale.reading.size)
+ }
+
+ /// `foreground.primary` for AppKit: #161616 on light, #FAFAFA on dark.
+ static let textColor = NSColor(name: nil) { appearance in
+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ ? NSColor(srgbRed: 0.98, green: 0.98, blue: 0.98, alpha: 1)
+ : NSColor(srgbRed: 0.086, green: 0.086, blue: 0.086, alpha: 1)
+ }
+
+ @MainActor
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ var parent: MorphComposerTextInput
+ /// The field's own undo history, apart from the window's.
+ let undo = UndoManager()
+
+ init(_ parent: MorphComposerTextInput) {
+ self.parent = parent
+ }
+
+ func undoManager(for view: NSTextView) -> UndoManager? {
+ undo
+ }
+
+ func textDidChange(_ notification: Notification) {
+ guard let textView = notification.object as? NSTextView else { return }
+ if parent.text != textView.string {
+ parent.text = textView.string
+ }
+ textView.enclosingScrollView?.invalidateIntrinsicContentSize()
+ }
+
+ func focusChanged(_ focused: Bool) {
+ if parent.isFocused != focused {
+ parent.isFocused = focused
+ }
+ }
+
+ func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
+ let keys = parent.keys
+ switch selector {
+ case #selector(NSResponder.insertNewline(_:)):
+ let flags = NSApp.currentEvent?.modifierFlags.intersection(.deviceIndependentFlagsMask) ?? []
+ if flags.contains(.shift) || flags.contains(.option) {
+ textView.insertNewlineIgnoringFieldEditor(nil)
+ return true
+ }
+ if keys.acceptSelection?() == true {
+ return true
+ }
+ keys.submit()
+ return true
+ case #selector(NSResponder.moveUp(_:)):
+ if keys.moveSelection?(-1) == true { return true }
+ // History only from the first line, so ↑ still moves through a multi-line request.
+ guard let history = keys.history,
+ let field = textView as? MorphComposerNSTextView,
+ field.caretIsOnFirstLine else { return false }
+ return history(-1)
+ case #selector(NSResponder.moveDown(_:)):
+ if keys.moveSelection?(1) == true { return true }
+ guard let history = keys.history,
+ let field = textView as? MorphComposerNSTextView,
+ field.caretIsOnLastLine else { return false }
+ return history(1)
+ case #selector(NSResponder.cancelOperation(_:)):
+ // NSTextView answers Esc with its word-completion list; the composer has none.
+ _ = keys.escape?()
+ return true
+ case #selector(NSResponder.insertTab(_:)):
+ if keys.tab?() == true { return true }
+ textView.window?.selectNextKeyView(nil)
+ return true
+ case #selector(NSResponder.insertBacktab(_:)):
+ if keys.backtab?() == true { return true }
+ textView.window?.selectPreviousKeyView(nil)
+ return true
+ default:
+ return false
+ }
+ }
+
+ // MARK: Images
+
+ /// A paste with images attaches them; anything else pastes as text.
+ func paste(from pasteboard: NSPasteboard) -> Bool {
+ guard let intake = parent.images, let picked = MorphPasteboardImages.images(pasteboard) else { return false }
+ intake.attach(picked)
+ return true
+ }
+
+ func canPaste(from pasteboard: NSPasteboard) -> Bool {
+ parent.images != nil && MorphPasteboardImages.images(pasteboard) != nil
+ }
+
+ func canDrop(_ pasteboard: NSPasteboard) -> Bool {
+ parent.images != nil && MorphPasteboardImages.hasImages(pasteboard)
+ }
+
+ func drop(_ pasteboard: NSPasteboard) -> Bool {
+ guard let intake = parent.images else { return false }
+ intake.onDropTargetChange(false)
+ if let picked = MorphPasteboardImages.images(pasteboard) {
+ intake.attach(picked)
+ return true
+ }
+ let promises = MorphPasteboardImages.imagePromises(pasteboard)
+ guard !promises.isEmpty else { return false }
+ MorphPasteboardImages.receive(promises) { picked in
+ intake.attach(picked)
+ }
+ return true
+ }
+
+ func dropTargetChanged(_ targeted: Bool) {
+ parent.images?.onDropTargetChange(targeted)
+ }
+ }
+}
+
+/// The field's scroll view. The text view fills at least its visible height, so a click anywhere in the field
+/// puts the caret in the text.
+final class MorphComposerScrollView: NSScrollView {
+ override func layout() {
+ super.layout()
+ guard let textView = documentView as? NSTextView else { return }
+ let height = contentSize.height
+ if abs(textView.minSize.height - height) > 0.5 {
+ textView.minSize = NSSize(width: 0, height: height)
+ textView.sizeToFit()
+ }
+ }
+}
+
+/// The text view behind `MorphComposerTextInput`: plain text, a drawn placeholder, and images taken from pastes and drops.
+final class MorphComposerNSTextView: NSTextView {
+ weak var coordinator: MorphComposerTextInput.Coordinator?
+ var placeholder = "" {
+ didSet {
+ guard oldValue != placeholder else { return }
+ needsDisplay = true
+ setAccessibilityPlaceholderValue(placeholder)
+ }
+ }
+ private var isDropTargeted = false
+
+ private struct FittingHeightCache {
+ var text: String
+ var width: CGFloat
+ var maxLines: Int
+ var minHeight: CGFloat
+ var fontName: String
+ var fontSize: CGFloat
+ var height: CGFloat
+ }
+ private var fittingCache: FittingHeightCache?
+
+ /// Detached offscreen layout scratchpad used when SwiftUI/AppKit probes `sizeThatFits` at a hypothetical width
+ /// (such as `NSHostingView.updateConstraints` -> `minSize()`). Never attached to a view or window, so probing
+ /// never mutates the live `NSTextContainer` or invalidates layout/display in an infinite DisplayLink cycle.
+ @MainActor
+ private final class OffscreenMeasurer {
+ static let shared = OffscreenMeasurer()
+ let storage = NSTextStorage()
+ let layout = NSLayoutManager()
+ let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
+
+ private init() {
+ storage.addLayoutManager(layout)
+ container.widthTracksTextView = false
+ container.lineFragmentPadding = 0
+ layout.addTextContainer(container)
+ }
+
+ func measureHeight(text: String, font: NSFont, width: CGFloat, lineFragmentPadding: CGFloat) -> CGFloat {
+ container.lineFragmentPadding = lineFragmentPadding
+ container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
+ storage.beginEditing()
+ storage.replaceCharacters(in: NSRange(location: 0, length: storage.length), with: text)
+ storage.setAttributes([.font: font], range: NSRange(location: 0, length: storage.length))
+ storage.endEditing()
+ layout.ensureLayout(for: container)
+ return layout.usedRect(for: container).height
+ }
+ }
+
+ func invalidateFittingHeightCache() {
+ fittingCache = nil
+ }
+
+ func configure(font: NSFont, color: NSColor) {
+ isRichText = false
+ importsGraphics = false
+ allowsImageEditing = false
+ usesFontPanel = false
+ allowsUndo = true
+ drawsBackground = false
+ self.font = font
+ textColor = color
+ insertionPointColor = color
+ typingAttributes = [.font: font, .foregroundColor: color]
+ textContainerInset = .zero
+ isVerticallyResizable = true
+ isHorizontallyResizable = false
+ minSize = .zero
+ maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
+ // A request often holds code: no curly quotes, dashes, replacements or corrections.
+ isAutomaticQuoteSubstitutionEnabled = false
+ isAutomaticDashSubstitutionEnabled = false
+ isAutomaticTextReplacementEnabled = false
+ isAutomaticSpellingCorrectionEnabled = false
+ isAutomaticTextCompletionEnabled = false
+ isContinuousSpellCheckingEnabled = false
+ isGrammarCheckingEnabled = false
+ isAutomaticLinkDetectionEnabled = false
+ isAutomaticDataDetectionEnabled = false
+ smartInsertDeleteEnabled = false
+ updateDragTypeRegistration()
+ }
+
+ /// The height the field takes at `width`: its lines, at least `minHeight`, at most `maxLines` lines.
+ /// Never mutates the live `textContainer.size`: probing a hypothetical width (e.g. `NSHostingView.minSize()`)
+ /// uses a detached offscreen layout manager so AppKit never re-dirties constraints, layout or display.
+ func fittingHeight(width: CGFloat, maxLines: Int, minHeight: CGFloat) -> CGFloat {
+ let activeFont = font ?? MorphComposerTextInput.font
+ let lineHeight = layoutManager?.defaultLineHeight(for: activeFont) ?? ceil(activeFont.ascender - activeFont.descender + activeFont.leading)
+ let maxHeight = ceil(lineHeight * CGFloat(maxLines))
+ if string.isEmpty {
+ return min(max(ceil(lineHeight), minHeight), maxHeight)
+ }
+ let quantizedWidth = (width * 2).rounded() / 2
+ if let cache = fittingCache,
+ cache.maxLines == maxLines,
+ abs(cache.width - quantizedWidth) < 0.25,
+ abs(cache.minHeight - minHeight) < 0.25,
+ cache.fontSize == activeFont.pointSize,
+ cache.fontName == activeFont.fontName,
+ cache.text == string {
+ return cache.height
+ }
+ let used: CGFloat
+ if let container = textContainer, let layout = layoutManager, abs(container.size.width - width) <= 0.5 {
+ layout.ensureLayout(for: container)
+ used = layout.usedRect(for: container).height
+ } else {
+ used = OffscreenMeasurer.shared.measureHeight(
+ text: string,
+ font: activeFont,
+ width: width,
+ lineFragmentPadding: textContainer?.lineFragmentPadding ?? 0
+ )
+ }
+ let result = min(max(ceil(used), minHeight), maxHeight)
+ fittingCache = FittingHeightCache(
+ text: string,
+ width: quantizedWidth,
+ maxLines: maxLines,
+ minHeight: minHeight,
+ fontName: activeFont.fontName,
+ fontSize: activeFont.pointSize,
+ height: result
+ )
+ return result
+ }
+
+ // MARK: Caret line
+
+ /// Whether the caret, with nothing selected, sits on the field's first visual line, wrapped lines included.
+ var caretIsOnFirstLine: Bool {
+ guard let caret = caretLineRect() else { return false }
+ guard !string.isEmpty, let layout = layoutManager, layout.numberOfGlyphs > 0 else { return true }
+ let first = layout.lineFragmentRect(forGlyphAt: 0, effectiveRange: nil)
+ return caret.minY <= first.minY + 0.5
+ }
+
+ /// Whether the caret, with nothing selected, sits on the field's last visual line, wrapped lines included.
+ var caretIsOnLastLine: Bool {
+ guard let caret = caretLineRect() else { return false }
+ guard !string.isEmpty, let layout = layoutManager, layout.numberOfGlyphs > 0 else { return true }
+ let last = layout.extraLineFragmentRect.isEmpty
+ ? layout.lineFragmentRect(forGlyphAt: layout.numberOfGlyphs - 1, effectiveRange: nil)
+ : layout.extraLineFragmentRect
+ return caret.maxY >= last.maxY - 0.5
+ }
+
+ /// The line fragment holding the caret, or nil while text is selected or marked.
+ private func caretLineRect() -> NSRect? {
+ let selection = selectedRange()
+ guard selection.length == 0, !hasMarkedText(), let layout = layoutManager, let container = textContainer else {
+ return nil
+ }
+ layout.ensureLayout(for: container)
+ let length = (string as NSString).length
+ guard length > 0, layout.numberOfGlyphs > 0 else { return .zero }
+ if selection.location >= length {
+ // After a trailing newline the caret is on the empty line below the text.
+ if !layout.extraLineFragmentRect.isEmpty {
+ return layout.extraLineFragmentRect
+ }
+ return layout.lineFragmentRect(forGlyphAt: layout.glyphIndexForCharacter(at: length - 1), effectiveRange: nil)
+ }
+ return layout.lineFragmentRect(forGlyphAt: layout.glyphIndexForCharacter(at: selection.location), effectiveRange: nil)
+ }
+
+ // MARK: Keys
+
+ /// ⌘Return has no text command for `doCommandBy` to see, so the field takes it here.
+ override func keyDown(with event: NSEvent) {
+ let flags = event.modifierFlags.intersection([.shift, .control, .option, .command])
+ let isReturn = event.keyCode == 36 || event.keyCode == 76
+ if isReturn, flags == .command, !hasMarkedText(), let alternateSubmit = coordinator?.parent.keys.alternateSubmit {
+ alternateSubmit()
+ return
+ }
+ super.keyDown(with: event)
+ }
+
+ // MARK: Focus
+
+ override func becomeFirstResponder() -> Bool {
+ let became = super.becomeFirstResponder()
+ if became { coordinator?.focusChanged(true) }
+ return became
+ }
+
+ override func resignFirstResponder() -> Bool {
+ let resigned = super.resignFirstResponder()
+ if resigned { coordinator?.focusChanged(false) }
+ return resigned
+ }
+
+ // MARK: Placeholder
+
+ override func draw(_ dirtyRect: NSRect) {
+ super.draw(dirtyRect)
+ guard string.isEmpty, !hasMarkedText(), !placeholder.isEmpty else { return }
+ let attributes: [NSAttributedString.Key: Any] = [
+ .font: font ?? MorphComposerTextInput.font,
+ .foregroundColor: NSColor.placeholderTextColor,
+ ]
+ let origin = NSPoint(x: textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0), y: textContainerOrigin.y)
+ NSAttributedString(string: placeholder, attributes: attributes).draw(at: origin)
+ }
+
+ override func didChangeText() {
+ super.didChangeText()
+ invalidateFittingHeightCache()
+ // The placeholder comes and goes with the first character.
+ needsDisplay = true
+ }
+
+ // MARK: Paste
+
+ /// Paste stays on for a clipboard that holds only an image, such as a screenshot, which a plain-text view
+ /// would grey out.
+ override func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
+ if item.action == #selector(paste(_:)), coordinator?.canPaste(from: .general) == true {
+ return true
+ }
+ return super.validateUserInterfaceItem(item)
+ }
+
+ override func paste(_ sender: Any?) {
+ if coordinator?.paste(from: .general) == true { return }
+ pasteAsPlainText(sender)
+ }
+
+ override func pasteAsRichText(_ sender: Any?) {
+ paste(sender)
+ }
+
+ // MARK: Drop
+
+ override var acceptableDragTypes: [NSPasteboard.PasteboardType] {
+ var types = super.acceptableDragTypes
+ let promised = NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }
+ for type in MorphPasteboardImages.imageTypes + [.fileURL] + promised where !types.contains(type) {
+ types.append(type)
+ }
+ return types
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ if coordinator?.canDrop(sender.draggingPasteboard) == true {
+ setDropTargeted(true)
+ return .copy
+ }
+ return super.draggingEntered(sender)
+ }
+
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ if isDropTargeted {
+ return .copy
+ }
+ return super.draggingUpdated(sender)
+ }
+
+ override func draggingExited(_ sender: NSDraggingInfo?) {
+ setDropTargeted(false)
+ super.draggingExited(sender)
+ }
+
+ override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ isDropTargeted ? true : super.prepareForDragOperation(sender)
+ }
+
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ guard isDropTargeted else { return super.performDragOperation(sender) }
+ isDropTargeted = false
+ return coordinator?.drop(sender.draggingPasteboard) ?? false
+ }
+
+ override func concludeDragOperation(_ sender: NSDraggingInfo?) {
+ setDropTargeted(false)
+ super.concludeDragOperation(sender)
+ }
+
+ override func draggingEnded(_ sender: NSDraggingInfo) {
+ setDropTargeted(false)
+ super.draggingEnded(sender)
+ }
+
+ private func setDropTargeted(_ targeted: Bool) {
+ guard isDropTargeted != targeted else { return }
+ isDropTargeted = targeted
+ coordinator?.dropTargetChanged(targeted)
+ }
+}
+#endif
diff --git a/apple/Apps/Shared/MorphConversationScroll.swift b/apple/Apps/Shared/MorphConversationScroll.swift
new file mode 100644
index 000000000..04c735541
--- /dev/null
+++ b/apple/Apps/Shared/MorphConversationScroll.swift
@@ -0,0 +1,141 @@
+import SwiftUI
+import MorphCore
+
+/// Keeps a conversation on its latest message the way a chat is expected to behave.
+///
+/// It opens at the bottom and stays there while an answer streams, an image loads, the keyboard comes up or the
+/// composer grows. The moment the member scrolls up it stops following, and nothing that arrives afterwards moves the
+/// view until the member scrolls back to the bottom or taps the round button. Sending a message and opening another
+/// conversation always go to the latest message.
+///
+/// Whether the member scrolled is read from where the view went, never from why the layout changed: while an answer
+/// streams, new content and a scroll arrive in the same step, and the scroll has to win. The owner of the scroll view
+/// must not scroll to the bottom on new content itself, or it drags a member who is reading older messages back down.
+/// When `animatedScrollTrigger` increments (on prompt submission), layout growth glides smoothly upward with
+/// `AnymorphMotion.submit` instead of snapping, coalescing redundant geometry ticks so the spring never restarts.
+struct MorphConversationScroll: ViewModifier {
+ /// Holds per-frame scroll metrics and phase outside SwiftUI `@State` so geometry ticks while scrolling never
+ /// invalidate `MorphConversationScroll.body`; only transitions of `followsLatest` redraw the floating button.
+ private final class ScrollStateBox {
+ var policy = ConversationScrollPolicy()
+ var scrollPhase: ScrollPhase = .idle
+
+ var isUserInteracting: Bool {
+ switch scrollPhase {
+ case .tracking, .interacting, .decelerating:
+ return true
+ case .idle, .animating:
+ return false
+ }
+ }
+ }
+
+ @Binding var position: ScrollPosition
+ var conversationID: String
+ var animatedScrollTrigger: Int = 0
+ @State private var box = ScrollStateBox()
+ @State private var followsLatest = true
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ private func syncFollowsLatest() {
+ let next = box.policy.followsLatest
+ if followsLatest != next {
+ followsLatest = next
+ }
+ }
+
+ private func execute(_ command: ConversationScrollPolicy.Command, animation: Animation = AnymorphMotion.submit) {
+ switch command {
+ case .none:
+ return
+ case .jumpToBottom:
+ position.scrollTo(edge: .bottom)
+ case .animateToBottom:
+ withAnimation(animation) {
+ position.scrollTo(edge: .bottom)
+ }
+ }
+ }
+
+ func body(content: Content) -> some View {
+ content
+ .scrollPosition($position)
+ .defaultScrollAnchor(.bottom, for: .initialOffset)
+ .onScrollPhaseChange { _, newPhase in
+ box.scrollPhase = newPhase
+ }
+ .onChange(of: conversationID) { _, _ in
+ let command = box.policy.conversationChanged()
+ syncFollowsLatest()
+ execute(command)
+ }
+ .onChange(of: animatedScrollTrigger) { _, _ in
+ let command = box.policy.submitTriggered(now: Date(), reduceMotion: reduceMotion)
+ syncFollowsLatest()
+ execute(command)
+ }
+ .onScrollGeometryChange(for: ConversationScrollPolicy.Metrics.self) { geometry in
+ ConversationScrollPolicy.Metrics(
+ contentHeight: Double(geometry.contentSize.height),
+ containerHeight: Double(geometry.containerSize.height),
+ topInset: Double(geometry.contentInsets.top),
+ bottomInset: Double(geometry.contentInsets.bottom),
+ offset: Double(geometry.contentOffset.y),
+ // How far the content runs on below what the member sees. The container size leaves out the
+ // insets (the composer, the safe area) and the offset counts from minus the top inset, so the
+ // part the insets leave uncovered ends at offset + top inset + container height. Less than zero
+ // while the view is pulled past the bottom.
+ distanceFromBottom: Double(
+ geometry.contentSize.height
+ - (geometry.contentOffset.y + geometry.contentInsets.top + geometry.containerSize.height)
+ )
+ )
+ } action: { old, new in
+ let command = box.policy.geometryChanged(
+ from: old,
+ to: new,
+ now: Date(),
+ isUserInteracting: box.isUserInteracting,
+ isProgrammaticAnimating: box.scrollPhase == .animating,
+ reduceMotion: reduceMotion
+ )
+ syncFollowsLatest()
+ execute(command)
+ }
+ .overlay(alignment: .bottom) {
+ Group {
+ if !followsLatest {
+ Button {
+ let command = box.policy.jumpToLatestTapped(reduceMotion: reduceMotion)
+ syncFollowsLatest()
+ execute(command, animation: AnymorphMotion.base)
+ } label: {
+ Image(systemName: "arrow.down")
+ }
+ .morphRound(diameter: 36, .floating)
+ .padding(.bottom, 12)
+ .transition(.opacity)
+ .help("최근 메시지로 이동")
+ .accessibilityLabel("최근 메시지로 이동")
+ }
+ }
+ .animation(AnymorphMotion.fast, value: followsLatest)
+ }
+ }
+}
+
+extension View {
+ /// See `MorphConversationScroll`. `conversationID` names what the scroll view shows, so opening another
+ /// conversation lands on its latest message.
+ func morphConversationScroll(
+ _ position: Binding,
+ conversationID: String = "",
+ animatedScrollTrigger: Int = 0
+ ) -> some View {
+ modifier(MorphConversationScroll(
+ position: position,
+ conversationID: conversationID,
+ animatedScrollTrigger: animatedScrollTrigger
+ ))
+ }
+}
diff --git a/apple/Apps/Shared/MorphCustomProvidersSection.swift b/apple/Apps/Shared/MorphCustomProvidersSection.swift
new file mode 100644
index 000000000..b214b1855
--- /dev/null
+++ b/apple/Apps/Shared/MorphCustomProvidersSection.swift
@@ -0,0 +1,441 @@
+import SwiftUI
+import MorphCore
+
+/// Orchestrator & per-provider execution harness settings for local Morph Code.
+struct MorphProviderHarnessesSection: View {
+ @Bindable var state: MorphAppState
+
+ private struct ProviderSpec: Identifiable {
+ let id: String
+ let title: String
+ let cliName: String
+ let brand: MorphBrand
+ }
+
+ private let providers: [ProviderSpec] = [
+ ProviderSpec(id: "claude", title: "Claude", cliName: "claude", brand: .claude),
+ ProviderSpec(id: "codex", title: "Codex", cliName: "codex", brand: .openai),
+ ]
+
+ private func concreteModelSections(selection: String) -> CodeModelMenu.Sections {
+ let concrete = state.availableCodeModels.filter { opt in
+ let id = opt.id.lowercased()
+ return id != "auto" && id != "orchestrator"
+ }
+ return CodeModelMenu.sections(concrete, selection: selection)
+ }
+
+ private func providerDisplayName(for modelId: String) -> String {
+ if let opt = CodeModelMenu.current(modelId, in: state.availableCodeModels) {
+ return MorphEngine.name(for: opt.provider)
+ }
+ let prefix = modelId.split(separator: "/").first.map(String.init) ?? modelId
+ return MorphEngine.name(for: prefix)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ MorphSettingsGroup(
+ "Orchestrator",
+ footnote: "When you pick Orchestrator in the model menu, the selected model decomposes and verifies tasks and dispatches worker subagents."
+ ) {
+ MorphSettingsRow(
+ "Orchestrator Model",
+ detail: "\(providerDisplayName(for: state.orchestratorModel)) · morphcode Go harness"
+ ) {
+ EmptyView()
+ } trailing: {
+ let current = state.orchestratorModel
+ let sections = concreteModelSections(selection: current)
+ MorphPopupButton(
+ CodeModelMenu.name(of: current, in: state.availableCodeModels),
+ brand: CodeModelMenu.current(current, in: state.availableCodeModels).flatMap(MorphBrand.init(codeModel:))
+ ?? MorphBrand(codeModelId: current),
+ disabled: state.isSavingProviderHarnesses,
+ menuWidth: 300,
+ name: "orchestrator-model"
+ ) {
+ MorphCodeModelRows(sections: sections, selection: current) { id in
+ guard id != current else { return }
+ Task { await state.setOrchestratorModel(id) }
+ }
+ MorphCodeMoreModels(groups: sections.more, selection: current) { id in
+ guard id != current else { return }
+ Task { await state.setOrchestratorModel(id) }
+ }
+ }
+ }
+
+ MorphSettingsRow(
+ "Default Worker Model",
+ detail: state.workerDefaultModel.isEmpty
+ ? "Workers inherit the Orchestrator model unless overridden"
+ : "\(providerDisplayName(for: state.workerDefaultModel)) · default model for worker subagents"
+ ) {
+ EmptyView()
+ } trailing: {
+ let current = state.workerDefaultModel
+ let sections = concreteModelSections(selection: current)
+ let title = current.isEmpty
+ ? "Same as Orchestrator"
+ : CodeModelMenu.name(of: current, in: state.availableCodeModels)
+ let brand: MorphBrand? = current.isEmpty
+ ? nil
+ : (CodeModelMenu.current(current, in: state.availableCodeModels).flatMap(MorphBrand.init(codeModel:))
+ ?? MorphBrand(codeModelId: current))
+ MorphPopupButton(
+ title,
+ brand: brand,
+ disabled: state.isSavingProviderHarnesses,
+ menuWidth: 300,
+ name: "worker-default-model"
+ ) {
+ MorphMenuItem(
+ "Same as Orchestrator",
+ subtitle: "Use \(CodeModelMenu.name(of: state.orchestratorModel, in: state.availableCodeModels))",
+ isSelected: current.isEmpty,
+ id: "worker-inherit"
+ ) {
+ guard !current.isEmpty else { return }
+ Task { await state.setWorkerDefaultModel("") }
+ }
+ if !sections.main.isEmpty {
+ MorphMenuDivider()
+ }
+ MorphCodeModelRows(sections: sections, selection: current) { id in
+ guard id != current else { return }
+ Task { await state.setWorkerDefaultModel(id) }
+ }
+ MorphCodeMoreModels(groups: sections.more, selection: current) { id in
+ guard id != current else { return }
+ Task { await state.setWorkerDefaultModel(id) }
+ }
+ }
+ }
+
+ let effectiveWorkerModel = state.workerDefaultModel.isEmpty ? state.orchestratorModel : state.workerDefaultModel
+ let workerEfforts = CodeModelMenu.efforts(of: effectiveWorkerModel, in: state.availableCodeModels)
+ if !workerEfforts.isEmpty {
+ let selectedWorkerEffort = CodeReasoningEffort(rawValue: state.workerEffort)
+ MorphSettingsRow(
+ "Worker Effort",
+ detail: selectedWorkerEffort == nil
+ ? "Follows the composer's selected reasoning effort"
+ : "Fixed at \(selectedWorkerEffort!.label) for worker subagents"
+ ) {
+ EmptyView()
+ } trailing: {
+ MorphPopupButton(
+ selectedWorkerEffort?.label ?? "Same as Orchestrator",
+ disabled: state.isSavingProviderHarnesses,
+ menuWidth: 268,
+ name: "worker-effort"
+ ) {
+ MorphMenuItem(
+ "Same as Orchestrator",
+ subtitle: "Inherit effort from the thread composer",
+ isSelected: selectedWorkerEffort == nil,
+ id: "worker-effort-inherit"
+ ) {
+ guard selectedWorkerEffort != nil else { return }
+ Task { await state.setWorkerEffort("") }
+ }
+ MorphMenuDivider()
+ ForEach(workerEfforts) { level in
+ MorphMenuItem(
+ level.label,
+ tag: level == .medium ? MorphMenuTag("Recommended") : nil,
+ isSelected: selectedWorkerEffort == level,
+ id: "worker-effort-\(level.rawValue)"
+ ) {
+ guard selectedWorkerEffort != level else { return }
+ Task { await state.setWorkerEffort(level.rawValue) }
+ }
+ }
+ }
+ }
+ }
+
+ ForEach(providers) { spec in
+ let workerMode = CodeProviderHarnessMode(
+ rawValue: (state.workerHarnesses[spec.id] ?? "morphcode").lowercased()
+ ) ?? .morphcode
+ let cliInstalled = state.nativeCliAvailable[spec.id]
+ let cliLabel: String = {
+ if let installed = cliInstalled {
+ return installed ? "\(spec.cliName) CLI installed" : "\(spec.cliName) CLI not found"
+ }
+ return "Checking \(spec.cliName) CLI"
+ }()
+ let detail = workerMode == .morphcode
+ ? "Worker: built-in morphcode Go harness · \(cliLabel)"
+ : "Worker: official \(spec.cliName) CLI · \(cliLabel)"
+
+ MorphSettingsRow("\(spec.title) Worker", detail: detail) {
+ MorphServiceIcon(brand: spec.brand)
+ } trailing: {
+ AnymorphSegmentControl(
+ items: CodeProviderHarnessMode.allCases,
+ selection: Binding(
+ get: { workerMode },
+ set: { newMode in
+ guard newMode != workerMode else { return }
+ Task {
+ await state.setWorkerHarness(provider: spec.id, mode: newMode)
+ }
+ }
+ ),
+ label: { $0.label }
+ )
+ .disabled(state.isSavingProviderHarnesses)
+ }
+ }
+ }
+
+ MorphSettingsGroup(
+ "Default Provider Harness",
+ footnote: "Choose whether Claude and Codex run through morphcode's built-in Go harness (zero external CLI dependency) or proxy through their official local CLI."
+ ) {
+ ForEach(providers) { spec in
+ let currentMode = CodeProviderHarnessMode(
+ rawValue: (state.providerHarnesses[spec.id] ?? "morphcode").lowercased()
+ ) ?? .morphcode
+ let cliInstalled = state.nativeCliAvailable[spec.id]
+ let cliState: String = {
+ if let installed = cliInstalled {
+ return installed ? "\(spec.cliName) CLI installed" : "\(spec.cliName) CLI not found"
+ }
+ return "Checking \(spec.cliName) CLI"
+ }()
+ let statusDetail = currentMode == .morphcode
+ ? "Built-in morphcode Go harness · \(cliState)"
+ : "Official \(spec.cliName) CLI proxy · \(cliState)"
+
+ MorphSettingsRow(spec.title, detail: statusDetail) {
+ MorphServiceIcon(brand: spec.brand)
+ } trailing: {
+ AnymorphSegmentControl(
+ items: CodeProviderHarnessMode.allCases,
+ selection: Binding(
+ get: { currentMode },
+ set: { newMode in
+ guard newMode != currentMode else { return }
+ Task {
+ await state.setProviderHarness(provider: spec.id, mode: newMode)
+ }
+ }
+ ),
+ label: { $0.label }
+ )
+ .disabled(state.isSavingProviderHarnesses)
+ }
+ }
+ }
+ }
+ .task {
+ await state.loadProviderHarnesses()
+ }
+ }
+}
+
+/// Dynamic Custom Provider management section (OpenRouter, Venice, Groq, xAI, Ollama, Anthropic-compatible, etc.).
+struct MorphCustomProvidersSection: View {
+ @Bindable var state: MorphAppState
+
+ @State private var showsAddForm = false
+ @State private var providerId = ""
+ @State private var providerName = ""
+ @State private var protocolKind: CustomProviderProtocol = .openAIChat
+ @State private var baseURL = ""
+ @State private var apiKey = ""
+ @State private var modelsCSV = ""
+ @State private var isSaving = false
+
+ var body: some View {
+ MorphSettingsGroup(
+ "Custom Model Providers",
+ footnote: "Add any OpenAI- or Anthropic-compatible endpoint (OpenRouter, Ollama, Groq, xAI, Venice, or self-hosted gateways) to use with morphcode's full toolset."
+ ) {
+ Button(showsAddForm ? "Close" : "Add Provider") {
+ withAnimation(AnymorphMotion.base) {
+ showsAddForm.toggle()
+ }
+ }
+ .anymorphButton(size: .inline, appearance: showsAddForm ? .ghost : .solid)
+ } content: {
+ if showsAddForm {
+ addFormView
+ }
+
+ if state.customProviders.isEmpty {
+ MorphSettingsRow(
+ "No custom providers configured",
+ detail: "Add OpenRouter, Ollama, xAI, Groq, or any OpenAI/Anthropic-compatible endpoint."
+ ) {
+ MorphServiceIcon("cpu")
+ } trailing: {
+ EmptyView()
+ }
+ } else {
+ ForEach(state.customProviders) { provider in
+ MorphSettingsRow(
+ provider.name,
+ detail: "\(provider.id) · \(provider.protocolKind.label) · \(provider.models?.count ?? 0) models · \(provider.baseUrl)"
+ ) {
+ if let brand = MorphBrand(provider: provider.id) {
+ MorphServiceIcon(brand: brand)
+ } else {
+ MorphServiceIcon("server.rack")
+ }
+ } trailing: {
+ HStack(spacing: 6) {
+ Button("Discover Models") {
+ Task { await state.discoverCustomProviderModels(id: provider.id) }
+ }
+ .anymorphButton(size: .inline, appearance: .secondary)
+
+ Button("Remove") {
+ Task { await state.deleteCustomProvider(id: provider.id) }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ }
+ }
+ }
+ }
+ }
+ .task {
+ await state.loadCustomProviders()
+ }
+ }
+
+ private var addFormView: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if !state.customProviderPresets.isEmpty {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(state.customProviderPresets) { preset in
+ Button(preset.name) {
+ applyPreset(preset)
+ }
+ .anymorphButton(size: .inline, appearance: providerId == preset.id ? .solid : .secondary)
+ }
+ }
+ }
+ }
+
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Provider ID")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ TextField("e.g. openrouter, ollama", text: $providerId)
+ .textFieldStyle(.plain)
+ .anymorphInputSurface()
+ }
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Display Name")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ TextField("e.g. OpenRouter", text: $providerName)
+ .textFieldStyle(.plain)
+ .anymorphInputSurface()
+ }
+ }
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Protocol")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ AnymorphSegmentControl(
+ items: CustomProviderProtocol.allCases,
+ selection: $protocolKind,
+ label: { $0.label }
+ )
+ }
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Base URL")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ TextField("https://openrouter.ai/api/v1", text: $baseURL)
+ .textFieldStyle(.plain)
+ .anymorphInputSurface()
+ }
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("API Key (optional for local Ollama)")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ SecureField("sk-...", text: $apiKey)
+ .textFieldStyle(.plain)
+ .anymorphInputSurface()
+ }
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Model IDs (comma-separated · leave empty to auto-discover via /models)")
+ .anymorphText(.caption, color: AnymorphColor.fgSecondary)
+ TextField("e.g. anthropic/claude-sonnet-4, google/gemini-2.5-pro", text: $modelsCSV)
+ .textFieldStyle(.plain)
+ .anymorphInputSurface()
+ }
+
+ HStack {
+ Spacer()
+ Button(isSaving ? "Saving…" : "Save") {
+ Task { await submitForm() }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(isSaving || providerId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ .padding(16)
+ }
+
+ private func applyPreset(_ preset: CustomProviderPreset) {
+ providerId = preset.id
+ providerName = preset.name
+ protocolKind = preset.protocolKind
+ baseURL = preset.baseUrl
+ modelsCSV = (preset.defaultModels ?? []).map(\.id).joined(separator: ", ")
+ }
+
+ private func submitForm() async {
+ isSaving = true
+ defer { isSaving = false }
+ let parsedModels: [CustomModelSpec] = modelsCSV
+ .split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ .map { CustomModelSpec(id: $0) }
+ let req = UpsertCustomProviderRequest(
+ id: providerId.trimmingCharacters(in: .whitespacesAndNewlines),
+ name: providerName.trimmingCharacters(in: .whitespacesAndNewlines),
+ protocolKind: protocolKind,
+ baseUrl: baseURL.trimmingCharacters(in: .whitespacesAndNewlines),
+ apiKey: apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : apiKey.trimmingCharacters(in: .whitespacesAndNewlines),
+ models: parsedModels.isEmpty ? nil : parsedModels,
+ enabled: true,
+ discoverModels: parsedModels.isEmpty
+ )
+ if await state.saveCustomProvider(req) {
+ providerId = ""
+ providerName = ""
+ baseURL = ""
+ apiKey = ""
+ modelsCSV = ""
+ withAnimation(AnymorphMotion.base) {
+ showsAddForm = false
+ }
+ }
+ }
+}
+
+private extension View {
+ func anymorphInputSurface() -> some View {
+ self
+ .anymorphText(.body)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .background(AnymorphColor.bgCard)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .stroke(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ }
+}
diff --git a/apple/Apps/Shared/MorphDesign.swift b/apple/Apps/Shared/MorphDesign.swift
new file mode 100644
index 000000000..8fe6bb8a1
--- /dev/null
+++ b/apple/Apps/Shared/MorphDesign.swift
@@ -0,0 +1,4841 @@
+import SwiftUI
+import CryptoKit
+import ImageIO
+import WebKit
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+// MARK: - 1. Semantic Colors (anymorph-monorepo apps/dashboard src/styles/tokens.gen.css, :root and .dark)
+//
+// Dark mode draws on a black canvas, as T3 Code does: the dashboard's .dark ink, strokes and translucent fills over
+// #000, and opaque gray steps for the surfaces laid on it.
+//
+// Morph is monochrome: ink, surfaces and strokes only. The dashboard's status, accent, brand and
+// identity hues are deliberately left out; a state reads from its words, weight and icon.
+
+public enum AnymorphColor {
+ private static func dynamic(lightHex: UInt32, lightAlpha: CGFloat = 1.0, darkHex: UInt32, darkAlpha: CGFloat = 1.0) -> Color {
+ #if os(macOS)
+ let nsColor = NSColor(name: nil) { appearance in
+ let isDark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ return Self.makeNSColor(hex: isDark ? darkHex : lightHex, alpha: isDark ? darkAlpha : lightAlpha)
+ }
+ return Color(nsColor: nsColor)
+ #else
+ let uiColor = UIColor { trait in
+ let isDark = trait.userInterfaceStyle == .dark
+ return Self.makeUIColor(hex: isDark ? darkHex : lightHex, alpha: isDark ? darkAlpha : lightAlpha)
+ }
+ return Color(uiColor: uiColor)
+ #endif
+ }
+
+ private static func fixed(hex: UInt32, alpha: CGFloat = 1.0) -> Color {
+ let r = Double((hex >> 16) & 0xFF) / 255.0
+ let g = Double((hex >> 8) & 0xFF) / 255.0
+ let b = Double(hex & 0xFF) / 255.0
+ return Color(.sRGB, red: r, green: g, blue: b, opacity: Double(alpha))
+ }
+
+ #if os(macOS)
+ private static func makeNSColor(hex: UInt32, alpha: CGFloat) -> NSColor {
+ let r = CGFloat((hex >> 16) & 0xFF) / 255.0
+ let g = CGFloat((hex >> 8) & 0xFF) / 255.0
+ let b = CGFloat(hex & 0xFF) / 255.0
+ return NSColor(srgbRed: r, green: g, blue: b, alpha: alpha)
+ }
+ #else
+ private static func makeUIColor(hex: UInt32, alpha: CGFloat) -> UIColor {
+ let r = CGFloat((hex >> 16) & 0xFF) / 255.0
+ let g = CGFloat((hex >> 8) & 0xFF) / 255.0
+ let b = CGFloat(hex & 0xFF) / 255.0
+ return UIColor(red: r, green: g, blue: b, alpha: alpha)
+ }
+ #endif
+
+ // Surfaces (background.*)
+ public static let bgBase = dynamic(lightHex: 0xFFFFFF, darkHex: 0x000000)
+ public static let bgSubtle = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.05, darkHex: 0xFAFAFA, darkAlpha: 0.04)
+ public static let bgSurface = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.10, darkHex: 0xA4A4A4, darkAlpha: 0.10)
+ public static let bgElevated = dynamic(lightHex: 0xFFFFFF, lightAlpha: 0.72, darkHex: 0xFAFAFA, darkAlpha: 0.04)
+ public static let bgHovered = dynamic(lightHex: 0xFFFFFF, lightAlpha: 0.16, darkHex: 0xFAFAFA, darkAlpha: 0.02)
+ public static let bgInverse = dynamic(lightHex: 0x161616, darkHex: 0xFAFAFA)
+ public static let bgDisabled = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.20, darkHex: 0xA4A4A4, darkAlpha: 0.10)
+
+ // Inks (foreground.*)
+ public static let fgPrimary = dynamic(lightHex: 0x161616, darkHex: 0xFAFAFA)
+ /// Softened reading ink for multi-line answers and documents so bold spans (`fgPrimary`) stand out without halation on black.
+ public static let fgReading = dynamic(lightHex: 0x161616, lightAlpha: 0.88, darkHex: 0xFAFAFA, darkAlpha: 0.82)
+ public static let fgSecondary = dynamic(lightHex: 0x161616, lightAlpha: 0.72, darkHex: 0xFAFAFA, darkAlpha: 0.72)
+ public static let fgTertiary = dynamic(lightHex: 0x161616, lightAlpha: 0.56, darkHex: 0xFAFAFA, darkAlpha: 0.56)
+ public static let fgQuaternary = dynamic(lightHex: 0x161616, lightAlpha: 0.36, darkHex: 0xFAFAFA, darkAlpha: 0.36)
+ public static let fgDisabled = dynamic(lightHex: 0x161616, lightAlpha: 0.24, darkHex: 0xFAFAFA, darkAlpha: 0.24)
+ public static let fgInverse = dynamic(lightHex: 0xFAFAFA, darkHex: 0x161616)
+ /// Clickable file path references and web links inside Markdown answers.
+ public static let fgLink = dynamic(lightHex: 0x0369A1, darkHex: 0x5CC8E6)
+
+ // Inline code chips inside Markdown answers.
+ public static let bgInlineCode = dynamic(lightHex: 0x161616, lightAlpha: 0.055, darkHex: 0xFAFAFA, darkAlpha: 0.095)
+ public static let strokeInlineCode = dynamic(lightHex: 0x161616, lightAlpha: 0.10, darkHex: 0xFAFAFA, darkAlpha: 0.13)
+
+ // Strokes (stroke.*)
+ public static let strokeLight = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.10, darkHex: 0xA4A4A4, darkAlpha: 0.10)
+ public static let strokeBase = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.20, darkHex: 0xA4A4A4, darkAlpha: 0.15)
+ public static let strokeElevated = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.20, darkHex: 0xA4A4A4, darkAlpha: 0.05)
+ public static let strokeStrong = dynamic(lightHex: 0x161616, lightAlpha: 0.72, darkHex: 0xFAFAFA, darkAlpha: 0.72)
+
+ // Shadows: the card's faint lift (Card, 0 2 4 #16161605) and the floating composer's (0 8 28 10%).
+ public static let cardShadow = fixed(hex: 0x161616, alpha: 0.02)
+ public static let floatShadow = fixed(hex: 0x000000, alpha: 0.10)
+
+ // Grok Bot layout neutrals. Opaque grays, so a selected row on the sidebar never doubles its fill.
+ /// Sidebar, settings navigation and the iPhone home. Black like the canvas on dark, set apart by the divider.
+ public static let bgSidebar = dynamic(lightHex: 0xF6F6F6, darkHex: 0x000000)
+ /// Settings groups, the composer field and other filled blocks on the base canvas.
+ public static let bgGrouped = dynamic(lightHex: 0xF2F2F2, darkHex: 0x161616)
+ /// A selected sidebar row or settings section.
+ public static let bgSelected = dynamic(lightHex: 0xE7E7E7, darkHex: 0x262626)
+ /// A hovered sidebar row or round button.
+ public static let bgHover = dynamic(lightHex: 0xEDEDED, darkHex: 0x1C1C1C)
+ /// The assistant's bubble.
+ public static let bubbleIncoming = dynamic(lightHex: 0xF1F1F1, darkHex: 0x1E1E1E)
+ /// The member's bubble and its text.
+ public static let bubbleOutgoing = dynamic(lightHex: 0x161616, darkHex: 0x333333)
+ public static let bubbleOutgoingText = fixed(hex: 0xFAFAFA)
+ /// Cards inside the conversation (drafts to approve, results) and floating round buttons.
+ public static let bgCard = dynamic(lightHex: 0xFFFFFF, darkHex: 0x0F0F0F)
+ /// Dims the window behind the settings dialog.
+ public static let scrim = dynamic(lightHex: 0x000000, lightAlpha: 0.24, darkHex: 0x000000, darkAlpha: 0.55)
+
+ // Controls laid over a photo or screenshot. The image decides the contrast, not the theme, so these stay black
+ // and white in both modes.
+ public static let mediaBackdrop = Color.black.opacity(0.82)
+ public static let mediaShadow = Color.black.opacity(0.35)
+ public static let mediaTileHover = Color.black.opacity(0.08)
+ public static let mediaChipFill = Color.black.opacity(0.56)
+ public static let mediaChipFillHover = Color.black.opacity(0.72)
+ public static let mediaChipStroke = Color.white.opacity(0.22)
+ public static let mediaInk = Color.white
+ public static let mediaInkSecondary = Color.white.opacity(0.92)
+ public static let mediaButtonFill = Color.white.opacity(0.14)
+ /// Swipe actions on list rows. iOS draws their labels in white, so both stay dark in either appearance.
+ /// The action a full swipe runs, such as archive.
+ public static let swipePrimary = dynamic(lightHex: 0x161616, darkHex: 0x4A4A4A)
+ /// The actions beside it, such as delete or mark as read.
+ public static let swipeSecondary = dynamic(lightHex: 0x6E6E6E, darkHex: 0x333333)
+
+ // Codex-style composer
+ /// The composer card: crisp white on light, one lifted layer above the canvas on dark.
+ public static let composerCard = dynamic(lightHex: 0xFFFFFF, darkHex: 0x0F0F0F)
+ /// The recessed context shelf tucked behind the composer card's top edge.
+ public static let composerShelf = dynamic(lightHex: 0xF5F5F5, darkHex: 0x0A0A0A)
+ /// The card's hairline while the field has focus.
+ public static let strokeStrongHairline = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.38, darkHex: 0xA4A4A4, darkAlpha: 0.26)
+ /// The card's soft lift.
+ public static let composerShadow = dynamic(lightHex: 0x000000, lightAlpha: 0.045, darkHex: 0x000000, darkAlpha: 0.30)
+
+ // Dropdown menus (MorphDropdown)
+ /// The menu card: white on light, a step above the composer on dark so it reads as floating.
+ public static let menuSurface = dynamic(lightHex: 0xFFFFFF, darkHex: 0x161616)
+ /// The row under the pointer or the arrow keys.
+ public static let menuHighlight = dynamic(lightHex: 0xEFEFEF, darkHex: 0x262626)
+ /// The menu card's outline.
+ public static let menuStroke = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.22, darkHex: 0xFAFAFA, darkAlpha: 0.08)
+
+ // The only hues in Morph: elevated permission modes in the composer, cautions, and Morph Code thread triage dots.
+ /// Full access (warm amber).
+ public static let accessFull = dynamic(lightHex: 0xD97706, darkHex: 0xF59E0B)
+ /// Plan (quiet indigo).
+ public static let accessPlan = dynamic(lightHex: 0x4F46E5, darkHex: 0x8B93F8)
+ /// A caution, such as a nearly full context window, a running check, or a thread awaiting user action.
+ public static var caution: Color { accessFull }
+ /// Completed unread Morph Code turn (crisp green).
+ public static let statusDone = dynamic(lightHex: 0x16A34A, darkHex: 0x22C55E)
+ /// Failed Morph Code turn requiring attention (crisp red).
+ public static let statusError = dynamic(lightHex: 0xDC2626, darkHex: 0xEF4444)
+
+ /// Semantic dot color for a Morph Code thread's triage state (`nil` for running and calm idle threads).
+ public static func codeStatus(_ status: CodeThreadVisualStatus) -> Color? {
+ switch status {
+ case .awaitingAction: return caution
+ case .failed: return statusError
+ case .completedUnread: return statusDone
+ case .running, .idle: return nil
+ }
+ }
+}
+
+// MARK: - 2. Typography (system font: SF Pro with the system's Korean fallback, base 400 / emphasis 500 / strong 600)
+
+public enum AnymorphFontWeight {
+ case base // 400
+ case emphasis // 500
+ case strong // 600
+
+ var swiftUIWeight: Font.Weight {
+ switch self {
+ case .base: return .regular
+ case .emphasis: return .medium
+ case .strong: return .semibold
+ }
+ }
+}
+
+public enum AnymorphTypeScale {
+ case display // 36 / 44
+ case title // 24 / 32
+ case headline // 20 / 28
+ case subhead // 17 / 25
+ case body // 15 / 24
+ case callout // 14 / 21
+ case footnote // 13 / 18
+ case caption // 12 / 16
+
+ public var size: CGFloat {
+ switch self {
+ case .display: return 36
+ case .title: return 24
+ case .headline: return 20
+ case .subhead: return 17
+ case .body: return 15
+ case .callout: return 14
+ case .footnote: return 13
+ case .caption: return 12
+ }
+ }
+
+ public var lineSpacing: CGFloat {
+ switch self {
+ case .display: return 6
+ case .title: return 5
+ case .headline: return 5
+ case .subhead: return 5
+ case .body: return 7
+ case .callout: return 5
+ case .footnote: return 3
+ case .caption: return 2
+ }
+ }
+}
+
+/// The system font (SF Pro, with Apple SD Gothic Neo for Korean) at its own spacing, the way native Mac and iPhone
+/// apps and T3 Code draw text.
+public enum AnymorphFonts {
+ /// The scale's font, or one `sizeScale` times as large rounded to whole points.
+ public static func font(
+ _ scale: AnymorphTypeScale,
+ weight: AnymorphFontWeight = .base,
+ monospaced: Bool = false,
+ sizeScale: CGFloat = 1
+ ) -> Font {
+ let size = (scale.size * sizeScale).rounded()
+ if monospaced {
+ return .system(size: size, weight: weight.swiftUIWeight, design: .monospaced)
+ }
+ return .system(size: size, weight: weight.swiftUIWeight)
+ }
+}
+
+extension EnvironmentValues {
+ /// How much larger than its type scale `anymorphText` draws, 1 everywhere but the lists that
+ /// `morphListTextSize()` enlarges.
+ @Entry var anymorphTextScale: CGFloat = 1
+}
+
+extension View {
+ /// A sidebar list's type on iPhone and iPad, slightly larger than on the Mac so a 14-point thread title reads at
+ /// 16 points, the size touch lists use. The Mac keeps the type scale.
+ func morphListTextSize() -> some View {
+ #if os(iOS)
+ environment(\.anymorphTextScale, 1.15)
+ #else
+ self
+ #endif
+ }
+}
+
+public struct AnymorphTextModifier: ViewModifier {
+ let scale: AnymorphTypeScale
+ let weight: AnymorphFontWeight
+ let color: Color
+ let tabular: Bool
+ let monospaced: Bool
+ @Environment(\.anymorphTextScale) private var textScale
+
+ public func body(content: Content) -> some View {
+ let base = content
+ .font(AnymorphFonts.font(scale, weight: weight, monospaced: monospaced, sizeScale: textScale))
+ .lineSpacing(scale.lineSpacing)
+ .foregroundStyle(color)
+ if tabular {
+ base.monospacedDigit()
+ } else {
+ base
+ }
+ }
+}
+
+public extension View {
+ func anymorphText(
+ _ scale: AnymorphTypeScale,
+ weight: AnymorphFontWeight = .base,
+ color: Color = AnymorphColor.fgPrimary,
+ tabular: Bool = false,
+ monospaced: Bool = false
+ ) -> some View {
+ modifier(AnymorphTextModifier(scale: scale, weight: weight, color: color, tabular: tabular, monospaced: monospaced))
+ }
+}
+
+// MARK: - Radius Tokens
+
+/// Corner radii, one step per size. Shapes use these instead of loose numbers so neighbouring controls match.
+public enum AnymorphRadius {
+ /// Small squares such as the stop glyph.
+ public static let xxs: CGFloat = 2
+ /// Badges and chips.
+ public static let xs: CGFloat = 4
+ public static let sm: CGFloat = 6
+ /// Rows, thumbnails, small plates.
+ public static let md: CGFloat = 8
+ /// Inputs and compact cards.
+ public static let lg: CGFloat = 10
+ public static let xl: CGFloat = 12
+ /// Cards in a conversation and the dropdown menus.
+ public static let xxl: CGFloat = 14
+ /// Large plates and dialogs.
+ public static let xxxl: CGFloat = 16
+ public static let round: CGFloat = 18
+ /// The composer card.
+ public static let panel: CGFloat = 22
+}
+
+// MARK: - 3. Motion Tokens (motion.md — Material 3 curves at Anymorph timings)
+
+public enum AnymorphMotion {
+ public static let instant: Animation = .timingCurve(0.2, 0, 0, 1, duration: 0.10)
+ public static let fast: Animation = .timingCurve(0.2, 0, 0, 1, duration: 0.15)
+ public static let base: Animation = .timingCurve(0.05, 0.7, 0.1, 1, duration: 0.20)
+ /// Codex-style critically damped upward glide when submitting a prompt from the composer.
+ public static let submit: Animation = .smooth(duration: 0.30, extraBounce: 0)
+}
+
+/// Frame-0 insertion transition for newly submitted prompts and live turn status rows.
+/// Animates opacity and a gentle vertical rise on insertion only (removal is instant so optimistic -> stored
+/// handoffs never flicker), avoiding `scaleEffect` on selectable text to prevent subpixel glyph snapping.
+public struct MorphSubmitRiseTransition: Transition {
+ public let distance: CGFloat
+
+ public init(distance: CGFloat = 16) {
+ self.distance = distance
+ }
+
+ public func body(content: Content, phase: TransitionPhase) -> some View {
+ let isInserting = phase == .willAppear
+ content
+ .opacity(isInserting ? 0 : 1)
+ .offset(y: isInserting ? distance : 0)
+ }
+}
+
+public extension Transition where Self == MorphSubmitRiseTransition {
+ static func morphSubmitRise(distance: CGFloat = 16) -> MorphSubmitRiseTransition {
+ MorphSubmitRiseTransition(distance: distance)
+ }
+}
+
+/// Smooth upward glide when a newly submitted prompt or live turn status rises into the conversation
+/// from the composer, matching Codex Desktop's tactile submit feel while honoring Reduce Motion.
+public struct MorphSubmitRiseModifier: ViewModifier {
+ let distance: CGFloat
+ let initialScale: CGFloat
+ let delay: Double
+ let anchor: UnitPoint
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var appeared = false
+
+ public init(
+ distance: CGFloat = 16,
+ initialScale: CGFloat = 1.0,
+ delay: Double = 0,
+ anchor: UnitPoint = .bottomTrailing
+ ) {
+ self.distance = distance
+ self.initialScale = initialScale
+ self.delay = delay
+ self.anchor = anchor
+ }
+
+ public func body(content: Content) -> some View {
+ let needsScale = initialScale != 1.0
+ content
+ .opacity(appeared ? 1 : 0)
+ .offset(y: (appeared || reduceMotion) ? 0 : distance)
+ .scaleEffect((appeared || reduceMotion || !needsScale) ? 1 : initialScale, anchor: anchor)
+ .onAppear {
+ guard !appeared else { return }
+ if reduceMotion {
+ withAnimation(AnymorphMotion.fast) {
+ appeared = true
+ }
+ } else {
+ withAnimation(delay > 0 ? AnymorphMotion.submit.delay(delay) : AnymorphMotion.submit) {
+ appeared = true
+ }
+ }
+ }
+ }
+}
+
+public extension View {
+ /// Glides a freshly submitted prompt or live status gently upward into place from the composer.
+ func morphSubmitRise(
+ distance: CGFloat = 16,
+ initialScale: CGFloat = 1.0,
+ delay: Double = 0,
+ anchor: UnitPoint = .bottomTrailing
+ ) -> some View {
+ modifier(MorphSubmitRiseModifier(distance: distance, initialScale: initialScale, delay: delay, anchor: anchor))
+ }
+}
+
+// MARK: - 4. Official Anymorph Logo Mark (public/anymorph_logo.svg — 3-diamond geometry)
+
+public struct AnymorphLogoMark: View {
+ public var width: CGFloat
+ public var color: Color
+
+ public init(width: CGFloat = 22, color: Color = AnymorphColor.fgPrimary) {
+ self.width = width
+ self.color = color
+ }
+
+ /// Left, top and right diamonds of the official mark, scaled into `size`.
+ static func diamondPaths(in size: CGSize) -> [Path] {
+ let sx = size.width / 27.0
+ let sy = size.height / 19.6216
+ func diamond(_ pts: [(CGFloat, CGFloat)]) -> Path {
+ var p = Path()
+ guard let first = pts.first else { return p }
+ p.move(to: CGPoint(x: first.0 * sx, y: first.1 * sy))
+ for pt in pts.dropFirst() {
+ p.addLine(to: CGPoint(x: pt.0 * sx, y: pt.1 * sy))
+ }
+ p.closeSubpath()
+ return p
+ }
+ return [
+ diamond([(12.2422, 13.5), (6.1211, 19.6211), (0, 13.5), (6.1211, 7.3779)]),
+ diamond([(19.6211, 6.1221), (13.499, 12.2432), (7.3779, 6.1221), (13.499, 0)]),
+ diamond([(27, 13.5), (20.8779, 19.6221), (14.7568, 13.5), (20.8779, 7.3789)]),
+ ]
+ }
+
+ public var body: some View {
+ Canvas { ctx, size in
+ for path in Self.diamondPaths(in: size) {
+ ctx.fill(path, with: .color(color))
+ }
+ }
+ .frame(width: width, height: width * (19.6216 / 27.0))
+ .accessibilityLabel("Anymorph")
+ }
+}
+
+// MARK: - 5. MorphPalette (local time labels)
+
+public enum MorphPalette {
+ /// Thread-safe cache of ICU date formatters and recently parsed ISO-8601 timestamps so SwiftUI list redraws
+ /// never allocate throwaway DateFormatters per row.
+ private final class FormatterStore: @unchecked Sendable {
+ static let shared = FormatterStore()
+ private let lock = NSLock()
+ private var parsedCache: [String: Date] = [:]
+ private let maxCacheCount = 512
+
+ private let isoWithFraction: ISO8601DateFormatter
+ private let isoPlain: ISO8601DateFormatter
+ private let dayOnly: DateFormatter
+ private let koHHmm: DateFormatter
+ private let koMonthDayHHmm: DateFormatter
+ private let koMonthDayEEEE: DateFormatter
+ private let koAmPm: DateFormatter
+ private let koMonthDayE: DateFormatter
+ private let koYearMonthDayE: DateFormatter
+ private let koMonthDay: DateFormatter
+ private let koYearMonthDay: DateFormatter
+ private let koMonthDayEHHmm: DateFormatter
+
+ private static func makeFormatter(_ format: String, locale: String = "ko_KR") -> DateFormatter {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: locale)
+ f.timeZone = .autoupdatingCurrent
+ f.dateFormat = format
+ return f
+ }
+
+ private init() {
+ let wf = ISO8601DateFormatter()
+ wf.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ self.isoWithFraction = wf
+
+ let pl = ISO8601DateFormatter()
+ pl.formatOptions = [.withInternetDateTime]
+ self.isoPlain = pl
+
+ self.dayOnly = Self.makeFormatter("yyyy-MM-dd", locale: "en_US_POSIX")
+ self.koHHmm = Self.makeFormatter("HH:mm")
+ self.koMonthDayHHmm = Self.makeFormatter("M월 d일 HH:mm")
+ self.koMonthDayEEEE = Self.makeFormatter("M월 d일 EEEE")
+ self.koAmPm = Self.makeFormatter("a h:mm")
+ self.koMonthDayE = Self.makeFormatter("M월 d일 (E)")
+ self.koYearMonthDayE = Self.makeFormatter("yyyy년 M월 d일 (E)")
+ self.koMonthDay = Self.makeFormatter("M월 d일")
+ self.koYearMonthDay = Self.makeFormatter("yyyy년 M월 d일")
+ self.koMonthDayEHHmm = Self.makeFormatter("M월 d일 (E) HH:mm")
+ }
+
+ func parseDate(_ iso: String) -> Date? {
+ guard !iso.isEmpty else { return nil }
+ lock.lock()
+ defer { lock.unlock() }
+ if let hit = parsedCache[iso] { return hit }
+ let parsed: Date?
+ if let d = isoWithFraction.date(from: iso) {
+ parsed = d
+ } else if let d = isoPlain.date(from: iso) {
+ parsed = d
+ } else if iso.count >= 10 {
+ parsed = dayOnly.date(from: String(iso.prefix(10)))
+ } else {
+ parsed = nil
+ }
+ if let parsed {
+ if parsedCache.count >= maxCacheCount {
+ parsedCache.removeAll(keepingCapacity: true)
+ }
+ parsedCache[iso] = parsed
+ }
+ return parsed
+ }
+
+ func isoString(from date: Date) -> String {
+ lock.lock()
+ defer { lock.unlock() }
+ return isoPlain.string(from: date)
+ }
+
+ func formatTimeLabel(_ date: Date) -> String {
+ lock.lock()
+ defer { lock.unlock() }
+ return Calendar.autoupdatingCurrent.isDateInToday(date)
+ ? koHHmm.string(from: date)
+ : koMonthDayHHmm.string(from: date)
+ }
+
+ func formatDayLabel(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ if calendar.isDateInToday(date) { return "오늘" }
+ if calendar.isDateInYesterday(date) { return "어제" }
+ lock.lock()
+ defer { lock.unlock() }
+ return koMonthDayEEEE.string(from: date)
+ }
+
+ func formatChatTimeLabel(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ lock.lock()
+ defer { lock.unlock() }
+ let clock = koAmPm.string(from: date)
+ if calendar.isDateInToday(date) { return "오늘 \(clock)" }
+ if calendar.isDateInYesterday(date) { return "어제 \(clock)" }
+ let day = calendar.isDate(date, equalTo: Date(), toGranularity: .year)
+ ? koMonthDayE.string(from: date)
+ : koYearMonthDayE.string(from: date)
+ return "\(day) \(clock)"
+ }
+
+ func formatDateLabel(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ lock.lock()
+ defer { lock.unlock() }
+ return calendar.isDate(date, equalTo: Date(), toGranularity: .year)
+ ? koMonthDay.string(from: date)
+ : koYearMonthDay.string(from: date)
+ }
+
+ func formatListTimeLabel(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ if calendar.isDateInToday(date) {
+ lock.lock()
+ defer { lock.unlock() }
+ return koHHmm.string(from: date)
+ }
+ if calendar.isDateInYesterday(date) { return "어제" }
+ return formatDateLabel(date)
+ }
+
+ func formatScheduledRunTime(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ lock.lock()
+ defer { lock.unlock() }
+ let clock = koHHmm.string(from: date)
+ if calendar.isDateInToday(date) { return "오늘 \(clock)" }
+ if calendar.isDateInTomorrow(date) { return "내일 \(clock)" }
+ if calendar.isDateInYesterday(date) { return "어제 \(clock)" }
+ return koMonthDayEHHmm.string(from: date)
+ }
+
+ func formatScheduledRunDay(_ date: Date) -> String {
+ let calendar = Calendar.autoupdatingCurrent
+ if calendar.isDateInToday(date) || calendar.isDateInTomorrow(date) {
+ return formatScheduledRunTime(date)
+ }
+ lock.lock()
+ defer { lock.unlock() }
+ return koMonthDayE.string(from: date)
+ }
+ }
+
+ public static func parseDate(_ iso: String) -> Date? {
+ FormatterStore.shared.parseDate(iso)
+ }
+
+ public static func isoString(from date: Date) -> String {
+ FormatterStore.shared.isoString(from: date)
+ }
+
+ /// "14:05" today, "11월 24일 14:05" on other days, in the device time zone.
+ public static func timeLabel(_ iso: String) -> String {
+ guard let date = parseDate(iso) else { return iso }
+ return FormatterStore.shared.formatTimeLabel(date)
+ }
+
+ /// "14:05" today, "11월 24일 14:05" on other days, directly from a Date without ISO round-tripping.
+ public static func timeLabel(for date: Date) -> String {
+ FormatterStore.shared.formatTimeLabel(date)
+ }
+
+ /// "오늘", "어제" or "11월 24일 월요일" for conversation day separators.
+ public static func dayLabel(_ date: Date) -> String {
+ FormatterStore.shared.formatDayLabel(date)
+ }
+
+ /// The centered time line Grok Bot puts where a conversation pauses:
+ /// "오늘 오후 4:43", "어제 오전 9:12", "11월 24일 (월) 오후 4:43".
+ public static func chatTimeLabel(_ date: Date) -> String {
+ FormatterStore.shared.formatChatTimeLabel(date)
+ }
+
+ /// Sidebar row time: "16:43" today, "어제", "11월 24일" before that.
+ public static func listTimeLabel(_ iso: String) -> String {
+ guard let date = parseDate(iso) else { return "" }
+ return FormatterStore.shared.formatListTimeLabel(date)
+ }
+
+ /// "11월 25일" for document metadata.
+ public static func dateLabel(_ iso: String) -> String {
+ guard let date = parseDate(iso) else { return iso }
+ return FormatterStore.shared.formatDateLabel(date)
+ }
+
+ /// "11월 25일" directly from a Date without ISO round-tripping.
+ public static func dateLabel(for date: Date) -> String {
+ FormatterStore.shared.formatDateLabel(date)
+ }
+
+ /// "오늘 09:00", "내일 09:00", "어제 18:00" or "12월 3일 (목) 09:00", in this device's time zone.
+ public static func scheduledRunTime(_ iso: String?) -> String? {
+ guard let iso, let date = parseDate(iso) else { return nil }
+ return FormatterStore.shared.formatScheduledRunTime(date)
+ }
+
+ /// Today/tomorrow with time, later days by date alone ("12월 4일 (금)").
+ public static func scheduledRunDay(_ iso: String?) -> String? {
+ guard let iso, let date = parseDate(iso) else { return nil }
+ return FormatterStore.shared.formatScheduledRunDay(date)
+ }
+}
+
+public extension AnymorphTypeScale {
+ /// Conversation and document reading size: 15pt on both macOS and iOS so headings (`subhead` 17pt,
+ /// `headline` 20pt) keep a clear visual hierarchy above body prose on iPhone as well as Mac.
+ static var reading: AnymorphTypeScale {
+ .body
+ }
+}
+
+
+// MARK: - 6. ButtonV2 (button/v2.tsx & v2.css.ts)
+
+public enum AnymorphButtonSize {
+ case lg // 40pt, r10, body 14pt medium — page header actions
+ case md // 32pt, r8, footnote 12pt medium — panels, filters, cards
+ case inline // 24pt, r6, footnote 12pt regular — row micro-actions
+
+ var height: CGFloat {
+ switch self {
+ case .lg: return 40
+ case .md: return 32
+ case .inline: return 24
+ }
+ }
+
+ var radius: CGFloat {
+ switch self {
+ case .lg: return 10
+ case .md: return 8
+ case .inline: return 6
+ }
+ }
+
+ var hPad: CGFloat {
+ switch self {
+ case .lg: return 16
+ case .md: return 10
+ case .inline: return 8
+ }
+ }
+
+ var typeScale: AnymorphTypeScale {
+ switch self {
+ case .lg: return .body
+ case .md, .inline: return .footnote
+ }
+ }
+
+ var weight: AnymorphFontWeight {
+ switch self {
+ case .lg, .md: return .emphasis
+ case .inline: return .base
+ }
+ }
+}
+
+public enum AnymorphButtonAppearance {
+ case solid // the single primary action: inverse fill
+ case light // other actions: outlined elevated box
+ case secondary // muted fill
+ case ghost // no box at rest; an icon-only ghost gets a plate on hover
+}
+
+/// ButtonV2 in one tone. Morph has no colored (negative or accent) buttons; the label says what happens.
+public struct AnymorphButtonStyle: ButtonStyle {
+ public let size: AnymorphButtonSize
+ public let appearance: AnymorphButtonAppearance
+ public let iconOnly: Bool
+
+ @Environment(\.isEnabled) private var isEnabled
+
+ public init(
+ size: AnymorphButtonSize = .md,
+ appearance: AnymorphButtonAppearance = .light,
+ iconOnly: Bool = false
+ ) {
+ self.size = size
+ self.appearance = appearance
+ self.iconOnly = iconOnly
+ }
+
+ public func makeBody(configuration: Configuration) -> some View {
+ AnymorphButtonInner(
+ configuration: configuration,
+ size: size,
+ appearance: appearance,
+ iconOnly: iconOnly,
+ isEnabled: isEnabled
+ )
+ }
+
+ private struct AnymorphButtonInner: View {
+ let configuration: Configuration
+ let size: AnymorphButtonSize
+ let appearance: AnymorphButtonAppearance
+ let iconOnly: Bool
+ let isEnabled: Bool
+ @State private var hovered = false
+
+ var body: some View {
+ configuration.label
+ .font(AnymorphFonts.font(size.typeScale, weight: size.weight))
+ .lineLimit(1)
+ .foregroundStyle(foregroundColor)
+ .padding(.horizontal, iconOnly ? 0 : size.hPad)
+ .frame(minWidth: iconOnly ? size.height : nil)
+ .frame(height: size.height)
+ .background(
+ RoundedRectangle(cornerRadius: size.radius, style: .continuous)
+ .fill(backgroundColor)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: size.radius, style: .continuous)
+ .strokeBorder(borderColor, lineWidth: 1)
+ )
+ .opacity(solidOpacity)
+ .scaleEffect(isEnabled && configuration.isPressed ? 0.97 : 1.0)
+ .animation(AnymorphMotion.instant, value: configuration.isPressed)
+ .animation(AnymorphMotion.fast, value: hovered)
+ .contentShape(RoundedRectangle(cornerRadius: size.radius, style: .continuous))
+ .onHover { hovering in hovered = hovering }
+ .morphPointerCursor()
+ }
+
+ private var active: Bool {
+ hovered || configuration.isPressed
+ }
+
+ private var solidOpacity: Double {
+ guard isEnabled, appearance == .solid else { return 1.0 }
+ if configuration.isPressed { return 0.85 }
+ return hovered ? 0.92 : 1.0
+ }
+
+ private var backgroundColor: Color {
+ guard isEnabled else {
+ switch appearance {
+ case .solid: return AnymorphColor.bgDisabled
+ case .light, .secondary: return AnymorphColor.bgSubtle
+ case .ghost: return .clear
+ }
+ }
+ switch appearance {
+ case .solid:
+ return AnymorphColor.bgInverse
+ case .light:
+ if configuration.isPressed { return AnymorphColor.bgSurface }
+ return hovered ? AnymorphColor.bgSubtle : AnymorphColor.bgElevated
+ case .secondary:
+ return configuration.isPressed ? AnymorphColor.bgHovered : AnymorphColor.bgSurface
+ case .ghost:
+ // A labeled ghost deepens its label only; an icon-only ghost needs the plate to read as a button.
+ guard iconOnly else { return .clear }
+ if configuration.isPressed { return AnymorphColor.bgHovered }
+ return hovered ? AnymorphColor.bgSurface : .clear
+ }
+ }
+
+ private var borderColor: Color {
+ guard isEnabled else {
+ return appearance == .light || appearance == .secondary ? AnymorphColor.strokeLight : .clear
+ }
+ switch appearance {
+ case .light: return AnymorphColor.strokeBase
+ case .secondary: return active ? AnymorphColor.strokeBase : .clear
+ case .solid, .ghost: return .clear
+ }
+ }
+
+ private var foregroundColor: Color {
+ guard isEnabled else {
+ // A disabled solid takes the page ground as ink, so its label sinks into the faint box.
+ return appearance == .solid ? AnymorphColor.bgBase : AnymorphColor.fgDisabled
+ }
+ switch appearance {
+ case .solid: return AnymorphColor.fgInverse
+ case .light: return AnymorphColor.fgPrimary
+ case .secondary, .ghost: return active ? AnymorphColor.fgPrimary : AnymorphColor.fgSecondary
+ }
+ }
+ }
+}
+
+public extension View {
+ /// Shows a pointing-hand cursor on macOS while enabled, returning to the default arrow when disabled.
+ func morphPointerCursor(_ active: Bool = true) -> some View {
+ modifier(MorphPointerCursorModifier(active: active))
+ }
+
+ func anymorphButton(
+ size: AnymorphButtonSize = .md,
+ appearance: AnymorphButtonAppearance = .light,
+ iconOnly: Bool = false
+ ) -> some View {
+ self.buttonStyle(AnymorphButtonStyle(size: size, appearance: appearance, iconOnly: iconOnly))
+ }
+}
+
+// MARK: - 7. Badge (badge — 4px radius, 20pt minimum height)
+
+/// A state or category label in the neutral fill. The word carries the meaning; there are no status hues.
+public struct AnymorphBadge: View {
+ public let text: String
+
+ public init(_ text: String) {
+ self.text = text
+ }
+
+ public var body: some View {
+ Text(text)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary, tabular: true)
+ .lineLimit(1)
+ .padding(.horizontal, 6)
+ .frame(minHeight: 20)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous).fill(AnymorphColor.bgSurface))
+ }
+}
+
+// MARK: - 8. Card (card — default and chat, sections layout)
+
+public enum AnymorphCardVariant {
+ /// Card default: r12, background.elevated, stroke.elevated and the faint lift. Settings groups.
+ case standard
+ /// Card chat: Grok Bot's r16 card inside a conversation, a shade above the canvas in dark mode.
+ case chat
+}
+
+/// A card in the sections layout: the content draws its own rows and insets, the card only frames them.
+public struct AnymorphCard: View {
+ private let variant: AnymorphCardVariant
+ private let content: Content
+ @Environment(\.colorScheme) private var colorScheme
+
+ public init(_ variant: AnymorphCardVariant = .standard, @ViewBuilder content: () -> Content) {
+ self.variant = variant
+ self.content = content()
+ }
+
+ public var body: some View {
+ let radius: CGFloat = variant == .chat ? 16 : 12
+ let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)
+ content
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(shape.fill(variant == .chat ? AnymorphColor.bgCard : AnymorphColor.bgElevated))
+ .clipShape(shape)
+ .overlay(shape.strokeBorder(variant == .chat ? AnymorphColor.strokeBase : AnymorphColor.strokeElevated, lineWidth: 1))
+ .shadow(
+ color: colorScheme == .light ? (variant == .chat ? Color.black.opacity(0.04) : AnymorphColor.cardShadow) : .clear,
+ radius: variant == .chat ? 6 : 2, x: 0, y: 2
+ )
+ }
+}
+
+
+private struct MorphPointerCursorModifier: ViewModifier {
+ let active: Bool
+ @Environment(\.isEnabled) private var isEnabled
+
+ func body(content: Content) -> some View {
+ #if os(macOS)
+ content.pointerStyle(active && isEnabled ? .link : .default)
+ #else
+ content
+ #endif
+ }
+}
+
+/// Plain button style that shows a pointing-hand cursor on macOS while enabled.
+public struct MorphPlainButtonStyle: ButtonStyle {
+ public init() {}
+
+ public func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .morphPointerCursor()
+ }
+}
+
+public extension ButtonStyle where Self == MorphPlainButtonStyle {
+ static var morphPlain: MorphPlainButtonStyle { MorphPlainButtonStyle() }
+}
+
+// MARK: - 9. Underline Tabs & Segment Control (tabs, segment-control)
+
+/// Underline tabs: callout at the emphasis weight in both states, so selecting a tab never shifts its width;
+/// tertiary at rest, primary when selected, with a 2pt primary bar over the row's base hairline.
+public struct AnymorphUnderlineTabs: View {
+ public let items: [Item]
+ @Binding public var selection: Item
+ public let title: (Item) -> String
+ public let count: (Item) -> Int?
+ @Namespace private var tabNamespace
+
+ public init(
+ items: [Item],
+ selection: Binding- ,
+ title: @escaping (Item) -> String,
+ count: @escaping (Item) -> Int? = { _ in nil }
+ ) {
+ self.items = items
+ self._selection = selection
+ self.title = title
+ self.count = count
+ }
+
+ public var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 4) {
+ ForEach(items) { item in
+ let isSelected = selection == item
+ Button {
+ guard selection != item else { return }
+ selection = item
+ } label: {
+ VStack(spacing: 0) {
+ HStack(spacing: 6) {
+ Text(title(item))
+ .anymorphText(
+ .callout,
+ weight: .emphasis,
+ color: isSelected ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary
+ )
+ if let c = count(item), c > 0 {
+ Text("\(c)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.top, 10)
+ .padding(.bottom, 8)
+
+ ZStack {
+ Color.clear.frame(height: 2)
+ if isSelected {
+ Rectangle()
+ .fill(AnymorphColor.fgPrimary)
+ .frame(height: 2)
+ .matchedGeometryEffect(id: "underline-tab", in: tabNamespace)
+ }
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+ }
+ .animation(AnymorphMotion.fast, value: selection)
+ }
+ .overlay(alignment: .bottom) {
+ Rectangle()
+ .fill(AnymorphColor.strokeBase)
+ .frame(height: 1)
+ }
+ }
+}
+
+/// Segment control (md, 32pt): a bordered r10 frame with a surface plate sliding under the selected segment.
+/// Labels are callout, primary at the emphasis weight when selected and quaternary otherwise.
+public struct AnymorphSegmentControl
: View {
+ public let items: [Item]
+ @Binding public var selection: Item
+ public let label: (Item) -> String
+ public let badgeCount: (Item) -> Int?
+ @Namespace private var segmentNamespace
+
+ public init(
+ items: [Item],
+ selection: Binding- ,
+ label: @escaping (Item) -> String,
+ badgeCount: @escaping (Item) -> Int? = { _ in nil }
+ ) {
+ self.items = items
+ self._selection = selection
+ self.label = label
+ self.badgeCount = badgeCount
+ }
+
+ public var body: some View {
+ HStack(spacing: 2) {
+ ForEach(items) { item in
+ let isSelected = selection == item
+ Button {
+ guard selection != item else { return }
+ selection = item
+ } label: {
+ HStack(spacing: 5) {
+ Text(label(item))
+ .anymorphText(
+ .callout,
+ weight: isSelected ? .emphasis : .base,
+ color: isSelected ? AnymorphColor.fgPrimary : AnymorphColor.fgQuaternary
+ )
+ if let c = badgeCount(item), c > 0 {
+ Text("\(c)")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ }
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 24)
+ .background {
+ if isSelected {
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(AnymorphColor.bgSurface)
+ .matchedGeometryEffect(id: "segment-plate", in: segmentNamespace)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+ }
+ .animation(AnymorphMotion.fast, value: selection)
+ .padding(3)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).fill(AnymorphColor.bgBase))
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ }
+}
+
+// MARK: - 10. Avatar, Divider, Switch, TextField
+
+/// A person's circular avatar: shows their synced profile image (e.g. Google Workspace photo)
+/// when available and falls back cleanly to initials on the neutral surface.
+public struct AnymorphAvatar: View {
+ public let initials: String
+ public let avatarURL: URL?
+ public let size: CGFloat
+
+ public init(initials: String, avatarURL: URL? = nil, size: CGFloat = 24) {
+ self.initials = initials
+ self.avatarURL = avatarURL
+ self.size = size
+ }
+
+ public var body: some View {
+ if let avatarURL {
+ AsyncImage(url: avatarURL) { phase in
+ switch phase {
+ case .success(let image):
+ image
+ .resizable()
+ .scaledToFill()
+ default:
+ fallbackInitials
+ }
+ }
+ .frame(width: size, height: size)
+ .clipShape(Circle())
+ .overlay(Circle().strokeBorder(AnymorphColor.strokeBase, lineWidth: 0.5))
+ } else {
+ fallbackInitials
+ }
+ }
+
+ private var fallbackInitials: some View {
+ let fontSize: CGFloat = size <= 20 ? 9 : (size <= 28 ? 11 : 13)
+ return Text(initials.prefix(2).uppercased())
+ .font(.system(size: fontSize, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: size, height: size)
+ .background(Circle().fill(AnymorphColor.bgSurface))
+ }
+}
+
+/// Leading avatar for a multi-account AI pool row: displays the account's synced profile photo
+/// (with a small monochrome provider badge in the corner) when available, or the provider icon otherwise.
+public struct MorphAccountAvatar: View {
+ public let provider: String
+ public let email: String
+ public let avatarURL: URL?
+ public let size: CGFloat
+
+ public init(provider: String, email: String, avatarURL: URL?, size: CGFloat = 28) {
+ self.provider = provider
+ self.email = email
+ self.avatarURL = avatarURL
+ self.size = size
+ }
+
+ public var body: some View {
+ if let avatarURL {
+ ZStack(alignment: .bottomTrailing) {
+ AnymorphAvatar(initials: accountInitials, avatarURL: avatarURL, size: size)
+ providerCornerBadge
+ .offset(x: 3, y: 3)
+ }
+ .frame(width: size, height: size)
+ } else if size == 28 {
+ MorphEngine.icon(for: provider)
+ } else {
+ Group {
+ if let brand = MorphBrand(provider: provider) {
+ MorphBrandMark(brand, size: max(12, round(size * 0.68)))
+ } else {
+ Image(systemName: "cpu")
+ .font(.system(size: max(10, round(size * 0.48)), weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ }
+ .frame(width: size, height: size)
+ }
+ }
+
+ private var accountInitials: String {
+ let local = email.split(separator: "@").first.map(String.init) ?? email
+ let trimmed = local.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? "AI" : String(trimmed.prefix(2))
+ }
+
+ @ViewBuilder
+ private var providerCornerBadge: some View {
+ Group {
+ if let brand = MorphBrand(provider: provider) {
+ MorphBrandMark(brand, size: 8, color: AnymorphColor.fgPrimary)
+ } else {
+ Image(systemName: "cpu")
+ .font(.system(size: 7, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ }
+ }
+ .frame(width: 14, height: 14)
+ .background(Circle().fill(AnymorphColor.bgCard))
+ .overlay(Circle().strokeBorder(AnymorphColor.bgGrouped, lineWidth: 1.5))
+ }
+}
+
+public struct AnymorphDivider: View {
+ public init() {}
+ public var body: some View {
+ Rectangle()
+ .fill(AnymorphColor.strokeLight)
+ .frame(height: 1)
+ }
+}
+
+/// Subtle shimmering status text ("Working", "Thinking · ...", live tool step):
+/// a calm horizontal light sweep across muted monochrome ink, without a spinning wheel.
+public struct MorphShimmerText: View {
+ public let text: String
+ public let scale: AnymorphTypeScale
+ public let weight: AnymorphFontWeight
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(_ text: String, scale: AnymorphTypeScale = .body, weight: AnymorphFontWeight = .base) {
+ self.text = text
+ self.scale = scale
+ self.weight = weight
+ }
+
+ public var body: some View {
+ if reduceMotion {
+ Text(text)
+ .anymorphText(scale, weight: weight, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { context in
+ let cycle: Double = 1.8
+ let t = context.date.timeIntervalSinceReferenceDate
+ .truncatingRemainder(dividingBy: cycle) / cycle
+ // Sweep highlight band smoothly from left (-0.35) to right (1.35)
+ let center = -0.35 + (t * 1.7)
+ let low = max(0, min(1, center - 0.24))
+ let mid = max(0, min(1, center))
+ let high = max(0, min(1, center + 0.24))
+
+ Text(text)
+ .anymorphText(scale, weight: weight, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ .overlay {
+ LinearGradient(
+ stops: [
+ .init(color: AnymorphColor.fgTertiary, location: 0),
+ .init(color: AnymorphColor.fgTertiary, location: low),
+ .init(color: AnymorphColor.fgPrimary, location: mid),
+ .init(color: AnymorphColor.fgTertiary, location: high),
+ .init(color: AnymorphColor.fgTertiary, location: 1),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ )
+ .mask(
+ Text(text)
+ .anymorphText(scale, weight: weight, color: .white)
+ .lineLimit(1)
+ )
+ }
+ }
+ }
+ }
+}
+
+/// Quiet monochrome rotating sync icon for remote thread and workspace syncing.
+/// Uses native SF Symbol rotation so idle layout stays at 0% CPU and respects Reduce Motion.
+public struct MorphSyncIcon: View {
+ public let size: CGFloat
+ public let color: Color
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(size: CGFloat = 12, color: Color = AnymorphColor.fgSecondary) {
+ self.size = size
+ self.color = color
+ }
+
+ public var body: some View {
+ Image(systemName: "arrow.triangle.2.circlepath")
+ .font(.system(size: size, weight: .medium))
+ .foregroundStyle(color)
+ .symbolEffect(.rotate.byLayer, options: .repeat(.continuous), isActive: !reduceMotion)
+ }
+}
+
+/// 2×2 animated dot matrix shown on running sidebar threads and active tool groups.
+public struct MorphRunningDots: View {
+ public let dotSize: CGFloat
+ public let spacing: CGFloat
+ public let color: Color
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(dotSize: CGFloat = 2.6, spacing: CGFloat = 2.4, color: Color = AnymorphColor.fgPrimary) {
+ self.dotSize = dotSize
+ self.spacing = spacing
+ self.color = color
+ }
+
+ public var body: some View {
+ if reduceMotion {
+ grid(phases: [0.95, 0.55, 0.55, 0.95])
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 24.0)) { context in
+ let t = context.date.timeIntervalSinceReferenceDate * 4.2
+ // Clockwise ripple: top-left (0), top-right (1), bottom-right (3), bottom-left (2)
+ let order: [Double] = [0.0, 1.0, 3.0, 2.0]
+ let phases = order.map { idx -> Double in
+ let wave = (sin(t - idx * (.pi / 2.0)) + 1.0) * 0.5
+ return 0.28 + (0.72 * wave)
+ }
+ grid(phases: phases)
+ }
+ }
+ }
+
+ private func grid(phases: [Double]) -> some View {
+ let side = dotSize * 2 + spacing
+ return Canvas { context, _ in
+ let points: [(CGFloat, CGFloat)] = [
+ (0, 0),
+ (dotSize + spacing, 0),
+ (0, dotSize + spacing),
+ (dotSize + spacing, dotSize + spacing),
+ ]
+ for (index, origin) in points.enumerated() {
+ let rect = CGRect(x: origin.0, y: origin.1, width: dotSize, height: dotSize)
+ context.fill(
+ Path(ellipseIn: rect),
+ with: .color(color.opacity(phases[index]))
+ )
+ }
+ }
+ .frame(width: side, height: side)
+ .accessibilityHidden(true)
+ }
+}
+
+/// Semantic status dot for Morph Code sidebar rows, folder headers, and mode switcher indicators.
+public struct MorphCodeStatusDot: View {
+ public let status: CodeThreadVisualStatus
+ public var size: CGFloat
+
+ public init(_ status: CodeThreadVisualStatus, size: CGFloat = 7) {
+ self.status = status
+ self.size = size
+ }
+
+ public var body: some View {
+ if let color = AnymorphColor.codeStatus(status) {
+ Circle()
+ .fill(color)
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+ }
+}
+
+/// Exact Lucide-geometry vector icons for action bar iconography
+/// (24×24 coordinate space, rounded caps/joins, uniform light-regular stroke).
+public enum MorphLucideKind: Sendable {
+ case copy
+ case check
+ case pencil
+ case undo
+ case redo
+ case x
+ case arrowUp
+ case arrowDown
+ case cornerDownRight
+ case gitBranch
+}
+
+public struct MorphLucideIcon: View {
+ public let kind: MorphLucideKind
+ public let size: CGFloat
+ public let lineWidth: CGFloat
+
+ public init(_ kind: MorphLucideKind, size: CGFloat = 13.5, lineWidth: CGFloat = 1.65) {
+ self.kind = kind
+ self.size = size
+ self.lineWidth = lineWidth
+ }
+
+ public var body: some View {
+ MorphLucideShape(kind: kind)
+ .stroke(style: StrokeStyle(lineWidth: lineWidth * (size / 24.0) * (24.0 / 15.0), lineCap: .round, lineJoin: .round))
+ .frame(width: size, height: size)
+ }
+}
+
+private struct MorphLucideShape: Shape {
+ let kind: MorphLucideKind
+
+ func path(in rect: CGRect) -> Path {
+ let sx = rect.width / 24.0
+ let sy = rect.height / 24.0
+ func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
+ CGPoint(x: rect.minX + x * sx, y: rect.minY + y * sy)
+ }
+ var p = Path()
+ switch kind {
+ case .copy:
+ // Lucide `copy`: front rounded square (8,8,14,14,r=2) + back L-frame
+ p.addRoundedRect(
+ in: CGRect(x: rect.minX + 8 * sx, y: rect.minY + 8 * sy, width: 14 * sx, height: 14 * sy),
+ cornerSize: CGSize(width: 2.2 * sx, height: 2.2 * sy)
+ )
+ p.move(to: pt(4, 16))
+ p.addQuadCurve(to: pt(2, 14), control: pt(2, 16))
+ p.addLine(to: pt(2, 4))
+ p.addQuadCurve(to: pt(4, 2), control: pt(2, 2))
+ p.addLine(to: pt(14, 2))
+ p.addQuadCurve(to: pt(16, 4), control: pt(16, 2))
+ case .check:
+ p.move(to: pt(20, 6))
+ p.addLine(to: pt(9, 17))
+ p.addLine(to: pt(4, 12))
+ case .pencil:
+ // Lucide `pencil`
+ p.move(to: pt(17.5, 3.5))
+ p.addQuadCurve(to: pt(20.5, 3.5), control: pt(19, 2))
+ p.addQuadCurve(to: pt(20.5, 6.5), control: pt(22, 5))
+ p.addLine(to: pt(7.5, 19.5))
+ p.addLine(to: pt(2.5, 21.5))
+ p.addLine(to: pt(4.5, 16.5))
+ p.closeSubpath()
+ p.move(to: pt(15, 6))
+ p.addLine(to: pt(18, 9))
+ case .undo:
+ // Lucide `undo-2`
+ p.move(to: pt(9, 14))
+ p.addLine(to: pt(4, 9))
+ p.addLine(to: pt(9, 4))
+ p.move(to: pt(4, 9))
+ p.addLine(to: pt(14.5, 9))
+ p.addArc(center: pt(14.5, 14.5), radius: 5.5 * sx, startAngle: .degrees(-90), endAngle: .degrees(90), clockwise: false)
+ p.addLine(to: pt(11, 20))
+ case .redo:
+ // Lucide `redo-2`
+ p.move(to: pt(15, 14))
+ p.addLine(to: pt(20, 9))
+ p.addLine(to: pt(15, 4))
+ p.move(to: pt(20, 9))
+ p.addLine(to: pt(9.5, 9))
+ p.addArc(center: pt(9.5, 14.5), radius: 5.5 * sx, startAngle: .degrees(-90), endAngle: .degrees(-270), clockwise: true)
+ p.addLine(to: pt(13, 20))
+ case .x:
+ p.move(to: pt(18, 6))
+ p.addLine(to: pt(6, 18))
+ p.move(to: pt(6, 6))
+ p.addLine(to: pt(18, 18))
+ case .arrowUp:
+ p.move(to: pt(12, 19))
+ p.addLine(to: pt(12, 5))
+ p.move(to: pt(5, 12))
+ p.addLine(to: pt(12, 5))
+ p.addLine(to: pt(19, 12))
+ case .arrowDown:
+ p.move(to: pt(12, 5))
+ p.addLine(to: pt(12, 19))
+ p.move(to: pt(19, 12))
+ p.addLine(to: pt(12, 19))
+ p.addLine(to: pt(5, 12))
+ case .cornerDownRight:
+ p.move(to: pt(15, 10))
+ p.addLine(to: pt(20, 15))
+ p.addLine(to: pt(15, 20))
+ p.move(to: pt(4, 4))
+ p.addLine(to: pt(4, 11))
+ p.addQuadCurve(to: pt(8, 15), control: pt(4, 15))
+ p.addLine(to: pt(20, 15))
+ case .gitBranch:
+ // Lucide `git-branch`
+ p.move(to: pt(6, 3))
+ p.addLine(to: pt(6, 15))
+ p.addEllipse(in: CGRect(x: 15 * sx, y: 3 * sy, width: 6 * sx, height: 6 * sy))
+ p.addEllipse(in: CGRect(x: 3 * sx, y: 15 * sy, width: 6 * sx, height: 6 * sy))
+ p.move(to: pt(18, 9))
+ p.addCurve(to: pt(9, 18), control1: pt(18, 14), control2: pt(14, 18))
+ }
+ return p
+ }
+}
+
+/// Switch (switch.tsx): a 36×20 track, inverse when on and disabled-gray when off, under a 16pt knob.
+/// Give the Toggle an accessibility label; the style draws the switch alone.
+public struct AnymorphSwitchStyle: ToggleStyle {
+ public init() {}
+
+ public func makeBody(configuration: Configuration) -> some View {
+ AnymorphSwitch(configuration: configuration)
+ }
+
+ private struct AnymorphSwitch: View {
+ let configuration: Configuration
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ let on = configuration.isOn
+ ZStack(alignment: on ? .trailing : .leading) {
+ Capsule().fill(on ? AnymorphColor.bgInverse : AnymorphColor.bgDisabled)
+ Circle()
+ .fill(on ? AnymorphColor.bgBase : Color.white)
+ .frame(width: 16, height: 16)
+ .shadow(color: Color.black.opacity(0.15), radius: 1, x: 0, y: 1)
+ .padding(2)
+ }
+ .frame(width: 36, height: 20)
+ .opacity(isEnabled ? 1 : 0.5)
+ .contentShape(Capsule())
+ .morphPointerCursor()
+ .onTapGesture {
+ guard isEnabled else { return }
+ withAnimation(AnymorphMotion.fast) { configuration.isOn.toggle() }
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityAddTraits(.isToggle)
+ .accessibilityValue(on ? "켜짐" : "꺼짐")
+ .accessibilityAction { configuration.isOn.toggle() }
+ }
+ }
+}
+
+/// A number with a minus and a plus button, the in-app stand-in for the system `Stepper`. Steps clamp to the range, and
+/// VoiceOver can adjust it with swipe up and down.
+public struct AnymorphStepper: View {
+ let label: String
+ @Binding var value: Int
+ let range: ClosedRange
+ let step: Int
+
+ public init(_ label: String, value: Binding, in range: ClosedRange, step: Int = 1) {
+ self.label = label
+ self._value = value
+ self.range = range
+ self.step = step
+ }
+
+ public var body: some View {
+ HStack(spacing: 10) {
+ Text(label)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ HStack(spacing: 4) {
+ button("minus", delta: -step, name: "줄이기")
+ button("plus", delta: step, name: "늘리기")
+ }
+ }
+ .fixedSize()
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(label)
+ .accessibilityAdjustableAction { direction in
+ switch direction {
+ case .increment: value = min(value + step, range.upperBound)
+ case .decrement: value = max(value - step, range.lowerBound)
+ @unknown default: break
+ }
+ }
+ }
+
+ private func button(_ symbol: String, delta: Int, name: String) -> some View {
+ let next = min(max(value + delta, range.lowerBound), range.upperBound)
+ let canStep = next != value
+ return Button {
+ value = next
+ } label: {
+ Image(systemName: symbol)
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(canStep ? AnymorphColor.fgSecondary : AnymorphColor.fgDisabled)
+ .frame(width: 24, height: 24)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous).fill(AnymorphColor.bgSelected))
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ }
+ .buttonStyle(MorphStepperPressStyle())
+ .disabled(!canStep)
+ }
+}
+
+private struct MorphStepperPressStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .opacity(configuration.isPressed ? 0.6 : 1)
+ .animation(AnymorphMotion.fast, value: configuration.isPressed)
+ .morphPointerCursor()
+ }
+}
+
+public enum AnymorphFieldAppearance {
+ /// Input: base fill with a base hairline that turns strong while typing.
+ case outlined
+ /// SearchBar: subtle fill without a border at rest; the border appears while typing.
+ case filled
+}
+
+public struct AnymorphTextField: View {
+ public let placeholder: String
+ @Binding public var text: String
+ public var leadingSystemImage: String?
+ public var appearance: AnymorphFieldAppearance
+ public var isSecure: Bool
+ public var focusOnAppear: Bool
+ public var onSubmit: (() -> Void)?
+ @FocusState private var focused: Bool
+
+ public init(
+ _ placeholder: String,
+ text: Binding,
+ leadingSystemImage: String? = nil,
+ appearance: AnymorphFieldAppearance = .outlined,
+ isSecure: Bool = false,
+ focusOnAppear: Bool = false,
+ onSubmit: (() -> Void)? = nil
+ ) {
+ self.placeholder = placeholder
+ self._text = text
+ self.leadingSystemImage = leadingSystemImage
+ self.appearance = appearance
+ self.isSecure = isSecure
+ self.focusOnAppear = focusOnAppear
+ self.onSubmit = onSubmit
+ }
+
+ private var fill: Color {
+ appearance == .filled && !focused ? AnymorphColor.bgSubtle : AnymorphColor.bgBase
+ }
+
+ private var border: Color {
+ switch appearance {
+ case .outlined: return focused ? AnymorphColor.strokeStrong : AnymorphColor.strokeBase
+ case .filled: return focused ? AnymorphColor.strokeBase : .clear
+ }
+ }
+
+ public var body: some View {
+ HStack(spacing: 8) {
+ if let leadingSystemImage {
+ Image(systemName: leadingSystemImage)
+ .font(.system(size: 13, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ Group {
+ if isSecure {
+ SecureField(placeholder, text: $text)
+ } else {
+ TextField(placeholder, text: $text)
+ }
+ }
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.callout, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .focused($focused)
+ .onSubmit { onSubmit?() }
+ }
+ .padding(.horizontal, appearance == .filled ? 10 : 12)
+ .frame(height: 32)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).fill(fill))
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).strokeBorder(border, lineWidth: 1))
+ .animation(AnymorphMotion.fast, value: focused)
+ .onAppear {
+ guard focusOnAppear else { return }
+ Task { @MainActor in focused = true }
+ }
+ }
+}
+
+// MARK: - 11. Assistant Chat Components (assistant mark, composer, steps, markdown, toast)
+
+/// The assistant's figure: the logo's three diamonds swollen into soft, gummy shapes, with two small eyes cut out of
+/// the top one. Like Pickle and Dots it gives the assistant a face without turning it into a drawn character, and it
+/// keeps the logo's layout. The app icon and menu bar keep the official sharp mark (`AnymorphLogoMark`).
+enum MorphAssistantFigure {
+ /// Centers of the left, top and right diamonds in `anymorph_logo.svg` units.
+ private static let centers = [
+ CGPoint(x: 6.1211, y: 13.5),
+ CGPoint(x: 13.499, y: 6.1221),
+ CGPoint(x: 20.8779, y: 13.5),
+ ]
+ /// The logo's diamond side grown by 10%, so the rounded shapes keep the logo's weight. The gaps stay open.
+ private static let side: CGFloat = 12.2422 / 2.0.squareRoot() * 1.10
+
+ /// One rounded diamond around `center`, in logo units.
+ private static func shape(at center: CGPoint) -> Path {
+ Path(
+ roundedRect: CGRect(x: -side / 2, y: -side / 2, width: side, height: side),
+ cornerRadius: side * 0.42,
+ style: .continuous
+ )
+ .applying(CGAffineTransform(rotationAngle: .pi / 4))
+ .applying(CGAffineTransform(translationX: center.x, y: center.y))
+ }
+
+ /// The three shapes' bounds in logo units.
+ private static let bounds = centers.reduce(CGRect.null) { $0.union(shape(at: $1).boundingRect) }
+
+ /// Height over width, about 0.70.
+ static let aspectRatio = bounds.height / bounds.width
+
+ /// The left, top and right shapes scaled into `size`. The top shape carries the eyes as holes, so fill each path
+ /// with `FillStyle(eoFill: true)`; whatever is behind the figure shows through them.
+ static func paths(in size: CGSize) -> [Path] {
+ let scale = size.width / bounds.width
+ let fit = CGAffineTransform(translationX: -bounds.minX, y: -bounds.minY)
+ .concatenating(CGAffineTransform(scaleX: scale, y: scale))
+ var shapes = centers.map { shape(at: $0).applying(fit) }
+ // Two upright capsules on the top shape. Below about 28pt they keep a minimum size, so the face still
+ // reads at the 22–24pt header and settings sizes.
+ let topSide = side * scale
+ let eye = CGSize(width: max(topSide * 0.12, 1.25), height: max(topSide * 0.22, 2.2))
+ let spread = max(topSide * 0.17, 1.45)
+ let face = centers[1].applying(fit)
+ for direction in [-1.0, 1.0] {
+ let eyeRect = CGRect(
+ x: face.x + direction * spread - eye.width / 2,
+ y: face.y + topSide * 0.02 - eye.height / 2,
+ width: eye.width,
+ height: eye.height
+ )
+ shapes[1].addPath(Path(roundedRect: eyeRect, cornerRadius: eye.width / 2))
+ }
+ return shapes
+ }
+}
+
+/// The assistant's avatar: `MorphAssistantFigure` in ink with no circle or tile behind it, the way Grok Bot draws a
+/// bot as a bare figure. Black in light mode and white in dark mode; the shapes pulse while the assistant works.
+public struct MorphAssistantMark: View {
+ /// The figure's width. The height follows its proportions (`MorphAssistantFigure.aspectRatio`).
+ public let width: CGFloat
+ public var isWorking: Bool
+
+ public init(width: CGFloat = 20, isWorking: Bool = false) {
+ self.width = width
+ self.isWorking = isWorking
+ }
+
+ public var body: some View {
+ if isWorking {
+ MorphThinkingMark(width: width, color: AnymorphColor.fgPrimary)
+ } else {
+ Canvas { ctx, size in
+ for path in MorphAssistantFigure.paths(in: size) {
+ ctx.fill(path, with: .color(AnymorphColor.fgPrimary), style: FillStyle(eoFill: true))
+ }
+ }
+ .frame(width: width, height: width * MorphAssistantFigure.aspectRatio)
+ // The assistant's name always sits next to the figure, so VoiceOver reads the name alone.
+ .accessibilityHidden(true)
+ }
+ }
+}
+
+/// The assistant's figure with its three shapes pulsing in turn. Used while the assistant works.
+public struct MorphThinkingMark: View {
+ public var width: CGFloat
+ public var color: Color
+
+ public init(width: CGFloat = 16, color: Color = AnymorphColor.fgTertiary) {
+ self.width = width
+ self.color = color
+ }
+
+ public var body: some View {
+ TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { timeline in
+ let t = timeline.date.timeIntervalSinceReferenceDate
+ Canvas { ctx, size in
+ for (index, path) in MorphAssistantFigure.paths(in: size).enumerated() {
+ let phase = (t / 1.1 - Double(index) * 0.22).truncatingRemainder(dividingBy: 1)
+ let wave = 0.5 + 0.5 * cos(2 * .pi * phase)
+ ctx.fill(path, with: .color(color.opacity(0.25 + 0.75 * wave)), style: FillStyle(eoFill: true))
+ }
+ }
+ }
+ .frame(width: width, height: width * MorphAssistantFigure.aspectRatio)
+ .accessibilityLabel("Working..")
+ }
+}
+
+/// The chat header's identity: the assistant's figure alone, without its name beside it. The figure pulses while the
+/// assistant works; `note` appears only when something needs attention, such as being offline. VoiceOver reads
+/// `name`.
+public struct MorphAssistantTitle: View {
+ public let name: String
+ public var note: String?
+ public var isWorking: Bool
+ public var scale: AnymorphTypeScale
+ public var markWidth: CGFloat
+
+ public init(
+ name: String,
+ note: String? = nil,
+ isWorking: Bool = false,
+ scale: AnymorphTypeScale = .callout,
+ markWidth: CGFloat = 24
+ ) {
+ self.name = name
+ self.note = note
+ self.isWorking = isWorking
+ self.scale = scale
+ self.markWidth = markWidth
+ }
+
+ public var body: some View {
+ HStack(spacing: 8) {
+ MorphAssistantMark(width: markWidth, isWorking: isWorking)
+ if let note {
+ Text(note)
+ .anymorphText(scale, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel([name, isWorking ? "Working.." : nil, note].compactMap { $0 }.joined(separator: ", "))
+ }
+}
+
+/// Grok Bot's composer: one rounded field on the conversation's foot with the add (+) menu before the text and
+/// send at the end of its last line. On macOS the + sits inside the field; on iPhone it floats beside it, as in
+/// Grok Bot's phone app. Return sends on macOS.
+public struct MorphComposer: View {
+ public let placeholder: String
+ @Binding public var text: String
+ public let isBusy: Bool
+ private let focused: FocusState.Binding
+ public let onSubmit: () -> Void
+ private let accessory: Accessory
+
+ public init(
+ placeholder: String,
+ text: Binding,
+ isBusy: Bool,
+ focused: FocusState.Binding,
+ onSubmit: @escaping () -> Void,
+ @ViewBuilder accessory: () -> Accessory
+ ) {
+ self.placeholder = placeholder
+ self._text = text
+ self.isBusy = isBusy
+ self.focused = focused
+ self.onSubmit = onSubmit
+ self.accessory = accessory()
+ }
+
+ private var canSend: Bool {
+ !isBusy && !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var fieldShape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AnymorphRadius.panel, style: .continuous)
+ }
+
+ public var body: some View {
+ let isFocused = focused.wrappedValue
+ #if os(macOS)
+ HStack(alignment: .bottom, spacing: 4) {
+ accessory
+ field
+ sendButton
+ }
+ .padding(6)
+ .background(fieldShape.fill(AnymorphColor.bgGrouped))
+ .overlay(fieldShape.strokeBorder(isFocused ? AnymorphColor.strokeBase : AnymorphColor.strokeLight, lineWidth: 1))
+ .animation(AnymorphMotion.fast, value: isFocused)
+ #else
+ HStack(alignment: .bottom, spacing: 8) {
+ accessory
+ HStack(alignment: .bottom, spacing: 4) {
+ field
+ sendButton
+ }
+ .padding(4)
+ .background(fieldShape.fill(AnymorphColor.bgGrouped))
+ .overlay(fieldShape.strokeBorder(isFocused ? AnymorphColor.strokeBase : AnymorphColor.strokeLight, lineWidth: 1))
+ }
+ .animation(AnymorphMotion.fast, value: isFocused)
+ #endif
+ }
+
+ private var field: some View {
+ TextField(placeholder, text: $text, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.reading, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .lineLimit(1...8)
+ .focused(focused)
+ .onSubmit { if canSend { onSubmit() } }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 7)
+ .frame(minHeight: 32)
+ }
+
+ private var sendButton: some View {
+ Button(action: onSubmit) {
+ Image(systemName: "arrow.up")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(canSend ? AnymorphColor.fgInverse : AnymorphColor.fgQuaternary)
+ .frame(width: 32, height: 32)
+ .background(Circle().fill(canSend ? AnymorphColor.bgInverse : AnymorphColor.bgSelected))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.morphPlain)
+ .disabled(!canSend)
+ .accessibilityLabel("보내기")
+ .animation(AnymorphMotion.fast, value: canSend)
+ }
+}
+
+/// Plain-language names for assistant tools. Tool ids never reach the screen.
+public enum MorphToolCopy {
+ /// Older activity keeps the names tools had before: list_inbox_threads, list_recent_gmail, list_slack_channels.
+ public static func label(for tool: String) -> String {
+ switch baseName(tool) {
+ case "list_inbox", "list_inbox_threads", "staff_list_inbox": return "받은 대화 확인"
+ case "staff_list_communications", "triage_scan": return "슬랙·메일·팀즈 선별"
+ case "staff_read_communication": return "대화 원문 전문 읽기"
+ case "read_conversation", "staff_read_conversation": return "대화 읽기"
+ case "search_messages", "staff_search_messages": return "메시지 검색"
+ case "sync_channels", "staff_sync_channels": return "새 메시지 가져오기"
+ case "mark_thread", "staff_mark_thread": return "대화 상태 변경"
+ case "list_approvals", "staff_list_approvals": return "승인 대기 확인"
+ case "search_space", "staff_search_space", "staff_list_space_docs": return "Team Brain 검색"
+ case "staff_read_space_doc": return "Team Brain 템플릿 읽기"
+ case "staff_draft_email": return "새 메일 초안 작성"
+ case "playbook_list", "playbook_load": return "업무 플레이북 실행"
+ case "list_tasks", "staff_list_tasks": return "할 일 확인"
+ case "save_memory_bubble", "staff_save_memory": return "기억 저장"
+ case "staff_list_memories": return "기억 확인"
+ case "staff_delete_memory": return "기억 삭제"
+ case "create_task", "staff_create_task": return "할 일 추가"
+ case "staff_complete_task": return "할 일 완료"
+ case "draft_customer_reply", "staff_draft_reply": return "답글 초안 작성"
+ case "schedule_wakeup", "schedule_create": return "루틴 예약"
+ case "schedule_list": return "루틴 확인"
+ case "schedule_delete": return "루틴 중지"
+ case "scheduled_wake": return "자동 점검"
+ case "morphcode_pool_turn", "morphcode_staff_turn": return "스태프 작업"
+ case "search_gmail", "list_recent_gmail": return "메일 확인"
+ case "gmail_search": return "메일 검색"
+ case "gmail_read_thread": return "메일 읽기"
+ case "list_calendar_events", "calendar_list_events": return "일정 확인"
+ case "list_slack_channels", "slack_list_conversations": return "Slack"
+ case "slack_read_conversation": return "Read Slack thread"
+ case let name where name.hasPrefix("linear_"): return "Linear"
+ case let name where name.hasPrefix("github_"): return "GitHub"
+ case let name where name.hasPrefix("browser_"): return "Browser"
+ default: return "Action"
+ }
+ }
+
+ public static func icon(for tool: String) -> String {
+ switch baseName(tool) {
+ case "list_inbox", "list_inbox_threads", "staff_list_inbox", "read_conversation", "staff_read_conversation", "draft_customer_reply", "staff_draft_reply": return "bubble.left"
+ case "search_messages", "staff_search_messages": return "magnifyingglass"
+ case "sync_channels", "staff_sync_channels": return "arrow.triangle.2.circlepath"
+ case "mark_thread", "staff_mark_thread", "staff_complete_task": return "checkmark.circle"
+ case "list_approvals", "staff_list_approvals": return "checkmark.seal"
+ case "search_space", "staff_search_space": return "doc.text.magnifyingglass"
+ case "list_tasks", "staff_list_tasks", "create_task", "staff_create_task": return "checklist"
+ case "save_memory_bubble", "staff_save_memory", "staff_list_memories", "staff_delete_memory": return "bookmark"
+ case "schedule_wakeup", "scheduled_wake", "schedule_create", "schedule_list", "schedule_delete": return "clock"
+ case "morphcode_pool_turn", "morphcode_staff_turn": return "sparkles"
+ case "search_gmail", "list_recent_gmail", "gmail_search", "gmail_read_thread": return "envelope"
+ case "list_calendar_events", "calendar_list_events": return "calendar"
+ case "list_slack_channels", "slack_list_conversations", "slack_read_conversation": return "number"
+ case let name where name.hasPrefix("browser_"): return "globe"
+ default: return "circle"
+ }
+ }
+
+ /// The service a tool reaches, shown by its logo in place of the symbol; nil for Morph's own tools.
+ public static func brand(for tool: String) -> MorphBrand? {
+ switch baseName(tool) {
+ case "search_gmail", "list_recent_gmail", "gmail_search", "gmail_read_thread": return .gmail
+ case "list_calendar_events", "calendar_list_events": return .googleCalendar
+ case "list_slack_channels", "slack_list_conversations", "slack_read_conversation": return .slack
+ case let name where name.hasPrefix("linear_"): return .linear
+ case let name where name.hasPrefix("github_"): return .github
+ default: return nil
+ }
+ }
+
+ /// The tool's own name. Strips MCP / plugin gateway prefixes.
+ private static func baseName(_ tool: String) -> String {
+ for prefix in ["morph-plugins.", "mcp__morph-plugins__", "mcp__morph-browser__"] {
+ if tool.hasPrefix(prefix) {
+ return String(tool.dropFirst(prefix.count))
+ }
+ }
+ return tool
+ }
+}
+
+/// The small icon in front of a tool step or an activity row: the logo of the service the tool reached, the
+/// symbol of one of Morph's own tools, or a warning circle when it failed. It sits on the line's text baseline.
+public struct MorphToolIcon: View {
+ public let tool: String
+ public let failed: Bool
+ public let weight: Font.Weight
+
+ public init(tool: String, failed: Bool = false, weight: Font.Weight = .regular) {
+ self.tool = tool
+ self.failed = failed
+ self.weight = weight
+ }
+
+ public var body: some View {
+ Group {
+ if !failed, let brand = MorphToolCopy.brand(for: tool) {
+ MorphBrandMark(brand, size: 12, color: AnymorphColor.fgTertiary)
+ .alignmentGuide(.firstTextBaseline) { $0.height * 0.88 }
+ } else {
+ Image(systemName: failed ? "exclamationmark.circle" : MorphToolCopy.icon(for: tool))
+ .font(.system(size: 11, weight: weight))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ }
+ .frame(width: 14)
+ }
+}
+
+/// Marks inline-code runs inside `MorphMarkdownText` so `MorphMarkdownTextRenderer` draws rounded pills
+/// behind them without injecting extra space characters into copied text.
+private struct MorphInlineCodePillAttribute: TextAttribute, Equatable, Sendable {
+ let chipId: Int
+ /// True on the slice carrying the trailing kern so the renderer does not double-pad the right edge.
+ let hasTrailingKern: Bool
+ /// Extra outer gap baked into the trailing kern when a non-space character (e.g. a Korean particle) follows immediately.
+ let trailingTrim: CGFloat
+}
+
+/// Draws only the rounded, lightly bordered pills behind inline code runs so it can sit behind a selectable
+/// `Text` (SwiftUI skips `TextRenderer` on `.textSelection(.enabled)` text on macOS 15) without double-drawing glyphs.
+private struct MorphMarkdownPillBackgroundRenderer: TextRenderer {
+ let fillColor: Color
+ let strokeColor: Color
+
+ func draw(layout: Text.Layout, in ctx: inout GraphicsContext) {
+ let hPad: CGFloat = 3.5
+ let vPad: CGFloat = 1.5
+ let radius: CGFloat = 4.5
+
+ for line in layout {
+ var activeChipId: Int? = nil
+ var activeRect: CGRect = .null
+ var activeHasTrailingKern = false
+ var activeTrailingTrim: CGFloat = 0
+
+ func flushChip() {
+ guard activeChipId != nil, !activeRect.isNull else { return }
+ let rightExtra: CGFloat = activeHasTrailingKern ? -activeTrailingTrim : hPad
+ let pillRect = CGRect(
+ x: activeRect.minX - hPad,
+ y: activeRect.minY - vPad,
+ width: max(0, activeRect.width + hPad + rightExtra),
+ height: activeRect.height + vPad * 2
+ )
+ let path = Path(roundedRect: pillRect, cornerRadius: radius, style: .continuous)
+ ctx.fill(path, with: .color(fillColor))
+ ctx.stroke(path, with: .color(strokeColor), lineWidth: 0.75)
+ activeChipId = nil
+ activeRect = .null
+ activeHasTrailingKern = false
+ activeTrailingTrim = 0
+ }
+
+ for run in line {
+ if let attr = run[MorphInlineCodePillAttribute.self] {
+ let runRect = run.typographicBounds.rect
+ if activeChipId == attr.chipId {
+ activeRect = activeRect.union(runRect)
+ activeHasTrailingKern = activeHasTrailingKern || attr.hasTrailingKern
+ activeTrailingTrim = max(activeTrailingTrim, attr.trailingTrim)
+ } else {
+ flushChip()
+ activeChipId = attr.chipId
+ activeRect = runRect
+ activeHasTrailingKern = attr.hasTrailingKern
+ activeTrailingTrim = attr.trailingTrim
+ }
+ } else {
+ flushChip()
+ }
+ }
+ flushChip()
+ }
+ }
+}
+
+/// Lightweight Markdown renderer for assistant replies and Space documents.
+/// Handles headings, bullet and numbered lists, quotes, fenced code, rules, tables, inline images and inline styles.
+public struct MorphMarkdownText: View {
+ public let markdown: String
+ public var scale: AnymorphTypeScale
+ public var skipDuplicateTitle: String?
+ public var preserveLineBreaks: Bool
+ public var cacheParse: Bool
+ public var imageLoader: ((String) async -> Data?)?
+ public var onTapImage: ((String, Data) -> Void)?
+ /// Opens `path:line` references in Morph's reader when the conversation provides it.
+ @Environment(\.morphOpenFileLocation) private var openFileLocation
+ @Environment(\.openURL) private var parentOpenURL
+
+ public init(
+ _ markdown: String,
+ scale: AnymorphTypeScale = .reading,
+ skipDuplicateTitle: String? = nil,
+ preserveLineBreaks: Bool = false,
+ cacheParse: Bool = true,
+ imageLoader: ((String) async -> Data?)? = nil,
+ onTapImage: ((String, Data) -> Void)? = nil
+ ) {
+ self.markdown = markdown
+ self.scale = scale
+ self.skipDuplicateTitle = skipDuplicateTitle
+ self.preserveLineBreaks = preserveLineBreaks
+ self.cacheParse = cacheParse
+ self.imageLoader = imageLoader
+ self.onTapImage = onTapImage
+ }
+
+ struct InlineImage: Equatable {
+ let alt: String
+ let source: String
+ }
+
+ /// A lone image gets more height than one of several, which share a line while they fit.
+ private static let singleImageMaxHeight: CGFloat = 360
+ private static let groupedImageMaxHeight: CGFloat = 280
+
+ enum Block: Identifiable {
+ case heading(id: Int, level: Int, text: String)
+ case bullet(id: Int, text: String)
+ case task(id: Int, checked: Bool, text: String)
+ case numbered(id: Int, marker: String, text: String)
+ case quote(id: Int, text: String)
+ case code(id: Int, language: String?, text: String)
+ /// Images that follow one another. They share a line while they fit.
+ case images(id: Int, items: [InlineImage])
+ case rule(id: Int)
+ case table(id: Int, headers: [String], rows: [[String]])
+ case paragraph(id: Int, text: String)
+
+ var id: Int {
+ switch self {
+ case .heading(let id, _, _), .bullet(let id, _), .task(let id, _, _), .numbered(let id, _, _), .quote(let id, _),
+ .code(let id, _, _), .images(let id, _), .rule(let id), .table(let id, _, _), .paragraph(let id, _):
+ return id
+ }
+ }
+
+ var layoutKind: MorphMarkdownLayout.BlockKind {
+ switch self {
+ case .heading(_, let level, _):
+ return .heading(level)
+ case .paragraph(_, let text):
+ return .paragraph(isStandaloneEmphasis: MorphMarkdownLayout.isStandaloneEmphasisParagraph(text))
+ case .bullet:
+ return .bullet
+ case .task:
+ return .task
+ case .numbered:
+ return .numbered
+ case .quote:
+ return .quote
+ case .code:
+ return .code
+ case .images:
+ return .images
+ case .rule:
+ return .rule
+ case .table:
+ return .table
+ }
+ }
+ }
+
+ static func numberedMarker(_ line: String) -> (marker: String, rest: String)? {
+ var digits = ""
+ var index = line.startIndex
+ while index < line.endIndex, line[index].isNumber, digits.count < 3 {
+ digits.append(line[index])
+ index = line.index(after: index)
+ }
+ guard !digits.isEmpty, index < line.endIndex, line[index] == "." || line[index] == ")" else { return nil }
+ let afterMarker = line.index(after: index)
+ guard afterMarker < line.endIndex, line[afterMarker] == " " else { return nil }
+ return ("\(digits).", String(line[line.index(after: afterMarker)...]))
+ }
+
+ private static let imgSrcRegex = try? NSRegularExpression(pattern: #"src\s*=\s*["']([^"']+)["']"#, options: [.caseInsensitive])
+ private static let imgAltRegex = try? NSRegularExpression(pattern: #"alt\s*=\s*["']([^"']*)["']"#, options: [.caseInsensitive])
+ private static let embeddedImageRegex = try? NSRegularExpression(pattern: #"!\[([^\]]*)\]\(([^)\s]+(?:\s+"[^"]*")?)\)"#)
+
+ private struct ParseCacheKey: Hashable {
+ let markdown: String
+ let skipDuplicateTitle: String?
+ let preserveLineBreaks: Bool
+ }
+
+ private struct InlineCacheKey: Hashable {
+ let raw: String
+ let linkFiles: Bool
+ let scale: AnymorphTypeScale
+ }
+
+ private struct InlineSegment {
+ let slice: AttributedString
+ let pill: MorphInlineCodePillAttribute?
+ }
+
+ private struct RenderedInline {
+ let segments: [InlineSegment]
+ let hasPills: Bool
+ }
+
+ @MainActor
+ private final class RenderCache {
+ static let shared = RenderCache()
+ private struct Entry {
+ let value: Value
+ var lastUsed: UInt64
+ }
+ private var blocksByKey: [ParseCacheKey: Entry<[Block]>] = [:]
+ private var inlineByKey: [InlineCacheKey: Entry] = [:]
+ private var tick: UInt64 = 0
+ private let maxBlockEntries = 256
+ private let maxInlineEntries = 512
+
+ private func nextTick() -> UInt64 {
+ tick &+= 1
+ return tick
+ }
+
+ private func evictOldestQuarter(from dict: inout [K: Entry], limit: Int) {
+ guard dict.count >= limit else { return }
+ let removeCount = max(1, limit / 4)
+ let oldest = dict.sorted { $0.value.lastUsed < $1.value.lastUsed }.prefix(removeCount)
+ for (k, _) in oldest {
+ dict.removeValue(forKey: k)
+ }
+ }
+
+ func blocks(for markdown: String, skipDuplicateTitle: String?, preserveLineBreaks: Bool, cache: Bool = true) -> [Block] {
+ if !cache {
+ return MorphMarkdownText.parse(markdown, skipDuplicateTitle: skipDuplicateTitle, preserveLineBreaks: preserveLineBreaks)
+ }
+ let key = ParseCacheKey(markdown: markdown, skipDuplicateTitle: skipDuplicateTitle, preserveLineBreaks: preserveLineBreaks)
+ if var hit = blocksByKey[key] {
+ hit.lastUsed = nextTick()
+ blocksByKey[key] = hit
+ return hit.value
+ }
+ let parsed = MorphMarkdownText.parse(markdown, skipDuplicateTitle: skipDuplicateTitle, preserveLineBreaks: preserveLineBreaks)
+ evictOldestQuarter(from: &blocksByKey, limit: maxBlockEntries)
+ blocksByKey[key] = Entry(value: parsed, lastUsed: nextTick())
+ return parsed
+ }
+
+ func inlineRendered(_ raw: String, linkFiles: Bool, scale: AnymorphTypeScale, cache: Bool = true) -> RenderedInline? {
+ let key = InlineCacheKey(raw: raw, linkFiles: linkFiles, scale: scale)
+ if cache, var hit = inlineByKey[key] {
+ hit.lastUsed = nextTick()
+ inlineByKey[key] = hit
+ return hit.value
+ }
+ let prepared = MorphMarkdownLayout.escapeSingleTildeStrikethrough(raw)
+ guard var attributed = try? AttributedString(
+ markdown: prepared,
+ options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
+ ) else {
+ return nil
+ }
+
+ let codeSize = max(scale.size - 1.5, 11.5)
+ struct PillMeta {
+ let range: Range
+ let chipId: Int
+ let trailingTrim: CGFloat
+ }
+ var pills: [PillMeta] = []
+ var nextChipId = 1
+
+ let openingBrackets: Set = ["(", "[", "{", "“", "‘"]
+ let closingPunctuation: Set = [")", "]", "}", ",", ".", ":", ";", "!", "?", "”", "’"]
+
+ let runSnapshots = attributed.runs.map { (range: $0.range, intent: $0.inlinePresentationIntent, link: $0.link) }
+ for run in runSnapshots {
+ let isCode = run.intent?.contains(.code) == true
+ let isBold = run.intent?.contains(.stronglyEmphasized) == true
+
+ if isCode {
+ let text = String(attributed[run.range].characters)
+ let isFileRef: Bool
+ if linkFiles, run.link == nil,
+ let reference = MorphFileLink.reference(text),
+ let url = MorphFileLink.url(path: reference.path, line: reference.line) {
+ attributed[run.range].link = url
+ isFileRef = true
+ } else if let existingLink = run.link, MorphFileLink.location(from: existingLink) != nil {
+ isFileRef = true
+ } else {
+ isFileRef = false
+ }
+
+ attributed[run.range].font = .system(
+ size: codeSize,
+ weight: isBold ? .semibold : .regular,
+ design: .monospaced
+ )
+
+ if isFileRef {
+ attributed[run.range].foregroundColor = AnymorphColor.fgLink
+ attributed[run.range].underlineStyle = nil
+ } else {
+ attributed[run.range].foregroundColor = isBold
+ ? AnymorphColor.fgPrimary
+ : AnymorphColor.fgPrimary.opacity(0.92)
+ // Add breathing room around the pill via kerning so copied text never gains stray spaces.
+ let chars = attributed.characters
+ if run.range.lowerBound > attributed.startIndex {
+ let prevIndex = chars.index(before: run.range.lowerBound)
+ let prevChar = chars[prevIndex]
+ let leadingKern: CGFloat
+ if prevChar.isWhitespace {
+ leadingKern = 2.0
+ } else if openingBrackets.contains(prevChar) {
+ leadingKern = 3.5
+ } else {
+ leadingKern = 5.0
+ }
+ attributed[prevIndex.. run.range.lowerBound {
+ let lastIndex = chars.index(before: run.range.upperBound)
+ if run.range.upperBound < attributed.endIndex {
+ let nextChar = chars[run.range.upperBound]
+ if nextChar.isWhitespace {
+ attributed[lastIndex.. 1 {
+ // Split off the final character so only the trailing slice carries `hasTrailingKern`.
+ // That keeps mid-token line wraps symmetrically padded on both wrapped lines.
+ let lastStart = chars.index(before: pill.range.upperBound)
+ segments.append(InlineSegment(
+ slice: AttributedString(attributed[pill.range.lowerBound.. (alt: String, source: String)? {
+ if trimmed.hasPrefix(" {
+ let alt = String(trimmed[trimmed.index(trimmed.startIndex, offsetBy: 2)..") {
+ let ns = trimmed as NSString
+ if let regex = imgSrcRegex,
+ let match = regex.firstMatch(in: trimmed, range: NSRange(location: 0, length: ns.length)),
+ match.numberOfRanges > 1 {
+ let src = ns.substring(with: match.range(at: 1))
+ var alt = ""
+ if let altRegex = imgAltRegex,
+ let altMatch = altRegex.firstMatch(in: trimmed, range: NSRange(location: 0, length: ns.length)),
+ altMatch.numberOfRanges > 1 {
+ alt = ns.substring(with: altMatch.range(at: 1))
+ }
+ return (alt, src)
+ }
+ }
+ return nil
+ }
+
+ private static func stripImageTitle(_ raw: String) -> String {
+ var s = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if s.hasPrefix("<"), s.hasSuffix(">"), s.count >= 2 {
+ s = String(s.dropFirst().dropLast())
+ }
+ if let space = s.firstIndex(of: " "),
+ (s[space...].contains("\"") || s[space...].contains("'")) {
+ s = String(s[.. [(isImage: Bool, alt: String, value: String)] {
+ guard text.contains("![") else { return [(false, "", text)] }
+ guard let regex = embeddedImageRegex else {
+ return [(false, "", text)]
+ }
+ let ns = text as NSString
+ let matches = regex.matches(in: text, range: NSRange(location: 0, length: ns.length))
+ guard !matches.isEmpty else { return [(false, "", text)] }
+ var segments: [(Bool, String, String)] = []
+ var cursor = 0
+ for m in matches {
+ if m.range.location > cursor {
+ let prefix = ns.substring(with: NSRange(location: cursor, length: m.range.location - cursor))
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if !prefix.isEmpty {
+ segments.append((false, "", prefix))
+ }
+ }
+ let alt = ns.substring(with: m.range(at: 1))
+ let src = stripImageTitle(ns.substring(with: m.range(at: 2)))
+ if !src.isEmpty {
+ segments.append((true, alt, src))
+ }
+ cursor = m.range.location + m.range.length
+ }
+ if cursor < ns.length {
+ let tail = ns.substring(from: cursor).trimmingCharacters(in: .whitespacesAndNewlines)
+ if !tail.isEmpty {
+ segments.append((false, "", tail))
+ }
+ }
+ return segments
+ }
+
+ static func startsBlock(_ trimmed: String) -> Bool {
+ trimmed.hasPrefix("#") || trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") || trimmed.hasPrefix("• ")
+ || trimmed.hasPrefix("> ") || trimmed.hasPrefix("|") || trimmed.hasPrefix("```")
+ || standaloneImage(trimmed) != nil
+ || numberedMarker(trimmed) != nil
+ }
+
+ static func parse(_ markdown: String, skipDuplicateTitle: String?, preserveLineBreaks: Bool) -> [Block] {
+ let lines = markdown.components(separatedBy: .newlines)
+ var result: [Block] = []
+ var i = 0
+ var nextId = 0
+ func push(_ make: (Int) -> Block) {
+ result.append(make(nextId))
+ nextId += 1
+ }
+ func pushImage(alt: String, source: String) {
+ let image = InlineImage(alt: alt, source: source)
+ if case .images(let id, let items)? = result.last {
+ result[result.count - 1] = .images(id: id, items: items + [image])
+ } else {
+ push { .images(id: $0, items: [image]) }
+ }
+ }
+
+ while i < lines.count {
+ let trimmed = lines[i].trimmingCharacters(in: .whitespaces)
+ if trimmed.isEmpty {
+ i += 1
+ continue
+ }
+ if trimmed.hasPrefix("```") {
+ let rawLang = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces)
+ let language = rawLang.isEmpty ? nil : rawLang
+ var code: [String] = []
+ i += 1
+ while i < lines.count, !lines[i].trimmingCharacters(in: .whitespaces).hasPrefix("```") {
+ code.append(lines[i])
+ i += 1
+ }
+ i += 1
+ let text = code.joined(separator: "\n")
+ push { .code(id: $0, language: language, text: text) }
+ } else if let img = standaloneImage(trimmed) {
+ pushImage(alt: img.alt, source: img.source)
+ i += 1
+ } else if trimmed == "---" || trimmed == "***" {
+ push { .rule(id: $0) }
+ i += 1
+ } else if trimmed.hasPrefix("### ") || trimmed.hasPrefix("## ") || trimmed.hasPrefix("# ") {
+ let level = trimmed.prefix(while: { $0 == "#" }).count
+ let text = String(trimmed.dropFirst(level)).trimmingCharacters(in: .whitespaces)
+ i += 1
+ if level == 1, result.isEmpty,
+ let dup = skipDuplicateTitle?.trimmingCharacters(in: .whitespaces),
+ text.caseInsensitiveCompare(dup) == .orderedSame {
+ continue
+ }
+ push { .heading(id: $0, level: level, text: text) }
+ } else if trimmed.hasPrefix("|"), i + 1 < lines.count, lines[i + 1].trimmingCharacters(in: .whitespaces).hasPrefix("|") {
+ let headers = splitTableRow(trimmed)
+ i += 2
+ var rows: [[String]] = []
+ while i < lines.count {
+ let row = lines[i].trimmingCharacters(in: .whitespaces)
+ guard row.hasPrefix("|") else { break }
+ rows.append(splitTableRow(row))
+ i += 1
+ }
+ push { .table(id: $0, headers: headers, rows: rows) }
+ } else if trimmed.hasPrefix("- [x] ") || trimmed.hasPrefix("- [X] ") {
+ let text = String(trimmed.dropFirst(6))
+ push { .task(id: $0, checked: true, text: text) }
+ i += 1
+ } else if trimmed.hasPrefix("- [ ] ") {
+ let text = String(trimmed.dropFirst(6))
+ push { .task(id: $0, checked: false, text: text) }
+ i += 1
+ } else if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") || trimmed.hasPrefix("• ") {
+ let text = String(trimmed.dropFirst(2))
+ push { .bullet(id: $0, text: text) }
+ i += 1
+ } else if let numbered = numberedMarker(trimmed) {
+ push { .numbered(id: $0, marker: numbered.marker, text: numbered.rest) }
+ i += 1
+ } else if trimmed.hasPrefix("> ") {
+ let text = String(trimmed.dropFirst(2))
+ push { .quote(id: $0, text: text) }
+ i += 1
+ } else {
+ var paragraph = [trimmed]
+ i += 1
+ while i < lines.count {
+ let next = lines[i].trimmingCharacters(in: .whitespaces)
+ if next.isEmpty || startsBlock(next) { break }
+ paragraph.append(next)
+ i += 1
+ }
+ let text = paragraph.joined(separator: preserveLineBreaks ? "\n" : " ")
+ for seg in splitEmbeddedImages(text) {
+ if seg.isImage {
+ pushImage(alt: seg.alt, source: seg.value)
+ } else {
+ push { .paragraph(id: $0, text: seg.value) }
+ }
+ }
+ }
+ }
+ return result
+ }
+
+ private static func splitTableRow(_ line: String) -> [String] {
+ var s = line.trimmingCharacters(in: .whitespaces)
+ if s.hasPrefix("|") { s.removeFirst() }
+ if s.hasSuffix("|") { s.removeLast() }
+ return s.components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }
+ }
+
+ private static func containsInlineMarkdownSyntax(_ raw: String) -> Bool {
+ for byte in raw.utf8 {
+ switch byte {
+ case 96, 42, 95, 126, 91, 60, 92: // ` * _ ~ [ < \
+ return true
+ default:
+ continue
+ }
+ }
+ return false
+ }
+
+ @ViewBuilder
+ private func inlineText(
+ _ raw: String,
+ scale targetScale: AnymorphTypeScale? = nil,
+ weight: AnymorphFontWeight = .base,
+ color: Color = AnymorphColor.fgReading
+ ) -> some View {
+ let resolvedScale = targetScale ?? scale
+ if !Self.containsInlineMarkdownSyntax(raw) {
+ Text(raw)
+ .anymorphText(resolvedScale, weight: weight, color: color)
+ } else if let rendered = RenderCache.shared.inlineRendered(
+ raw,
+ linkFiles: openFileLocation != nil,
+ scale: resolvedScale,
+ cache: cacheParse
+ ) {
+ let combined: Text = rendered.segments.reduce(Text("")) { partial, seg in
+ let piece = seg.pill.map { Text(seg.slice).customAttribute($0) } ?? Text(seg.slice)
+ return partial + piece
+ }
+ if rendered.hasPills {
+ combined
+ .anymorphText(resolvedScale, weight: weight, color: color)
+ .background {
+ combined
+ .anymorphText(resolvedScale, weight: weight, color: color)
+ .textSelection(.disabled)
+ .textRenderer(
+ MorphMarkdownPillBackgroundRenderer(
+ fillColor: AnymorphColor.bgInlineCode,
+ strokeColor: AnymorphColor.strokeInlineCode
+ )
+ )
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+ } else {
+ combined
+ .anymorphText(resolvedScale, weight: weight, color: color)
+ }
+ } else {
+ Text(raw)
+ .anymorphText(resolvedScale, weight: weight, color: color)
+ }
+ }
+
+ static func cellHasImage(_ text: String) -> Bool {
+ text.contains("![") && splitEmbeddedImages(text).contains(where: \.isImage)
+ }
+
+ /// A table cell: its words, and any pictures in it as pictures.
+ @ViewBuilder
+ private func tableCell(_ text: String, isHeader: Bool) -> some View {
+ let weight: AnymorphFontWeight = isHeader ? .strong : .base
+ let color = isHeader ? AnymorphColor.fgPrimary : AnymorphColor.fgReading
+ if Self.cellHasImage(text) {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(Array(Self.splitEmbeddedImages(text).enumerated()), id: \.offset) { _, segment in
+ if segment.isImage {
+ MorphInlineImageView(
+ source: segment.value,
+ alt: segment.alt,
+ maxHeight: Self.groupedImageMaxHeight,
+ loader: imageLoader,
+ onTap: onTapImage
+ )
+ } else {
+ inlineText(segment.value, scale: .footnote, weight: weight, color: color)
+ }
+ }
+ }
+ } else {
+ inlineText(text, scale: .footnote, weight: weight, color: color)
+ }
+ }
+
+ /// Sends file links to Morph's reader and every other link where it went before.
+ private var fileAwareOpenURL: OpenURLAction {
+ let openFile = openFileLocation
+ let parent = parentOpenURL
+ return OpenURLAction { url in
+ MainActor.assumeIsolated {
+ if let openFile, let location = MorphFileLink.location(from: url) {
+ openFile(path: location.path, line: location.line)
+ } else {
+ parent(url)
+ }
+ }
+ return .handled
+ }
+ }
+
+ private var headingScales: (AnymorphTypeScale, AnymorphTypeScale, AnymorphTypeScale) {
+ (.headline, .subhead, .subhead)
+ }
+
+ public var body: some View {
+ let blocks = RenderCache.shared.blocks(
+ for: markdown,
+ skipDuplicateTitle: skipDuplicateTitle,
+ preserveLineBreaks: preserveLineBreaks,
+ cache: cacheParse
+ )
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(blocks.enumerated()), id: \.element.id) { index, block in
+ let prevKind = index > 0 ? blocks[index - 1].layoutKind : nil
+ let topGap = CGFloat(MorphMarkdownLayout.topSpacing(previous: prevKind, current: block.layoutKind))
+ Group {
+ switch block {
+ case .heading(_, let level, let text):
+ let scales = headingScales
+ let headingScale = level == 1 ? scales.0 : (level == 2 ? scales.1 : scales.2)
+ inlineText(text, scale: headingScale, weight: .strong, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ case .bullet(_, let text):
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Text("•")
+ .anymorphText(scale, color: AnymorphColor.fgSecondary)
+ inlineText(text, color: AnymorphColor.fgReading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(.leading, 4)
+ case .task(_, let checked, let text):
+ HStack(alignment: .firstTextBaseline, spacing: 9) {
+ Image(systemName: checked ? "checkmark.square.fill" : "square")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(checked ? AnymorphColor.fgPrimary : AnymorphColor.fgSecondary)
+ inlineText(text, color: checked ? AnymorphColor.fgSecondary : AnymorphColor.fgReading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(.leading, 4)
+ case .numbered(_, let marker, let text):
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(marker)
+ .anymorphText(scale, color: AnymorphColor.fgSecondary, tabular: true)
+ inlineText(text, color: AnymorphColor.fgReading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(.leading, 4)
+ case .quote(_, let text):
+ inlineText(text, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.leading, 12)
+ .overlay(alignment: .leading) {
+ Rectangle().fill(AnymorphColor.strokeBase).frame(width: 2)
+ }
+ case .code(_, let language, let text):
+ MorphMarkdownCodeBlock(language: language, text: text, cacheHighlight: cacheParse)
+ case .images(_, let items):
+ MorphFlowLayout(spacing: 8, lineSpacing: 10) {
+ ForEach(Array(items.enumerated()), id: \.offset) { _, item in
+ MorphInlineImageView(
+ source: item.source,
+ alt: item.alt,
+ maxHeight: items.count > 1 ? Self.groupedImageMaxHeight : Self.singleImageMaxHeight,
+ loader: imageLoader,
+ onTap: onTapImage
+ )
+ }
+ }
+ case .rule:
+ AnymorphDivider().padding(.vertical, 2)
+ case .paragraph(_, let text):
+ let isLead = MorphMarkdownLayout.isStandaloneEmphasisParagraph(text)
+ inlineText(text, color: isLead ? AnymorphColor.fgPrimary : AnymorphColor.fgReading)
+ .fixedSize(horizontal: false, vertical: true)
+ case .table(_, let headers, let rows):
+ MorphMarkdownTableView(
+ headers: headers,
+ rows: rows,
+ hasImages: (headers + rows.joined()).contains(where: Self.cellHasImage),
+ cell: { text, isHeader in
+ tableCell(text, isHeader: isHeader)
+ }
+ )
+ }
+ }
+ .padding(.top, topGap)
+ }
+ }
+ .tint(AnymorphColor.fgLink)
+ .textSelection(.enabled)
+ .environment(\.openURL, fileAwareOpenURL)
+ }
+}
+
+/// Full-width Markdown table backed by `Grid`. Fills the conversation width directly when columns fit (avoiding
+/// horizontal `ScrollView` height clipping and dead trailing space), and switches to horizontal scrolling only when
+/// the column count exceeds the available width.
+private struct MorphMarkdownTableView: View {
+ let headers: [String]
+ let rows: [[String]]
+ /// Whether a cell holds a picture, which turns the rows into cards where columns would squeeze it.
+ let hasImages: Bool
+ @ViewBuilder let cell: (_ text: String, _ isHeader: Bool) -> Cell
+ @State private var availableWidth: CGFloat = 0
+
+ private var columnCount: Int {
+ max(headers.count, rows.map(\.count).max() ?? 1)
+ }
+
+ private var minTotalWidth: CGFloat {
+ CGFloat(MorphMarkdownLayout.tableMinimumWidth(columnCount: columnCount))
+ }
+
+ private var needsHorizontalScroll: Bool {
+ MorphMarkdownLayout.tableNeedsHorizontalScroll(
+ columnCount: columnCount,
+ availableWidth: Double(availableWidth)
+ )
+ }
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ Group {
+ if MorphMarkdownLayout.tableStacksRows(
+ columnCount: columnCount,
+ hasImages: hasImages,
+ availableWidth: Double(availableWidth)
+ ) {
+ stackedRows
+ } else if needsHorizontalScroll {
+ ScrollView(.horizontal, showsIndicators: true) {
+ tableGrid
+ .frame(width: minTotalWidth)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ } else {
+ tableGrid
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .background(AnymorphColor.bgBase)
+ .clipShape(shape)
+ .overlay(shape.strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in
+ if abs(width - availableWidth) > 0.5 {
+ availableWidth = width
+ }
+ }
+ }
+
+ /// Each row as a card, one under the other: a first cell of words titles the row, and every other cell sits
+ /// under its column's header at the full width, so a picture stays readable on a phone.
+ private var stackedRows: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ ForEach(Array(rows.enumerated()), id: \.offset) { index, row in
+ if index > 0 {
+ AnymorphDivider()
+ }
+ VStack(alignment: .leading, spacing: 12) {
+ ForEach(0.. = ["http", "https", "mailto", "tel", "sms", "ftp", "data"]
+
+ static func url(path: String, line: Int?) -> URL? {
+ var components = URLComponents()
+ components.scheme = scheme
+ components.host = "open"
+ var items = [URLQueryItem(name: "path", value: path)]
+ if let line {
+ items.append(URLQueryItem(name: "line", value: String(line)))
+ }
+ components.queryItems = items
+ return components.url
+ }
+
+ /// The path and line an inline code span names. Plain names such as `node.js` are left alone: a reference
+ /// needs a folder or a line number.
+ static func reference(_ raw: String) -> (path: String, line: Int?)? {
+ let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ let range = NSRange(text.startIndex..., in: text)
+ guard let match = referencePattern?.firstMatch(in: text, range: range),
+ let pathRange = Range(match.range(at: 1), in: text) else { return nil }
+ let path = String(text[pathRange])
+ let line = Range(match.range(at: 2), in: text).flatMap { Int(text[$0]) }
+ guard path.contains("/") || line != nil else { return nil }
+ return (path, line)
+ }
+
+ /// The file a link opens, or nil for a web link.
+ static func location(from url: URL) -> (path: String, line: Int?)? {
+ let scheme = url.scheme?.lowercased()
+ if scheme == Self.scheme {
+ let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ guard let path = items.first(where: { $0.name == "path" })?.value, !path.isEmpty else { return nil }
+ return (path, items.first(where: { $0.name == "line" })?.value.flatMap(Int.init))
+ }
+ if scheme == "file" {
+ // A file URL keeps "#L42" (or non-line fragments like "#page=5") outside the path.
+ return MorphFileViewerSupport.parseFileURL(url)
+ }
+ let raw = url.absoluteString.removingPercentEncoding ?? url.absoluteString
+ if let scheme {
+ // `[foo.ts:42](foo.ts:42)` parses "foo.ts" as a scheme.
+ guard !webSchemes.contains(scheme), let reference = reference(raw) else { return nil }
+ return reference
+ }
+ guard !raw.isEmpty, !raw.hasPrefix("#"), !raw.hasPrefix("?") else { return nil }
+ return splitLine(raw)
+ }
+
+ /// "/a/b.go:42", "/a/b.go:42:7" and "/a/b.go#L42" → the path and 42.
+ private static func splitLine(_ raw: String) -> (path: String, line: Int?)? {
+ guard !raw.isEmpty else { return nil }
+ let range = NSRange(raw.startIndex..., in: raw)
+ guard let match = lineSuffixPattern?.firstMatch(in: raw, range: range),
+ let pathRange = Range(match.range(at: 1), in: raw) else { return (raw, nil) }
+ let lineRange = Range(match.range(at: 2), in: raw) ?? Range(match.range(at: 3), in: raw)
+ return (String(raw[pathRange]), lineRange.flatMap { Int(raw[$0]) })
+ }
+}
+
+/// Syntax-highlighted lines of code with an optional line-number gutter. Lines either wrap or keep their width for
+/// a sideways scroll; each line carries its 1-based number as its id so a reader can scroll to it.
+struct MorphCodeLines: View {
+ let lines: [[SyntaxToken]]
+ var showsLineNumbers = true
+ var wraps = false
+ /// The line to mark, 1-based.
+ var highlightedLine: Int? = nil
+ /// Tints added, removed and hunk-header lines, for diffs.
+ var tintsDiffLines = false
+ /// Builds rows as they scroll into view, for whole files.
+ var lazy = false
+ /// The narrowest a row is drawn, so a marked line spans the reader when lines scroll sideways.
+ var minRowWidth: CGFloat? = nil
+ var fontSize: CGFloat = 12
+
+ var body: some View {
+ if lazy {
+ LazyVStack(alignment: .leading, spacing: 0) { rows }
+ } else {
+ VStack(alignment: .leading, spacing: 0) { rows }
+ }
+ }
+
+ private var gutterWidth: CGFloat {
+ CGFloat(String(lines.count).count) * fontSize * 0.62 + 2
+ }
+
+ private var rows: some View {
+ ForEach(lines.indices, id: \.self) { index in
+ let tokens = lines[index]
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ if showsLineNumbers {
+ Text(String(index + 1))
+ .font(.system(size: fontSize - 1, design: .monospaced))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .frame(width: gutterWidth, alignment: .trailing)
+ .accessibilityHidden(true)
+ }
+ Text(tokens.isEmpty ? AttributedString(" ") : MorphSyntaxPalette.attributedLine(tokens, fontSize: fontSize))
+ .fixedSize(horizontal: !wraps, vertical: true)
+ .frame(maxWidth: wraps ? .infinity : nil, alignment: .leading)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 1)
+ .frame(minWidth: minRowWidth, alignment: .leading)
+ .background(rowBackground(index: index, tokens: tokens))
+ .id(index + 1)
+ }
+ }
+
+ @ViewBuilder
+ private func rowBackground(index: Int, tokens: [SyntaxToken]) -> some View {
+ if index + 1 == highlightedLine {
+ AnymorphColor.bgSelected
+ .overlay(alignment: .leading) {
+ Rectangle().fill(AnymorphColor.fgTertiary).frame(width: 2)
+ }
+ } else if tintsDiffLines {
+ switch tokens.first?.kind {
+ case .diffAdd: MorphSyntaxPalette.diffAddBg
+ case .diffRemove: MorphSyntaxPalette.diffRemoveBg
+ case .diffHeader: MorphSyntaxPalette.diffHeaderBg
+ default: Color.clear
+ }
+ } else {
+ Color.clear
+ }
+ }
+}
+
+/// Bounded MainActor cache for syntax-highlighted code blocks so SwiftUI body passes never re-tokenize unchanged code.
+@MainActor
+final class SyntaxHighlightCache {
+ static let shared = SyntaxHighlightCache()
+
+ private struct Key: Hashable {
+ let language: String
+ let codeHash: Int
+ let codeCount: Int
+ let exactCode: String?
+
+ init(language: String, code: String) {
+ self.language = language
+ self.codeCount = code.utf8.count
+ self.codeHash = code.hashValue
+ // Keep exact string for blocks up to 32 KB to guarantee zero collisions; hash+length for huge blocks.
+ self.exactCode = self.codeCount <= 32_768 ? code : nil
+ }
+ }
+
+ private struct Entry {
+ let lines: [[SyntaxToken]]
+ var lastUsed: UInt64
+ }
+
+ private var entries: [Key: Entry] = [:]
+ private var tick: UInt64 = 0
+ private let maxEntries = 256
+
+ func tokenize(_ code: String, language: String) -> [[SyntaxToken]] {
+ let key = Key(language: language, code: code)
+ tick &+= 1
+ if var hit = entries[key] {
+ hit.lastUsed = tick
+ entries[key] = hit
+ return hit.lines
+ }
+ let lines = MorphSyntaxHighlighter.tokenize(code, language: language)
+ if entries.count >= maxEntries {
+ let removeCount = max(1, maxEntries / 4)
+ let oldest = entries.sorted { $0.value.lastUsed < $1.value.lastUsed }.prefix(removeCount)
+ for (k, _) in oldest {
+ entries.removeValue(forKey: k)
+ }
+ }
+ entries[key] = Entry(lines: lines, lastUsed: tick)
+ return lines
+ }
+}
+
+/// Codex-style fenced code block: language label, syntax colors, line numbers from three lines on, a wrap toggle
+/// and one-click clipboard copy.
+private struct MorphMarkdownCodeBlock: View {
+ let language: String?
+ let text: String
+ var cacheHighlight: Bool = true
+ @State private var copied = false
+ @State private var wraps = false
+
+ var body: some View {
+ let detectedLanguage = MorphSyntaxHighlighter.detectLanguage(hint: language, filePath: nil)
+ let lines = cacheHighlight
+ ? SyntaxHighlightCache.shared.tokenize(text, language: detectedLanguage)
+ : MorphSyntaxHighlighter.tokenize(text, language: detectedLanguage)
+ let numbered = lines.count >= 3
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 12) {
+ Text(language?.isEmpty == false ? language! : "code")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary, monospaced: true)
+ Spacer()
+ Button {
+ wraps.toggle()
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "text.word.spacing")
+ .font(.system(size: 10, weight: .medium))
+ Text("줄바꿈")
+ .anymorphText(.caption, weight: wraps ? .emphasis : .base, color: wraps ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ }
+ .foregroundStyle(wraps ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ .padding(.horizontal, 4)
+ .padding(.vertical, 2)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityAddTraits(wraps ? .isSelected : [])
+ .help(wraps ? "줄바꿈 끄기" : "긴 줄 줄바꿈")
+ Button {
+ MorphClipboard.copy(text)
+ copied = true
+ Task {
+ try? await Task.sleep(for: .seconds(1.4))
+ copied = false
+ }
+ } label: {
+ HStack(spacing: 4) {
+ MorphLucideIcon(copied ? .check : .copy, size: 12)
+ Text(copied ? "복사됨" : "복사")
+ .anymorphText(.caption, weight: .base, color: copied ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ }
+ .foregroundStyle(copied ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ .padding(.horizontal, 4)
+ .padding(.vertical, 2)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 7)
+ .background(AnymorphColor.bgGrouped)
+
+ AnymorphDivider()
+
+ Group {
+ if wraps {
+ MorphCodeLines(lines: lines, showsLineNumbers: numbered, wraps: true)
+ } else {
+ ScrollView(.horizontal, showsIndicators: false) {
+ MorphCodeLines(lines: lines, showsLineNumbers: numbered)
+ }
+ }
+ }
+ .padding(.vertical, 10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .textSelection(.enabled)
+ .background(AnymorphColor.bgSubtle)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ }
+}
+
+/// Lays its children out left to right at their own sizes and starts a new line when the next one would not fit.
+/// SwiftUI has no wrapping stack, so image groups use this. With `fillsLines` every line spans the full width, as
+/// a card's buttons do.
+struct MorphFlowLayout: Layout {
+ var spacing: CGFloat = 8
+ var lineSpacing: CGFloat = 8
+ /// `.trailing` pushes every line to the right edge, as under the member's own message.
+ var alignment: HorizontalAlignment = .leading
+ /// Widens each line's children, the narrowest first, until the line spans the full width, so they come out the
+ /// same width wherever that fits. The children must take the extra width, as a button whose label has
+ /// `.frame(maxWidth: .infinity)` does.
+ var fillsLines = false
+
+ private struct Arrangement {
+ var sizes: [CGSize] = []
+ var lines: [Range] = []
+ var lineWidths: [CGFloat] = []
+ var lineHeights: [CGFloat] = []
+ }
+
+ private func arrange(_ subviews: Subviews, width: CGFloat) -> Arrangement {
+ var arrangement = Arrangement()
+ // A child that takes the width it is offered would measure the whole line, so filled lines start from each
+ // child's own size.
+ let measuring = fillsLines ? ProposedViewSize.unspecified : ProposedViewSize(width: width, height: nil)
+ arrangement.sizes = subviews.map { $0.sizeThatFits(measuring) }
+ var lineStart = 0
+ var lineWidth: CGFloat = 0
+ var lineHeight: CGFloat = 0
+ for (index, size) in arrangement.sizes.enumerated() {
+ let wanted = index == lineStart ? size.width : lineWidth + spacing + size.width
+ if index > lineStart, wanted > width {
+ arrangement.lines.append(lineStart.. CGSize {
+ let arrangement = arrange(subviews, width: proposal.width ?? .infinity)
+ let gaps = lineSpacing * CGFloat(max(arrangement.lines.count - 1, 0))
+ let widestLine = arrangement.lineWidths.max() ?? 0
+ // Filled lines reach the offered width when there is a finite one.
+ let offeredWidth = proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 0
+ return CGSize(
+ width: fillsLines ? max(widestLine, offeredWidth) : widestLine,
+ height: arrangement.lineHeights.reduce(0, +) + gaps
+ )
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ let arrangement = arrange(subviews, width: bounds.width)
+ var y = bounds.minY
+ for (lineIndex, line) in arrangement.lines.enumerated() {
+ let gaps = spacing * CGFloat(line.count - 1)
+ let ownWidths = line.map { arrangement.sizes[$0].width }
+ let widths = fillsLines ? Self.filled(ownWidths, toWidth: bounds.width - gaps) : ownWidths
+ let lineWidth = widths.reduce(0, +) + gaps
+ var x = alignment == .trailing ? bounds.maxX - lineWidth : bounds.minX
+ for (index, width) in zip(line, widths) {
+ subviews[index].place(
+ at: CGPoint(x: x, y: y),
+ anchor: .topLeading,
+ proposal: ProposedViewSize(width: width, height: arrangement.sizes[index].height)
+ )
+ x += width + spacing
+ }
+ y += arrangement.lineHeights[lineIndex] + lineSpacing
+ }
+ }
+
+ /// Widths for one line's children that add up to `total`: the narrow ones grow to a shared width, and a child
+ /// already wider than that share keeps its own.
+ private static func filled(_ widths: [CGFloat], toWidth total: CGFloat) -> [CGFloat] {
+ var remaining = total
+ var growing = widths.count
+ var shared: CGFloat = 0
+ for width in widths.sorted(by: >) {
+ shared = remaining / CGFloat(growing)
+ guard width > shared else { break }
+ remaining -= width
+ growing -= 1
+ }
+ return widths.map { max($0, shared) }
+ }
+}
+
+/// Inline image card for Markdown replies, tool-generated charts/screenshots, and attachments.
+/// Supports local disk paths, `data:image/...;base64,...`, public URLs, and authenticated workspace loaders.
+/// The card is exactly as big as the picture: it keeps the picture's proportions, never grows past its own size, the
+/// space it is given or `maxHeight`, and leaves no empty margin beside it.
+public struct MorphInlineImageView: View {
+ public let source: String
+ public var alt: String
+ public var maxHeight: CGFloat
+ public var maxWidth: CGFloat
+ public var preloadedData: Data?
+ public var loader: ((String) async -> Data?)?
+ public var onTap: ((String, Data) -> Void)?
+
+ @State private var loadedSource: String?
+ @State private var loadedData: Data?
+ @State private var decodedImage: (image: Image, size: CGSize)?
+ @State private var isLoading = false
+ @State private var failed = false
+ @State private var retryCount = 0
+
+ public init(
+ source: String,
+ alt: String = "",
+ maxHeight: CGFloat = 360,
+ maxWidth: CGFloat = .infinity,
+ preloadedData: Data? = nil,
+ loader: ((String) async -> Data?)? = nil,
+ onTap: ((String, Data) -> Void)? = nil
+ ) {
+ self.source = source
+ self.alt = alt
+ self.maxHeight = maxHeight
+ self.maxWidth = maxWidth
+ self.preloadedData = preloadedData
+ self.loader = loader
+ self.onTap = onTap
+ }
+
+ private var imageShape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ }
+
+ public var body: some View {
+ let effectiveData = preloadedData ?? loadedData
+ VStack(alignment: .leading, spacing: 6) {
+ if let data = effectiveData, Self.isSVG(data: data, source: source),
+ let svgMarkup = String(data: data, encoding: .utf8) {
+ let width = min(Self.svgPreferredWidth(svgMarkup, maxHeight: maxHeight), maxWidth)
+ let height = min(Self.svgPreferredHeight(svgMarkup, maxWidth: width, maxHeight: maxHeight), maxHeight)
+ MorphInlineSVGView(svg: svgMarkup)
+ .frame(maxWidth: width)
+ .frame(height: height)
+ .background(AnymorphColor.bgBase)
+ .clipShape(imageShape)
+ .overlay(imageShape.strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ if !alt.isEmpty {
+ Text(alt)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(2)
+ .frame(maxWidth: width, alignment: .leading)
+ }
+ } else if let data = effectiveData, let decoded = decodedImage ?? Self.cachedOrDecode(data, maxHeight: maxHeight) {
+ // The widest the picture gets: its own width, `maxWidth`, or the width of `maxHeight` of it. A smaller
+ // space given by the parent narrows it further, and its height follows.
+ let width = min(Self.fittedWidth(of: decoded.size, maxHeight: maxHeight), maxWidth)
+ decoded.image
+ .resizable()
+ .scaledToFit()
+ .frame(maxWidth: width)
+ .clipShape(imageShape)
+ .overlay(imageShape.strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .contentShape(imageShape)
+ .morphPointerCursor(onTap != nil)
+ .onTapGesture {
+ onTap?(alt.isEmpty ? Self.displayName(source) : alt, data)
+ }
+ if !alt.isEmpty {
+ // Under the picture and never wider than it.
+ Text(alt)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(2)
+ .frame(maxWidth: width, alignment: .leading)
+ }
+ } else if failed {
+ HStack(spacing: 8) {
+ Image(systemName: "photo.badge.exclamationmark")
+ .font(.system(size: 13, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(alt.isEmpty ? "이미지를 불러올 수 없습니다 (\(source))" : "\(alt) · 불러오기 실패")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(2)
+ Spacer(minLength: 4)
+ Button("다시 시도") {
+ retryCount += 1
+ }
+ .morphPill(.secondary, height: 22)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 10)
+ .frame(maxWidth: 360, alignment: .leading)
+ .background(imageShape.fill(AnymorphColor.bgGrouped))
+ } else {
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("이미지 불러오는 중…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize()
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 14)
+ .background(imageShape.fill(AnymorphColor.bgGrouped))
+ }
+ }
+ .task(id: "\(source)#\(retryCount)") {
+ if loadedSource != source {
+ loadedSource = source
+ loadedData = nil
+ decodedImage = nil
+ failed = false
+ }
+ if let preloadedData {
+ if !Self.isSVG(data: preloadedData, source: source), decodedImage == nil {
+ let maxH = maxHeight
+ let decoded = await Task.detached(priority: .userInitiated) {
+ Self.cachedOrDecode(preloadedData, maxHeight: maxH)
+ }.value
+ guard !Task.isCancelled else { return }
+ decodedImage = decoded
+ }
+ return
+ }
+ if loadedData != nil { return }
+ isLoading = true
+ failed = false
+ defer { isLoading = false }
+ let data = await Self.resolveData(source: source, loader: loader)
+ guard !Task.isCancelled else { return }
+ guard let data else {
+ failed = true
+ return
+ }
+ if Self.isSVG(data: data, source: source) {
+ loadedData = data
+ return
+ }
+ let maxH = maxHeight
+ let decoded = await Task.detached(priority: .userInitiated) {
+ Self.cachedOrDecode(data, maxHeight: maxH)
+ }.value
+ guard !Task.isCancelled else { return }
+ if let decoded {
+ loadedData = data
+ decodedImage = decoded
+ } else {
+ failed = true
+ }
+ }
+ }
+
+ static func isSVG(data: Data, source: String) -> Bool {
+ let lowerSource = source.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ if lowerSource.hasPrefix("data:image/svg+xml") { return true }
+ let withoutQuery = lowerSource.split(separator: "?").first.map(String.init) ?? lowerSource
+ if withoutQuery.hasSuffix(".svg") { return true }
+ let prefix = String(decoding: data.prefix(512), as: UTF8.self).lowercased()
+ return prefix.contains(" CGSize? {
+ let pattern = #"viewBox\s*=\s*["']\s*[-\d.]+\s+[-\d.]+\s+([\d.]+)\s+([\d.]+)\s*["']"#
+ guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]),
+ let match = regex.firstMatch(in: svg, range: NSRange(svg.startIndex..., in: svg)),
+ match.numberOfRanges >= 3,
+ let wRange = Range(match.range(at: 1), in: svg),
+ let hRange = Range(match.range(at: 2), in: svg),
+ let w = Double(svg[wRange]), let h = Double(svg[hRange]), w > 0, h > 0 else {
+ return nil
+ }
+ return CGSize(width: w, height: h)
+ }
+
+ private static func svgPreferredWidth(_ svg: String, maxHeight: CGFloat) -> CGFloat {
+ if let vb = svgViewBoxSize(svg) {
+ return max(120, min(600, fittedWidth(of: vb, maxHeight: maxHeight)))
+ }
+ return 420
+ }
+
+ private static func svgPreferredHeight(_ svg: String, maxWidth: CGFloat, maxHeight: CGFloat) -> CGFloat {
+ if let vb = svgViewBoxSize(svg) {
+ let effectiveWidth = maxWidth.isFinite ? maxWidth : 420
+ let aspectH = effectiveWidth * (vb.height / vb.width)
+ return max(80, min(maxHeight, aspectH))
+ }
+ return min(240, maxHeight)
+ }
+
+ /// The width a picture of `size` takes at the tallest allowed: never past its own size, never past `maxHeight`.
+ static func fittedWidth(of size: CGSize, maxHeight: CGFloat) -> CGFloat {
+ guard size.width > 0, size.height > 0 else { return 0 }
+ return min(size.height, maxHeight) * size.width / size.height
+ }
+
+ /// Bounded memory cache for downsampled inline images so SwiftUI body passes never re-decode raw bytes
+ /// and huge 4K screenshots stay within a tight ImageIO memory budget.
+ private final class DecodedImageEntry: NSObject, @unchecked Sendable {
+ let image: Image
+ let size: CGSize
+ init(image: Image, size: CGSize) {
+ self.image = image
+ self.size = size
+ }
+ }
+
+ nonisolated(unsafe) private static let decodedCache: NSCache = {
+ let cache = NSCache()
+ cache.countLimit = 48
+ cache.totalCostLimit = 24 * 1024 * 1024
+ return cache
+ }()
+
+ /// Decodes (and downsamples to display pixel size when large) with bounded caching.
+ nonisolated static func cachedOrDecode(_ data: Data, maxHeight: CGFloat) -> (image: Image, size: CGSize)? {
+ let maxPixelSize = max(512, min(1600, Int(ceil(maxHeight * 2.5))))
+ let digest = SHA256.hash(data: data)
+ let key = "\(digest.prefix(16).map { String(format: "%02x", $0) }.joined()):\(maxPixelSize)" as NSString
+ if let hit = decodedCache.object(forKey: key) {
+ return (hit.image, hit.size)
+ }
+ let decoded: (image: Image, size: CGSize)?
+ let pixelCost: Int
+ if let source = CGImageSourceCreateWithData(data as CFData, nil) {
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
+ ]
+ if let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary),
+ cg.width > 0, cg.height > 0 {
+ let ptSize = CGSize(width: CGFloat(cg.width) / 2.0, height: CGFloat(cg.height) / 2.0)
+ #if os(macOS)
+ let img = Image(nsImage: NSImage(cgImage: cg, size: ptSize))
+ #else
+ let img = Image(uiImage: UIImage(cgImage: cg, scale: 2.0, orientation: .up))
+ #endif
+ decoded = (img, ptSize)
+ pixelCost = cg.bytesPerRow * cg.height
+ } else {
+ decoded = decode(data)
+ pixelCost = data.count * 4
+ }
+ } else {
+ decoded = decode(data)
+ pixelCost = data.count * 4
+ }
+ guard let decoded else { return nil }
+ decodedCache.setObject(DecodedImageEntry(image: decoded.image, size: decoded.size), forKey: key, cost: max(1, pixelCost))
+ return decoded
+ }
+
+ /// The picture and its size in points, or nil when the data is not an image.
+ nonisolated static func decode(_ data: Data) -> (image: Image, size: CGSize)? {
+ #if os(macOS)
+ guard let ns = NSImage(data: data), ns.size.width > 0, ns.size.height > 0 else { return nil }
+ return (Image(nsImage: ns), ns.size)
+ #else
+ guard let ui = UIImage(data: data), ui.size.width > 0, ui.size.height > 0 else { return nil }
+ return (Image(uiImage: ui), ui.size)
+ #endif
+ }
+
+ /// A name for an image without alt text: the file name of its path or link, "이미지" for inline data.
+ static func displayName(_ source: String) -> String {
+ guard !source.hasPrefix("data:") else { return "이미지" }
+ let withoutQuery = source.split(separator: "?").first.map(String.init) ?? source
+ let name = (withoutQuery as NSString).lastPathComponent
+ return name.isEmpty ? "이미지" : name
+ }
+
+ public static func swiftUIImage(from data: Data) -> Image? {
+ decode(data)?.image
+ }
+
+ private static func resolveData(source: String, loader: ((String) async -> Data?)?) async -> Data? {
+ let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.isEmpty { return nil }
+ if trimmed.hasPrefix("data:image/"), let comma = trimmed.firstIndex(of: ",") {
+ let header = String(trimmed[.. Coordinator { Coordinator() }
+
+ func makeNSView(context: Context) -> WKWebView {
+ let config = WKWebViewConfiguration()
+ config.websiteDataStore = .nonPersistent()
+ let webView = WKWebView(frame: .zero, configuration: config)
+ webView.navigationDelegate = context.coordinator
+ webView.setValue(false, forKey: "drawsBackground")
+ loadIfNeeded(webView, coordinator: context.coordinator)
+ return webView
+ }
+
+ func updateNSView(_ nsView: WKWebView, context: Context) {
+ loadIfNeeded(nsView, coordinator: context.coordinator)
+ }
+
+ private func loadIfNeeded(_ webView: WKWebView, coordinator: Coordinator) {
+ let key = "\(isDark ? "d" : "l"):\(svg.hashValue):\(svg.utf8.count)"
+ guard coordinator.lastKey != key else { return }
+ coordinator.lastKey = key
+ webView.loadHTMLString(Self.wrapHTML(svg: svg, isDark: isDark), baseURL: nil)
+ }
+
+ @MainActor
+ final class Coordinator: NSObject, WKNavigationDelegate {
+ var lastKey: String?
+
+ func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) {
+ if navigationAction.navigationType == .other,
+ navigationAction.request.url?.absoluteString == "about:blank" {
+ decisionHandler(.allow)
+ } else {
+ decisionHandler(.cancel)
+ }
+ }
+ }
+
+ static func wrapHTML(svg: String, isDark: Bool) -> String {
+ let fg = isDark ? "#FAFAFA" : "#161616"
+ return """
+
+
+
+
+
+
+
+ \(svg)
+
+ """
+ }
+}
+#else
+private struct MorphInlineSVGWebView: UIViewRepresentable {
+ let svg: String
+ let isDark: Bool
+
+ func makeCoordinator() -> Coordinator { Coordinator() }
+
+ func makeUIView(context: Context) -> WKWebView {
+ let config = WKWebViewConfiguration()
+ config.websiteDataStore = .nonPersistent()
+ let webView = WKWebView(frame: .zero, configuration: config)
+ webView.navigationDelegate = context.coordinator
+ webView.isOpaque = false
+ webView.backgroundColor = .clear
+ webView.scrollView.isScrollEnabled = false
+ webView.scrollView.backgroundColor = .clear
+ loadIfNeeded(webView, coordinator: context.coordinator)
+ return webView
+ }
+
+ func updateUIView(_ uiView: WKWebView, context: Context) {
+ loadIfNeeded(uiView, coordinator: context.coordinator)
+ }
+
+ private func loadIfNeeded(_ webView: WKWebView, coordinator: Coordinator) {
+ let key = "\(isDark ? "d" : "l"):\(svg.hashValue):\(svg.utf8.count)"
+ guard coordinator.lastKey != key else { return }
+ coordinator.lastKey = key
+ webView.loadHTMLString(Self.wrapHTML(svg: svg, isDark: isDark), baseURL: nil)
+ }
+
+ @MainActor
+ final class Coordinator: NSObject, WKNavigationDelegate {
+ var lastKey: String?
+
+ func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) {
+ if navigationAction.navigationType == .other,
+ navigationAction.request.url?.absoluteString == "about:blank" {
+ decisionHandler(.allow)
+ } else {
+ decisionHandler(.cancel)
+ }
+ }
+ }
+
+ static func wrapHTML(svg: String, isDark: Bool) -> String {
+ let fg = isDark ? "#FAFAFA" : "#161616"
+ return """
+
+
+
+
+
+
+
+ \(svg)
+
+ """
+ }
+}
+#endif
+
+public struct MorphLightboxImageItem: Identifiable, Equatable {
+ public let id = UUID()
+ public let title: String
+ public let data: Data
+
+ public init(title: String, data: Data) {
+ self.title = title
+ self.data = data
+ }
+}
+
+/// Syntax-tinted unified diff card shared by inline turn blocks and the Git inspector.
+public struct MorphDiffBlockView: View {
+ public let title: String
+ public let diffText: String
+ public var defaultCollapsed: Bool
+ @State private var collapsed: Bool
+ @State private var copied = false
+
+ public init(title: String = "변경 내역 (Diff)", diffText: String, defaultCollapsed: Bool = false) {
+ self.title = title
+ self.diffText = diffText
+ self.defaultCollapsed = defaultCollapsed
+ _collapsed = State(initialValue: defaultCollapsed)
+ }
+
+ private var stats: (added: Int, removed: Int) {
+ var add = 0
+ var del = 0
+ for line in diffText.components(separatedBy: .newlines) {
+ if line.hasPrefix("+"), !line.hasPrefix("+++") { add += 1 }
+ else if line.hasPrefix("-"), !line.hasPrefix("---") { del += 1 }
+ }
+ return (add, del)
+ }
+
+ public var body: some View {
+ let s = stats
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 8) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { collapsed.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "doc.text.magnifyingglass")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(title)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ if s.added > 0 {
+ Text("+\(s.added)")
+ .anymorphText(.caption, weight: .emphasis, color: Color.green.opacity(0.85), monospaced: true)
+ }
+ if s.removed > 0 {
+ Text("-\(s.removed)")
+ .anymorphText(.caption, weight: .emphasis, color: Color.red.opacity(0.85), monospaced: true)
+ }
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ .rotationEffect(.degrees(collapsed ? 0 : 90))
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+
+ Spacer()
+
+ Button {
+ MorphClipboard.copy(diffText)
+ copied = true
+ Task {
+ try? await Task.sleep(for: .seconds(1.4))
+ copied = false
+ }
+ } label: {
+ MorphLucideIcon(copied ? .check : .copy, size: 12.5)
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 22, height: 22)
+ }
+ .buttonStyle(.morphPlain)
+ .help("Patch 복사")
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(AnymorphColor.bgGrouped)
+
+ if !collapsed {
+ AnymorphDivider()
+ ScrollView(.horizontal, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 0) {
+ let lines = diffText.components(separatedBy: .newlines).prefix(260)
+ ForEach(Array(lines.enumerated()), id: \.offset) { _, line in
+ Text(line.isEmpty ? " " : line)
+ .anymorphText(.caption, weight: line.hasPrefix("@@") ? .emphasis : .base, color: diffForeground(line), monospaced: true)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(diffBackground(line))
+ }
+ }
+ .padding(.vertical, 6)
+ }
+ .textSelection(.enabled)
+ .background(AnymorphColor.bgCard)
+ }
+ }
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeLight, lineWidth: 1)
+ )
+ }
+
+ private func diffForeground(_ line: String) -> Color {
+ if line.hasPrefix("+"), !line.hasPrefix("+++") { return Color.green.opacity(0.9) }
+ if line.hasPrefix("-"), !line.hasPrefix("---") { return Color.red.opacity(0.9) }
+ if line.hasPrefix("@@") || line.hasPrefix("diff --git") { return AnymorphColor.accessPlan }
+ return AnymorphColor.fgSecondary
+ }
+
+ private func diffBackground(_ line: String) -> Color {
+ if line.hasPrefix("+"), !line.hasPrefix("+++") { return Color.green.opacity(0.08) }
+ if line.hasPrefix("-"), !line.hasPrefix("---") { return Color.red.opacity(0.08) }
+ if line.hasPrefix("@@") { return AnymorphColor.bgSubtle }
+ return .clear
+ }
+}
+
+/// Notice: a floating capsule at the top of the window. It fades on its own, an error later than info, or closes from
+/// its button.
+public struct MorphNoticeToast: View {
+ public let text: String
+ public let isError: Bool
+ public let onClose: () -> Void
+
+ public init(text: String, isError: Bool, onClose: @escaping () -> Void) {
+ self.text = text
+ self.isError = isError
+ self.onClose = onClose
+ }
+
+ public var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: isError ? "exclamationmark.circle" : "checkmark.circle")
+ .font(.system(size: 13, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ Text(text)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(2)
+ Button(action: onClose) {
+ Image(systemName: "xmark")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .frame(width: 18, height: 18)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityLabel("닫기")
+ }
+ .padding(.leading, 12)
+ .padding(.trailing, 8)
+ .padding(.vertical, 8)
+ .background {
+ Capsule()
+ .fill(AnymorphColor.bgBase)
+ .shadow(color: AnymorphColor.floatShadow, radius: 12, x: 0, y: 6)
+ }
+ .overlay(Capsule().strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ }
+}
+
+// MARK: - 12. Settings Rows, Engine Identity & Quota Bars
+
+/// Grok Bot's settings group: a gray caption over one filled block whose rows are split by inset hairlines.
+public struct MorphSettingsGroup: View {
+ public let title: String
+ public let footnote: String?
+ private let accessory: Accessory
+ private let content: Content
+
+ public init(
+ _ title: String,
+ footnote: String? = nil,
+ @ViewBuilder accessory: () -> Accessory = { EmptyView() },
+ @ViewBuilder content: () -> Content
+ ) {
+ self.title = title
+ self.footnote = footnote
+ self.accessory = accessory()
+ self.content = content()
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ if !title.isEmpty {
+ HStack(alignment: .firstTextBaseline) {
+ Text(title)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ Spacer(minLength: 8)
+ accessory
+ }
+ .padding(.horizontal, 4)
+ }
+
+ Group(subviews: content) { subviews in
+ VStack(spacing: 0) {
+ ForEach(subviews) { subview in
+ subview
+ if subview.id != subviews.last?.id {
+ Rectangle()
+ .fill(AnymorphColor.strokeBase)
+ .frame(height: 1)
+ .padding(.horizontal, 16)
+ }
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.xxl, style: .continuous).fill(AnymorphColor.bgGrouped))
+
+ if let footnote {
+ Text(footnote)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 4)
+ }
+ }
+ }
+}
+
+/// One settings row in Grok Bot's layout: optional leading icon, the title over a gray description, the control
+/// at the end. On a narrow screen a wide control, such as a segment or two buttons, sits under the description.
+public struct MorphSettingsRow: View {
+ public let title: String
+ public let detail: String?
+ private let leading: Leading
+ private let trailing: Trailing
+
+ public init(
+ _ title: String,
+ detail: String? = nil,
+ @ViewBuilder leading: () -> Leading = { EmptyView() },
+ @ViewBuilder trailing: () -> Trailing = { EmptyView() }
+ ) {
+ self.title = title
+ self.detail = detail
+ self.leading = leading()
+ self.trailing = trailing()
+ }
+
+ /// The narrowest the description wraps to beside the control. The title keeps its whole width there, so a long
+ /// title, or a description that would wrap narrower, moves the control under them.
+ static var minLabelWidth: CGFloat { 150 }
+
+ public var body: some View {
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 12) {
+ leading
+ label(besideControl: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ trailing
+ // The control keeps its full width; the description wraps in what is left.
+ .layoutPriority(1)
+ }
+ HStack(alignment: .top, spacing: 12) {
+ leading
+ VStack(alignment: .leading, spacing: 10) {
+ label(besideControl: false)
+ trailing
+ }
+ Spacer(minLength: 0)
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 11)
+ .frame(minHeight: 52)
+ }
+
+ private func label(besideControl: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .fixedSize(horizontal: besideControl, vertical: false)
+ if let detail, !detail.isEmpty {
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(3)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(minWidth: 0, idealWidth: besideControl ? Self.minLabelWidth : nil, maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }
+}
+
+/// Grok Bot's popup button: the current choice and a chevron on the selected gray. It opens its choices as
+/// MorphMenuItem rows in a dropdown under it, lined up with its trailing edge. Settings rows and the scheduled task
+/// editor put their choices in it.
+public struct MorphPopupButton: View {
+ public let title: String
+ public let brand: MorphBrand?
+ public let disabled: Bool
+ private let menuWidth: CGFloat
+ private let name: String?
+ private let items: () -> Items
+
+ /// - Parameter name: The menu's accessibility identifier, which the DEBUG screenshot harness also opens it by.
+ public init(
+ _ title: String,
+ brand: MorphBrand? = nil,
+ disabled: Bool = false,
+ menuWidth: CGFloat = 220,
+ name: String? = nil,
+ @ViewBuilder items: @escaping () -> Items
+ ) {
+ self.title = title
+ self.brand = brand
+ self.disabled = disabled
+ self.menuWidth = menuWidth
+ self.name = name
+ self.items = items
+ }
+
+ public var body: some View {
+ MorphDropdown(placement: .belowTrailing, width: menuWidth, name: name, content: items) {
+ HStack(spacing: 6) {
+ if let brand {
+ MorphBrandMark(brand, size: 12, color: disabled ? AnymorphColor.fgDisabled : AnymorphColor.fgPrimary)
+ }
+ Text(title)
+ .anymorphText(.footnote, weight: .emphasis, color: disabled ? AnymorphColor.fgDisabled : AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ .padding(.horizontal, 12)
+ .frame(height: 30)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).fill(AnymorphColor.bgSelected))
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+ .fixedSize()
+ .disabled(disabled)
+ }
+}
+
+/// Logos of the AI engines and services Morph works with. They come from the asset catalog (`Brands`) as
+/// one-color vector glyphs, so they take the ink of the text around them in both themes and never bring a
+/// brand color into the monochrome screen.
+public enum MorphBrand: String, CaseIterable, Sendable {
+ case openai, claude, gemini, deepseek, google, gmail, googleCalendar, slack, kakaotalk, naverworks, jandi, teams
+ case github, linear
+ case onepassword, notion, figma, cloudflare, vercel, supabase, stripe, sentry, atlassian
+
+ public var assetName: String { "brand-" + rawValue.lowercased() }
+
+ /// The service's name, for a logo's tooltip and VoiceOver.
+ public var displayName: String {
+ switch self {
+ case .openai: return "OpenAI"
+ case .claude: return "Claude"
+ case .gemini: return "Gemini"
+ case .deepseek: return "DeepSeek"
+ case .google: return "Google"
+ case .gmail: return "Gmail"
+ case .googleCalendar: return "Google Calendar"
+ case .slack: return "Slack"
+ case .kakaotalk: return "KakaoTalk"
+ case .naverworks: return "NAVER WORKS"
+ case .jandi: return "JANDI"
+ case .teams: return "Teams"
+ case .github: return "GitHub"
+ case .linear: return "Linear"
+ case .onepassword: return "1Password"
+ case .notion: return "Notion"
+ case .figma: return "Figma"
+ case .cloudflare: return "Cloudflare"
+ case .vercel: return "Vercel"
+ case .supabase: return "Supabase"
+ case .stripe: return "Stripe"
+ case .sentry: return "Sentry"
+ case .atlassian: return "Jira · Confluence"
+ }
+ }
+
+ /// The logo behind a provider id from the server (engines, usage and connections); nil when there is none.
+ public init?(provider: String) {
+ switch provider.lowercased() {
+ case "codex", "openai": self = .openai
+ case "claude", "anthropic": self = .claude
+ case "gemini": self = .gemini
+ case "deepseek", "venice": self = .deepseek
+ case "google": self = .google
+ case "gmail": self = .gmail
+ case "slack": self = .slack
+ case "kakaotalk": self = .kakaotalk
+ case "naverworks": self = .naverworks
+ case "jandi": self = .jandi
+ case "teams", "microsoft_teams", "msteams": self = .teams
+ case "github": self = .github
+ case "linear": self = .linear
+ case "onepassword", "1password": self = .onepassword
+ case "notion": self = .notion
+ case "figma": self = .figma
+ case "cloudflare": self = .cloudflare
+ case "vercel": self = .vercel
+ case "supabase": self = .supabase
+ case "stripe": self = .stripe
+ case "sentry": self = .sentry
+ case "atlassian", "jira", "confluence": self = .atlassian
+ default: return nil
+ }
+ }
+
+ /// The logo behind a model id such as `gemini-4-neon-medium` or `claude-opus-5-5-high`.
+ public init?(model: String) {
+ let raw = model.lowercased()
+ let id = raw.contains("/") ? String(raw.split(separator: "/", maxSplits: 1).last ?? Substring(raw)) : raw
+ if id.hasPrefix("gemini") || raw.hasPrefix("gemini/") {
+ self = .gemini
+ } else if id.hasPrefix("claude") || raw.hasPrefix("claude/") {
+ self = .claude
+ } else if id.hasPrefix("gpt") || id.hasPrefix("codex") || raw.hasPrefix("codex/") {
+ self = .openai
+ } else if id.hasPrefix("deepseek") || id.hasPrefix("venice") || raw.hasPrefix("deepseek/") {
+ self = .deepseek
+ } else {
+ return nil
+ }
+ }
+}
+
+/// A brand logo in one ink, sized by its square.
+public struct MorphBrandMark: View {
+ public let brand: MorphBrand
+ public let size: CGFloat
+ public let color: Color
+
+ public init(_ brand: MorphBrand, size: CGFloat, color: Color = AnymorphColor.fgPrimary) {
+ self.brand = brand
+ self.size = size
+ self.color = color
+ }
+
+ public var body: some View {
+ Image(brand.assetName)
+ .renderingMode(.template)
+ .resizable()
+ .scaledToFit()
+ .frame(width: size, height: size)
+ .foregroundStyle(color)
+ .accessibilityHidden(true)
+ }
+}
+
+/// Icon for connections and engines: the service's logo in ink, or a symbol for the items without a brand. It
+/// sits in a 28pt slot, an account avatar's size, so rows line up, and has no tile of its own: the gray settings
+/// blocks, cards and headers it sits in are already a box. Each service keeps one icon everywhere.
+public struct MorphServiceIcon: View {
+ private enum Glyph {
+ case symbol(String)
+ case brand(MorphBrand)
+ }
+
+ private let glyph: Glyph
+
+ public init(_ systemImage: String) {
+ glyph = .symbol(systemImage)
+ }
+
+ public init(brand: MorphBrand) {
+ glyph = .brand(brand)
+ }
+
+ public var body: some View {
+ Group {
+ switch glyph {
+ case .brand(let brand):
+ MorphBrandMark(brand, size: 17)
+ case .symbol(let systemImage):
+ Image(systemName: systemImage)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ }
+ .frame(width: 28, height: 28)
+ }
+}
+
+public enum MorphEngine {
+ /// The engine's or service's logo, or a chip for an engine Morph has no logo for.
+ @MainActor
+ public static func icon(for provider: String) -> MorphServiceIcon {
+ if let brand = MorphBrand(provider: provider) {
+ return MorphServiceIcon(brand: brand)
+ }
+ switch provider.lowercased() {
+ case "onepassword", "1password": return MorphServiceIcon("key.fill")
+ case "notion": return MorphServiceIcon("doc.text")
+ case "anymorph": return MorphServiceIcon("sparkles")
+ case "cloudflare": return MorphServiceIcon("cloud")
+ case "figma": return MorphServiceIcon("square.on.circle")
+ case "vercel": return MorphServiceIcon("triangle")
+ case "supabase", "neon": return MorphServiceIcon("cylinder.split.1x2")
+ case "sentry": return MorphServiceIcon("exclamationmark.shield")
+ case "stripe", "paypal": return MorphServiceIcon("creditcard")
+ case "atlassian", "asana", "monday": return MorphServiceIcon("checklist")
+ case "posthog", "hubspot": return MorphServiceIcon("chart.bar")
+ case "intercom": return MorphServiceIcon("bubble.left.and.bubble.right")
+ case "canva", "webflow": return MorphServiceIcon("paintbrush")
+ case "context7": return MorphServiceIcon("book.closed")
+ default: return MorphServiceIcon("puzzlepiece.extension")
+ }
+ }
+
+ public static func name(for provider: String) -> String {
+ switch provider.lowercased() {
+ case "codex", "openai": return "Codex"
+ case "claude", "anthropic": return "Claude"
+ case "gemini": return "Gemini"
+ case "deepseek": return "DeepSeek"
+ case "venice": return "Venice"
+ case "onepassword", "1password": return "1Password"
+ case "google": return "Google"
+ case "slack": return "Slack"
+ case "github": return "GitHub"
+ case "linear": return "Linear"
+ case "notion": return "Notion"
+ case "anymorph": return "Anymorph"
+ case "cloudflare": return "Cloudflare"
+ case "figma": return "Figma"
+ case "vercel": return "Vercel"
+ case "supabase": return "Supabase"
+ case "sentry": return "Sentry"
+ case "stripe": return "Stripe"
+ case "atlassian": return "Jira · Confluence"
+ case "posthog": return "PostHog"
+ case "neon": return "Neon"
+ case "intercom": return "Intercom"
+ case "asana": return "Asana"
+ case "hubspot": return "HubSpot"
+ case "canva": return "Canva"
+ case "webflow": return "Webflow"
+ case "paypal": return "PayPal"
+ case "monday": return "monday.com"
+ case "context7": return "Context7"
+ case "gmail": return "Gmail"
+ case "kakaotalk": return "카카오톡"
+ case "jandi": return "잔디"
+ case "teams", "microsoft_teams", "msteams": return "Teams"
+ case "naverworks": return "NAVER WORKS"
+ default: return provider
+ }
+ }
+}
+
+/// The customer channels the assistant reads and replies in. Each keeps one name and one mark everywhere; a
+/// channel Morph has no logo for uses a speech symbol.
+public enum MorphChannel {
+ public static func name(for channel: String?) -> String {
+ guard let channel, !channel.isEmpty else { return "고객 채널" }
+ return MorphEngine.name(for: channel)
+ }
+
+ @MainActor
+ public static func icon(for channel: String?) -> MorphServiceIcon {
+ if let channel, let brand = MorphBrand(provider: channel) {
+ return MorphServiceIcon(brand: brand)
+ }
+ return MorphServiceIcon("bubble.left.and.bubble.right")
+ }
+
+ /// The mark alone, in the ink of the surrounding text.
+ @MainActor @ViewBuilder
+ public static func mark(for channel: String?, size: CGFloat, color: Color = AnymorphColor.fgPrimary) -> some View {
+ if let channel, let brand = MorphBrand(provider: channel) {
+ MorphBrandMark(brand, size: size, color: color)
+ } else {
+ Image(systemName: "bubble.left.and.bubble.right")
+ .font(.system(size: size * 0.72, weight: .medium))
+ .foregroundStyle(color)
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+ }
+}
+
+/// Progress (progress): a 4pt bar of remaining quota, primary ink over the base hairline.
+public struct MorphQuotaBar: View {
+ public let percent: Int
+ public var width: CGFloat?
+
+ public init(percent: Int, width: CGFloat? = nil) {
+ self.percent = max(0, min(100, percent))
+ self.width = width
+ }
+
+ public var body: some View {
+ GeometryReader { geo in
+ ZStack(alignment: .leading) {
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxs, style: .continuous)
+ .fill(AnymorphColor.strokeBase)
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxs, style: .continuous)
+ .fill(AnymorphColor.fgPrimary)
+ .frame(width: geo.size.width * CGFloat(percent) / 100.0)
+ }
+ }
+ .frame(width: width, height: 4)
+ }
+}
+
+/// Compact circular progress ring of remaining quota (0...100), primary ink over the base hairline.
+public struct MorphQuotaRing: View {
+ public let percent: Int
+ public var size: CGFloat
+ public var lineWidth: CGFloat
+
+ public init(percent: Int, size: CGFloat = 20, lineWidth: CGFloat = 2.5) {
+ self.percent = max(0, min(100, percent))
+ self.size = size
+ self.lineWidth = lineWidth
+ }
+
+ public var body: some View {
+ ZStack {
+ Circle()
+ .stroke(AnymorphColor.strokeBase, lineWidth: lineWidth)
+ Circle()
+ .trim(from: 0, to: CGFloat(percent) / 100.0)
+ .stroke(
+ AnymorphColor.fgPrimary,
+ style: StrokeStyle(lineWidth: lineWidth, lineCap: .round)
+ )
+ .rotationEffect(.degrees(-90))
+ }
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+}
+
+/// Compact circular gauge paired with its window label (`5h`, `7d`), remaining percentage, and optional reset countdown.
+public struct MorphQuotaRingMetric: View {
+ public let label: String
+ public let percent: Int
+ public let resetText: String?
+ public var ringSize: CGFloat
+ public var compact: Bool
+
+ public init(
+ label: String,
+ percent: Int,
+ resetText: String? = nil,
+ ringSize: CGFloat = 20,
+ compact: Bool = false
+ ) {
+ self.label = label
+ self.percent = max(0, min(100, percent))
+ self.resetText = resetText
+ self.ringSize = ringSize
+ self.compact = compact
+ }
+
+ public var body: some View {
+ let strokeWidth: CGFloat = ringSize <= 17 ? 2.2 : 2.5
+ HStack(spacing: compact ? 4 : 5) {
+ MorphQuotaRing(percent: percent, size: ringSize, lineWidth: strokeWidth)
+ if compact || resetText != nil {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(alignment: .firstTextBaseline, spacing: 3) {
+ Text(label)
+ .font(.system(size: 9.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ // Every reading takes the width of "100%", so metrics line up from row to row.
+ ZStack(alignment: .leading) {
+ Text("100%").hidden()
+ Text("\(percent)%")
+ }
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ }
+ .lineLimit(1)
+ if let resetText, !resetText.isEmpty {
+ Text(resetText)
+ .font(.system(size: 9.5, weight: .regular))
+ .monospacedDigit()
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ .frame(minWidth: compact ? 48 : nil, alignment: .leading)
+ } else {
+ VStack(alignment: .leading, spacing: 0) {
+ Text(label)
+ .font(.system(size: 9.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ // Every reading takes the width of "100%", so metrics line up from row to row.
+ ZStack(alignment: .leading) {
+ Text("100%").hidden()
+ Text("\(percent)%")
+ }
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ .lineLimit(1)
+ }
+ }
+ }
+ // A tight row never shortens the reading to "100…".
+ .fixedSize()
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(
+ resetText.map { "\(label) \(percent)% 남음, \($0) 리셋" } ?? "\(label) \(percent)% 남음"
+ )
+ }
+}
+
+
+// MARK: - 13. Menu Bar Quota Row
+
+public struct QuotaProgressBar: View {
+ public let label: String
+ public let percent: Int
+ public let brand: MorphBrand?
+
+ public init(label: String, percent: Int, brand: MorphBrand? = nil) {
+ self.label = label
+ self.percent = max(0, min(100, percent))
+ self.brand = brand
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(alignment: .firstTextBaseline) {
+ HStack(spacing: 6) {
+ if let brand {
+ MorphBrandMark(brand, size: 13)
+ }
+ Text(label)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ }
+ Spacer()
+ Text("\(percent)% 남음")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary, tabular: true)
+ }
+ MorphQuotaBar(percent: percent)
+ }
+ }
+}
+
+
+// MARK: - 14. Grok Bot Layout (bubbles, round and pill buttons, count badge, tiles, sidebar rows)
+
+/// A chat bubble in Grok Bot's two tones: the assistant's on the gray fill, the member's in ink.
+public struct MorphBubbleModifier: ViewModifier {
+ public let outgoing: Bool
+
+ public func body(content: Content) -> some View {
+ content
+ .padding(.horizontal, 14)
+ .padding(.vertical, 9)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous)
+ .fill(outgoing ? AnymorphColor.bubbleOutgoing : AnymorphColor.bubbleIncoming)
+ )
+ }
+}
+
+public extension View {
+ /// Wraps the content in a chat bubble. On the member's side, set the text to `AnymorphColor.bubbleOutgoingText`.
+ func morphBubble(outgoing: Bool) -> some View {
+ modifier(MorphBubbleModifier(outgoing: outgoing))
+ }
+}
+
+/// The assistant's bubble while it works: the assistant's figure pulsing in turn.
+public struct MorphTypingBubble: View {
+ public init() {}
+
+ public var body: some View {
+ MorphThinkingMark(width: 20, color: AnymorphColor.fgSecondary)
+ .frame(height: 20)
+ .morphBubble(outgoing: false)
+ .accessibilityLabel("Working..")
+ }
+}
+
+public enum MorphRoundButtonAppearance {
+ /// The bare icon with a round plate on hover: window and pane headers.
+ case plain
+ /// A white disc lifted by a soft shadow: the iPhone chat header and the + beside the phone composer.
+ case floating
+ /// An outlined disc: the + inside the macOS composer.
+ case outlined
+}
+
+/// Grok Bot's round icon buttons. Give the label an SF Symbol; the style sizes it to the disc.
+public struct MorphRoundButtonStyle: ButtonStyle {
+ public let diameter: CGFloat
+ public let appearance: MorphRoundButtonAppearance
+
+ public init(diameter: CGFloat = 28, appearance: MorphRoundButtonAppearance = .plain) {
+ self.diameter = diameter
+ self.appearance = appearance
+ }
+
+ public func makeBody(configuration: Configuration) -> some View {
+ RoundButton(configuration: configuration, diameter: diameter, appearance: appearance)
+ }
+
+ private struct RoundButton: View {
+ let configuration: Configuration
+ let diameter: CGFloat
+ let appearance: MorphRoundButtonAppearance
+ @State private var hovered = false
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ configuration.label
+ .font(.system(size: (diameter * 0.44).rounded(), weight: .medium))
+ .foregroundStyle(isEnabled ? AnymorphColor.fgPrimary : AnymorphColor.fgDisabled)
+ .frame(width: diameter, height: diameter)
+ .background { plate }
+ .contentShape(Circle())
+ .scaleEffect(isEnabled && configuration.isPressed ? 0.94 : 1)
+ .animation(AnymorphMotion.instant, value: configuration.isPressed)
+ .animation(AnymorphMotion.fast, value: hovered)
+ .onHover { hovered = $0 }
+ .morphPointerCursor()
+ }
+
+ @ViewBuilder
+ private var plate: some View {
+ switch appearance {
+ case .plain:
+ Circle().fill(configuration.isPressed ? AnymorphColor.bgSelected : (hovered ? AnymorphColor.bgHover : Color.clear))
+ case .floating:
+ Circle()
+ .fill(configuration.isPressed ? AnymorphColor.bgSelected : (hovered ? AnymorphColor.bgHover : AnymorphColor.bgCard))
+ .overlay(Circle().strokeBorder(hovered ? AnymorphColor.strokeBase : AnymorphColor.strokeLight, lineWidth: 1))
+ .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2)
+ case .outlined:
+ Circle()
+ .fill(configuration.isPressed || hovered ? AnymorphColor.bgHover : AnymorphColor.bgCard)
+ .overlay(Circle().strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ }
+ }
+ }
+}
+
+public enum MorphPillProminence {
+ /// The one action that does the thing: the ink capsule (승인).
+ case primary
+ /// Another action on a card: the gray capsule (보기, 열기).
+ case secondary
+ /// A quiet word beside the primary (반려, 수정 요청).
+ case plain
+}
+
+/// Grok Bot's capsule buttons on chat cards and in the details pane.
+public struct MorphPillButtonStyle: ButtonStyle {
+ public let prominence: MorphPillProminence
+ public let height: CGFloat
+
+ public init(_ prominence: MorphPillProminence = .secondary, height: CGFloat = 28) {
+ self.prominence = prominence
+ self.height = height
+ }
+
+ public func makeBody(configuration: Configuration) -> some View {
+ Pill(configuration: configuration, prominence: prominence, height: height)
+ }
+
+ private struct Pill: View {
+ let configuration: Configuration
+ let prominence: MorphPillProminence
+ let height: CGFloat
+ @State private var hovered = false
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ configuration.label
+ .font(AnymorphFonts.font(.callout, weight: .emphasis))
+ .lineLimit(1)
+ .foregroundStyle(foreground)
+ .padding(.horizontal, prominence == .plain ? 8 : 14)
+ .frame(height: height)
+ .background(Capsule().fill(background))
+ .contentShape(Capsule())
+ .opacity(isEnabled && prominence == .primary && configuration.isPressed ? 0.85 : 1)
+ .scaleEffect(isEnabled && configuration.isPressed ? 0.97 : 1)
+ .animation(AnymorphMotion.instant, value: configuration.isPressed)
+ .animation(AnymorphMotion.fast, value: hovered)
+ .onHover { hovered = $0 }
+ .morphPointerCursor()
+ }
+
+ private var background: Color {
+ guard isEnabled else { return prominence == .plain ? .clear : AnymorphColor.bgDisabled }
+ switch prominence {
+ case .primary: return AnymorphColor.bgInverse
+ // The selected gray reads on white cards and on gray blocks alike; hovering lightens it.
+ case .secondary: return hovered || configuration.isPressed ? AnymorphColor.bgSelected.opacity(0.65) : AnymorphColor.bgSelected
+ case .plain: return hovered || configuration.isPressed ? AnymorphColor.bgHover : .clear
+ }
+ }
+
+ private var foreground: Color {
+ guard isEnabled else { return prominence == .primary ? AnymorphColor.bgBase : AnymorphColor.fgDisabled }
+ switch prominence {
+ case .primary: return AnymorphColor.fgInverse
+ case .secondary: return AnymorphColor.fgPrimary
+ case .plain: return hovered || configuration.isPressed ? AnymorphColor.fgPrimary : AnymorphColor.fgSecondary
+ }
+ }
+ }
+}
+
+public extension View {
+ func morphPill(_ prominence: MorphPillProminence = .secondary, height: CGFloat = 28) -> some View {
+ buttonStyle(MorphPillButtonStyle(prominence, height: height))
+ }
+
+ func morphRound(diameter: CGFloat = 28, _ appearance: MorphRoundButtonAppearance = .plain) -> some View {
+ buttonStyle(MorphRoundButtonStyle(diameter: diameter, appearance: appearance))
+ }
+}
+
+/// A count in an ink capsule, such as the approvals waiting on the details button.
+public struct MorphCountBadge: View {
+ public let count: Int
+
+ public init(_ count: Int) {
+ self.count = count
+ }
+
+ public var body: some View {
+ Text(count > 99 ? "99+" : "\(count)")
+ .font(.system(size: 10, weight: .semibold))
+ .monospacedDigit()
+ .foregroundStyle(AnymorphColor.fgInverse)
+ .padding(.horizontal, 4)
+ .frame(minWidth: 16, minHeight: 16)
+ .background(Capsule().fill(AnymorphColor.bgInverse))
+ }
+}
+
+/// A rounded square holding an icon, for an icon that stands alone on the canvas, such as an empty state's. An icon
+/// inside a pill, card, settings block, menu, header or list row is drawn without one, so boxes do not nest.
+public struct MorphTileIcon: View {
+ public let systemImage: String
+ public let size: CGFloat
+
+ public init(_ systemImage: String, size: CGFloat = 32) {
+ self.systemImage = systemImage
+ self.size = size
+ }
+
+ public var body: some View {
+ let shape = RoundedRectangle(cornerRadius: (size * 0.28).rounded(), style: .continuous)
+ Image(systemName: systemImage)
+ .font(.system(size: (size * 0.42).rounded(), weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: size, height: size)
+ .background(shape.fill(AnymorphColor.bgCard))
+ .overlay(shape.strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ }
+}
+
+/// A Grok Bot sidebar row: a leading avatar or tile, the name with its time and a one-line preview underneath.
+/// A status can end its line. The open row sits on the selected gray, a hovered one on the hover gray.
+public struct MorphSidebarRow: View {
+ public let title: String
+ public let subtitle: String?
+ public let meta: String?
+ public let isSelected: Bool
+ public let action: () -> Void
+ private let leading: Leading
+ private let trailing: Trailing
+ @State private var hovered = false
+
+ public init(
+ _ title: String,
+ subtitle: String? = nil,
+ meta: String? = nil,
+ isSelected: Bool = false,
+ action: @escaping () -> Void,
+ @ViewBuilder leading: () -> Leading,
+ @ViewBuilder trailing: () -> Trailing
+ ) {
+ self.title = title
+ self.subtitle = subtitle
+ self.meta = meta
+ self.isSelected = isSelected
+ self.action = action
+ self.leading = leading()
+ self.trailing = trailing()
+ }
+
+ public var body: some View {
+ Button(action: action) {
+ HStack(spacing: 10) {
+ leading
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ if let meta, !meta.isEmpty {
+ Text(meta)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ trailing
+ }
+ if let subtitle, !subtitle.isEmpty {
+ Text(subtitle)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgSelected : (hovered ? AnymorphColor.bgHover : Color.clear))
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { hovered = $0 }
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ }
+}
+
+extension MorphSidebarRow where Trailing == EmptyView {
+ /// A row with only its leading avatar or tile.
+ public init(
+ _ title: String,
+ subtitle: String? = nil,
+ meta: String? = nil,
+ isSelected: Bool = false,
+ action: @escaping () -> Void,
+ @ViewBuilder leading: () -> Leading
+ ) {
+ self.init(
+ title,
+ subtitle: subtitle,
+ meta: meta,
+ isSelected: isSelected,
+ action: action,
+ leading: leading,
+ trailing: { EmptyView() }
+ )
+ }
+}
+
diff --git a/apple/Apps/Shared/MorphDialog.swift b/apple/Apps/Shared/MorphDialog.swift
new file mode 100644
index 000000000..89e0a7a42
--- /dev/null
+++ b/apple/Apps/Shared/MorphDialog.swift
@@ -0,0 +1,533 @@
+import SwiftUI
+#if os(macOS)
+import AppKit
+#endif
+
+// MARK: - Dialogs
+//
+// On a Mac, Morph asks and confirms inside its own window, as Codex does: a compact card over the dimmed window with
+// a title, one quiet line, an optional text field, and 취소 beside the action at the bottom right. Return takes the
+// action, and Esc or a click outside cancels. An action that waits for its server (a rename) keeps the card open with
+// a spinner on its button, and with the error under the field when the server refuses. The system's alert panel,
+// with the app icon and stacked buttons, no longer appears.
+//
+// A view asks with `.morphDialog(item:)`; the nearest `.morphDialogHost()` above it draws the card over its whole
+// area: the window's root, or a sheet's content for a dialog asked from inside the sheet. iPhone and iPad keep the
+// system alert, which is how those platforms ask.
+
+/// What a dialog shows and does.
+struct MorphDialogContent {
+ let title: String
+ var message: String?
+ var field: Field?
+ let confirmTitle: String
+ var cancelTitle = "취소"
+ /// Deletes or discards something. The Mac card keeps one ink button, as Morph has no red; iPhone marks it red.
+ var isDestructive = false
+ /// Waits for `perform` with a spinner and stays open when it throws. Otherwise the dialog closes at once and the
+ /// action reports its own errors.
+ var waitsForCompletion = false
+ /// What a refused action says under the field on a Mac, before the error itself.
+ var failureMessage = "저장하지 못했습니다."
+ /// Runs the action with the field's text, or an empty string without a field.
+ let perform: (String) async throws -> Void
+ /// Reports a refused action where the dialog cannot show it: iPhone and iPad close their alert first.
+ var reportFailure: ((Error) -> Void)?
+
+ struct Field {
+ var text: String
+ var placeholder: String
+ var accessibilityLabel: String
+ }
+}
+
+extension View {
+ /// Shows a dialog while `item` is set, built from it, and clears `item` when the dialog closes.
+ func morphDialog- (item: Binding
- , content: @escaping (Item) -> MorphDialogContent) -> some View {
+ modifier(MorphDialogRequest(item: item, makeContent: content))
+ }
+
+ /// Draws the dialogs asked for inside this view over its whole area.
+ func morphDialogHost() -> some View {
+ modifier(MorphDialogHostModifier())
+ }
+}
+
+#if os(macOS)
+
+// MARK: Mac
+
+/// What a host shows over its view, if anything, and who asked for it: a dialog, or an image opened full size.
+@MainActor
+@Observable
+final class MorphDialogPresenter {
+ enum Kind {
+ case dialog(MorphDialogContent)
+ case image(MorphLightboxImageItem)
+ }
+
+ struct Presented: Identifiable {
+ let id = UUID()
+ let kind: Kind
+ let onClose: () -> Void
+ }
+
+ private(set) var presented: Presented? {
+ didSet {
+ #if DEBUG
+ Self.qaShowing += (presented != nil ? 1 : 0) - (oldValue != nil ? 1 : 0)
+ #endif
+ }
+ }
+
+ #if DEBUG
+ /// QA only: how many hosts show a dialog or an image right now.
+ static var qaShowing = 0
+ #endif
+
+ func present(_ kind: Kind, onClose: @escaping () -> Void = {}) -> UUID {
+ presented?.onClose()
+ let next = Presented(kind: kind, onClose: onClose)
+ presented = next
+ return next.id
+ }
+
+ /// Closes what shows with this id, if it still shows.
+ func close(_ id: UUID) {
+ guard let presented, presented.id == id else { return }
+ self.presented = nil
+ presented.onClose()
+ }
+}
+
+private struct MorphDialogRequest
- : ViewModifier {
+ @Binding var item: Item?
+ let makeContent: (Item) -> MorphDialogContent
+ @Environment(MorphDialogPresenter.self) private var presenter: MorphDialogPresenter?
+ @State private var shownId: UUID?
+
+ func body(content: Content) -> some View {
+ content
+ .onChange(of: item != nil, initial: true) { _, isSet in
+ if isSet, let item {
+ assert(presenter != nil, "morphDialog needs a morphDialogHost above it")
+ shownId = presenter?.present(.dialog(makeContent(item))) {
+ shownId = nil
+ self.item = nil
+ }
+ } else if !isSet, let shownId {
+ presenter?.close(shownId)
+ }
+ }
+ }
+}
+
+private struct MorphDialogHostModifier: ViewModifier {
+ @State private var presenter = MorphDialogPresenter()
+
+ func body(content: Content) -> some View {
+ content
+ .environment(presenter)
+ .overlay {
+ if let presented = presenter.presented {
+ Group {
+ switch presented.kind {
+ case .dialog(let dialog):
+ MorphDialogScreen(content: dialog) {
+ presenter.close(presented.id)
+ }
+ case .image(let image):
+ MorphImageLightboxScreen(item: image) {
+ presenter.close(presented.id)
+ }
+ }
+ }
+ .id(presented.id)
+ .transition(.opacity)
+ }
+ }
+ .animation(AnymorphMotion.base, value: presenter.presented?.id)
+ }
+}
+
+/// The keys of a dialog or an opened image, taken before any view sees them: Esc closes it, Return takes a field-less
+/// dialog's action, and other typing goes to the dialog's field or nowhere, never to the composer behind. Shortcuts
+/// with ⌘ go on as usual. Return in a field is left to the field, so a Korean syllable still being composed is
+/// committed before the action reads the text. The view that had the keyboard gets it back after.
+private struct MorphOverlayKeys: ViewModifier {
+ let onEscape: () -> Void
+ /// Return; nil leaves Return to the dialog's field.
+ let onReturn: (() -> Void)?
+ /// Typing goes on to a field in the dialog.
+ let passesTyping: Bool
+ @State private var monitor: Any?
+ @State private var previousResponder: NSResponder?
+
+ func body(content: Content) -> some View {
+ content
+ .onAppear {
+ let window = NSApp.keyWindow
+ previousResponder = window?.firstResponder
+ if !passesTyping {
+ window?.makeFirstResponder(nil)
+ }
+ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
+ if event.modifierFlags.intersection(.deviceIndependentFlagsMask).contains(.command) {
+ return event
+ }
+ switch event.keyCode {
+ case 53:
+ onEscape()
+ return nil
+ case 36, 76:
+ guard let onReturn else { return event }
+ onReturn()
+ return nil
+ default:
+ return passesTyping ? event : nil
+ }
+ }
+ }
+ .onDisappear {
+ if let monitor {
+ NSEvent.removeMonitor(monitor)
+ }
+ monitor = nil
+ if let view = previousResponder as? NSView, let window = view.window {
+ window.makeFirstResponder(view)
+ }
+ }
+ }
+}
+
+/// The dimmed window and the dialog card on it.
+private struct MorphDialogScreen: View {
+ let content: MorphDialogContent
+ let close: () -> Void
+
+ @State private var text: String
+ @State private var isWorking = false
+ @State private var failure: String?
+ @State private var appeared = false
+ @FocusState private var fieldFocused: Bool
+
+ init(content: MorphDialogContent, close: @escaping () -> Void) {
+ self.content = content
+ self.close = close
+ _text = State(initialValue: content.field?.text ?? "")
+ }
+
+ private var canConfirm: Bool {
+ guard !isWorking else { return false }
+ guard content.field != nil else { return true }
+ return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ var body: some View {
+ ZStack {
+ AnymorphColor.scrim
+ .ignoresSafeArea()
+ .contentShape(Rectangle())
+ .onTapGesture { cancel() }
+ card
+ .scaleEffect(appeared ? 1 : 0.97)
+ .opacity(appeared ? 1 : 0)
+ }
+ .modifier(MorphOverlayKeys(
+ onEscape: { cancel() },
+ onReturn: content.field == nil ? { confirm() } : nil,
+ passesTyping: content.field != nil
+ ))
+ .onAppear {
+ if content.field != nil {
+ Task { @MainActor in
+ fieldFocused = true
+ // The name is selected, as Codex and Finder do, so typing replaces it.
+ try? await Task.sleep(for: .milliseconds(30))
+ NSApp.sendAction(#selector(NSText.selectAll(_:)), to: nil, from: nil)
+ }
+ }
+ withAnimation(AnymorphMotion.base) { appeared = true }
+ }
+ }
+
+ private var card: some View {
+ let shape = RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ return VStack(alignment: .leading, spacing: 0) {
+ Text(content.title)
+ .anymorphText(.subhead, weight: .strong, color: AnymorphColor.fgPrimary)
+ .fixedSize(horizontal: false, vertical: true)
+ if let message = content.message {
+ Text(message)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.top, 4)
+ }
+ if let field = content.field {
+ MorphDialogTextField(placeholder: field.placeholder, text: $text, focused: $fieldFocused) {
+ confirm()
+ }
+ .accessibilityLabel(field.accessibilityLabel)
+ .disabled(isWorking)
+ .padding(.top, 16)
+ }
+ if let failure {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Image(systemName: "exclamationmark.circle")
+ .font(.system(size: 11, weight: .medium))
+ Text(failure)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .padding(.top, 8)
+ .transition(.opacity)
+ .accessibilityAddTraits(.isStaticText)
+ }
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button(content.cancelTitle) { cancel() }
+ .anymorphButton(size: .md, appearance: .light)
+ .disabled(isWorking)
+ Button {
+ confirm()
+ } label: {
+ ZStack {
+ Text(content.confirmTitle).opacity(isWorking ? 0 : 1)
+ if isWorking {
+ ProgressView()
+ .controlSize(.small)
+ .tint(AnymorphColor.fgInverse)
+ }
+ }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(!canConfirm)
+ }
+ .padding(.top, 20)
+ }
+ .padding(20)
+ .frame(width: 400, alignment: .leading)
+ .background(shape.fill(AnymorphColor.menuSurface))
+ .overlay(shape.strokeBorder(AnymorphColor.menuStroke, lineWidth: 1))
+ .shadow(color: Color.black.opacity(0.16), radius: 32, x: 0, y: 14)
+ .animation(AnymorphMotion.fast, value: failure)
+ .accessibilityElement(children: .contain)
+ .accessibilityAddTraits(.isModal)
+ .accessibilityLabel(content.title)
+ }
+
+ private func cancel() {
+ guard !isWorking else { return }
+ close()
+ }
+
+ private func confirm() {
+ guard canConfirm else { return }
+ let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard content.waitsForCompletion else {
+ close()
+ Task { try? await content.perform(value) }
+ return
+ }
+ isWorking = true
+ failure = nil
+ Task {
+ do {
+ try await content.perform(value)
+ isWorking = false
+ close()
+ } catch {
+ isWorking = false
+ failure = "\(content.failureMessage) \(error.localizedDescription)"
+ fieldFocused = true
+ }
+ }
+ }
+}
+
+/// An image opened full size over the dimmed window, as Codex opens one: the picture fitted to the window, its name
+/// at the top left, copy and close at the top right. Esc, the close button or a click beside the picture closes it.
+private struct MorphImageLightboxScreen: View {
+ let item: MorphLightboxImageItem
+ let close: () -> Void
+ @State private var image: Image?
+ @State private var copied = false
+ @State private var appeared = false
+
+ var body: some View {
+ ZStack {
+ AnymorphColor.mediaBackdrop
+ .ignoresSafeArea()
+ .contentShape(Rectangle())
+ .onTapGesture { close() }
+ if let image {
+ image
+ .resizable()
+ .scaledToFit()
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous))
+ .shadow(color: AnymorphColor.mediaShadow, radius: 24, x: 0, y: 8)
+ .padding(.horizontal, 64)
+ .padding(.top, 64)
+ .padding(.bottom, 40)
+ .scaleEffect(appeared ? 1 : 0.97)
+ .onTapGesture {}
+ .accessibilityLabel(item.title)
+ }
+ VStack {
+ HStack(spacing: 8) {
+ Text(item.title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.mediaInkSecondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 16)
+ lightboxButton(copied ? "checkmark" : "square.on.square", label: copied ? "복사됨" : "이미지 복사") {
+ copy()
+ }
+ lightboxButton("xmark", label: "닫기") {
+ close()
+ }
+ }
+ .padding(.horizontal, 20)
+ .padding(.top, 16)
+ Spacer()
+ }
+ }
+ .modifier(MorphOverlayKeys(onEscape: close, onReturn: nil, passesTyping: false))
+ .task(id: item.id) {
+ if let ns = NSImage(data: item.data) {
+ image = Image(nsImage: ns)
+ }
+ withAnimation(AnymorphMotion.base) { appeared = true }
+ }
+ }
+
+ private func lightboxButton(_ symbol: String, label: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Image(systemName: symbol)
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(AnymorphColor.mediaInk)
+ .frame(width: 32, height: 32)
+ .background(Circle().fill(AnymorphColor.mediaButtonFill))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(label)
+ .accessibilityLabel(label)
+ }
+
+ private func copy() {
+ guard let ns = NSImage(data: item.data) else { return }
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.writeObjects([ns])
+ copied = true
+ Task {
+ try? await Task.sleep(for: .seconds(1.5))
+ copied = false
+ }
+ }
+}
+
+/// The dialog's single-line field: the outlined input of the design system at the dialog's 36pt height.
+private struct MorphDialogTextField: View {
+ let placeholder: String
+ @Binding var text: String
+ var focused: FocusState
.Binding
+ let onSubmit: () -> Void
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ TextField(placeholder, text: $text)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.body, weight: .base))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .focused(focused)
+ .onSubmit(onSubmit)
+ .padding(.horizontal, 12)
+ .frame(height: 36)
+ .background(shape.fill(AnymorphColor.bgBase))
+ .overlay(shape.strokeBorder(focused.wrappedValue ? AnymorphColor.strokeStrong : AnymorphColor.strokeBase, lineWidth: 1))
+ .animation(AnymorphMotion.fast, value: focused.wrappedValue)
+ }
+}
+
+#if DEBUG
+/// QA only: an image the screenshot scenario opens, which the workspace shows as a tile's click does.
+@MainActor
+@Observable
+final class MorphQAImageRequest {
+ static let shared = MorphQAImageRequest()
+ var item: MorphLightboxImageItem?
+}
+#endif
+
+/// Opens an image over the nearest host on a Mac, the way `morphImagePreview` asks for it.
+struct MorphImagePreviewRequest: ViewModifier {
+ @Binding var item: MorphLightboxImageItem?
+ @Environment(MorphDialogPresenter.self) private var presenter: MorphDialogPresenter?
+
+ func body(content: Content) -> some View {
+ content
+ .onChange(of: item) { _, opened in
+ guard let opened else { return }
+ // The overlay owns the image from here; the next click is a new item.
+ item = nil
+ assert(presenter != nil, "morphImagePreview needs a morphDialogHost above it")
+ _ = presenter?.present(.image(opened))
+ }
+ }
+}
+
+#else
+
+// MARK: iPhone and iPad
+
+private struct MorphDialogRequest- : ViewModifier {
+ @Binding var item: Item?
+ let makeContent: (Item) -> MorphDialogContent
+ @State private var text = ""
+
+ func body(content: Content) -> some View {
+ let dialog = item.map(makeContent)
+ content
+ .alert(
+ dialog?.title ?? "",
+ isPresented: Binding(get: { item != nil }, set: { if !$0 { item = nil } }),
+ presenting: dialog
+ ) { dialog in
+ if let field = dialog.field {
+ TextField(field.placeholder, text: $text)
+ .accessibilityLabel(field.accessibilityLabel)
+ }
+ Button(dialog.cancelTitle, role: .cancel) {}
+ Button(dialog.confirmTitle, role: dialog.isDestructive ? .destructive : nil) {
+ let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ Task {
+ do {
+ try await dialog.perform(value)
+ } catch {
+ dialog.reportFailure?(error)
+ }
+ }
+ }
+ .disabled(dialog.field != nil && text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ } message: { dialog in
+ if let message = dialog.message {
+ Text(message)
+ }
+ }
+ .onChange(of: item != nil) { _, isSet in
+ if isSet, let field = dialog?.field {
+ text = field.text
+ }
+ }
+ }
+}
+
+private struct MorphDialogHostModifier: ViewModifier {
+ func body(content: Content) -> some View {
+ content
+ }
+}
+
+#endif
diff --git a/apple/Apps/Shared/MorphDropdown.swift b/apple/Apps/Shared/MorphDropdown.swift
new file mode 100644
index 000000000..b1f866c96
--- /dev/null
+++ b/apple/Apps/Shared/MorphDropdown.swift
@@ -0,0 +1,1213 @@
+import SwiftUI
+#if os(macOS)
+import AppKit
+#endif
+
+// MARK: - Dropdown menus
+//
+// Morph's click menus, drawn the way Claude's model menu is instead of as the system's plain list: a card over or
+// under its button whose rows carry an icon or logo, a title, an optional quieter second line and a check on the
+// current choice. A row can open a submenu beside it, as Effort does in the composer.
+//
+// On a Mac the card floats in a borderless panel above the window, so it can reach past the window's edge like a
+// menu. ↑ and ↓ move between rows, Return picks, → opens a submenu and ← closes it, Esc or a click outside closes
+// the menu, and typing closes it and lets the keys go on to the composer. iPhone and iPad show the same rows in a
+// popover, where a submenu opens in place with a back row.
+
+/// Where a dropdown opens from its button.
+public struct MorphDropdownPlacement: Equatable, Sendable {
+ enum Edge: Equatable, Sendable {
+ case above, below, beside
+ }
+
+ enum Side: Equatable, Sendable {
+ case leading, trailing
+ }
+
+ let edge: Edge
+ let side: Side
+
+ /// Over the button, lined up with its leading edge: the composer's controls at the foot of the window.
+ public static let aboveLeading = MorphDropdownPlacement(edge: .above, side: .leading)
+ /// Over the button, lined up with its trailing edge.
+ public static let aboveTrailing = MorphDropdownPlacement(edge: .above, side: .trailing)
+ /// Under the button, lined up with its leading edge.
+ public static let belowLeading = MorphDropdownPlacement(edge: .below, side: .leading)
+ /// Under the button, lined up with its trailing edge: settings rows and card menus.
+ public static let belowTrailing = MorphDropdownPlacement(edge: .below, side: .trailing)
+ /// Beside a row of an open menu: a submenu.
+ static let beside = MorphDropdownPlacement(edge: .beside, side: .trailing)
+}
+
+extension EnvironmentValues {
+ /// Whether the dropdown this label opens is showing, so the label keeps its hover plate while it is.
+ @Entry var morphDropdownIsOpen = false
+ /// What a row asks of the menu it sits in.
+ @Entry var morphMenuActions = MorphMenuActions()
+}
+
+/// What a row asks of the menu it sits in.
+struct MorphMenuActions {
+ /// Closes the menu and any submenu.
+ var dismiss: @MainActor () -> Void = {}
+ /// Shows a submenu in place of the rows, on iPhone and iPad. A Mac opens submenus beside their row instead.
+ var push: (@MainActor (MorphMenuPage) -> Void)?
+}
+
+/// A submenu shown in place of its menu's rows.
+struct MorphMenuPage {
+ let title: String
+ let content: AnyView
+}
+
+// MARK: - Dropdown button
+
+/// A button that opens a dropdown card of MorphMenuItem rows.
+public struct MorphDropdown
: View {
+ private let placement: MorphDropdownPlacement
+ private let width: CGFloat
+ private let name: String?
+ private let content: () -> Content
+ private let label: Label
+ @State private var isPresented = false
+
+ /// - Parameter name: The menu's accessibility identifier, which the DEBUG screenshot harness also opens it by.
+ public init(
+ placement: MorphDropdownPlacement = .belowLeading,
+ width: CGFloat = 248,
+ name: String? = nil,
+ @ViewBuilder content: @escaping () -> Content,
+ @ViewBuilder label: () -> Label
+ ) {
+ self.placement = placement
+ self.width = width
+ self.name = name
+ self.content = content
+ self.label = label()
+ }
+
+ public var body: some View {
+ Button {
+ isPresented.toggle()
+ } label: {
+ label.environment(\.morphDropdownIsOpen, isPresented)
+ }
+ .buttonStyle(.morphPlain)
+ .accessibilityIdentifier(name ?? "")
+ .morphDropdown(isPresented: $isPresented, placement: placement, width: width, content: content)
+ #if DEBUG
+ .onChange(of: MorphDropdownQA.shared.request) { _, request in
+ guard let request, let name else { return }
+ if request.name == name {
+ isPresented = true
+ }
+ }
+ .onChange(of: MorphDropdownQA.shared.closeSerial) { _, _ in
+ isPresented = false
+ }
+ #endif
+ }
+}
+
+extension View {
+ /// Shows a dropdown card from this view while isPresented is true.
+ func morphDropdown(
+ isPresented: Binding,
+ placement: MorphDropdownPlacement,
+ width: CGFloat,
+ highlightsFirstRow: Bool = false,
+ @ViewBuilder content: @escaping () -> Content
+ ) -> some View {
+ #if os(macOS)
+ background(
+ MorphDropdownAnchor(
+ isPresented: isPresented,
+ placement: placement,
+ width: width,
+ highlightsFirstRow: highlightsFirstRow,
+ content: content
+ )
+ )
+ #else
+ popover(isPresented: isPresented, attachmentAnchor: .rect(.bounds), arrowEdge: placement.edge == .above ? .bottom : .top) {
+ MorphDropdownPopover(isPresented: isPresented, width: width, content: content)
+ }
+ #endif
+ }
+}
+
+#if DEBUG
+/// QA screenshots only: opens the dropdown with a given name.
+@MainActor
+@Observable
+final class MorphDropdownQA {
+ struct Request: Equatable {
+ let name: String
+ let serial: Int
+ }
+
+ static let shared = MorphDropdownQA()
+ private(set) var request: Request?
+ private(set) var submenu: Request?
+ private(set) var closeSerial: Int = 0
+
+ func open(_ name: String) {
+ request = Request(name: name, serial: (request?.serial ?? 0) + 1)
+ }
+
+ /// Opens the submenu row with this id in the open menu, as → does.
+ func openSubmenu(_ id: String) {
+ submenu = Request(name: id, serial: (submenu?.serial ?? 0) + 1)
+ }
+
+ func closeAll() {
+ closeSerial += 1
+ #if os(macOS)
+ MorphDropdownStack.shared.closeAll()
+ #endif
+ }
+}
+#endif
+
+// MARK: - Rows
+
+/// The mark in front of a menu row.
+public enum MorphMenuIcon {
+ case none
+ case symbol(String)
+ case brand(MorphBrand)
+}
+
+/// A small tag after a row's title, such as Medium's 추천.
+public struct MorphMenuTag {
+ let text: String
+
+ public init(_ text: String) {
+ self.text = text
+ }
+}
+
+/// One choice or action in a dropdown: an icon or logo, a title with an optional tag, an optional second line, and
+/// on the trailing edge a value or shortcut and the check of the current choice. Picking it closes the menu.
+public struct MorphMenuItem: View {
+ private let id: String
+ private let title: String
+ private let subtitle: String?
+ private let icon: MorphMenuIcon
+ private let tag: MorphMenuTag?
+ private let trailing: String?
+ private let isSelected: Bool
+ private let isMuted: Bool
+ private let isEnabled: Bool
+ private let action: () -> Void
+
+ @Environment(MorphMenuNavigator.self) private var navigator: MorphMenuNavigator?
+ @Environment(\.morphMenuActions) private var actions
+
+ /// - Parameters:
+ /// - isMuted: Draws the title quieter while the row can still be picked, as an engine out of quota is.
+ /// - id: Tells rows apart for the arrow keys; the title by default.
+ public init(
+ _ title: String,
+ subtitle: String? = nil,
+ icon: MorphMenuIcon = .none,
+ tag: MorphMenuTag? = nil,
+ trailing: String? = nil,
+ isSelected: Bool = false,
+ isMuted: Bool = false,
+ isEnabled: Bool = true,
+ id: String? = nil,
+ action: @escaping () -> Void
+ ) {
+ self.id = id ?? title
+ self.title = title
+ self.subtitle = subtitle
+ self.icon = icon
+ self.tag = tag
+ self.trailing = trailing
+ self.isSelected = isSelected
+ self.isMuted = isMuted
+ self.isEnabled = isEnabled
+ self.action = action
+ }
+
+ public var body: some View {
+ Button(action: perform) {
+ MorphMenuRowLabel(
+ title: title,
+ subtitle: subtitle,
+ icon: icon,
+ tag: tag,
+ titleColor: !isEnabled ? AnymorphColor.fgDisabled : (isMuted ? AnymorphColor.fgTertiary : AnymorphColor.fgPrimary)
+ ) {
+ if let trailing {
+ Text(trailing)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ if isSelected {
+ Image(systemName: "checkmark")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .accessibilityHidden(true)
+ }
+ }
+ }
+ .buttonStyle(MorphMenuRowStyle(isHighlighted: isEnabled && navigator?.highlightedID == id))
+ .disabled(!isEnabled)
+ .morphMenuRow(id: id, isEnabled: isEnabled, navigator: navigator)
+ .onChange(of: navigator?.activation) { _, request in
+ if request?.id == id {
+ perform()
+ }
+ }
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ }
+
+ private func perform() {
+ actions.dismiss()
+ action()
+ }
+}
+
+/// A row that opens a submenu: beside it on a Mac, when the pointer rests on it or on → and Return; in place on
+/// iPhone and iPad. The trailing value says what the submenu has chosen, as Claude's Effort row shows Medium.
+public struct MorphMenuSubmenu: View {
+ private let id: String
+ private let title: String
+ private let value: String?
+ private let icon: MorphMenuIcon
+ private let width: CGFloat
+ private let content: () -> Content
+
+ @State private var isOpen = false
+ @State private var opensWithHighlight = false
+ @State private var hoverOpen: Task?
+ @Environment(MorphMenuNavigator.self) private var navigator: MorphMenuNavigator?
+ @Environment(\.morphMenuActions) private var actions
+
+ public init(
+ _ title: String,
+ value: String? = nil,
+ icon: MorphMenuIcon = .none,
+ width: CGFloat = 280,
+ id: String? = nil,
+ @ViewBuilder content: @escaping () -> Content
+ ) {
+ self.id = id ?? title
+ self.title = title
+ self.value = value
+ self.icon = icon
+ self.width = width
+ self.content = content
+ }
+
+ public var body: some View {
+ Button {
+ open(withHighlight: false)
+ } label: {
+ MorphMenuRowLabel(title: title, subtitle: nil, icon: icon, tag: nil, titleColor: AnymorphColor.fgPrimary) {
+ if let value {
+ Text(value)
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ }
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ .accessibilityHidden(true)
+ }
+ }
+ .buttonStyle(MorphMenuRowStyle(isHighlighted: isOpen || navigator?.highlightedID == id))
+ .morphMenuRow(id: id, isEnabled: true, navigator: navigator)
+ .onHover { inside in
+ hoverOpen?.cancel()
+ guard inside, navigator?.pointerMoved() ?? true else { return }
+ #if os(macOS)
+ // Opens once the pointer rests, so passing over the row on the way down does not flash the submenu.
+ hoverOpen = Task { @MainActor in
+ try? await Task.sleep(for: .milliseconds(140))
+ guard !Task.isCancelled, navigator?.highlightedID == id else { return }
+ opensWithHighlight = false
+ isOpen = true
+ }
+ #endif
+ }
+ .onChange(of: isOpen) { _, open in
+ if open {
+ navigator?.openSubmenuID = id
+ } else if navigator?.openSubmenuID == id {
+ navigator?.openSubmenuID = nil
+ }
+ }
+ .onChange(of: navigator?.highlightedID) { _, highlighted in
+ // Another row closes the submenu. The pointer leaving for the submenu itself does not.
+ if let highlighted, highlighted != id {
+ isOpen = false
+ }
+ }
+ .onChange(of: navigator?.submenuRequest) { _, request in
+ if request?.id == id {
+ open(withHighlight: true)
+ }
+ }
+ .onChange(of: navigator?.activation) { _, request in
+ if request?.id == id {
+ open(withHighlight: true)
+ }
+ }
+ #if os(macOS)
+ .morphDropdown(isPresented: $isOpen, placement: .beside, width: width, highlightsFirstRow: opensWithHighlight, content: content)
+ #endif
+ #if DEBUG
+ .onChange(of: MorphDropdownQA.shared.submenu) { _, request in
+ if request?.name == id {
+ open(withHighlight: true)
+ }
+ }
+ #endif
+ .accessibilityHint("하위 메뉴를 엽니다")
+ }
+
+ private func open(withHighlight: Bool) {
+ #if os(macOS)
+ navigator?.highlightedID = id
+ opensWithHighlight = withHighlight
+ isOpen = withHighlight ? true : !isOpen
+ #else
+ actions.push?(MorphMenuPage(title: title, content: AnyView(content())))
+ #endif
+ }
+}
+
+/// A thin line between groups of rows.
+public struct MorphMenuDivider: View {
+ public init() {}
+
+ public var body: some View {
+ Rectangle()
+ .fill(AnymorphColor.strokeLight)
+ .frame(height: 1)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 5)
+ .accessibilityHidden(true)
+ }
+}
+
+/// A group's name over its rows, with an optional status on the trailing edge, such as an engine's 주간 한도 소진.
+public struct MorphMenuSectionHeader: View {
+ private let title: String
+ private let status: String?
+
+ public init(_ title: String, status: String? = nil) {
+ self.title = title
+ self.status = status
+ }
+
+ public var body: some View {
+ HStack(spacing: 8) {
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgTertiary)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ if let status, !status.isEmpty {
+ Text(status)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.top, 6)
+ .padding(.bottom, 3)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits(.isHeader)
+ }
+}
+
+/// A short explanation at the top of a menu, as Claude's Effort submenu opens with one.
+public struct MorphMenuNote: View {
+ private let text: String
+
+ public init(_ text: String) {
+ self.text = text
+ }
+
+ public var body: some View {
+ Text(text)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 10)
+ .padding(.top, 7)
+ .padding(.bottom, 5)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+/// The row content every menu row shares.
+struct MorphMenuRowLabel: View {
+ let title: String
+ let subtitle: String?
+ let icon: MorphMenuIcon
+ let tag: MorphMenuTag?
+ let titleColor: Color
+ @ViewBuilder let trailing: Trailing
+
+ var body: some View {
+ HStack(alignment: subtitle == nil ? .center : .top, spacing: 9) {
+ if hasIcon {
+ iconView
+ .frame(width: 16, height: subtitle == nil ? 16 : 18)
+ }
+ VStack(alignment: .leading, spacing: 1) {
+ HStack(spacing: 6) {
+ Text(title)
+ .anymorphText(.callout, weight: .base, color: titleColor)
+ .lineLimit(1)
+ if let tag {
+ MorphMenuTagView(tag: tag)
+ }
+ }
+ if let subtitle, !subtitle.isEmpty {
+ Text(subtitle)
+ .anymorphText(.footnote, weight: .base, color: isQuiet ? AnymorphColor.fgQuaternary : AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ Spacer(minLength: 8)
+ HStack(spacing: 8) {
+ trailing
+ }
+ .frame(minHeight: subtitle == nil ? 16 : 18)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, subtitle == nil ? 6 : 5)
+ .frame(minHeight: 30)
+ .contentShape(Rectangle())
+ }
+
+ /// A row without an icon starts its title at the menu's edge, as Claude's model rows do.
+ private var hasIcon: Bool {
+ if case .none = icon {
+ return false
+ }
+ return true
+ }
+
+ /// A muted or disabled row: its second line and logo step back with its title.
+ private var isQuiet: Bool {
+ titleColor != AnymorphColor.fgPrimary
+ }
+
+ @ViewBuilder
+ private var iconView: some View {
+ switch icon {
+ case .none:
+ EmptyView()
+ case .symbol(let name):
+ Image(systemName: name)
+ .font(.system(size: 12.5, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .symbolRenderingMode(.monochrome)
+ case .brand(let brand):
+ MorphBrandMark(brand, size: 13, color: isQuiet ? AnymorphColor.fgTertiary : AnymorphColor.fgPrimary)
+ }
+ }
+}
+
+private struct MorphMenuTagView: View {
+ let tag: MorphMenuTag
+
+ var body: some View {
+ Text(tag.text)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ .padding(.horizontal, 5)
+ .frame(height: 17)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xs, style: .continuous)
+ .fill(AnymorphColor.bgSurface)
+ )
+ }
+}
+
+/// A row's plate: the highlight under the pointer or the arrow keys, and while pressed.
+private struct MorphMenuRowStyle: ButtonStyle {
+ let isHighlighted: Bool
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous)
+ .fill(isHighlighted || configuration.isPressed ? AnymorphColor.menuHighlight : Color.clear)
+ )
+ .morphPointerCursor()
+ }
+}
+
+extension View {
+ /// Puts a row in its menu's arrow-key order, by where it sits, and moves the highlight with the pointer.
+ fileprivate func morphMenuRow(id: String, isEnabled: Bool, navigator: MorphMenuNavigator?) -> some View {
+ self
+ .id(id)
+ .onHover { inside in
+ guard isEnabled else { return }
+ navigator?.hover(id, inside: inside)
+ }
+ .onGeometryChange(for: CGFloat.self) { proxy in
+ proxy.frame(in: .named(MorphMenuNavigator.space)).minY
+ } action: { minY in
+ if isEnabled {
+ navigator?.place(id, at: minY)
+ } else {
+ navigator?.remove(id)
+ }
+ }
+ .onDisappear {
+ navigator?.remove(id)
+ }
+ }
+}
+
+// MARK: - Keyboard and pointer state
+
+/// The highlighted row of one open menu, and the requests the arrow keys and Return make of its rows.
+@MainActor
+@Observable
+final class MorphMenuNavigator {
+ nonisolated static let space = "morph-menu"
+
+ struct Request: Equatable {
+ let id: String
+ let serial: Int
+ }
+
+ var highlightedID: String?
+ /// The submenu row whose submenu is open. Its highlight stays while the pointer crosses into the submenu.
+ var openSubmenuID: String?
+ /// Return on the highlighted row: the row acts, or opens its submenu.
+ private(set) var activation: Request?
+ /// → on the highlighted row: a submenu row opens.
+ private(set) var submenuRequest: Request?
+ /// The row the arrow keys moved to, which a scrolling menu brings into view.
+ private(set) var keyboardTarget: Request?
+
+ @ObservationIgnored private var rowTops: [String: CGFloat] = [:]
+ @ObservationIgnored private var serial = 0
+ /// Set when the menu opened from the keyboard: the top row takes the highlight as rows report in.
+ @ObservationIgnored var highlightsTopRow = false
+ #if os(macOS)
+ /// Where the pointer rested when the menu opened or a key was last pressed. The pointer moves the highlight only
+ /// once it leaves that spot, as in a system menu, so a menu opening or closing under a resting pointer neither
+ /// takes the highlight from the keys nor opens a submenu.
+ @ObservationIgnored private var restingPointer: NSPoint?
+ #endif
+
+ private var orderedIDs: [String] {
+ rowTops.sorted { $0.value < $1.value }.map(\.key)
+ }
+
+ func place(_ id: String, at top: CGFloat) {
+ rowTops[id] = top
+ if highlightsTopRow {
+ highlightedID = orderedIDs.first
+ }
+ }
+
+ func remove(_ id: String) {
+ rowTops[id] = nil
+ if highlightedID == id {
+ highlightedID = nil
+ }
+ }
+
+ /// Keeps the pointer from moving the highlight until it moves: the menu opened or a key was pressed.
+ func pointerRests() {
+ #if os(macOS)
+ restingPointer = NSEvent.mouseLocation
+ #endif
+ }
+
+ /// Whether the pointer has left the spot where it last rested.
+ func pointerMoved() -> Bool {
+ #if os(macOS)
+ if let restingPointer {
+ guard NSEvent.mouseLocation != restingPointer else { return false }
+ self.restingPointer = nil
+ }
+ #endif
+ return true
+ }
+
+ func hover(_ id: String, inside: Bool) {
+ guard pointerMoved() else { return }
+ highlightsTopRow = false
+ if inside {
+ highlightedID = id
+ } else if highlightedID == id, openSubmenuID != id {
+ highlightedID = nil
+ }
+ }
+
+ func move(_ step: Int) {
+ highlightsTopRow = false
+ let ids = orderedIDs
+ guard !ids.isEmpty else { return }
+ if let current = highlightedID, let index = ids.firstIndex(of: current) {
+ highlightedID = ids[(index + step + ids.count) % ids.count]
+ } else {
+ highlightedID = step > 0 ? ids.first : ids.last
+ }
+ if let highlightedID {
+ serial += 1
+ keyboardTarget = Request(id: highlightedID, serial: serial)
+ }
+ }
+
+ /// Asks the highlighted row to act. False when no row is highlighted.
+ func activateHighlighted() -> Bool {
+ guard let id = highlightedID else { return false }
+ serial += 1
+ activation = Request(id: id, serial: serial)
+ return true
+ }
+
+ func openSubmenu(_ id: String) {
+ highlightedID = id
+ serial += 1
+ submenuRequest = Request(id: id, serial: serial)
+ }
+
+ func openHighlightedSubmenu() {
+ guard let id = highlightedID else { return }
+ openSubmenu(id)
+ }
+
+ func reset() {
+ highlightedID = nil
+ openSubmenuID = nil
+ activation = nil
+ submenuRequest = nil
+ keyboardTarget = nil
+ highlightsTopRow = false
+ rowTops = [:]
+ pointerRests()
+ }
+}
+
+// MARK: - Card
+
+/// The card a dropdown's rows sit on. A Mac sizes its panel from the rows' height and scrolls them when the screen
+/// is shorter than the menu.
+struct MorphDropdownCard: View {
+ let width: CGFloat
+ let layout: MorphDropdownLayout?
+ @ViewBuilder let content: Content
+ @Environment(MorphMenuNavigator.self) private var navigator: MorphMenuNavigator?
+
+ static var radius: CGFloat { 12 }
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: Self.radius, style: .continuous)
+ rows
+ .frame(width: width)
+ .background(shape.fill(AnymorphColor.menuSurface))
+ .clipShape(shape)
+ .overlay(shape.strokeBorder(AnymorphColor.menuStroke, lineWidth: 1))
+ .coordinateSpace(.named(MorphMenuNavigator.space))
+ }
+
+ @ViewBuilder
+ private var rows: some View {
+ let stack = VStack(alignment: .leading, spacing: 0) {
+ content
+ }
+ .padding(5)
+ .fixedSize(horizontal: false, vertical: true)
+ .onGeometryChange(for: CGFloat.self) { proxy in
+ proxy.size.height
+ } action: { height in
+ layout?.contentHeightChanged(height)
+ }
+ if let maxHeight = layout?.maxContentHeight {
+ ScrollViewReader { proxy in
+ ScrollView(.vertical) {
+ stack
+ }
+ .frame(height: maxHeight)
+ .onChange(of: navigator?.keyboardTarget) { _, target in
+ if let target {
+ proxy.scrollTo(target.id)
+ }
+ }
+ }
+ } else {
+ stack
+ }
+ }
+}
+
+/// The height a Mac dropdown's rows want, and the height it scrolls them in when the screen has less room.
+@MainActor
+@Observable
+final class MorphDropdownLayout {
+ private(set) var maxContentHeight: CGFloat?
+ @ObservationIgnored private(set) var contentHeight: CGFloat = 0
+ @ObservationIgnored var onContentHeightChange: (() -> Void)?
+
+ func contentHeightChanged(_ height: CGFloat) {
+ guard abs(height - contentHeight) > 0.5 else { return }
+ contentHeight = height
+ onContentHeightChange?()
+ }
+
+ func setMaxContentHeight(_ height: CGFloat?) {
+ if maxContentHeight != height {
+ maxContentHeight = height
+ }
+ }
+
+ func reset() {
+ maxContentHeight = nil
+ contentHeight = 0
+ }
+}
+
+// MARK: - iPhone and iPad
+
+#if os(iOS)
+/// The dropdown in a popover. A submenu replaces the rows, under a back row with its name.
+private struct MorphDropdownPopover: View {
+ @Binding var isPresented: Bool
+ let width: CGFloat
+ let content: () -> Content
+ @State private var page: MorphMenuPage?
+ @State private var navigator = MorphMenuNavigator()
+
+ var body: some View {
+ ViewThatFits(in: .vertical) {
+ rows
+ ScrollView(.vertical) {
+ rows
+ }
+ }
+ .frame(width: width)
+ .environment(navigator)
+ .environment(\.morphMenuActions, MorphMenuActions(dismiss: { isPresented = false }, push: { page = $0 }))
+ .presentationCompactAdaptation(.popover)
+ .presentationBackground(AnymorphColor.menuSurface)
+ }
+
+ private var rows: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ if let page {
+ Button {
+ withAnimation(AnymorphMotion.fast) { self.page = nil }
+ } label: {
+ MorphMenuRowLabel(title: page.title, subtitle: nil, icon: .symbol("chevron.left"), tag: nil, titleColor: AnymorphColor.fgPrimary) {
+ EmptyView()
+ }
+ }
+ .buttonStyle(MorphMenuRowStyle(isHighlighted: false))
+ .accessibilityLabel("뒤로")
+ MorphMenuDivider()
+ page.content
+ } else {
+ content()
+ }
+ }
+ .padding(6)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
+#endif
+
+// MARK: - Mac panel
+
+#if os(macOS)
+/// Sits behind the button and shows the card in a panel while the binding is true.
+private struct MorphDropdownAnchor: NSViewRepresentable {
+ @Binding var isPresented: Bool
+ let placement: MorphDropdownPlacement
+ let width: CGFloat
+ let highlightsFirstRow: Bool
+ let content: () -> Content
+
+ func makeCoordinator() -> MorphDropdownController {
+ MorphDropdownController()
+ }
+
+ func makeNSView(context: Context) -> NSView {
+ NSView()
+ }
+
+ func updateNSView(_ view: NSView, context: Context) {
+ let controller = context.coordinator
+ guard isPresented || controller.isActive else { return }
+ let binding = $isPresented
+ controller.onClose = { binding.wrappedValue = false }
+ controller.request(
+ isPresented: isPresented,
+ anchor: view,
+ placement: placement,
+ width: width,
+ highlightsFirstRow: highlightsFirstRow,
+ content: isPresented ? AnyView(content()) : nil
+ )
+ }
+
+ static func dismantleNSView(_ view: NSView, coordinator: MorphDropdownController) {
+ coordinator.close(notify: false)
+ }
+}
+
+/// A borderless panel that never takes the keyboard from the window, so the composer keeps its text and focus while
+/// a menu is open.
+private final class MorphDropdownPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+}
+
+/// Lets the first click on a row act, as a menu's does, though the panel is not the key window.
+private final class MorphDropdownHostingView: NSHostingView {
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+}
+
+/// Opens, sizes, places and closes one dropdown's panel.
+@MainActor
+final class MorphDropdownController {
+ var onClose: (() -> Void)?
+ let navigator = MorphMenuNavigator()
+ let layout = MorphDropdownLayout()
+ fileprivate private(set) var panel: NSPanel?
+ private var hosting: MorphDropdownHostingView?
+ private weak var anchor: NSView?
+ private var placement = MorphDropdownPlacement.belowLeading
+ private var width: CGFloat = 248
+ private var wantsOpen = false
+ private var highlightsFirstRow = false
+ private var pendingContent: AnyView?
+ private var isApplyScheduled = false
+ private var isLayoutScheduled = false
+
+ var isActive: Bool {
+ wantsOpen || panel != nil || isApplyScheduled
+ }
+
+ init() {
+ layout.onContentHeightChange = { [weak self] in
+ self?.scheduleLayout()
+ }
+ }
+
+ /// Called from SwiftUI's update. The panel changes after the update, since moving windows during one can
+ /// update SwiftUI again.
+ func request(
+ isPresented: Bool,
+ anchor: NSView,
+ placement: MorphDropdownPlacement,
+ width: CGFloat,
+ highlightsFirstRow: Bool,
+ content: AnyView?
+ ) {
+ if !isPresented && !wantsOpen && panel == nil && !isApplyScheduled {
+ return
+ }
+ self.anchor = anchor
+ self.placement = placement
+ self.width = width
+ self.highlightsFirstRow = highlightsFirstRow
+ wantsOpen = isPresented
+ pendingContent = content
+ guard !isApplyScheduled else { return }
+ isApplyScheduled = true
+ Task { @MainActor [weak self] in
+ self?.apply()
+ }
+ }
+
+ private func apply() {
+ isApplyScheduled = false
+ guard wantsOpen, let content = pendingContent, let anchor, let window = anchor.window, window.isVisible else {
+ close(notify: wantsOpen)
+ return
+ }
+ let root = AnyView(
+ MorphDropdownCard(width: width, layout: layout) {
+ content
+ }
+ .environment(navigator)
+ .environment(\.morphMenuActions, MorphMenuActions(dismiss: { MorphDropdownStack.shared.closeAll() }))
+ )
+ if let hosting {
+ hosting.rootView = root
+ return
+ }
+ open(root: root, from: window)
+ }
+
+ private func open(root: AnyView, from window: NSWindow) {
+ let panel = MorphDropdownPanel(
+ contentRect: NSRect(x: 0, y: 0, width: width, height: 10),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: true
+ )
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.level = .popUpMenu
+ panel.isReleasedWhenClosed = false
+ panel.hidesOnDeactivate = false
+ panel.worksWhenModal = true
+ panel.becomesKeyOnlyIfNeeded = true
+ panel.animationBehavior = .none
+ panel.collectionBehavior = [.transient, .ignoresCycle, .fullScreenAuxiliary]
+ panel.appearance = window.effectiveAppearance
+ panel.setAccessibilityRole(.popover)
+
+ let hosting = MorphDropdownHostingView(rootView: root)
+ hosting.sizingOptions = []
+ hosting.autoresizingMask = [.width, .height]
+ panel.contentView = hosting
+ self.hosting = hosting
+ self.panel = panel
+
+ navigator.reset()
+ navigator.highlightsTopRow = highlightsFirstRow
+ layout.reset()
+ layout.contentHeightChanged(hosting.fittingSize.height)
+ MorphDropdownStack.shared.push(self, over: window)
+ layoutPanel()
+
+ panel.alphaValue = 0
+ panel.orderFront(nil)
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.12
+ panel.animator().alphaValue = 1
+ }
+ // The shadow follows the card's rounded shape once it has drawn.
+ Task { @MainActor [weak panel] in
+ try? await Task.sleep(for: .milliseconds(60))
+ panel?.invalidateShadow()
+ }
+ }
+
+ func close(notify: Bool) {
+ guard let panel else { return }
+ self.panel = nil
+ hosting = nil
+ MorphDropdownStack.shared.remove(self)
+ panel.orderOut(nil)
+ panel.contentView = nil
+ navigator.reset()
+ layout.reset()
+ if notify {
+ onClose?()
+ }
+ }
+
+ private func scheduleLayout() {
+ guard !isLayoutScheduled else { return }
+ isLayoutScheduled = true
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.isLayoutScheduled = false
+ self.layoutPanel()
+ }
+ }
+
+ /// Places the panel over or under its button, or beside its row for a submenu, keeping it on screen and
+ /// letting the rows scroll when the screen is shorter than the menu.
+ private func layoutPanel() {
+ guard let panel, let anchor, let window = anchor.window else { return }
+ let button = window.convertToScreen(anchor.convert(anchor.bounds, to: nil))
+ let screen = (window.screen ?? NSScreen.main)?.visibleFrame ?? window.frame
+ let margin: CGFloat = 8
+ let gap: CGFloat = 6
+ let natural = max(layout.contentHeight, 1)
+ var size = CGSize(width: width, height: natural)
+ var origin = CGPoint.zero
+
+ switch placement.edge {
+ case .above, .below:
+ let roomAbove = screen.maxY - button.maxY - gap - margin
+ let roomBelow = button.minY - screen.minY - gap - margin
+ let goesAbove = placement.edge == .above
+ ? natural <= roomAbove || roomAbove >= roomBelow
+ : natural > roomBelow && roomAbove > roomBelow
+ size.height = min(natural, goesAbove ? roomAbove : roomBelow)
+ origin.y = goesAbove ? button.maxY + gap : button.minY - gap - size.height
+ origin.x = placement.side == .leading ? button.minX : button.maxX - size.width
+ case .beside:
+ // The submenu's first row lines up with the row that opened it, just past the menu's edge. A row that
+ // has scrolled part way out of its menu counts from the menu's edge.
+ let menu = window.frame
+ let rowTop = min(max(button.maxY, menu.minY + 30), menu.maxY - 5)
+ let fitsRight = menu.maxX - 4 + size.width <= screen.maxX - margin
+ origin.x = fitsRight ? menu.maxX - 4 : menu.minX + 4 - size.width
+ size.height = min(natural, screen.height - margin * 2)
+ origin.y = rowTop + 5 - size.height
+ }
+ origin.x = min(max(origin.x, screen.minX + margin), screen.maxX - margin - size.width)
+ origin.y = min(max(origin.y, screen.minY + margin), screen.maxY - margin - size.height)
+
+ layout.setMaxContentHeight(size.height < natural - 0.5 ? size.height : nil)
+ panel.setFrame(NSRect(origin: origin, size: size), display: true)
+ panel.invalidateShadow()
+ }
+}
+
+/// The open dropdowns, a menu and its submenus, and the event handling they share: the arrow keys, Return, Esc,
+/// a click outside, and leaving the app or the window.
+@MainActor
+final class MorphDropdownStack {
+ static let shared = MorphDropdownStack()
+
+ private var levels: [MorphDropdownController] = []
+ private var monitors: [Any] = []
+ private var observers: [NSObjectProtocol] = []
+
+ private enum Key {
+ static let returnKey: UInt16 = 36
+ static let tab: UInt16 = 48
+ static let escape: UInt16 = 53
+ static let enter: UInt16 = 76
+ static let left: UInt16 = 123
+ static let right: UInt16 = 124
+ static let down: UInt16 = 125
+ static let up: UInt16 = 126
+ }
+
+ /// Adds a menu on top. A submenu replaces any other submenu open from the same menu, and a menu opened from
+ /// outside the open ones replaces them all.
+ func push(_ controller: MorphDropdownController, over window: NSWindow) {
+ if let parent = levels.firstIndex(where: { $0.panel === window }) {
+ for level in levels[(parent + 1)...].reversed() {
+ level.close(notify: true)
+ }
+ } else {
+ closeAll()
+ }
+ levels.append(controller)
+ if monitors.isEmpty {
+ install(watching: window)
+ }
+ }
+
+ /// Takes a menu off, with any submenu it opened.
+ func remove(_ controller: MorphDropdownController) {
+ guard let index = levels.firstIndex(where: { $0 === controller }) else { return }
+ let deeper = Array(levels[(index + 1)...])
+ levels.removeSubrange(index...)
+ for level in deeper.reversed() {
+ level.close(notify: true)
+ }
+ if levels.isEmpty {
+ uninstall()
+ }
+ }
+
+ func closeAll() {
+ for level in levels.reversed() {
+ level.close(notify: true)
+ }
+ }
+
+ private func isMenuWindow(_ window: NSWindow?) -> Bool {
+ guard let window else { return false }
+ return levels.contains { $0.panel === window }
+ }
+
+ private func install(watching window: NSWindow) {
+ if let monitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown], handler: { [weak self] event in
+ guard let self else { return event }
+ return self.handleMouseDown(event)
+ }) {
+ monitors.append(monitor)
+ }
+ if let monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown], handler: { [weak self] event in
+ guard let self else { return event }
+ return self.handleKeyDown(event)
+ }) {
+ monitors.append(monitor)
+ }
+ if let monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel], handler: { [weak self] event in
+ guard let self else { return event }
+ if !self.isMenuWindow(event.window) {
+ self.closeAll()
+ }
+ return event
+ }) {
+ monitors.append(monitor)
+ }
+ if let monitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown], handler: { [weak self] _ in
+ MainActor.assumeIsolated {
+ self?.closeAll()
+ }
+ }) {
+ monitors.append(monitor)
+ }
+ let center = NotificationCenter.default
+ let closeAll: @Sendable (Notification) -> Void = { [weak self] _ in
+ MainActor.assumeIsolated {
+ self?.closeAll()
+ }
+ }
+ observers.append(center.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main, using: closeAll))
+ for name in [NSWindow.didResignKeyNotification, NSWindow.didMoveNotification, NSWindow.didResizeNotification, NSWindow.willCloseNotification] {
+ observers.append(center.addObserver(forName: name, object: window, queue: .main, using: closeAll))
+ }
+ }
+
+ private func uninstall() {
+ monitors.forEach(NSEvent.removeMonitor)
+ monitors.removeAll()
+ observers.forEach(NotificationCenter.default.removeObserver)
+ observers.removeAll()
+ }
+
+ /// A click in a menu goes to its row. A click anywhere else only closes the menus, as it does for a menu.
+ private func handleMouseDown(_ event: NSEvent) -> NSEvent? {
+ if isMenuWindow(event.window) {
+ return event
+ }
+ closeAll()
+ return nil
+ }
+
+ private func handleKeyDown(_ event: NSEvent) -> NSEvent? {
+ guard let top = levels.last else { return event }
+ // The keys take over from the pointer until it moves again.
+ for level in levels {
+ level.navigator.pointerRests()
+ }
+ let navigator = top.navigator
+ switch event.keyCode {
+ case Key.escape:
+ top.close(notify: true)
+ case Key.down:
+ navigator.move(1)
+ case Key.up:
+ navigator.move(-1)
+ case Key.tab:
+ navigator.move(event.modifierFlags.contains(.shift) ? -1 : 1)
+ case Key.returnKey, Key.enter:
+ if !navigator.activateHighlighted() {
+ closeAll()
+ }
+ case Key.right:
+ navigator.openHighlightedSubmenu()
+ case Key.left:
+ if levels.count > 1 {
+ top.close(notify: true)
+ }
+ default:
+ // Typing or a shortcut closes the menus and goes on, so the composer gets the keys.
+ closeAll()
+ return event
+ }
+ return nil
+ }
+}
+#endif
diff --git a/apple/Apps/Shared/MorphInlineHTMLView.swift b/apple/Apps/Shared/MorphInlineHTMLView.swift
new file mode 100644
index 000000000..9ed4b0488
--- /dev/null
+++ b/apple/Apps/Shared/MorphInlineHTMLView.swift
@@ -0,0 +1,533 @@
+import SwiftUI
+import WebKit
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+// MARK: - Inline HTML / Chart / Diagram Card
+
+/// Sandboxed inline HTML renderer for charts, diagrams, mockups, and `html_preview` turn blocks.
+/// Injects Anymorph monochrome `:root` CSS variables matching the active Light/Dark appearance,
+/// disables navigation hijacking, measures content height cleanly (80–1200 pt), and offers a fullscreen/sheet toggle.
+public struct MorphInlineHTMLCardView: View {
+ public let html: String
+ public let title: String?
+ public let requestedHeight: CGFloat?
+
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.openURL) private var openURL
+ @State private var measuredHeight: CGFloat
+ @State private var isExpanded = false
+ @State private var reloadNonce = 0
+
+ private static let minHeight: CGFloat = 80
+ private static let maxHeight: CGFloat = 1200
+
+ public init(html: String, title: String? = nil, requestedHeight: CGFloat? = nil) {
+ self.html = html
+ self.title = title
+ self.requestedHeight = requestedHeight
+ let initial = requestedHeight.map { Self.clampHeight($0) } ?? 280
+ _measuredHeight = State(initialValue: initial)
+ }
+
+ private static func clampHeight(_ value: CGFloat) -> CGFloat {
+ min(maxHeight, max(minHeight, value))
+ }
+
+ private var displayTitle: String {
+ let trimmed = (title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? "시각화 미리보기" : trimmed
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ headerBar
+ AnymorphDivider()
+ MorphRenderedHTMLWebView(
+ html: html,
+ isDark: colorScheme == .dark,
+ scrollEnabled: false,
+ reloadNonce: reloadNonce,
+ onHeightChange: { next in
+ let clamped = Self.clampHeight(next)
+ if abs(clamped - measuredHeight) > 2 {
+ measuredHeight = clamped
+ }
+ },
+ onExternalLink: { url in
+ openURL(url)
+ }
+ )
+ .frame(maxWidth: .infinity)
+ .frame(height: measuredHeight)
+ .background(AnymorphColor.bgBase)
+ }
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.xxxl, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ .sheet(isPresented: $isExpanded) {
+ MorphInlineHTMLExpandedSheet(
+ html: html,
+ title: displayTitle,
+ isDark: colorScheme == .dark
+ )
+ }
+ }
+
+ private var headerBar: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "rectangle.3.group")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ Text(displayTitle)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ Spacer(minLength: 4)
+ Button {
+ reloadNonce &+= 1
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgTertiary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help("다시 불러오기")
+
+ Button {
+ isExpanded = true
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "arrow.up.left.and.arrow.down.right")
+ .font(.system(size: 10, weight: .medium))
+ Text("크게 보기")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgSecondary)
+ }
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ .help("전체 화면으로 보기")
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 7)
+ .background(AnymorphColor.bgGrouped)
+ }
+}
+
+/// Expanded modal sheet for inspecting an inline HTML visualization at full size with scrolling enabled.
+private struct MorphInlineHTMLExpandedSheet: View {
+ let html: String
+ let title: String
+ let isDark: Bool
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.openURL) private var openURL
+ @State private var reloadNonce = 0
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 10) {
+ Text(title)
+ .anymorphText(.subhead, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ Button {
+ reloadNonce &+= 1
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .md, appearance: .ghost, iconOnly: true)
+ .help("다시 불러오기")
+
+ Button("닫기") { dismiss() }
+ .morphPill(.primary)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .background(AnymorphColor.bgBase)
+
+ AnymorphDivider()
+
+ MorphRenderedHTMLWebView(
+ html: html,
+ isDark: isDark,
+ scrollEnabled: true,
+ reloadNonce: reloadNonce,
+ onExternalLink: { url in
+ openURL(url)
+ }
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+ }
+ #if os(macOS)
+ .frame(minWidth: 720, idealWidth: 920, minHeight: 540, idealHeight: 700)
+ #endif
+ .background(AnymorphColor.bgBase)
+ }
+}
+
+// MARK: - Sandboxed WKWebView Wrapper (macOS + iOS)
+
+/// Reusable sandboxed `WKWebView` that renders HTML or SVG with Anymorph monochrome `:root` CSS variables,
+/// disables navigation hijacking, and reports measured document height cleanly.
+struct MorphRenderedHTMLWebView: View {
+ let html: String
+ let isDark: Bool
+ var isSVG: Bool = false
+ var scrollEnabled: Bool = true
+ var reloadNonce: Int = 0
+ var onHeightChange: ((CGFloat) -> Void)? = nil
+ var onExternalLink: ((URL) -> Void)? = nil
+
+ var body: some View {
+ MorphRenderedHTMLRepresentable(
+ document: Self.buildDocument(html: html, isDark: isDark, isSVG: isSVG),
+ isDark: isDark,
+ scrollEnabled: scrollEnabled,
+ reloadNonce: reloadNonce,
+ onHeightChange: onHeightChange,
+ onExternalLink: onExternalLink
+ )
+ }
+
+ /// Injects Anymorph monochrome `:root` tokens and height measurement script into raw HTML or SVG.
+ static func buildDocument(html: String, isDark: Bool, isSVG: Bool) -> String {
+ let tokensCSS = anmorphThemeCSS(isDark: isDark)
+ let heightScript = heightMeasurementScript
+
+ if isSVG {
+ return """
+
+
+
+
+
+
+
+
+ \(html)
+
+
+
+ """
+ }
+
+ let trimmed = html.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lower = trimmed.lowercased()
+ let injection = ""
+ let scriptTag = ""
+
+ if lower.contains("", options: .caseInsensitive) {
+ doc.insert(contentsOf: "\n\(injection)\n", at: headClose.lowerBound)
+ } else if let headOpen = doc.range(of: "", options: .caseInsensitive) {
+ doc.insert(contentsOf: "\n\(injection)\n", at: headOpen.upperBound)
+ } else if let bodyOpen = doc.range(of: "\(injection)\n", at: bodyOpen.lowerBound)
+ } else {
+ doc = injection + "\n" + doc
+ }
+ if let bodyClose = doc.range(of: "", options: .caseInsensitive) {
+ doc.insert(contentsOf: "\n\(scriptTag)\n", at: bodyClose.lowerBound)
+ } else {
+ doc += "\n\(scriptTag)"
+ }
+ return doc
+ }
+
+ return """
+
+
+
+
+
+ \(injection)
+
+
+ \(trimmed)
+ \(scriptTag)
+
+
+ """
+ }
+
+ private static func anmorphThemeCSS(isDark: Bool) -> String {
+ if isDark {
+ return """
+ :root {
+ color-scheme: dark;
+ --background: #000000;
+ --foreground: #FAFAFA;
+ --muted: #161616;
+ --muted-foreground: rgba(250, 250, 250, 0.56);
+ --card: #0F0F0F;
+ --card-foreground: #FAFAFA;
+ --popover: #161616;
+ --popover-foreground: #FAFAFA;
+ --secondary: #262626;
+ --secondary-foreground: #FAFAFA;
+ --border: rgba(164, 164, 164, 0.15);
+ --ring: rgba(250, 250, 250, 0.72);
+ --primary: #FAFAFA;
+ --primary-foreground: #161616;
+ --accent: #1C1C1C;
+ --accent-foreground: #FAFAFA;
+ --chart-1: #FAFAFA;
+ --chart-2: #BDBDBD;
+ --chart-3: #8E8E8E;
+ --chart-4: #666666;
+ --chart-5: #474747;
+ --chart-6: #D9D9D9;
+ --radius: 10px;
+ --font-sans: -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', sans-serif;
+ --font-mono: ui-monospace, 'SF Mono', Menlo, monospace;
+ }
+ html, body {
+ margin: 0;
+ padding: 12px;
+ height: auto !important;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: var(--font-sans);
+ font-size: 14px;
+ line-height: 1.5;
+ -webkit-font-smoothing: antialiased;
+ box-sizing: border-box;
+ }
+ *, *::before, *::after { box-sizing: inherit; }
+ """
+ } else {
+ return """
+ :root {
+ color-scheme: light;
+ --background: #FFFFFF;
+ --foreground: #161616;
+ --muted: #F2F2F2;
+ --muted-foreground: rgba(22, 22, 22, 0.56);
+ --card: #FFFFFF;
+ --card-foreground: #161616;
+ --popover: #FFFFFF;
+ --popover-foreground: #161616;
+ --secondary: #E7E7E7;
+ --secondary-foreground: #161616;
+ --border: rgba(164, 164, 164, 0.20);
+ --ring: rgba(22, 22, 22, 0.72);
+ --primary: #161616;
+ --primary-foreground: #FAFAFA;
+ --accent: #EDEDED;
+ --accent-foreground: #161616;
+ --chart-1: #161616;
+ --chart-2: #4A4A4A;
+ --chart-3: #737373;
+ --chart-4: #9E9E9E;
+ --chart-5: #C7C7C7;
+ --chart-6: #333333;
+ --radius: 10px;
+ --font-sans: -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', sans-serif;
+ --font-mono: ui-monospace, 'SF Mono', Menlo, monospace;
+ }
+ html, body {
+ margin: 0;
+ padding: 12px;
+ height: auto !important;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: var(--font-sans);
+ font-size: 14px;
+ line-height: 1.5;
+ -webkit-font-smoothing: antialiased;
+ box-sizing: border-box;
+ }
+ *, *::before, *::after { box-sizing: inherit; }
+ """
+ }
+ }
+
+ private static let heightMeasurementScript = #"""
+ (function () {
+ var handler = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.morphInlineHeight;
+ if (!handler) { return; }
+ var last = 0;
+ function report() {
+ try {
+ var body = document.body;
+ if (!body) { return; }
+ var rectH = body.getBoundingClientRect ? body.getBoundingClientRect().height : 0;
+ var h = Math.ceil(Math.max(rectH, body.scrollHeight, body.offsetHeight));
+ if (h > 0 && Math.abs(h - last) > 1) {
+ last = h;
+ handler.postMessage({ height: h });
+ }
+ } catch (e) {}
+ }
+ window.addEventListener('load', report);
+ setTimeout(report, 60);
+ setTimeout(report, 260);
+ if (window.ResizeObserver && document.body) {
+ new ResizeObserver(report).observe(document.body);
+ }
+ })();
+ """#
+}
+
+#if os(macOS)
+private struct MorphRenderedHTMLRepresentable: NSViewRepresentable {
+ let document: String
+ let isDark: Bool
+ let scrollEnabled: Bool
+ let reloadNonce: Int
+ let onHeightChange: ((CGFloat) -> Void)?
+ let onExternalLink: ((URL) -> Void)?
+
+ func makeCoordinator() -> MorphInlineHTMLCoordinator {
+ MorphInlineHTMLCoordinator(onHeightChange: onHeightChange, onExternalLink: onExternalLink)
+ }
+
+ func makeNSView(context: Context) -> WKWebView {
+ let controller = WKUserContentController()
+ controller.add(MorphInlineHTMLWeakHandler(target: context.coordinator), name: "morphInlineHeight")
+ let config = WKWebViewConfiguration()
+ config.websiteDataStore = .nonPersistent()
+ config.userContentController = controller
+ let webView = WKWebView(frame: .zero, configuration: config)
+ webView.navigationDelegate = context.coordinator
+ webView.setValue(false, forKey: "drawsBackground")
+ context.coordinator.loadIfNeeded(webView: webView, document: document, reloadNonce: reloadNonce)
+ return webView
+ }
+
+ func updateNSView(_ nsView: WKWebView, context: Context) {
+ context.coordinator.onHeightChange = onHeightChange
+ context.coordinator.onExternalLink = onExternalLink
+ context.coordinator.loadIfNeeded(webView: nsView, document: document, reloadNonce: reloadNonce)
+ }
+
+ static func dismantleNSView(_ nsView: WKWebView, coordinator: MorphInlineHTMLCoordinator) {
+ nsView.configuration.userContentController.removeScriptMessageHandler(forName: "morphInlineHeight")
+ nsView.navigationDelegate = nil
+ }
+}
+#else
+private struct MorphRenderedHTMLRepresentable: UIViewRepresentable {
+ let document: String
+ let isDark: Bool
+ let scrollEnabled: Bool
+ let reloadNonce: Int
+ let onHeightChange: ((CGFloat) -> Void)?
+ let onExternalLink: ((URL) -> Void)?
+
+ func makeCoordinator() -> MorphInlineHTMLCoordinator {
+ MorphInlineHTMLCoordinator(onHeightChange: onHeightChange, onExternalLink: onExternalLink)
+ }
+
+ func makeUIView(context: Context) -> WKWebView {
+ let controller = WKUserContentController()
+ controller.add(MorphInlineHTMLWeakHandler(target: context.coordinator), name: "morphInlineHeight")
+ let config = WKWebViewConfiguration()
+ config.websiteDataStore = .nonPersistent()
+ config.userContentController = controller
+ let webView = WKWebView(frame: .zero, configuration: config)
+ webView.navigationDelegate = context.coordinator
+ webView.isOpaque = false
+ webView.backgroundColor = .clear
+ webView.scrollView.backgroundColor = .clear
+ webView.scrollView.isScrollEnabled = scrollEnabled
+ context.coordinator.loadIfNeeded(webView: webView, document: document, reloadNonce: reloadNonce)
+ return webView
+ }
+
+ func updateUIView(_ uiView: WKWebView, context: Context) {
+ context.coordinator.onHeightChange = onHeightChange
+ context.coordinator.onExternalLink = onExternalLink
+ uiView.scrollView.isScrollEnabled = scrollEnabled
+ context.coordinator.loadIfNeeded(webView: uiView, document: document, reloadNonce: reloadNonce)
+ }
+
+ static func dismantleUIView(_ uiView: WKWebView, coordinator: MorphInlineHTMLCoordinator) {
+ uiView.configuration.userContentController.removeScriptMessageHandler(forName: "morphInlineHeight")
+ uiView.navigationDelegate = nil
+ }
+}
+#endif
+
+@MainActor
+private final class MorphInlineHTMLCoordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
+ var onHeightChange: ((CGFloat) -> Void)?
+ var onExternalLink: ((URL) -> Void)?
+ private var lastKey: String?
+
+ init(onHeightChange: ((CGFloat) -> Void)?, onExternalLink: ((URL) -> Void)?) {
+ self.onHeightChange = onHeightChange
+ self.onExternalLink = onExternalLink
+ }
+
+ func loadIfNeeded(webView: WKWebView, document: String, reloadNonce: Int) {
+ let key = "\(reloadNonce):\(document.hashValue):\(document.utf8.count)"
+ guard lastKey != key else { return }
+ lastKey = key
+ webView.loadHTMLString(document, baseURL: nil)
+ }
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard let body = message.body as? [String: Any],
+ let num = body["height"] as? NSNumber else { return }
+ onHeightChange?(CGFloat(num.doubleValue))
+ }
+
+ func webView(
+ _ webView: WKWebView,
+ decidePolicyFor navigationAction: WKNavigationAction,
+ decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void
+ ) {
+ if navigationAction.navigationType == .other,
+ navigationAction.request.url?.absoluteString == "about:blank" {
+ decisionHandler(.allow)
+ return
+ }
+ if navigationAction.navigationType == .linkActivated,
+ let url = navigationAction.request.url,
+ let scheme = url.scheme?.lowercased(),
+ scheme == "http" || scheme == "https" {
+ onExternalLink?(url)
+ }
+ decisionHandler(.cancel)
+ }
+}
+
+@MainActor
+private final class MorphInlineHTMLWeakHandler: NSObject, WKScriptMessageHandler {
+ weak var target: WKScriptMessageHandler?
+
+ init(target: WKScriptMessageHandler) {
+ self.target = target
+ }
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ target?.userContentController(userContentController, didReceive: message)
+ }
+}
diff --git a/apple/Apps/Shared/MorphNotifications.swift b/apple/Apps/Shared/MorphNotifications.swift
new file mode 100644
index 000000000..fcc0d323f
--- /dev/null
+++ b/apple/Apps/Shared/MorphNotifications.swift
@@ -0,0 +1,107 @@
+import Foundation
+import UserNotifications
+import AppKit
+import MorphCore
+
+/// Desktop notifications for Morph Code: turn completed, turn failed, or pending approval/question.
+/// Runs safely as a no-op outside a signed `.app` bundle (unit tests, `swift run`).
+@MainActor
+final class MorphNotificationManager: NSObject, UNUserNotificationCenterDelegate {
+ static let shared = MorphNotificationManager()
+
+ private weak var state: MorphAppState?
+ private var isConfigured = false
+ private var hasRequestedAuthorization = false
+
+ private var canUseNotificationCenter: Bool {
+ guard let identifier = Bundle.main.bundleIdentifier, !identifier.isEmpty else { return false }
+ return Bundle.main.bundleURL.pathExtension == "app"
+ }
+
+ private override init() {
+ super.init()
+ }
+
+ func configure(state: MorphAppState) {
+ self.state = state
+ state.codeOnNotificationEvent = { [weak self, weak state] event in
+ guard let self, let state else { return }
+ MainActor.assumeIsolated {
+ self.deliver(event, state: state)
+ }
+ }
+ guard !isConfigured else { return }
+ isConfigured = true
+ guard canUseNotificationCenter else { return }
+ UNUserNotificationCenter.current().delegate = self
+ requestAuthorizationIfNeeded()
+ }
+
+ func requestAuthorizationIfNeeded() {
+ guard canUseNotificationCenter, !hasRequestedAuthorization else { return }
+ hasRequestedAuthorization = true
+ Task {
+ _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
+ }
+ }
+
+ func deliver(_ event: CodeNotificationEvent, state: MorphAppState) {
+ guard state.isCodeNotificationEnabled(for: event.kind) else { return }
+ playSound(for: event.kind, state: state)
+ guard canUseNotificationCenter else { return }
+
+ let content = UNMutableNotificationContent()
+ content.title = MorphNotificationText.cleanInline(event.title, limit: 80)
+ if let rawSub = event.subtitle {
+ let cleanSub = MorphNotificationText.cleanInline(rawSub, limit: 80)
+ if !cleanSub.isEmpty {
+ content.subtitle = cleanSub
+ }
+ }
+ let cleanBody = MorphNotificationText.excerpt(event.body, limit: 160)
+ content.body = cleanBody.isEmpty ? "Thread updated." : cleanBody
+ content.userInfo = ["threadId": event.threadId]
+ content.threadIdentifier = "code-\(event.threadId)"
+ content.sound = nil
+
+ let request = UNNotificationRequest(
+ identifier: "morph-code-\(event.kind.rawValue)-\(event.threadId)-\(UUID().uuidString)",
+ content: content,
+ trigger: nil
+ )
+ Task {
+ try? await UNUserNotificationCenter.current().add(request)
+ }
+ }
+
+ private func playSound(for kind: CodeNotificationEvent.Kind, state: MorphAppState) {
+ guard state.codeNotificationSoundEnabled else { return }
+ let name: String = switch kind {
+ case .turnCompleted: "Glass"
+ case .turnFailed: "Basso"
+ case .approvalRequired, .questionRequired: "Ping"
+ }
+ NSSound(named: NSSound.Name(name))?.play()
+ }
+
+ nonisolated func userNotificationCenter(
+ _ center: UNUserNotificationCenter,
+ willPresent notification: UNNotification
+ ) async -> UNNotificationPresentationOptions {
+ [.banner, .list]
+ }
+
+ nonisolated func userNotificationCenter(
+ _ center: UNUserNotificationCenter,
+ didReceive response: UNNotificationResponse
+ ) async {
+ let threadId = response.notification.request.content.userInfo["threadId"] as? String
+ await MainActor.run {
+ NSApp.activate(ignoringOtherApps: true)
+ if let threadId, !threadId.isEmpty, let state = self.state,
+ let thread = state.codeThreads.first(where: { $0.id == threadId }) {
+ Task { await state.selectCodeThread(thread) }
+ }
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphPreview.swift b/apple/Apps/Shared/MorphPreview.swift
new file mode 100644
index 000000000..87023c2ee
--- /dev/null
+++ b/apple/Apps/Shared/MorphPreview.swift
@@ -0,0 +1,1314 @@
+import SwiftUI
+import UniformTypeIdentifiers
+import ImageIO
+import PDFKit
+import QuickLook
+#if os(macOS)
+import AppKit
+import QuickLookUI
+#else
+import UIKit
+#endif
+import MorphCore
+
+// MARK: - Opening images and files
+//
+// An image or a file the member opens from a conversation, a Space document, the files tree, or the composer.
+// MorphFileReader renders PDFs (PDFKit), images, HTML/SVG (sandboxed WKWebView), Markdown, syntax-highlighted code,
+// and Quick Look documents (Office, iWork, media) natively inside the sheet, with Finder / Open in External App on
+// macOS and Share on iOS.
+
+/// A file the work produced, as the conversation or the files pane knows it.
+struct MorphFileItem: Identifiable, Equatable {
+ let id: String
+ let name: String
+ let path: String?
+ let mimeType: String?
+ /// Text already in hand: the conversation block's content or the files pane's preview.
+ let text: String?
+ /// Where the whole file loads from; nil when `text` or `data` is already the whole file.
+ let source: String?
+ /// Bytes already in hand (for example, an attachment queued in the composer before send).
+ let data: Data?
+ /// Local filesystem URL when this Mac already has the file on disk (for Finder, Open, and zero-copy Quick Look).
+ let localURL: URL?
+
+ init(
+ id: String,
+ name: String,
+ path: String?,
+ mimeType: String?,
+ text: String?,
+ source: String?,
+ data: Data? = nil,
+ localURL: URL? = nil
+ ) {
+ self.id = id
+ self.name = name
+ self.path = path
+ self.mimeType = mimeType
+ self.text = text
+ self.source = source
+ self.data = data
+ self.localURL = localURL
+ }
+
+ var contentType: UTType? {
+ if let mimeType, let type = UTType(mimeType: mimeType) {
+ return type
+ }
+ let ext = ((path ?? name) as NSString).pathExtension
+ return ext.isEmpty ? nil : UTType(filenameExtension: ext)
+ }
+
+ var initialKind: MorphFileViewerKind {
+ MorphFileViewerSupport.classify(
+ name: name,
+ path: path,
+ mimeType: mimeType,
+ hasInlineText: text != nil
+ )
+ }
+
+ var isMarkdown: Bool { initialKind == .markdown }
+ var isHTML: Bool { initialKind == .html }
+ var isSVG: Bool { initialKind == .svg }
+
+ /// Artifacts that render directly in a sandboxed WKWebView by default (`.html`, `.htm`, `.svg`).
+ var isWebRenderable: Bool { isHTML || isSVG }
+
+ /// Text the reader draws. A file of unknown type counts as text when its text is already here.
+ var isText: Bool {
+ switch initialKind {
+ case .markdown, .html, .svg, .codeOrText:
+ return true
+ case .pdf, .image, .quickLook, .binary:
+ return false
+ }
+ }
+}
+
+/// Temporary file copies for Quick Look, external app launch, and iOS ShareLink.
+enum MorphPreviewFile {
+ private static var rootFolder: URL {
+ FileManager.default.temporaryDirectory.appendingPathComponent("MorphPreview", isDirectory: true)
+ }
+
+ static func write(_ data: Data, name: String, type: UTType?) -> URL? {
+ let folder = rootFolder
+ try? FileManager.default.removeItem(at: folder)
+ do {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let url = folder.appendingPathComponent(fileName(name, type: type))
+ try data.write(to: url)
+ return url
+ } catch {
+ return nil
+ }
+ }
+
+ /// Writes a per-preview temporary file into `MorphPreview//` so concurrent previews do not overwrite each other.
+ static func writeTemporary(_ data: Data, id: String, name: String, type: UTType?) -> URL? {
+ let safeId = id.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) ? Character($0) : "-" }
+ let token = String(safeId.prefix(48))
+ let folder = rootFolder.appendingPathComponent(token.isEmpty ? UUID().uuidString : token, isDirectory: true)
+ do {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let url = folder.appendingPathComponent(fileName(name, type: type))
+ try data.write(to: url, options: .atomic)
+ return url
+ } catch {
+ return nil
+ }
+ }
+
+ static func cleanupTemporary(_ url: URL?) {
+ guard let url else { return }
+ let rootPath = rootFolder.standardizedFileURL.path
+ let parent = url.deletingLastPathComponent().standardizedFileURL
+ guard parent.path.hasPrefix(rootPath + "/") else { return }
+ try? FileManager.default.removeItem(at: parent)
+ }
+
+ /// "주간 AI 언급률" as PNG → "주간 AI 언급률.png". A name whose extension already fits the type keeps it.
+ static func fileName(_ name: String, type: UTType?) -> String {
+ var base = name
+ .replacingOccurrences(of: "/", with: "-")
+ .replacingOccurrences(of: ":", with: "-")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if base.isEmpty {
+ base = "Morph"
+ }
+ base = String(base.prefix(80))
+ guard let type, let preferred = type.preferredFilenameExtension else {
+ return base
+ }
+ let current = (base as NSString).pathExtension
+ if !current.isEmpty, let currentType = UTType(filenameExtension: current), currentType.conforms(to: type) {
+ return base
+ }
+ return base + "." + preferred
+ }
+
+ /// The image's format from its bytes: PNG, JPEG, HEIC, GIF or WebP.
+ static func imageType(_ data: Data) -> UTType? {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),
+ let identifier = CGImageSourceGetType(source) else { return nil }
+ return UTType(identifier as String)
+ }
+
+ /// Reads image pixel dimensions without decoding the full bitmap when possible.
+ static func imagePixelSize(_ data: Data) -> (width: Int, height: Int)? {
+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),
+ let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let w = props[kCGImagePropertyPixelWidth] as? Int,
+ let h = props[kCGImagePropertyPixelHeight] as? Int,
+ w > 0, h > 0 else {
+ return nil
+ }
+ return (w, h)
+ }
+}
+
+extension View {
+ /// Opens a tapped image: Quick Look on iPhone and iPad, the full-window viewer of the nearest dialog host on a Mac.
+ func morphImagePreview(_ item: Binding) -> some View {
+ #if os(macOS)
+ modifier(MorphImagePreviewRequest(item: item))
+ #else
+ modifier(MorphImagePreview(item: item))
+ #endif
+ }
+
+ /// Opens any file in Morph's unified viewer sheet (PDF, image, Quick Look documents, Markdown, HTML/SVG, and code).
+ func morphFilePreview(
+ _ item: Binding,
+ load: @escaping (String) async -> Data?,
+ onError: @escaping (String) -> Void
+ ) -> some View {
+ modifier(MorphFilePreview(item: item, load: load, onError: onError))
+ }
+}
+
+#if os(iOS)
+private struct MorphImagePreview: ViewModifier {
+ @Binding var item: MorphLightboxImageItem?
+ @State private var fileURL: URL?
+
+ func body(content: Content) -> some View {
+ content
+ .quickLookPreview($fileURL)
+ .onChange(of: item) { _, opened in
+ guard let opened else { return }
+ // Quick Look owns the preview from here; the next tap is a new item.
+ item = nil
+ fileURL = MorphPreviewFile.write(opened.data, name: opened.title, type: MorphPreviewFile.imageType(opened.data))
+ }
+ }
+}
+#endif
+
+private struct MorphFilePreview: ViewModifier {
+ @Binding var item: MorphFileItem?
+ let load: (String) async -> Data?
+ let onError: (String) -> Void
+ @State private var reading: MorphFileItem?
+
+ func body(content: Content) -> some View {
+ content
+ .sheet(item: $reading) { file in
+ MorphFileReader(file: file, load: load)
+ }
+ .onChange(of: item) { _, opened in
+ guard let opened else { return }
+ item = nil
+ reading = opened
+ }
+ }
+}
+
+// MARK: - Native PDF & Quick Look Views
+
+private struct MorphPDFPageInfo: Equatable {
+ let current: Int
+ let total: Int
+}
+
+private struct MorphPDFZoomCommand: Equatable {
+ enum Action: Equatable {
+ case zoomIn
+ case zoomOut
+ case fit
+ }
+ let id = UUID()
+ let action: Action
+}
+
+#if os(macOS)
+private struct MorphPDFRepresentableView: NSViewRepresentable {
+ let data: Data
+ let zoomCommand: MorphPDFZoomCommand?
+ @Binding var pageInfo: MorphPDFPageInfo?
+
+ @MainActor
+ final class Coordinator: NSObject {
+ var loadedData: Data?
+ var lastZoomId: UUID?
+ nonisolated(unsafe) var observer: NSObjectProtocol?
+ weak var pdfView: PDFView?
+ var onPageChange: ((MorphPDFPageInfo?) -> Void)?
+
+ func attachObserver(to view: PDFView) {
+ if let observer {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ pdfView = view
+ observer = NotificationCenter.default.addObserver(
+ forName: .PDFViewPageChanged,
+ object: view,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.publishPageInfo()
+ }
+ }
+ }
+
+ func publishPageInfo() {
+ guard let view = pdfView, let doc = view.document, doc.pageCount > 0 else {
+ onPageChange?(nil)
+ return
+ }
+ let current: Int
+ if let page = view.currentPage {
+ current = doc.index(for: page) + 1
+ } else {
+ current = 1
+ }
+ onPageChange?(MorphPDFPageInfo(current: current, total: doc.pageCount))
+ }
+
+ deinit {
+ if let observer {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ }
+ }
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator()
+ }
+
+ func makeNSView(context: Context) -> PDFView {
+ let view = PDFView()
+ view.autoScales = true
+ view.displayMode = .singlePageContinuous
+ view.displaysPageBreaks = true
+ view.displaysAsBook = false
+ view.backgroundColor = .clear
+ context.coordinator.onPageChange = { info in
+ if pageInfo != info {
+ pageInfo = info
+ }
+ }
+ context.coordinator.attachObserver(to: view)
+ return view
+ }
+
+ func updateNSView(_ nsView: PDFView, context: Context) {
+ context.coordinator.onPageChange = { info in
+ if pageInfo != info {
+ pageInfo = info
+ }
+ }
+ if context.coordinator.loadedData != data {
+ context.coordinator.loadedData = data
+ nsView.document = PDFDocument(data: data)
+ nsView.autoScales = true
+ Task { @MainActor in
+ context.coordinator.publishPageInfo()
+ }
+ }
+ if let cmd = zoomCommand, cmd.id != context.coordinator.lastZoomId {
+ context.coordinator.lastZoomId = cmd.id
+ switch cmd.action {
+ case .zoomIn:
+ nsView.autoScales = false
+ nsView.zoomIn(nil)
+ case .zoomOut:
+ nsView.autoScales = false
+ nsView.zoomOut(nil)
+ case .fit:
+ nsView.autoScales = true
+ }
+ }
+ }
+}
+
+private struct MorphQuickLookRepresentableView: NSViewRepresentable {
+ let url: URL
+
+ final class Coordinator {
+ var currentURL: URL?
+ }
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator()
+ }
+
+ func makeNSView(context: Context) -> QLPreviewView {
+ let view = QLPreviewView(frame: .zero, style: .normal) ?? QLPreviewView()
+ view.autostarts = true
+ view.shouldCloseWithWindow = false
+ context.coordinator.currentURL = url
+ view.previewItem = url as NSURL
+ return view
+ }
+
+ func updateNSView(_ nsView: QLPreviewView, context: Context) {
+ guard context.coordinator.currentURL != url else { return }
+ context.coordinator.currentURL = url
+ nsView.previewItem = url as NSURL
+ }
+
+ static func dismantleNSView(_ nsView: QLPreviewView, coordinator: Coordinator) {
+ nsView.previewItem = nil
+ coordinator.currentURL = nil
+ }
+}
+#else
+private struct MorphPDFRepresentableView: UIViewRepresentable {
+ let data: Data
+ @Binding var pageInfo: MorphPDFPageInfo?
+
+ @MainActor
+ final class Coordinator: NSObject {
+ var loadedData: Data?
+ nonisolated(unsafe) var observer: NSObjectProtocol?
+ weak var pdfView: PDFView?
+ var onPageChange: ((MorphPDFPageInfo?) -> Void)?
+
+ func attachObserver(to view: PDFView) {
+ if let observer {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ pdfView = view
+ observer = NotificationCenter.default.addObserver(
+ forName: .PDFViewPageChanged,
+ object: view,
+ queue: .main
+ ) { [weak self] _ in
+ Task { @MainActor [weak self] in
+ self?.publishPageInfo()
+ }
+ }
+ }
+
+ func publishPageInfo() {
+ guard let view = pdfView, let doc = view.document, doc.pageCount > 0 else {
+ onPageChange?(nil)
+ return
+ }
+ let current: Int
+ if let page = view.currentPage {
+ current = doc.index(for: page) + 1
+ } else {
+ current = 1
+ }
+ onPageChange?(MorphPDFPageInfo(current: current, total: doc.pageCount))
+ }
+
+ deinit {
+ if let observer {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ }
+ }
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator()
+ }
+
+ func makeUIView(context: Context) -> PDFView {
+ let view = PDFView()
+ view.autoScales = true
+ view.displayMode = .singlePageContinuous
+ view.displaysPageBreaks = true
+ view.backgroundColor = .clear
+ context.coordinator.onPageChange = { info in
+ if pageInfo != info {
+ pageInfo = info
+ }
+ }
+ context.coordinator.attachObserver(to: view)
+ return view
+ }
+
+ func updateUIView(_ uiView: PDFView, context: Context) {
+ context.coordinator.onPageChange = { info in
+ if pageInfo != info {
+ pageInfo = info
+ }
+ }
+ if context.coordinator.loadedData != data {
+ context.coordinator.loadedData = data
+ uiView.document = PDFDocument(data: data)
+ uiView.autoScales = true
+ Task { @MainActor in
+ context.coordinator.publishPageInfo()
+ }
+ }
+ }
+}
+
+private struct MorphQuickLookRepresentableView: UIViewControllerRepresentable {
+ let url: URL
+
+ final class Coordinator: NSObject, QLPreviewControllerDataSource {
+ var url: URL
+
+ init(url: URL) {
+ self.url = url
+ }
+
+ func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
+ 1
+ }
+
+ func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> any QLPreviewItem {
+ url as NSURL
+ }
+ }
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(url: url)
+ }
+
+ func makeUIViewController(context: Context) -> QLPreviewController {
+ let controller = QLPreviewController()
+ controller.dataSource = context.coordinator
+ return controller
+ }
+
+ func updateUIViewController(_ uiViewController: QLPreviewController, context: Context) {
+ if context.coordinator.url != url {
+ context.coordinator.url = url
+ uiViewController.reloadData()
+ }
+ }
+}
+#endif
+
+// MARK: - Universal Reader
+
+/// Universal viewer for files opened from conversations, agent steps, artifacts, the files tree, or the composer.
+/// Renders PDFs, images, Quick Look documents, HTML/SVG, Markdown, and syntax-highlighted code, with graceful
+/// metadata fallback and Finder / external-app / Share actions for any binary format.
+struct MorphFileReader: View {
+ private enum WebViewMode: String, CaseIterable, Identifiable, Hashable {
+ case preview
+ case source
+
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .preview: return "미리보기"
+ case .source: return "소스"
+ }
+ }
+ }
+
+ let file: MorphFileItem
+ let load: (String) async -> Data?
+ /// The 1-based line to open at, as a `path:line` link names it.
+ let initialLine: Int?
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.openURL) private var openURL
+
+ @State private var resolvedKind: MorphFileViewerKind
+ @State private var loadedFileId: String?
+ @State private var loadedData: Data?
+ @State private var text: String?
+ @State private var tempFileURL: URL?
+ @State private var isLoading = false
+ @State private var loadFailed = false
+ @State private var retryCount = 0
+ @State private var previewImage: MorphLightboxImageItem?
+ /// The text's lines, colored off the main thread once the text is here.
+ @State private var highlightedLines: [[SyntaxToken]]?
+ @State private var wraps = false
+ @State private var copied = false
+ @State private var webViewMode: WebViewMode = .preview
+ @State private var pdfPageInfo: MorphPDFPageInfo?
+ @State private var pdfZoomCommand: MorphPDFZoomCommand?
+ @State private var imageScale: CGFloat = 1.0
+ @State private var imagePixelSize: (width: Int, height: Int)?
+
+ init(file: MorphFileItem, load: @escaping (String) async -> Data?, initialLine: Int? = nil) {
+ self.file = file
+ self.load = load
+ self.initialLine = initialLine
+ _resolvedKind = State(initialValue: file.initialKind)
+ _loadedData = State(initialValue: file.data)
+ _text = State(initialValue: file.text)
+ _webViewMode = State(initialValue: initialLine != nil ? .source : .preview)
+ }
+
+ var body: some View {
+ chrome
+ .background(AnymorphColor.bgBase)
+ .morphImagePreview($previewImage)
+ // The reader is a sheet on its own window on a Mac: its images open over the sheet.
+ .morphDialogHost()
+ .task(id: "\(file.id)#\(retryCount)") {
+ await loadFile()
+ }
+ .task(id: "\(text?.hashValue ?? 0)|\(webViewMode.rawValue)|\(resolvedKind.rawValue)") {
+ guard let text, showsCode else {
+ if resolvedKind == .markdown { highlightedLines = nil }
+ return
+ }
+ let language = MorphSyntaxHighlighter.detectLanguage(hint: nil, filePath: file.path ?? file.name)
+ highlightedLines = await Task.detached(priority: .userInitiated) {
+ MorphSyntaxHighlighter.tokenize(text, language: language)
+ }.value
+ }
+ .onDisappear {
+ MorphPreviewFile.cleanupTemporary(tempFileURL)
+ tempFileURL = nil
+ }
+ }
+
+ @MainActor
+ private func loadFile() async {
+ if loadedFileId != file.id {
+ MorphPreviewFile.cleanupTemporary(tempFileURL)
+ tempFileURL = nil
+ loadedFileId = file.id
+ resolvedKind = file.initialKind
+ loadedData = file.data
+ text = file.text
+ highlightedLines = nil
+ pdfPageInfo = nil
+ imagePixelSize = nil
+ loadFailed = false
+ }
+ isLoading = true
+ loadFailed = false
+ defer { isLoading = false }
+
+ let data: Data?
+ if let existing = file.data {
+ data = existing
+ } else if let source = file.source {
+ data = await load(source)
+ } else {
+ data = nil
+ }
+ guard !Task.isCancelled else { return }
+
+ guard let data else {
+ // If a local file exists on disk for Quick Look even when load returned nil, we can still show it.
+ if existingLocalURL != nil, resolvedKind == .quickLook {
+ loadFailed = false
+ } else {
+ loadFailed = (text == nil)
+ }
+ return
+ }
+
+ loadedData = data
+ let refined = MorphFileViewerSupport.refineKind(file.initialKind, data: data)
+ resolvedKind = refined
+
+ switch refined {
+ case .pdf:
+ #if os(iOS)
+ prepareTempFileIfNeeded(data: data, kind: refined)
+ #endif
+ case .image:
+ imagePixelSize = MorphPreviewFile.imagePixelSize(data)
+ #if os(iOS)
+ prepareTempFileIfNeeded(data: data, kind: refined)
+ #endif
+ case .quickLook:
+ if existingLocalURL == nil {
+ prepareTempFileIfNeeded(data: data, kind: refined)
+ }
+ case .markdown, .html, .svg, .codeOrText:
+ if let decoded = String(data: data, encoding: .utf8) {
+ text = decoded
+ } else {
+ resolvedKind = .binary
+ #if os(iOS)
+ prepareTempFileIfNeeded(data: data, kind: .binary)
+ #endif
+ }
+ case .binary:
+ #if os(iOS)
+ prepareTempFileIfNeeded(data: data, kind: refined)
+ #endif
+ }
+ }
+
+ private var existingLocalURL: URL? {
+ #if os(macOS)
+ guard let url = file.localURL, FileManager.default.fileExists(atPath: url.path) else {
+ return nil
+ }
+ return url
+ #else
+ return nil
+ #endif
+ }
+
+ @discardableResult
+ @MainActor
+ private func prepareTempFileIfNeeded(data: Data, kind: MorphFileViewerKind) -> URL? {
+ if let tempFileURL, FileManager.default.fileExists(atPath: tempFileURL.path) {
+ return tempFileURL
+ }
+ let type: UTType?
+ switch kind {
+ case .pdf:
+ type = .pdf
+ case .image:
+ type = MorphPreviewFile.imageType(data) ?? file.contentType
+ default:
+ type = file.contentType
+ }
+ let url = MorphPreviewFile.writeTemporary(data, id: file.id, name: file.name, type: type)
+ tempFileURL = url
+ return url
+ }
+
+ /// URL available for Quick Look, external app launch, or iOS ShareLink.
+ private var previewableFileURL: URL? {
+ existingLocalURL ?? tempFileURL
+ }
+
+ /// Code and plain text: the colored lines, or the plain lines until the colors are ready.
+ private var codeLines: [[SyntaxToken]] {
+ if let highlightedLines {
+ return highlightedLines
+ }
+ return (text ?? "").components(separatedBy: "\n").map { [SyntaxToken(text: $0, kind: .plain)] }
+ }
+
+ private var isWebRenderable: Bool {
+ resolvedKind == .html || resolvedKind == .svg
+ }
+
+ private var showsWebPreview: Bool {
+ text != nil && isWebRenderable && webViewMode == .preview
+ }
+
+ private var showsCode: Bool {
+ text != nil && (resolvedKind == .codeOrText || (isWebRenderable && webViewMode == .source))
+ }
+
+ private var showsPDF: Bool {
+ resolvedKind == .pdf && loadedData != nil
+ }
+
+ private var showsImage: Bool {
+ resolvedKind == .image && loadedData != nil
+ }
+
+ private var showsQuickLook: Bool {
+ resolvedKind == .quickLook && previewableFileURL != nil
+ }
+
+ private var showsBinaryFallback: Bool {
+ resolvedKind == .binary && (loadedData != nil || existingLocalURL != nil)
+ }
+
+ private var usesExpandedCanvasSize: Bool {
+ switch resolvedKind {
+ case .pdf, .image, .quickLook, .html, .svg:
+ return true
+ case .markdown, .codeOrText, .binary:
+ return false
+ }
+ }
+
+ private var metadataLabel: String? {
+ var parts: [String] = []
+ if let pdfPageInfo, resolvedKind == .pdf {
+ parts.append("\(pdfPageInfo.current) / \(pdfPageInfo.total)쪽")
+ }
+ if let dims = imagePixelSize, resolvedKind == .image {
+ parts.append("\(dims.width) × \(dims.height)")
+ }
+ if let data = loadedData {
+ parts.append(ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .file))
+ }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+
+ private var webPreviewArea: some View {
+ MorphRenderedHTMLWebView(
+ html: text ?? "",
+ isDark: colorScheme == .dark,
+ isSVG: resolvedKind == .svg,
+ scrollEnabled: true,
+ onExternalLink: { url in
+ openURL(url)
+ }
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ }
+
+ @ViewBuilder
+ private var pdfArea: some View {
+ if let data = loadedData {
+ #if os(macOS)
+ MorphPDFRepresentableView(data: data, zoomCommand: pdfZoomCommand, pageInfo: $pdfPageInfo)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgSubtle)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ #else
+ MorphPDFRepresentableView(data: data, pageInfo: $pdfPageInfo)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgSubtle)
+ #endif
+ }
+ }
+
+ @ViewBuilder
+ private var imageArea: some View {
+ if let data = loadedData {
+ #if os(macOS)
+ if let nsImage = NSImage(data: data) {
+ GeometryReader { proxy in
+ ScrollView([.horizontal, .vertical]) {
+ let baseWidth = max(120, proxy.size.width - 32)
+ let baseHeight = max(120, proxy.size.height - 32)
+ Image(nsImage: nsImage)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(
+ width: imageScale == 1.0 ? nil : min(nsImage.size.width * imageScale, 6000),
+ height: imageScale == 1.0 ? nil : min(nsImage.size.height * imageScale, 6000)
+ )
+ .frame(
+ maxWidth: imageScale == 1.0 ? baseWidth : nil,
+ maxHeight: imageScale == 1.0 ? baseHeight : nil
+ )
+ .padding(16)
+ .frame(minWidth: proxy.size.width, minHeight: proxy.size.height)
+ }
+ }
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ } else {
+ binaryFallbackArea
+ }
+ #else
+ if let uiImage = UIImage(data: data) {
+ GeometryReader { proxy in
+ ScrollView([.horizontal, .vertical]) {
+ Image(uiImage: uiImage)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .scaleEffect(imageScale)
+ .frame(maxWidth: max(120, proxy.size.width - 24), maxHeight: max(120, proxy.size.height - 24))
+ .padding(12)
+ .frame(minWidth: proxy.size.width, minHeight: proxy.size.height)
+ .onTapGesture(count: 2) {
+ withAnimation(AnymorphMotion.fast) {
+ imageScale = imageScale > 1.05 ? 1.0 : 2.0
+ }
+ }
+ }
+ }
+ .background(AnymorphColor.bgSubtle)
+ } else {
+ binaryFallbackArea
+ }
+ #endif
+ }
+ }
+
+ @ViewBuilder
+ private var quickLookArea: some View {
+ if let url = previewableFileURL {
+ #if os(macOS)
+ MorphQuickLookRepresentableView(url: url)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgSubtle)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ #else
+ MorphQuickLookRepresentableView(url: url)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ #endif
+ }
+ }
+
+ private var binaryFallbackArea: some View {
+ VStack(spacing: 14) {
+ Spacer()
+ MorphTileIcon("doc", size: 42)
+ VStack(spacing: 4) {
+ Text(file.name)
+ .anymorphText(.subhead, weight: .strong, color: AnymorphColor.fgPrimary)
+ .multilineTextAlignment(.center)
+ if let detail = metadataLabel ?? file.contentType?.localizedDescription {
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ Text("앱 안에서 직접 미리보기를 지원하지 않는 형식입니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .padding(.top, 4)
+ }
+ #if os(macOS)
+ HStack(spacing: 8) {
+ Button("외부 앱으로 열기") {
+ openInExternalApp()
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ if existingLocalURL != nil {
+ Button("Finder에서 보기") {
+ revealInFinder()
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+ }
+ .padding(.top, 4)
+ #else
+ if let shareURL = previewableFileURL {
+ ShareLink(item: shareURL) {
+ Label("다른 앱으로 열기 · 공유", systemImage: "square.and.arrow.up")
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .padding(.top, 4)
+ }
+ #endif
+ Spacer()
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .padding(24)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ }
+
+ #if os(macOS)
+ private func openInExternalApp() {
+ if let localURL = existingLocalURL {
+ NSWorkspace.shared.open(localURL)
+ return
+ }
+ let payload = loadedData ?? text.flatMap { $0.data(using: .utf8) }
+ guard let payload, let url = prepareTempFileIfNeeded(data: payload, kind: resolvedKind) else {
+ return
+ }
+ NSWorkspace.shared.open(url)
+ }
+
+ private func revealInFinder() {
+ guard let localURL = existingLocalURL else { return }
+ NSWorkspace.shared.activateFileViewerSelecting([localURL])
+ }
+
+ private var canOpenExternally: Bool {
+ existingLocalURL != nil || loadedData != nil || text != nil
+ }
+
+ private var chrome: some View {
+ VStack(alignment: .leading, spacing: 14) {
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 8) {
+ Text(file.name)
+ .anymorphText(.subhead, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if let meta = metadataLabel {
+ Text(meta)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ }
+ if let path = file.path {
+ Text(initialLine.map { "\(path):\($0)" } ?? path)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ }
+ Spacer(minLength: 8)
+ if showsPDF {
+ pdfZoomControls
+ } else if showsImage {
+ imageZoomControls
+ }
+ if isWebRenderable && text != nil {
+ AnymorphSegmentControl(
+ items: WebViewMode.allCases,
+ selection: $webViewMode,
+ label: { $0.title }
+ )
+ .fixedSize()
+ }
+ if showsCode {
+ wrapButton
+ .anymorphButton(size: .md, appearance: .ghost)
+ }
+ if text != nil {
+ copyButton
+ .anymorphButton(size: .md, appearance: .ghost)
+ }
+ if existingLocalURL != nil {
+ Button {
+ revealInFinder()
+ } label: {
+ Label("Finder", systemImage: "folder")
+ .labelStyle(.titleAndIcon)
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ .help("Finder에서 파일 위치 보기")
+ }
+ if canOpenExternally {
+ Button {
+ openInExternalApp()
+ } label: {
+ Label("열기", systemImage: "arrow.up.forward.square")
+ .labelStyle(.titleAndIcon)
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ .help("기본 앱으로 열기")
+ }
+ Button("닫기") { dismiss() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+ AnymorphDivider()
+ contentArea
+ }
+ .padding(20)
+ .frame(
+ minWidth: usesExpandedCanvasSize ? 760 : 640,
+ idealWidth: usesExpandedCanvasSize ? 940 : 780,
+ minHeight: usesExpandedCanvasSize ? 580 : 480,
+ idealHeight: usesExpandedCanvasSize ? 760 : 620
+ )
+ }
+
+ private var pdfZoomControls: some View {
+ HStack(spacing: 2) {
+ Button {
+ pdfZoomCommand = MorphPDFZoomCommand(action: .zoomOut)
+ } label: {
+ Image(systemName: "minus.magnifyingglass")
+ }
+ .anymorphButton(size: .md, appearance: .ghost, iconOnly: true)
+ .help("축소")
+
+ Button("맞춤") {
+ pdfZoomCommand = MorphPDFZoomCommand(action: .fit)
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ .help("창에 맞추기")
+
+ Button {
+ pdfZoomCommand = MorphPDFZoomCommand(action: .zoomIn)
+ } label: {
+ Image(systemName: "plus.magnifyingglass")
+ }
+ .anymorphButton(size: .md, appearance: .ghost, iconOnly: true)
+ .help("확대")
+ }
+ }
+
+ private var imageZoomControls: some View {
+ HStack(spacing: 2) {
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ imageScale = max(0.25, imageScale / 1.25)
+ }
+ } label: {
+ Image(systemName: "minus.magnifyingglass")
+ }
+ .anymorphButton(size: .md, appearance: .ghost, iconOnly: true)
+ .help("축소")
+
+ Button("맞춤") {
+ withAnimation(AnymorphMotion.fast) {
+ imageScale = 1.0
+ }
+ }
+ .anymorphButton(size: .md, appearance: .ghost)
+ .help("창에 맞추기")
+
+ Button {
+ withAnimation(AnymorphMotion.fast) {
+ imageScale = min(4.0, imageScale * 1.25)
+ }
+ } label: {
+ Image(systemName: "plus.magnifyingglass")
+ }
+ .anymorphButton(size: .md, appearance: .ghost, iconOnly: true)
+ .help("확대")
+ }
+ }
+ #else
+ private var chrome: some View {
+ NavigationStack {
+ VStack(spacing: 0) {
+ if isWebRenderable && text != nil {
+ HStack {
+ AnymorphSegmentControl(
+ items: WebViewMode.allCases,
+ selection: $webViewMode,
+ label: { $0.title }
+ )
+ .fixedSize()
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 18)
+ .padding(.vertical, 8)
+ AnymorphDivider()
+ } else if let meta = metadataLabel, showsPDF || showsImage {
+ HStack(spacing: 8) {
+ pathLabel
+ Spacer(minLength: 4)
+ Text(meta)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, tabular: true)
+ .lineLimit(1)
+ }
+ .padding(.horizontal, 18)
+ .padding(.vertical, 6)
+ AnymorphDivider()
+ }
+ contentArea
+ }
+ .navigationTitle(file.name)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ if let shareURL = previewableFileURL {
+ ToolbarItem(placement: .topBarLeading) {
+ ShareLink(item: shareURL, subject: Text(file.name)) {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .accessibilityLabel("공유")
+ }
+ } else if let text {
+ ToolbarItem(placement: .topBarLeading) {
+ ShareLink(item: text, subject: Text(file.name)) {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .accessibilityLabel("공유")
+ }
+ }
+ if showsCode {
+ ToolbarItemGroup(placement: .bottomBar) {
+ wrapButton
+ Spacer()
+ copyButton
+ }
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("완료") { dismiss() }
+ .font(AnymorphFonts.font(.body, weight: .emphasis))
+ }
+ }
+ }
+ .tint(AnymorphColor.fgPrimary)
+ .presentationDragIndicator(.visible)
+ }
+
+ @ViewBuilder
+ private var pathLabel: some View {
+ if let path = file.path, path != file.name {
+ Text(initialLine.map { "\(path):\($0)" } ?? path)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ }
+ #endif
+
+ @ViewBuilder
+ private var contentArea: some View {
+ if showsPDF {
+ pdfArea
+ } else if showsImage {
+ imageArea
+ } else if showsQuickLook {
+ quickLookArea
+ } else if showsBinaryFallback {
+ binaryFallbackArea
+ } else if showsWebPreview {
+ #if os(macOS)
+ webPreviewArea
+ #else
+ webPreviewArea.padding(12)
+ #endif
+ } else if showsCode {
+ #if os(macOS)
+ codeReader
+ #else
+ VStack(alignment: .leading, spacing: 8) {
+ pathLabel
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ codeReader
+ }
+ #endif
+ } else {
+ #if os(macOS)
+ ScrollView {
+ reading
+ }
+ #else
+ ScrollView {
+ VStack(alignment: .leading, spacing: 14) {
+ pathLabel
+ reading
+ }
+ .frame(maxWidth: 840, alignment: .leading)
+ .padding(.horizontal, 18)
+ .padding(.top, 12)
+ .padding(.bottom, 28)
+ .frame(maxWidth: .infinity)
+ }
+ #endif
+ }
+ }
+
+ private var wrapButton: some View {
+ Button {
+ wraps.toggle()
+ } label: {
+ Label("줄바꿈", systemImage: "text.word.spacing")
+ .labelStyle(.titleAndIcon)
+ .foregroundStyle(wraps ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary)
+ }
+ .accessibilityAddTraits(wraps ? .isSelected : [])
+ .help(wraps ? "줄바꿈 끄기" : "긴 줄 줄바꿈")
+ }
+
+ private var copyButton: some View {
+ Button {
+ guard let text else { return }
+ MorphClipboard.copy(text)
+ copied = true
+ Task {
+ try? await Task.sleep(for: .seconds(1.4))
+ copied = false
+ }
+ } label: {
+ Label(copied ? "복사됨" : "복사", systemImage: copied ? "checkmark" : "doc.on.doc")
+ .labelStyle(.titleAndIcon)
+ }
+ .help("파일 내용 복사")
+ }
+
+ /// Numbered, colored lines that scroll to `initialLine` once the whole file is in.
+ private var codeReader: some View {
+ let lines = codeLines
+ return GeometryReader { geometry in
+ ScrollViewReader { proxy in
+ ScrollView(wraps ? .vertical : [.vertical, .horizontal]) {
+ VStack(alignment: .leading, spacing: 10) {
+ MorphCodeLines(
+ lines: lines,
+ showsLineNumbers: true,
+ wraps: wraps,
+ highlightedLine: initialLine,
+ lazy: true,
+ minRowWidth: wraps ? nil : geometry.size.width
+ )
+ if loadFailed {
+ Text("미리보기만 표시합니다. 전체 파일을 불러오지 못했습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(.horizontal, 12)
+ }
+ }
+ .padding(.vertical, 8)
+ .frame(maxWidth: wraps ? .infinity : nil, alignment: .leading)
+ .textSelection(.enabled)
+ }
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgSubtle)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ .task(id: ScrollTarget(line: initialLine, lineCount: lines.count, colored: highlightedLines != nil)) {
+ guard let initialLine, initialLine <= lines.count else { return }
+ // Rows lay out on the next pass; scroll once they exist.
+ try? await Task.sleep(for: .milliseconds(60))
+ withAnimation(AnymorphMotion.base) {
+ proxy.scrollTo(initialLine, anchor: .center)
+ }
+ }
+ }
+ }
+ }
+
+ /// What the reader scrolls again for: the target line, and the file arriving or getting its colors.
+ private struct ScrollTarget: Equatable {
+ let line: Int?
+ let lineCount: Int
+ let colored: Bool
+ }
+
+ @ViewBuilder
+ private var reading: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if let text {
+ MorphMarkdownText(
+ text,
+ scale: .reading,
+ imageLoader: load,
+ onTapImage: { title, data in
+ previewImage = MorphLightboxImageItem(title: title, data: data)
+ }
+ )
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if loadFailed {
+ Text("미리보기만 표시합니다. 전체 파일을 불러오지 못했습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ } else if loadFailed {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("파일을 불러오지 못했습니다.")
+ .anymorphText(.callout, weight: .base, color: AnymorphColor.fgTertiary)
+ Button("다시 시도") {
+ retryCount += 1
+ }
+ .morphPill(.secondary, height: 28)
+ }
+ } else if isLoading || file.source != nil {
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("불러오는 중…")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphRootView.swift b/apple/Apps/Shared/MorphRootView.swift
new file mode 100644
index 000000000..4a2467f40
--- /dev/null
+++ b/apple/Apps/Shared/MorphRootView.swift
@@ -0,0 +1,493 @@
+import SwiftUI
+import MorphCore
+import AppKit
+
+/// Morph Code's main macOS window: resizable sidebar on the left, active thread / scheduled view in the center
+/// under a slim unified header, and the resizable inspector pane (Git Changes, Terminal, Web Preview) on the right.
+public struct MorphRootView: View {
+ @Bindable var state: MorphAppState
+ @State private var windowWidth: CGFloat = 0
+ @State private var isBridgeBannerDismissed = false
+
+ public init(state: MorphAppState) {
+ self.state = state
+ }
+
+ private var preferredScheme: ColorScheme? {
+ switch state.themeMode {
+ case .system: return nil
+ case .light: return .light
+ case .dark: return .dark
+ }
+ }
+
+ static let sidebarWidth: CGFloat = 272
+ static let mainMinWidth: CGFloat = 420
+ static let headerHeight: CGFloat = 40
+ /// Room the window's traffic lights take at the top left.
+ static let trafficLightsWidth: CGFloat = 72
+ static let codeSidebarDefaultWidth: CGFloat = 272
+ static let codeInspectorDefaultWidth: CGFloat = 380
+
+ private var sidebarWidth: CGFloat {
+ state.codeSidebarWidth
+ }
+
+ private var paneWidth: CGFloat {
+ state.codeInspectorWidth
+ }
+
+ private var macMinWidth: CGFloat {
+ let side = state.isSidebarVisible ? sidebarWidth : 0
+ let pane = state.isCodeInspectorPresented ? paneWidth : 0
+ return side + Self.mainMinWidth + pane
+ }
+
+ private var sidebarDragLimit: CGFloat {
+ guard windowWidth > 0 else { return 420 }
+ let pane = state.isCodeInspectorPresented ? paneWidth : 0
+ return max(220, min(420, windowWidth - Self.mainMinWidth - pane))
+ }
+
+ private var inspectorDragLimit: CGFloat {
+ guard windowWidth > 0 else { return 760 }
+ let side = state.isSidebarVisible ? sidebarWidth : 0
+ return max(320, min(760, windowWidth - Self.mainMinWidth - side))
+ }
+
+ public var body: some View {
+ macContent
+ .preferredColorScheme(preferredScheme)
+ .morphNotices(state)
+ .sheet(isPresented: $state.isCommandPalettePresented) {
+ CommandPaletteView(state: state)
+ .preferredColorScheme(preferredScheme)
+ }
+ .sheet(item: $state.codeScheduleDraft) { draft in
+ CodeScheduleEditorSheet(state: state, draft: draft)
+ .preferredColorScheme(preferredScheme)
+ }
+ .onOpenURL { url in
+ Task { await state.handleIncomingURL(url) }
+ }
+ .onAppear {
+ syncMacAppearance(state.themeMode)
+ state.startRealtimeSync()
+ MorphNotificationManager.shared.configure(state: state)
+ MorphNotificationManager.shared.requestAuthorizationIfNeeded()
+ }
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ if let threadId = state.selectedCodeThread?.id {
+ state.markCodeThreadReadIfViewing(threadId)
+ }
+ }
+ .onChange(of: state.themeMode) { _, mode in
+ syncMacAppearance(mode)
+ }
+ }
+
+ private var macContent: some View {
+ HStack(spacing: 0) {
+ if state.isSidebarVisible {
+ VStack(spacing: 0) {
+ sidebarBar
+ MorphCodeSidebarView(state: state)
+ }
+ .frame(width: sidebarWidth)
+ .background(AnymorphColor.bgSidebar)
+ .overlay(alignment: .trailing) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(width: 1)
+ }
+ .overlay(alignment: .trailing) {
+ MorphPaneResizeHandle(
+ width: $state.codeSidebarWidth,
+ range: 220...sidebarDragLimit,
+ defaultWidth: Self.codeSidebarDefaultWidth,
+ growsTowardTrailing: true,
+ accessibilityName: "Sidebar width"
+ )
+ .offset(x: MorphPaneResizeHandle.hitWidth / 2)
+ }
+ .zIndex(2)
+ }
+
+ VStack(spacing: 0) {
+ mainHeader
+ if state.isLocalBridgeOutdated, !isBridgeBannerDismissed {
+ bridgeOutdatedBanner
+ .transition(.move(edge: .top).combined(with: .opacity))
+ }
+ MorphCodeMainArea(state: state)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .frame(minWidth: Self.mainMinWidth, maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+
+ if state.isCodeInspectorPresented {
+ MorphCodeInspectorView(state: state)
+ .frame(width: paneWidth)
+ .overlay(alignment: .leading) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(width: 1)
+ }
+ .overlay(alignment: .leading) {
+ MorphPaneResizeHandle(
+ width: $state.codeInspectorWidth,
+ range: 320...inspectorDragLimit,
+ defaultWidth: Self.codeInspectorDefaultWidth,
+ growsTowardTrailing: false,
+ accessibilityName: "Inspector width"
+ )
+ .offset(x: -MorphPaneResizeHandle.hitWidth / 2)
+ }
+ .zIndex(1)
+ }
+ }
+ .ignoresSafeArea()
+ .onChange(of: state.codeDestination) { _, _ in
+ NSApp.keyWindow?.makeFirstResponder(nil)
+ }
+ .overlay {
+ settingsDialog
+ }
+ .animation(AnymorphMotion.base, value: state.isSettingsPresented)
+ .morphCodeThreadDialogs(state)
+ .morphDialogHost()
+ .frame(minWidth: macMinWidth, minHeight: 560)
+ .background(AnymorphColor.bgBase)
+ .onGeometryChange(for: CGFloat.self) { proxy in
+ proxy.size.width
+ } action: { width in
+ windowWidth = width
+ }
+ .animation(AnymorphMotion.base, value: isBridgeBannerDismissed)
+ }
+
+ private var bridgeOutdatedBanner: some View {
+ let current = state.localBridgeHealth?.version ?? state.localCodeDaemonVersion ?? "?"
+ return HStack(spacing: 10) {
+ Image(systemName: "exclamationmark.arrow.triangle.2.circlepath")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ Text("Local morphcode daemon is outdated (v\(current); recommended v\(MorphAppState.minimumSupportedDaemonVersion)+)")
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgPrimary, tabular: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 8)
+ Button("Open Harness Settings") {
+ state.openSettings(.harness)
+ }
+ .morphPill(.secondary, height: 24)
+ Button {
+ isBridgeBannerDismissed = true
+ } label: {
+ Image(systemName: "xmark")
+ }
+ .morphRound(diameter: 24)
+ .help("Dismiss")
+ .accessibilityLabel("Dismiss daemon version banner")
+ }
+ .padding(.leading, 14)
+ .padding(.trailing, 8)
+ .frame(height: 36)
+ .background(AnymorphColor.bgGrouped)
+ .overlay(alignment: .bottom) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(height: 1)
+ }
+ }
+
+ private var sidebarBar: some View {
+ HStack(spacing: 6) {
+ Color.clear.frame(width: Self.trafficLightsWidth - 8, height: 1)
+ HStack(spacing: 7) {
+ MorphAssistantMark(width: 18)
+ Text("Morph Code")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ }
+ .morphWindowTitlebar()
+ Spacer(minLength: 2)
+ sidebarToggle
+ }
+ .padding(.horizontal, 8)
+ .frame(height: Self.headerHeight)
+ .background {
+ Color.clear
+ .morphWindowTitlebar()
+ }
+ }
+
+ private var mainHeader: some View {
+ let showsLeadingWindowControls = !state.isSidebarVisible
+ return HStack(spacing: 6) {
+ if showsLeadingWindowControls {
+ Color.clear.frame(width: Self.trafficLightsWidth, height: 1)
+ sidebarToggle
+ }
+ identity
+ Spacer(minLength: 8)
+ MorphCodeInlineSyncIndicator(state: state)
+ if state.codeDestination == .threads, let thread = state.selectedCodeThread {
+ MorphCodeHeaderContextRing(state: state, thread: thread)
+ }
+ detailsToggle
+ }
+ .padding(.leading, showsLeadingWindowControls ? 4 : 12)
+ .padding(.trailing, 10)
+ .frame(height: Self.headerHeight)
+ .background {
+ AnymorphColor.bgBase
+ .morphWindowTitlebar()
+ }
+ .overlay(alignment: .bottom) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(height: 1)
+ }
+ }
+
+ @ViewBuilder
+ private var identity: some View {
+ let header = state.codeHeader
+ HStack(spacing: 2) {
+ Text(header.title)
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ .padding(.horizontal, 6)
+ .help(header.context)
+ .morphWindowTitlebar()
+ if state.codeDestination == .threads, let thread = state.selectedCodeThread {
+ if let pr = thread.primaryLinkedPR {
+ CodeLinkedPRBadge(pr: pr)
+ .padding(.trailing, 4)
+ }
+ MorphCodeThreadActionsMenu(state: state, thread: thread)
+ }
+ }
+ }
+
+ private var sidebarToggle: some View {
+ Button {
+ state.isSidebarVisible.toggle()
+ } label: {
+ Image(systemName: "sidebar.left")
+ }
+ .morphRound(diameter: 28)
+ .help(state.isSidebarVisible ? "Hide Sidebar (⌃⌘S)" : "Show Sidebar (⌃⌘S)")
+ .accessibilityLabel(state.isSidebarVisible ? "Hide Sidebar" : "Show Sidebar")
+ }
+
+ private var detailsToggle: some View {
+ let pending = state.pendingCodeApprovalCount
+ return Button {
+ state.isCodeInspectorPresented.toggle()
+ } label: {
+ Image(systemName: "sidebar.right")
+ }
+ .morphRound(diameter: 28)
+ .overlay(alignment: .topTrailing) {
+ if !state.isCodeInspectorPresented, pending > 0 {
+ MorphCountBadge(pending)
+ .offset(x: 4, y: -1)
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+ }
+ .help(state.isCodeInspectorPresented ? "Close Inspector (⌘J)" : "Open Inspector (⌘J)")
+ .accessibilityLabel(pending == 0 ? "Inspector" : "Inspector, \(pending) pending approvals")
+ }
+
+ @ViewBuilder
+ private var settingsDialog: some View {
+ if state.isSettingsPresented {
+ ZStack {
+ AnymorphColor.scrim
+ .ignoresSafeArea()
+ .onTapGesture { state.isSettingsPresented = false }
+ SettingsView(state: state)
+ .frame(maxWidth: 880, maxHeight: 640)
+ .background(AnymorphColor.bgBase)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.round, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ .shadow(color: Color.black.opacity(0.18), radius: 40, x: 0, y: 16)
+ .padding(.horizontal, 40)
+ .padding(.vertical, 44)
+ }
+ .transition(.opacity)
+ }
+ }
+
+ private func syncMacAppearance(_ mode: MorphThemeMode) {
+ switch mode {
+ case .system: NSApp.appearance = nil
+ case .light: NSApp.appearance = NSAppearance(named: .aqua)
+ case .dark: NSApp.appearance = NSAppearance(named: .darkAqua)
+ }
+ }
+}
+
+/// Shows the app's current notice as a toast at the top of a window, under the header.
+private struct MorphNoticeHost: ViewModifier {
+ @Bindable var state: MorphAppState
+
+ func body(content: Content) -> some View {
+ content
+ .overlay(alignment: .top) {
+ if let notice = state.notice {
+ MorphNoticeToast(text: notice.text, isError: notice.kind == .error) {
+ state.notice = nil
+ }
+ .frame(maxWidth: 520)
+ .padding(.top, 22)
+ .padding(.horizontal, 16)
+ .transition(.move(edge: .top).combined(with: .opacity))
+ .id(notice.id)
+ }
+ }
+ .animation(AnymorphMotion.base, value: state.notice?.id)
+ .task(id: state.notice?.id) {
+ guard let notice = state.notice else { return }
+ try? await Task.sleep(for: .seconds(notice.kind == .error ? 8 : 3))
+ if state.notice?.id == notice.id {
+ state.notice = nil
+ }
+ }
+ }
+}
+
+public extension View {
+ func morphNotices(_ state: MorphAppState) -> some View {
+ modifier(MorphNoticeHost(state: state))
+ }
+}
+
+/// A 6 pt hit target over a pane's 1 pt divider. Dragging it resizes the pane, and a double click resets its default width.
+private struct MorphPaneResizeHandle: View {
+ static let hitWidth: CGFloat = 6
+
+ @Binding var width: CGFloat
+ let range: ClosedRange
+ let defaultWidth: CGFloat
+ let growsTowardTrailing: Bool
+ let accessibilityName: String
+
+ @State private var dragStartWidth: CGFloat?
+ @State private var isHovering = false
+ @State private var isCursorPushed = false
+
+ var body: some View {
+ Rectangle()
+ .fill(Color.clear)
+ .frame(width: Self.hitWidth)
+ .frame(maxHeight: .infinity)
+ .contentShape(Rectangle())
+ .overlay {
+ Rectangle()
+ .fill(AnymorphColor.strokeBase)
+ .frame(width: 2)
+ .opacity(isHovering || dragStartWidth != nil ? 1 : 0)
+ .animation(AnymorphMotion.fast, value: isHovering || dragStartWidth != nil)
+ .allowsHitTesting(false)
+ }
+ .onHover { inside in
+ isHovering = inside
+ updateCursor()
+ }
+ .onTapGesture(count: 2) {
+ withAnimation(AnymorphMotion.base) {
+ width = clamp(defaultWidth)
+ }
+ }
+ .gesture(
+ DragGesture(minimumDistance: 1, coordinateSpace: .global)
+ .onChanged { value in
+ let start = dragStartWidth ?? width
+ if dragStartWidth == nil {
+ dragStartWidth = start
+ updateCursor()
+ }
+ let delta = growsTowardTrailing ? value.translation.width : -value.translation.width
+ let next = clamp(start + delta).rounded()
+ if next != width {
+ width = next
+ }
+ }
+ .onEnded { _ in
+ dragStartWidth = nil
+ updateCursor()
+ }
+ )
+ .onDisappear {
+ if isCursorPushed {
+ NSCursor.pop()
+ isCursorPushed = false
+ }
+ }
+ .accessibilityElement()
+ .accessibilityLabel(accessibilityName)
+ .accessibilityValue("\(Int(width)) points")
+ .accessibilityAdjustableAction { direction in
+ switch direction {
+ case .increment: width = clamp(width + 20)
+ case .decrement: width = clamp(width - 20)
+ @unknown default: break
+ }
+ }
+ .help("Drag to resize · Double-click to reset")
+ }
+
+ private func clamp(_ value: CGFloat) -> CGFloat {
+ min(range.upperBound, max(range.lowerBound, value))
+ }
+
+ private func updateCursor() {
+ let wantsCursor = isHovering || dragStartWidth != nil
+ if wantsCursor, !isCursorPushed {
+ NSCursor.resizeLeftRight.push()
+ isCursorPushed = true
+ } else if !wantsCursor, isCursorPushed {
+ NSCursor.pop()
+ isCursorPushed = false
+ }
+ }
+}
+
+/// Keeps visited layers mounted in a `ZStack` so switching inspector tabs or code views swaps
+/// the visible layer immediately without tearing down or recreating `WKWebView`, terminal, or `NSTextView` trees.
+struct MorphKeepAliveStack: View {
+ let active: Key
+ let items: [Key]
+ @ViewBuilder let content: (Key) -> Content
+ @State private var visited: Set
+
+ init(
+ active: Key,
+ items: [Key],
+ @ViewBuilder content: @escaping (Key) -> Content
+ ) {
+ self.active = active
+ self.items = items
+ self.content = content
+ self._visited = State(initialValue: [active])
+ }
+
+ var body: some View {
+ ZStack {
+ ForEach(items, id: \.self) { item in
+ if visited.contains(item) || item == active {
+ let isItemActive = item == active
+ content(item)
+ .opacity(isItemActive ? 1 : 0)
+ .allowsHitTesting(isItemActive)
+ .disabled(!isItemActive)
+ .accessibilityHidden(!isItemActive)
+ .zIndex(isItemActive ? 1 : 0)
+ }
+ }
+ }
+ .animation(nil, value: active)
+ .onChange(of: active) { _, newValue in
+ visited.insert(newValue)
+ }
+ }
+}
diff --git a/apple/Apps/Shared/MorphSyntaxRendering.swift b/apple/Apps/Shared/MorphSyntaxRendering.swift
new file mode 100644
index 000000000..0e647130e
--- /dev/null
+++ b/apple/Apps/Shared/MorphSyntaxRendering.swift
@@ -0,0 +1,119 @@
+import SwiftUI
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// Muted, Anymorph-harmonious semantic syntax and diff palette for light and dark appearances.
+/// Avoids neon/system-blue oversaturation while making code, diffs, and terminals effortless to scan.
+public enum MorphSyntaxPalette {
+ private static func dynamic(lightHex: UInt32, lightAlpha: CGFloat = 1.0, darkHex: UInt32, darkAlpha: CGFloat = 1.0) -> Color {
+ #if os(macOS)
+ let nsColor = NSColor(name: nil) { appearance in
+ let isDark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ let hex = isDark ? darkHex : lightHex
+ let alpha = isDark ? darkAlpha : lightAlpha
+ return NSColor(
+ srgbRed: CGFloat((hex >> 16) & 0xFF) / 255.0,
+ green: CGFloat((hex >> 8) & 0xFF) / 255.0,
+ blue: CGFloat(hex & 0xFF) / 255.0,
+ alpha: alpha
+ )
+ }
+ return Color(nsColor: nsColor)
+ #else
+ let uiColor = UIColor { trait in
+ let isDark = trait.userInterfaceStyle == .dark
+ let hex = isDark ? darkHex : lightHex
+ let alpha = isDark ? darkAlpha : lightAlpha
+ return UIColor(
+ red: CGFloat((hex >> 16) & 0xFF) / 255.0,
+ green: CGFloat((hex >> 8) & 0xFF) / 255.0,
+ blue: CGFloat(hex & 0xFF) / 255.0,
+ alpha: alpha
+ )
+ }
+ return Color(uiColor: uiColor)
+ #endif
+ }
+
+ public static let keyword = dynamic(lightHex: 0x8F3F71, darkHex: 0xD3869B)
+ public static let type = dynamic(lightHex: 0x2B6CB0, darkHex: 0x83A598)
+ public static let string = dynamic(lightHex: 0x2F7A4D, darkHex: 0x98C379)
+ public static let number = dynamic(lightHex: 0xB45309, darkHex: 0xE5C07B)
+ public static let comment = dynamic(lightHex: 0x737373, darkHex: 0x8A8A8A)
+ public static let property = dynamic(lightHex: 0x0F766E, darkHex: 0x7EC8C1)
+ public static let function = dynamic(lightHex: 0x4F46E5, darkHex: 0x9FA8FA)
+ public static let `operator` = dynamic(lightHex: 0x525252, darkHex: 0xB5B5B5)
+
+ // Subtle diff foreground & line tint colors
+ public static let diffAddFg = dynamic(lightHex: 0x166534, darkHex: 0x86EFAC)
+ public static let diffAddBg = dynamic(lightHex: 0x16A34A, lightAlpha: 0.10, darkHex: 0x22C55E, darkAlpha: 0.14)
+ public static let diffRemoveFg = dynamic(lightHex: 0x991B1B, darkHex: 0xFCA5A5)
+ public static let diffRemoveBg = dynamic(lightHex: 0xDC2626, lightAlpha: 0.09, darkHex: 0xEF4444, darkAlpha: 0.14)
+ public static let diffHeaderFg = dynamic(lightHex: 0x525252, darkHex: 0xA3A3A3)
+ public static let diffHeaderBg = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.09, darkHex: 0xFAFAFA, darkAlpha: 0.06)
+
+ public static func color(for kind: SyntaxTokenKind) -> Color {
+ switch kind {
+ case .plain: return AnymorphColor.fgPrimary
+ case .keyword: return keyword
+ case .type: return type
+ case .string: return string
+ case .number: return number
+ case .comment: return comment
+ case .property: return property
+ case .function: return function
+ case .operator: return `operator`
+ case .diffAdd: return diffAddFg
+ case .diffRemove: return diffRemoveFg
+ case .diffHeader: return diffHeaderFg
+ }
+ }
+
+ /// Builds a styled `AttributedString` for a single tokenized line of code.
+ public static func attributedLine(_ tokens: [SyntaxToken], fontSize: CGFloat = 12) -> AttributedString {
+ var result = AttributedString()
+ let baseFont = Font.system(size: fontSize, design: .monospaced)
+ for token in tokens {
+ var part = AttributedString(token.text)
+ part.font = token.kind == .keyword ? baseFont.weight(.medium) : baseFont
+ part.foregroundColor = color(for: token.kind)
+ result.append(part)
+ }
+ return result
+ }
+
+ /// Builds a multi-line syntax-highlighted `AttributedString` for compact inline code blocks.
+ public static func attributedCode(_ code: String, language: String?, fontSize: CGFloat = 12) -> AttributedString {
+ let lines = MorphSyntaxHighlighter.tokenize(code, language: language)
+ var out = AttributedString()
+ for (idx, lineTokens) in lines.enumerated() {
+ if idx > 0 {
+ out.append(AttributedString("\n"))
+ }
+ out.append(attributedLine(lineTokens, fontSize: fontSize))
+ }
+ return out
+ }
+}
+
+/// Environment hook allowing Markdown links and tool rows to open `path:line` inside Morph's code reader.
+public struct MorphOpenFileLocationAction: Sendable {
+ public let handler: @MainActor @Sendable (_ path: String, _ line: Int?) -> Void
+
+ public init(_ handler: @escaping @MainActor @Sendable (_ path: String, _ line: Int?) -> Void) {
+ self.handler = handler
+ }
+
+ @MainActor
+ public func callAsFunction(path: String, line: Int? = nil) {
+ handler(path, line)
+ }
+}
+
+extension EnvironmentValues {
+ @Entry public var morphOpenFileLocation: MorphOpenFileLocationAction? = nil
+}
diff --git a/apple/Apps/Shared/MorphTerminalView.swift b/apple/Apps/Shared/MorphTerminalView.swift
new file mode 100644
index 000000000..5f3db2db4
--- /dev/null
+++ b/apple/Apps/Shared/MorphTerminalView.swift
@@ -0,0 +1,1261 @@
+import SwiftUI
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+#if os(macOS)
+typealias MorphTerminalPlatformColor = NSColor
+typealias MorphTerminalPlatformFont = NSFont
+#else
+typealias MorphTerminalPlatformColor = UIColor
+typealias MorphTerminalPlatformFont = UIFont
+#endif
+
+// MARK: - Palette
+
+/// Muted ANSI palette for Morph's terminal. The sixteen base colors follow the Anymorph syntax palette for light and
+/// dark appearances, so `ls --color`, git and test runners stay readable without neon hues. The 256-color cube and
+/// true colors are drawn as the program asks.
+@MainActor
+enum MorphTerminalPalette {
+ private static let darkBase16: [UInt32] = [
+ 0x3A3A3A, 0xE06C75, 0x98C379, 0xE5C07B, 0x83A598, 0xD3869B, 0x7EC8C1, 0xD4D4D4,
+ 0x6B6B6B, 0xF28B94, 0xB5E08F, 0xF0D28F, 0xA3C4B8, 0xE3A5B7, 0x9EDCD5, 0xFAFAFA,
+ ]
+ private static let lightBase16: [UInt32] = [
+ 0x161616, 0xB42318, 0x2F7A4D, 0x9A6700, 0x2B6CB0, 0x8F3F71, 0x0F766E, 0x8C8C8C,
+ 0x5C5C5C, 0xD92D20, 0x3E9A62, 0xB45309, 0x3B82C4, 0xA84D88, 0x14968B, 0xB8B8B8,
+ ]
+
+ static let defaultForeground = dynamic(lightHex: 0x161616, darkHex: 0xFAFAFA)
+ static let defaultBackground = dynamic(lightHex: 0xFFFFFF, darkHex: 0x000000)
+ static let unfocusedCursor = dynamic(lightHex: 0x161616, lightAlpha: 0.28, darkHex: 0xFAFAFA, darkAlpha: 0.32)
+ static let markedTextBackground = dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.22, darkHex: 0xA4A4A4, darkAlpha: 0.22)
+
+ private static let base16: [MorphTerminalPlatformColor] = (0..<16).map { index in
+ dynamic(lightHex: lightBase16[index], darkHex: darkBase16[index])
+ }
+
+ private static let extended: [MorphTerminalPlatformColor] = (16..<256).map { index in
+ let rgb = TerminalColor.xtermRGB(paletteIndex: index)
+ return rgbColor(rgb.red, rgb.green, rgb.blue)
+ }
+
+ static func dynamic(lightHex: UInt32, lightAlpha: CGFloat = 1, darkHex: UInt32, darkAlpha: CGFloat = 1) -> MorphTerminalPlatformColor {
+ #if os(macOS)
+ return NSColor(name: nil) { appearance in
+ let isDark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ return hexColor(isDark ? darkHex : lightHex, alpha: isDark ? darkAlpha : lightAlpha)
+ }
+ #else
+ return UIColor { trait in
+ let isDark = trait.userInterfaceStyle == .dark
+ return hexColor(isDark ? darkHex : lightHex, alpha: isDark ? darkAlpha : lightAlpha)
+ }
+ #endif
+ }
+
+ private nonisolated static func hexColor(_ hex: UInt32, alpha: CGFloat) -> MorphTerminalPlatformColor {
+ let r = CGFloat((hex >> 16) & 0xFF) / 255
+ let g = CGFloat((hex >> 8) & 0xFF) / 255
+ let b = CGFloat(hex & 0xFF) / 255
+ #if os(macOS)
+ return NSColor(srgbRed: r, green: g, blue: b, alpha: alpha)
+ #else
+ return UIColor(red: r, green: g, blue: b, alpha: alpha)
+ #endif
+ }
+
+ private static func rgbColor(_ r: UInt8, _ g: UInt8, _ b: UInt8) -> MorphTerminalPlatformColor {
+ hexColor(UInt32(r) << 16 | UInt32(g) << 8 | UInt32(b), alpha: 1)
+ }
+
+ /// The color to draw, or nil for the terminal's default color.
+ static func color(_ color: TerminalColor) -> MorphTerminalPlatformColor? {
+ switch color {
+ case .default:
+ return nil
+ case let .rgb(r, g, b):
+ return rgbColor(r, g, b)
+ default:
+ guard let index = color.paletteIndex else { return nil }
+ return index < 16 ? base16[index] : extended[index - 16]
+ }
+ }
+
+ /// Foreground and background for a cell style, with inverse and dim applied.
+ static func resolve(_ style: TerminalCellStyle, isCursor: Bool, focused: Bool) -> (fg: MorphTerminalPlatformColor, bg: MorphTerminalPlatformColor?) {
+ var fg = color(style.fg) ?? defaultForeground
+ var bg = color(style.bg)
+ if style.inverse {
+ let swappedBg = fg
+ fg = bg ?? defaultBackground
+ bg = swappedBg
+ }
+ if style.dim {
+ fg = fg.withAlphaComponent(0.6)
+ }
+ if isCursor {
+ if focused {
+ let cursorBg = fg
+ fg = bg ?? defaultBackground
+ bg = cursorBg
+ } else {
+ bg = unfocusedCursor
+ }
+ }
+ return (fg, bg)
+ }
+}
+
+// MARK: - Line Layout
+
+/// A run to draw: a span of a terminal line, or the cell under the cursor.
+struct MorphTerminalSegment: Equatable {
+ var text: String
+ var style: TerminalCellStyle
+ var isCursor: Bool
+}
+
+enum MorphTerminalLayout {
+ /// How many cells a character takes: two for Hangul, CJK and emoji, one otherwise.
+ static func cellWidth(_ character: Character) -> Int {
+ guard let scalar = character.unicodeScalars.first?.value else { return 1 }
+ switch scalar {
+ case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF,
+ 0xA000...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60,
+ 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD:
+ return 2
+ default:
+ return 1
+ }
+ }
+
+ /// Splits a line into segments, with the character at `cursorCell` as its own cursor segment. A cursor past the
+ /// end of the line is drawn on a blank padded out to its column.
+ static func segments(for line: TerminalStyledLine, cursorCell: Int?) -> [MorphTerminalSegment] {
+ guard let cursorCell, cursorCell >= 0 else {
+ return line.spans.map { MorphTerminalSegment(text: $0.text, style: $0.style, isCursor: false) }
+ }
+ var out: [MorphTerminalSegment] = []
+ out.reserveCapacity(line.spans.count + 2)
+ var cell = 0
+ var placed = false
+ for span in line.spans {
+ if placed {
+ out.append(MorphTerminalSegment(text: span.text, style: span.style, isCursor: false))
+ continue
+ }
+ let spanCells = span.text.reduce(0) { $0 + cellWidth($1) }
+ if cursorCell >= cell + spanCells {
+ out.append(MorphTerminalSegment(text: span.text, style: span.style, isCursor: false))
+ cell += spanCells
+ continue
+ }
+ var before = ""
+ var after = ""
+ var cursorChar: Character = " "
+ var found = false
+ var c = cell
+ for ch in span.text {
+ if found {
+ after.append(ch)
+ continue
+ }
+ let w = cellWidth(ch)
+ if cursorCell < c + w {
+ cursorChar = ch
+ found = true
+ } else {
+ before.append(ch)
+ }
+ c += w
+ }
+ if !before.isEmpty { out.append(MorphTerminalSegment(text: before, style: span.style, isCursor: false)) }
+ out.append(MorphTerminalSegment(text: String(cursorChar), style: span.style, isCursor: true))
+ if !after.isEmpty { out.append(MorphTerminalSegment(text: after, style: span.style, isCursor: false)) }
+ placed = true
+ }
+ if !placed {
+ let pad = cursorCell - cell
+ if pad > 0 {
+ out.append(MorphTerminalSegment(text: String(repeating: " ", count: pad), style: .default, isCursor: false))
+ }
+ out.append(MorphTerminalSegment(text: " ", style: .default, isCursor: true))
+ }
+ return out
+ }
+
+ /// The lines to draw: the styled snapshot, or the plain output split into lines when no styled rows exist yet.
+ static func displayLines(_ lines: [TerminalStyledLine], fallbackText: String) -> [TerminalStyledLine] {
+ if !lines.isEmpty || fallbackText.isEmpty { return lines }
+ return fallbackText.split(separator: "\n", omittingEmptySubsequences: false).map {
+ TerminalStyledLine(spans: [TerminalStyledSpan(text: String($0), style: .default)], isScrollback: false)
+ }
+ }
+
+ /// The index in `lines` of the row the cursor is on.
+ static func cursorLineIndex(lines: [TerminalStyledLine], cursor: CodeTerminalCursorState?) -> Int? {
+ guard let cursor, cursor.visible else { return nil }
+ let scrollback = cursor.isAlternateScreen ? 0 : (lines.firstIndex(where: { !$0.isScrollback }) ?? lines.count)
+ return scrollback + cursor.row
+ }
+}
+
+/// Sends keystrokes to the PTY one batch at a time, in the order they were typed.
+@MainActor
+final class MorphTerminalInputQueue {
+ private struct Pending {
+ let sessionKey: String
+ let projectId: String
+ var data: String
+ }
+
+ private var pending: [Pending] = []
+ private var isDraining = false
+
+ func enqueue(_ data: String, sessionKey: String, projectId: String, send: @escaping @MainActor (String, String, String) async -> Void) {
+ guard !data.isEmpty else { return }
+ if var last = pending.last, last.sessionKey == sessionKey, last.projectId == projectId {
+ last.data += data
+ pending[pending.count - 1] = last
+ } else {
+ pending.append(Pending(sessionKey: sessionKey, projectId: projectId, data: data))
+ }
+ guard !isDraining else { return }
+ isDraining = true
+ Task { @MainActor in
+ while !pending.isEmpty {
+ let next = pending.removeFirst()
+ await send(next.sessionKey, next.projectId, next.data)
+ }
+ isDraining = false
+ }
+ }
+}
+
+// MARK: - Public View
+
+/// Live interactive terminal for one PTY session: ANSI colors and attributes, the cursor, typing straight into the
+/// shell, selection and copy, and the grid size reported back to the PTY as the pane resizes.
+public struct MorphTerminalView: View {
+ @Bindable var state: MorphAppState
+ let sessionKey: String
+ let projectId: String
+ let searchMatches: [TerminalSearchMatch]
+ let activeSearchMatchIndex: Int
+ let links: [TerminalLinkMatch]
+ let mouseTrackingMode: TerminalMouseMode
+ let sgrMouseMode: Bool
+ let onOpenURL: ((URL) -> Void)?
+ let onOpenFileLink: ((String, Int?) -> Void)?
+ let onFindShortcut: (() -> Void)?
+ @State private var inputQueue = MorphTerminalInputQueue()
+
+ public init(
+ state: MorphAppState,
+ sessionKey: String,
+ projectId: String,
+ searchMatches: [TerminalSearchMatch] = [],
+ activeSearchMatchIndex: Int = 0,
+ links: [TerminalLinkMatch] = [],
+ mouseTrackingMode: TerminalMouseMode = .none,
+ sgrMouseMode: Bool = false,
+ onOpenURL: ((URL) -> Void)? = nil,
+ onOpenFileLink: ((String, Int?) -> Void)? = nil,
+ onFindShortcut: (() -> Void)? = nil
+ ) {
+ self.state = state
+ self.sessionKey = sessionKey
+ self.projectId = projectId
+ self.searchMatches = searchMatches
+ self.activeSearchMatchIndex = activeSearchMatchIndex
+ self.links = links
+ self.mouseTrackingMode = mouseTrackingMode
+ self.sgrMouseMode = sgrMouseMode
+ self.onOpenURL = onOpenURL
+ self.onOpenFileLink = onOpenFileLink
+ self.onFindShortcut = onFindShortcut
+ }
+
+ public var body: some View {
+ let key = sessionKey
+ let pid = projectId
+ MorphTerminalSurface(
+ lines: state.codeTerminalStyledLines[key] ?? [],
+ fallbackText: state.codeTerminalOutputs[key] ?? "",
+ cursor: state.codeTerminalCursorByKey[key],
+ isRunning: state.codeTerminalSessions[key]?.running == true,
+ decorations: MorphTerminalDecorations(
+ searchMatches: searchMatches,
+ activeSearchMatchIndex: activeSearchMatchIndex,
+ links: links
+ ),
+ mouseTrackingMode: mouseTrackingMode,
+ sgrMouseMode: sgrMouseMode,
+ onOpenLink: { link in openLink(link) },
+ onFindShortcut: onFindShortcut,
+ onInput: { data in
+ guard !pid.isEmpty else { return }
+ inputQueue.enqueue(data, sessionKey: key, projectId: pid) { k, p, d in
+ await state.sendCodeTerminalInput(sessionKey: k, projectId: p, data: d)
+ }
+ },
+ onResize: { cols, rows in
+ guard !pid.isEmpty else { return }
+ Task { await state.resizeCodeTerminalSession(sessionKey: key, projectId: pid, cols: cols, rows: rows) }
+ },
+ onClear: {
+ guard !pid.isEmpty else { return }
+ state.clearCodeTerminalOutput(sessionKey: key)
+ // Ask the shell to redraw its prompt on the cleared screen.
+ inputQueue.enqueue("\u{0C}", sessionKey: key, projectId: pid) { k, p, d in
+ await state.sendCodeTerminalInput(sessionKey: k, projectId: p, data: d)
+ }
+ }
+ )
+ .id(key)
+ }
+
+ private func openLink(_ link: TerminalLinkMatch) {
+ switch link.kind {
+ case .url:
+ if let url = URL(string: link.target) { onOpenURL?(url) }
+ case let .filePath(path, line):
+ onOpenFileLink?(path, line)
+ }
+ }
+}
+
+/// Search matches and links drawn over the terminal text, with ranges on the lines of the styled snapshot.
+struct MorphTerminalDecorations: Equatable {
+ var searchMatches: [TerminalSearchMatch] = []
+ var activeSearchMatchIndex: Int = 0
+ var links: [TerminalLinkMatch] = []
+
+ static let none = MorphTerminalDecorations()
+
+ var activeMatch: TerminalSearchMatch? {
+ searchMatches.indices.contains(activeSearchMatchIndex) ? searchMatches[activeSearchMatchIndex] : nil
+ }
+
+ /// Matches and links on one line, for the touch terminal that draws line by line.
+ func matches(onLine lineIndex: Int) -> [(match: TerminalSearchMatch, isActive: Bool)] {
+ searchMatches.enumerated().compactMap { index, match in
+ match.lineIndex == lineIndex ? (match, index == activeSearchMatchIndex) : nil
+ }
+ }
+
+ func links(onLine lineIndex: Int) -> [TerminalLinkMatch] {
+ links.filter { $0.lineIndex == lineIndex }
+ }
+}
+
+/// Colors for search matches, in Morph's one tone: every match on a gray wash, the current one in inverse ink.
+@MainActor
+enum MorphTerminalHighlight {
+ static let match = MorphTerminalPalette.dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.35, darkHex: 0xA4A4A4, darkAlpha: 0.35)
+ static let activeMatch = MorphTerminalPalette.dynamic(lightHex: 0x161616, darkHex: 0xFAFAFA)
+ static let activeMatchForeground = MorphTerminalPalette.dynamic(lightHex: 0xFAFAFA, darkHex: 0x161616)
+}
+
+/// The terminal surface without app state, for one snapshot of lines and cursor.
+struct MorphTerminalSurface: View {
+ let lines: [TerminalStyledLine]
+ let fallbackText: String
+ let cursor: CodeTerminalCursorState?
+ let isRunning: Bool
+ var decorations: MorphTerminalDecorations = .none
+ var mouseTrackingMode: TerminalMouseMode = .none
+ var sgrMouseMode: Bool = false
+ var onOpenLink: (@MainActor (TerminalLinkMatch) -> Void)? = nil
+ var onFindShortcut: (() -> Void)? = nil
+ let onInput: @MainActor (String) -> Void
+ let onResize: @MainActor (Int, Int) -> Void
+ let onClear: @MainActor () -> Void
+
+ static let fontSize: CGFloat = 12
+
+ var body: some View {
+ let display = MorphTerminalLayout.displayLines(lines, fallbackText: fallbackText)
+ ZStack(alignment: .topLeading) {
+ #if os(macOS)
+ MorphInteractiveTerminalRepresentable(
+ lines: display,
+ cursor: isRunning ? cursor : nil,
+ decorations: decorations,
+ mouseTrackingMode: isRunning ? mouseTrackingMode : .none,
+ sgrMouseMode: sgrMouseMode,
+ onOpenLink: onOpenLink,
+ onFindShortcut: onFindShortcut,
+ onInput: onInput,
+ onResize: onResize,
+ onClear: onClear
+ )
+ #else
+ MorphTerminalTouchView(
+ lines: display,
+ cursor: isRunning ? cursor : nil,
+ isRunning: isRunning,
+ decorations: decorations,
+ onOpenLink: onOpenLink,
+ onInput: onInput,
+ onResize: onResize,
+ onClear: onClear
+ )
+ #endif
+ if display.isEmpty {
+ Text(isRunning ? "Waiting for shell output…" : "Starting interactive terminal…")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .padding(12)
+ .allowsHitTesting(false)
+ }
+ }
+ }
+}
+
+#if os(macOS)
+
+// MARK: - macOS Interactive Terminal
+
+/// Translates a key press into the bytes a PTY expects, or nil for keys the terminal leaves to the app.
+enum MorphTerminalKeyTranslator {
+ static func bytes(for event: NSEvent) -> String? {
+ let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
+ if flags.contains(.command) { return nil }
+ let option = flags.contains(.option)
+ switch event.keyCode {
+ case 36, 76: return "\r"
+ case 51: return option ? "\u{1B}\u{7F}" : "\u{7F}"
+ case 117: return "\u{1B}[3~"
+ case 48: return flags.contains(.shift) ? "\u{1B}[Z" : "\t"
+ case 53: return "\u{1B}"
+ case 126: return "\u{1B}[A"
+ case 125: return "\u{1B}[B"
+ case 124: return option ? "\u{1B}f" : "\u{1B}[C"
+ case 123: return option ? "\u{1B}b" : "\u{1B}[D"
+ case 115: return "\u{1B}[H"
+ case 119: return "\u{1B}[F"
+ case 116: return "\u{1B}[5~"
+ case 121: return "\u{1B}[6~"
+ default: break
+ }
+ if flags.contains(.control), let raw = event.charactersIgnoringModifiers?.lowercased(), let scalar = raw.unicodeScalars.first {
+ switch scalar.value {
+ case 0x61...0x7A: // a-z → 0x01-0x1A
+ return String(UnicodeScalar(UInt8(scalar.value - 0x60)))
+ case 0x20, 0x40, 0x32: return "\u{00}" // Ctrl+Space, Ctrl+@, Ctrl+2
+ case 0x5B: return "\u{1B}" // Ctrl+[
+ case 0x5C: return "\u{1C}" // Ctrl+\
+ case 0x5D: return "\u{1D}" // Ctrl+]
+ case 0x5E, 0x36: return "\u{1E}" // Ctrl+^
+ case 0x5F, 0x2D: return "\u{1F}" // Ctrl+_
+ default: break
+ }
+ }
+ return nil
+ }
+}
+
+/// Scroll view that reports its size so the terminal grid can follow it.
+final class MorphTerminalScrollView: NSScrollView {
+ var onSizeChange: (@MainActor () -> Void)?
+
+ override func setFrameSize(_ newSize: NSSize) {
+ let changed = newSize != frame.size
+ super.setFrameSize(newSize)
+ if changed { onSizeChange?() }
+ }
+}
+
+/// Selectable text view that is also the terminal's keyboard: it takes focus on click, sends typed keys, IME text,
+/// paste and control keys to the PTY, and keeps ⌘C, ⌘A and ⌘F for selection, copy and find.
+final class MorphInteractiveTerminalNSView: NSTextView {
+ var onInput: (@MainActor (String) -> Void)?
+ var onClear: (@MainActor () -> Void)?
+ var onFocusChange: (@MainActor (Bool) -> Void)?
+ var onMarkedTextChange: (@MainActor (String) -> Void)?
+ var onFindShortcut: (() -> Void)?
+ /// Opens the link with this index in the coordinator's link list.
+ var onLinkActivate: (@MainActor (Int) -> Void)?
+ /// The 1-based grid cell under a point in this view, or nil outside the screen.
+ var gridCell: (@MainActor (NSPoint) -> (col: Int, row: Int)?)?
+ var mouseTrackingMode: TerminalMouseMode = .none
+ var sgrMouseMode = false
+ /// Character index of the cursor in the text storage, for placing the IME candidate window.
+ var cursorCharacterIndex: Int = 0
+ private var markedBuffer = ""
+ private var pressedMouseButton: Int?
+ private var scrollRemainder: CGFloat = 0
+
+ static let linkIndexKey = NSAttributedString.Key("MorphTerminalLinkIndex")
+
+ override var acceptsFirstResponder: Bool { true }
+
+ override func becomeFirstResponder() -> Bool {
+ let ok = super.becomeFirstResponder()
+ if ok { onFocusChange?(true) }
+ return ok
+ }
+
+ override func resignFirstResponder() -> Bool {
+ let ok = super.resignFirstResponder()
+ if ok { onFocusChange?(false) }
+ return ok
+ }
+
+ override func keyDown(with event: NSEvent) {
+ if hasMarkedText() {
+ interpretKeyEvents([event])
+ return
+ }
+ if let bytes = MorphTerminalKeyTranslator.bytes(for: event) {
+ onInput?(bytes)
+ return
+ }
+ if event.modifierFlags.contains(.command) {
+ if event.charactersIgnoringModifiers?.lowercased() == "f", let onFindShortcut {
+ onFindShortcut()
+ return
+ }
+ super.keyDown(with: event)
+ return
+ }
+ interpretKeyEvents([event])
+ }
+
+ // MARK: Links and mouse reporting
+
+ /// The index of the link drawn at a point in window coordinates, if any.
+ private func linkIndex(at windowPoint: NSPoint) -> Int? {
+ guard let layoutManager, let textContainer, let storage = textStorage, storage.length > 0 else { return nil }
+ var point = convert(windowPoint, from: nil)
+ point.x -= textContainerOrigin.x
+ point.y -= textContainerOrigin.y
+ let glyph = layoutManager.glyphIndex(for: point, in: textContainer)
+ let glyphRect = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: textContainer)
+ guard glyphRect.contains(point) else { return nil }
+ let characterIndex = layoutManager.characterIndexForGlyph(at: glyph)
+ guard characterIndex < storage.length else { return nil }
+ return storage.attribute(Self.linkIndexKey, at: characterIndex, effectiveRange: nil) as? Int
+ }
+
+ /// Whether a full-screen program asked for mouse events; holding Option keeps the click for text selection.
+ private func reportsMouse(_ event: NSEvent) -> Bool {
+ mouseTrackingMode != .none && !event.modifierFlags.contains(.option)
+ }
+
+ private func sendMouse(button: Int, event: NSEvent, pressed: Bool) {
+ guard let cell = gridCell?(convert(event.locationInWindow, from: nil)) else { return }
+ if sgrMouseMode {
+ onInput?(TerminalScreen.encodeSGRMouse(button: button, col: cell.col, row: cell.row, pressed: pressed))
+ } else {
+ // The X10 form: one byte each for the button, column and row, offset by 32. Releases report button 3.
+ let code = pressed ? button : 3 + (button & ~3)
+ let bytes = [32 + code, 32 + min(cell.col, 223), 32 + min(cell.row, 223)].compactMap { UnicodeScalar($0) }
+ onInput?("\u{1B}[M" + String(String.UnicodeScalarView(bytes)))
+ }
+ }
+
+ private static func modifierBits(_ event: NSEvent) -> Int {
+ var bits = 0
+ if event.modifierFlags.contains(.shift) { bits |= 4 }
+ if event.modifierFlags.contains(.control) { bits |= 16 }
+ return bits
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ if event.modifierFlags.contains(.command), let index = linkIndex(at: event.locationInWindow) {
+ onLinkActivate?(index)
+ return
+ }
+ if reportsMouse(event) {
+ window?.makeFirstResponder(self)
+ pressedMouseButton = 0
+ sendMouse(button: Self.modifierBits(event), event: event, pressed: true)
+ return
+ }
+ super.mouseDown(with: event)
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ if reportsMouse(event), pressedMouseButton != nil {
+ if mouseTrackingMode != .x10 {
+ sendMouse(button: 32 + Self.modifierBits(event), event: event, pressed: true)
+ }
+ return
+ }
+ super.mouseDragged(with: event)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ if pressedMouseButton != nil {
+ pressedMouseButton = nil
+ if reportsMouse(event) {
+ sendMouse(button: Self.modifierBits(event), event: event, pressed: false)
+ }
+ return
+ }
+ super.mouseUp(with: event)
+ }
+
+ override func rightMouseDown(with event: NSEvent) {
+ if reportsMouse(event) {
+ sendMouse(button: 2 + Self.modifierBits(event), event: event, pressed: true)
+ return
+ }
+ super.rightMouseDown(with: event)
+ }
+
+ override func rightMouseUp(with event: NSEvent) {
+ if reportsMouse(event) {
+ sendMouse(button: 2 + Self.modifierBits(event), event: event, pressed: false)
+ return
+ }
+ super.rightMouseUp(with: event)
+ }
+
+ override func scrollWheel(with event: NSEvent) {
+ guard reportsMouse(event) else {
+ super.scrollWheel(with: event)
+ return
+ }
+ // Trackpads report small precise deltas; about one terminal line per 12 points.
+ scrollRemainder += event.hasPreciseScrollingDeltas ? event.scrollingDeltaY / 12 : event.scrollingDeltaY
+ let steps = Int(scrollRemainder.rounded(.towardZero))
+ guard steps != 0 else { return }
+ scrollRemainder -= CGFloat(steps)
+ let button = steps > 0 ? 64 : 65
+ for _ in 0.. Bool {
+ guard window?.firstResponder === self else { return super.performKeyEquivalent(with: event) }
+ let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
+ guard flags.contains(.command), !flags.contains(.control), !flags.contains(.option) else {
+ return super.performKeyEquivalent(with: event)
+ }
+ switch event.charactersIgnoringModifiers?.lowercased() {
+ case "f" where onFindShortcut != nil:
+ onFindShortcut?()
+ return true
+ case "v":
+ paste(nil)
+ return true
+ case "k":
+ onClear?()
+ return true
+ default:
+ return super.performKeyEquivalent(with: event)
+ }
+ }
+
+ override func paste(_ sender: Any?) {
+ guard let text = NSPasteboard.general.string(forType: .string), !text.isEmpty else { return }
+ // Shells take Return, not newline, as the end of a pasted line.
+ onInput?(text.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r"))
+ }
+
+ override func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool {
+ if item.action == #selector(paste(_:)) {
+ return NSPasteboard.general.string(forType: .string) != nil
+ }
+ return super.validateUserInterfaceItem(item)
+ }
+
+ // MARK: Text input (IME composition such as Korean)
+
+ override func insertText(_ string: Any, replacementRange: NSRange) {
+ let text = (string as? NSAttributedString)?.string ?? (string as? String) ?? ""
+ markedBuffer = ""
+ onMarkedTextChange?("")
+ if !text.isEmpty { onInput?(text) }
+ }
+
+ override func setMarkedText(_ string: Any, selectedRange: NSRange, replacementRange: NSRange) {
+ markedBuffer = (string as? NSAttributedString)?.string ?? (string as? String) ?? ""
+ onMarkedTextChange?(markedBuffer)
+ }
+
+ override func unmarkText() {
+ if !markedBuffer.isEmpty { onInput?(markedBuffer) }
+ markedBuffer = ""
+ onMarkedTextChange?("")
+ }
+
+ override func hasMarkedText() -> Bool { !markedBuffer.isEmpty }
+
+ override func markedRange() -> NSRange {
+ markedBuffer.isEmpty ? NSRange(location: NSNotFound, length: 0) : NSRange(location: cursorCharacterIndex, length: (markedBuffer as NSString).length)
+ }
+
+ override func firstRect(forCharacterRange range: NSRange, actualRange: NSRangePointer?) -> NSRect {
+ guard let layoutManager, let textContainer, let window else { return .zero }
+ let length = textStorage?.length ?? 0
+ let index = min(cursorCharacterIndex, max(0, length - 1))
+ var rect: NSRect
+ if length == 0 {
+ rect = NSRect(x: 0, y: 0, width: 1, height: 16)
+ } else {
+ let glyphRange = layoutManager.glyphRange(forCharacterRange: NSRange(location: index, length: 1), actualCharacterRange: nil)
+ rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
+ }
+ rect.origin.x += textContainerOrigin.x
+ rect.origin.y += textContainerOrigin.y
+ return window.convertToScreen(convert(rect, to: nil))
+ }
+
+ override func doCommand(by selector: Selector) {
+ switch selector {
+ case #selector(insertNewline(_:)): onInput?("\r")
+ case #selector(deleteBackward(_:)): onInput?("\u{7F}")
+ case #selector(deleteForward(_:)): onInput?("\u{1B}[3~")
+ case #selector(insertTab(_:)): onInput?("\t")
+ case #selector(insertBacktab(_:)): onInput?("\u{1B}[Z")
+ case #selector(cancelOperation(_:)): onInput?("\u{1B}")
+ case #selector(moveUp(_:)): onInput?("\u{1B}[A")
+ case #selector(moveDown(_:)): onInput?("\u{1B}[B")
+ case #selector(moveRight(_:)): onInput?("\u{1B}[C")
+ case #selector(moveLeft(_:)): onInput?("\u{1B}[D")
+ default: break
+ }
+ }
+}
+
+struct MorphInteractiveTerminalRepresentable: NSViewRepresentable {
+ let lines: [TerminalStyledLine]
+ let cursor: CodeTerminalCursorState?
+ let decorations: MorphTerminalDecorations
+ let mouseTrackingMode: TerminalMouseMode
+ let sgrMouseMode: Bool
+ let onOpenLink: (@MainActor (TerminalLinkMatch) -> Void)?
+ let onFindShortcut: (() -> Void)?
+ let onInput: @MainActor (String) -> Void
+ let onResize: @MainActor (Int, Int) -> Void
+ let onClear: @MainActor () -> Void
+
+ func makeCoordinator() -> Coordinator { Coordinator() }
+
+ func makeNSView(context: Context) -> MorphTerminalScrollView {
+ let coordinator = context.coordinator
+ let scrollView = MorphTerminalScrollView()
+ scrollView.drawsBackground = false
+ scrollView.hasVerticalScroller = true
+ scrollView.hasHorizontalScroller = false
+ scrollView.autohidesScrollers = true
+ scrollView.borderType = .noBorder
+ scrollView.scrollerStyle = .overlay
+
+ let textView = MorphInteractiveTerminalNSView(frame: .zero)
+ textView.isEditable = false
+ textView.isSelectable = true
+ textView.isRichText = true
+ textView.drawsBackground = false
+ textView.usesFindBar = true
+ textView.allowsUndo = false
+ textView.textContainerInset = NSSize(width: Coordinator.inset.width, height: Coordinator.inset.height)
+ textView.isVerticallyResizable = true
+ textView.isHorizontallyResizable = false
+ textView.autoresizingMask = [.width]
+ textView.minSize = NSSize(width: 0, height: 0)
+ textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
+ textView.textContainer?.widthTracksTextView = true
+ textView.textContainer?.lineFragmentPadding = 0
+ textView.selectedTextAttributes = [.backgroundColor: MorphTerminalPalette.dynamic(lightHex: 0xA4A4A4, lightAlpha: 0.32, darkHex: 0xA4A4A4, darkAlpha: 0.32)]
+ textView.insertionPointColor = .clear
+ textView.setAccessibilityLabel("Terminal")
+
+ scrollView.documentView = textView
+ coordinator.scrollView = scrollView
+ coordinator.textView = textView
+ coordinator.callbacks = (onInput, onResize, onClear)
+
+ textView.onInput = { [weak coordinator] in coordinator?.callbacks?.input($0) }
+ textView.onClear = { [weak coordinator] in coordinator?.callbacks?.clear() }
+ textView.onFocusChange = { [weak coordinator] focused in coordinator?.setFocused(focused) }
+ textView.onMarkedTextChange = { [weak coordinator] text in coordinator?.setMarkedText(text) }
+ textView.onLinkActivate = { [weak coordinator] index in coordinator?.activateLink(at: index) }
+ textView.gridCell = { [weak coordinator] point in coordinator?.gridCell(at: point) }
+ scrollView.onSizeChange = { [weak coordinator] in coordinator?.scheduleResize() }
+ applyOptions(to: textView, coordinator: coordinator)
+
+ coordinator.render(lines: lines, cursor: cursor, decorations: decorations, force: true)
+ DispatchQueue.main.async { [weak coordinator, weak textView, weak scrollView] in
+ guard let textView, let scrollView, !scrollView.isHidden, let window = textView.window else { return }
+ window.makeFirstResponder(textView)
+ coordinator?.scheduleResize()
+ }
+ return scrollView
+ }
+
+ func updateNSView(_ nsView: MorphTerminalScrollView, context: Context) {
+ context.coordinator.callbacks = (onInput, onResize, onClear)
+ let isEnabled = context.environment.isEnabled
+ if nsView.isHidden != !isEnabled {
+ nsView.isHidden = !isEnabled
+ }
+ if let textView = context.coordinator.textView {
+ applyOptions(to: textView, coordinator: context.coordinator)
+ if !isEnabled, textView.window?.firstResponder === textView {
+ textView.window?.makeFirstResponder(nil)
+ }
+ }
+ context.coordinator.render(lines: lines, cursor: cursor, decorations: decorations, force: false)
+ }
+
+ private func applyOptions(to textView: MorphInteractiveTerminalNSView, coordinator: Coordinator) {
+ coordinator.onOpenLink = onOpenLink
+ textView.onFindShortcut = onFindShortcut
+ textView.sgrMouseMode = sgrMouseMode
+ if textView.mouseTrackingMode != mouseTrackingMode {
+ textView.mouseTrackingMode = mouseTrackingMode
+ textView.window?.invalidateCursorRects(for: textView)
+ }
+ }
+
+ static func dismantleNSView(_ nsView: MorphTerminalScrollView, coordinator: Coordinator) {
+ coordinator.resizeTask?.cancel()
+ }
+
+ @MainActor
+ final class Coordinator {
+ static let inset = CGSize(width: 10, height: 8)
+
+ weak var scrollView: MorphTerminalScrollView?
+ weak var textView: MorphInteractiveTerminalNSView?
+ var callbacks: (input: @MainActor (String) -> Void, resize: @MainActor (Int, Int) -> Void, clear: @MainActor () -> Void)?
+ var resizeTask: Task?
+ var onOpenLink: (@MainActor (TerminalLinkMatch) -> Void)?
+
+ private var lastLines: [TerminalStyledLine] = []
+ private var lastCursor: CodeTerminalCursorState?
+ private var lastDecorations: MorphTerminalDecorations = .none
+ private var focused = false
+ private var markedText = ""
+ private var lastGrid: (cols: Int, rows: Int)?
+
+ private let regularFont = NSFont.monospacedSystemFont(ofSize: MorphTerminalSurface.fontSize, weight: .regular)
+ private let boldFont = NSFont.monospacedSystemFont(ofSize: MorphTerminalSurface.fontSize, weight: .bold)
+ private lazy var italicFont: NSFont = NSFontManager.shared.convert(regularFont, toHaveTrait: .italicFontMask)
+ private lazy var boldItalicFont: NSFont = NSFontManager.shared.convert(boldFont, toHaveTrait: .italicFontMask)
+ private lazy var lineHeight: CGFloat = ceil(NSLayoutManager().defaultLineHeight(for: regularFont))
+ private lazy var cellWidth: CGFloat = ("W" as NSString).size(withAttributes: [.font: regularFont]).width
+ private lazy var paragraph: NSParagraphStyle = {
+ let p = NSMutableParagraphStyle()
+ p.minimumLineHeight = lineHeight
+ p.maximumLineHeight = lineHeight
+ p.lineBreakMode = .byCharWrapping
+ return p
+ }()
+
+ func setFocused(_ value: Bool) {
+ guard focused != value else { return }
+ focused = value
+ render(lines: lastLines, cursor: lastCursor, decorations: lastDecorations, force: true)
+ }
+
+ func setMarkedText(_ value: String) {
+ guard markedText != value else { return }
+ markedText = value
+ render(lines: lastLines, cursor: lastCursor, decorations: lastDecorations, force: true)
+ }
+
+ func activateLink(at index: Int) {
+ guard lastDecorations.links.indices.contains(index) else { return }
+ onOpenLink?(lastDecorations.links[index])
+ }
+
+ /// The 1-based column and screen row under a point in the text view, counting rows from the top of the
+ /// screen below the scrollback.
+ func gridCell(at point: NSPoint) -> (col: Int, row: Int)? {
+ guard let textView else { return nil }
+ let origin = textView.textContainerOrigin
+ let lineIndex = Int(floor((point.y - origin.y) / max(lineHeight, 1)))
+ let column = Int(floor((point.x - origin.x) / max(cellWidth, 1)))
+ guard lineIndex >= 0, column >= 0 else { return nil }
+ let screenTop = lastCursor?.isAlternateScreen == true ? 0 : (lastLines.firstIndex(where: { !$0.isScrollback }) ?? lastLines.count)
+ let row = lineIndex - screenTop + 1
+ guard row >= 1 else { return nil }
+ let maxRow = lastCursor?.rows ?? Int.max
+ let maxColumn = lastCursor?.columns ?? Int.max
+ return (min(column + 1, maxColumn), min(row, maxRow))
+ }
+
+ func render(lines: [TerminalStyledLine], cursor: CodeTerminalCursorState?, decorations: MorphTerminalDecorations, force: Bool) {
+ guard let textView, let scrollView, let storage = textView.textStorage else { return }
+ if !force, lines == lastLines, cursor == lastCursor, decorations == lastDecorations { return }
+ let activeMatchChanged = decorations.activeMatch != lastDecorations.activeMatch
+ || decorations.searchMatches.isEmpty != lastDecorations.searchMatches.isEmpty
+ lastLines = lines
+ lastCursor = cursor
+ lastDecorations = decorations
+
+ let wasAtBottom = isAtBottom(scrollView)
+ let savedSelection = textView.selectedRanges
+ let built = build(lines: lines, cursor: cursor)
+ let highlighted = NSMutableAttributedString(attributedString: built.text)
+ let activeRange = decorate(highlighted, lineStarts: built.lineStarts, decorations: decorations)
+ storage.beginEditing()
+ storage.setAttributedString(highlighted)
+ storage.endEditing()
+ textView.cursorCharacterIndex = built.cursorIndex
+
+ let length = storage.length
+ let restored = savedSelection.compactMap { value -> NSValue? in
+ let range = value.rangeValue
+ guard range.length > 0, NSMaxRange(range) <= length else { return nil }
+ return value
+ }
+ textView.selectedRanges = restored.isEmpty ? [NSValue(range: NSRange(location: min(built.cursorIndex, length), length: 0))] : restored
+
+ if let activeRange, activeMatchChanged {
+ if let container = textView.textContainer {
+ textView.layoutManager?.ensureLayout(for: container)
+ }
+ textView.scrollRangeToVisible(activeRange)
+ } else if wasAtBottom || (force && lastGrid == nil) {
+ if let container = textView.textContainer {
+ textView.layoutManager?.ensureLayout(for: container)
+ }
+ textView.scrollToEndOfDocument(nil)
+ }
+ }
+
+ /// Underlines links and highlights search matches, and returns the range of the active match.
+ private func decorate(_ text: NSMutableAttributedString, lineStarts: [Int], decorations: MorphTerminalDecorations) -> NSRange? {
+ let length = text.length
+ func range(lineIndex: Int, location: Int, length matchLength: Int) -> NSRange? {
+ guard lineStarts.indices.contains(lineIndex) else { return nil }
+ let start = lineStarts[lineIndex] + location
+ guard start >= 0, start < length else { return nil }
+ return NSRange(location: start, length: min(matchLength, length - start))
+ }
+ for (index, link) in decorations.links.enumerated() {
+ guard let linkRange = range(lineIndex: link.lineIndex, location: link.utf16Location, length: link.utf16Length) else { continue }
+ text.addAttributes([
+ .underlineStyle: NSUnderlineStyle.single.rawValue,
+ MorphInteractiveTerminalNSView.linkIndexKey: index,
+ ], range: linkRange)
+ }
+ var activeRange: NSRange?
+ for (index, match) in decorations.searchMatches.enumerated() {
+ guard let matchRange = range(lineIndex: match.lineIndex, location: match.utf16Location, length: match.utf16Length) else { continue }
+ if index == decorations.activeSearchMatchIndex {
+ text.addAttributes([
+ .backgroundColor: MorphTerminalHighlight.activeMatch,
+ .foregroundColor: MorphTerminalHighlight.activeMatchForeground,
+ ], range: matchRange)
+ activeRange = matchRange
+ } else {
+ text.addAttribute(.backgroundColor, value: MorphTerminalHighlight.match, range: matchRange)
+ }
+ }
+ return activeRange
+ }
+
+ private func isAtBottom(_ scrollView: NSScrollView) -> Bool {
+ guard let doc = scrollView.documentView else { return true }
+ let visible = scrollView.contentView.bounds
+ return visible.maxY >= doc.frame.height - lineHeight * 1.5
+ }
+
+ private func build(lines: [TerminalStyledLine], cursor: CodeTerminalCursorState?) -> (text: NSAttributedString, cursorIndex: Int, lineStarts: [Int]) {
+ let out = NSMutableAttributedString()
+ var lineStarts: [Int] = []
+ let cursorLine = MorphTerminalLayout.cursorLineIndex(lines: lines, cursor: cursor)
+ let lineCount = max(lines.count, (cursorLine ?? -1) + 1)
+ var cursorIndex = 0
+ let baseAttributes: [NSAttributedString.Key: Any] = [
+ .font: regularFont,
+ .foregroundColor: MorphTerminalPalette.defaultForeground,
+ .paragraphStyle: paragraph,
+ ]
+ for index in 0.. 0 { out.append(NSAttributedString(string: "\n", attributes: baseAttributes)) }
+ lineStarts.append(out.length)
+ let line = index < lines.count ? lines[index] : TerminalStyledLine(spans: [], isScrollback: false)
+ let isCursorLine = index == cursorLine
+ let segments = MorphTerminalLayout.segments(for: line, cursorCell: isCursorLine ? cursor?.column : nil)
+ for segment in segments {
+ if segment.isCursor {
+ cursorIndex = out.length
+ if !markedText.isEmpty {
+ var marked = baseAttributes
+ marked[.underlineStyle] = NSUnderlineStyle.single.rawValue
+ marked[.backgroundColor] = MorphTerminalPalette.markedTextBackground
+ out.append(NSAttributedString(string: markedText, attributes: marked))
+ }
+ }
+ out.append(NSAttributedString(string: segment.text, attributes: attributes(for: segment)))
+ }
+ }
+ return (out, cursorIndex, lineStarts)
+ }
+
+ private func attributes(for segment: MorphTerminalSegment) -> [NSAttributedString.Key: Any] {
+ let style = segment.style
+ let colors = MorphTerminalPalette.resolve(style, isCursor: segment.isCursor, focused: focused)
+ let font: NSFont
+ switch (style.bold, style.italic) {
+ case (true, true): font = boldItalicFont
+ case (true, false): font = boldFont
+ case (false, true): font = italicFont
+ case (false, false): font = regularFont
+ }
+ var attrs: [NSAttributedString.Key: Any] = [
+ .font: font,
+ .foregroundColor: colors.fg,
+ .paragraphStyle: paragraph,
+ ]
+ if let bg = colors.bg { attrs[.backgroundColor] = bg }
+ if style.underline { attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue }
+ return attrs
+ }
+
+ /// Reports the grid that fits the pane after the size settles for a moment.
+ func scheduleResize() {
+ resizeTask?.cancel()
+ resizeTask = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .milliseconds(160))
+ guard !Task.isCancelled else { return }
+ self?.reportGrid()
+ }
+ }
+
+ private func reportGrid() {
+ guard let scrollView else { return }
+ let size = scrollView.contentSize
+ guard size.width > 40, size.height > 30 else { return }
+ let cols = Int(floor((size.width - Self.inset.width * 2) / max(cellWidth, 1)))
+ let rows = Int(floor((size.height - Self.inset.height * 2) / max(lineHeight, 1)))
+ guard cols > 0, rows > 0 else { return }
+ if let lastGrid, lastGrid.cols == cols, lastGrid.rows == rows { return }
+ lastGrid = (cols, rows)
+ callbacks?.resize(cols, rows)
+ }
+ }
+}
+
+#else
+
+// MARK: - iOS Terminal
+
+/// Touch terminal: styled ANSI lines, a command field, and a key row for Esc, Tab, Ctrl+C, arrows and Clear.
+struct MorphTerminalTouchView: View {
+ let lines: [TerminalStyledLine]
+ let cursor: CodeTerminalCursorState?
+ let isRunning: Bool
+ var decorations: MorphTerminalDecorations = .none
+ var onOpenLink: (@MainActor (TerminalLinkMatch) -> Void)? = nil
+ let onInput: @MainActor (String) -> Void
+ let onResize: @MainActor (Int, Int) -> Void
+ let onClear: @MainActor () -> Void
+
+ @State private var draft = ""
+ @State private var isAtBottom = true
+ @State private var grid: MorphTerminalGrid = MorphTerminalGrid(cols: 0, rows: 0)
+ @FocusState private var fieldFocused: Bool
+
+ private static let font = UIFont.monospacedSystemFont(ofSize: MorphTerminalSurface.fontSize, weight: .regular)
+ private static let cellWidth: CGFloat = ("W" as NSString).size(withAttributes: [.font: font]).width
+ private static let lineHeight: CGFloat = ceil(font.lineHeight)
+ private static let inset: CGFloat = 10
+
+ var body: some View {
+ VStack(spacing: 0) {
+ GeometryReader { geo in
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ let cursorLine = MorphTerminalLayout.cursorLineIndex(lines: lines, cursor: cursor)
+ let count = max(lines.count, (cursorLine ?? -1) + 1)
+ ForEach(0..= g.contentSize.height - Self.lineHeight * 2
+ } action: { _, atBottom in
+ isAtBottom = atBottom
+ }
+ .onChange(of: lines) { _, _ in
+ if isAtBottom, decorations.activeMatch == nil { proxy.scrollTo("terminal-end", anchor: .bottom) }
+ }
+ .onChange(of: decorations.activeMatch) { _, match in
+ guard let match else { return }
+ withAnimation(AnymorphMotion.fast) { proxy.scrollTo(match.lineIndex, anchor: .center) }
+ }
+ .environment(\.openURL, OpenURLAction { url in
+ openTappedLink(url)
+ return .handled
+ })
+ .onTapGesture { fieldFocused = true }
+ }
+ .onAppear { updateGrid(geo.size) }
+ .onChange(of: geo.size) { _, size in updateGrid(size) }
+ }
+ .task(id: grid) {
+ guard grid.cols > 0, grid.rows > 0 else { return }
+ try? await Task.sleep(for: .milliseconds(160))
+ guard !Task.isCancelled else { return }
+ onResize(grid.cols, grid.rows)
+ }
+
+ keyRow
+ inputRow
+ }
+ }
+
+ private func updateGrid(_ size: CGSize) {
+ let cols = Int(floor((size.width - Self.inset * 2) / max(Self.cellWidth, 1)))
+ let rows = Int(floor((size.height - Self.inset * 2) / max(Self.lineHeight, 1)))
+ let next = MorphTerminalGrid(cols: max(cols, 0), rows: max(rows, 0))
+ if next != grid { grid = next }
+ }
+
+ /// Links in the text carry this scheme and the link's index, so a tap opens the link it came from.
+ private static let linkScheme = "morph-terminal-link"
+
+ private func openTappedLink(_ url: URL) {
+ guard url.scheme == Self.linkScheme, let index = Int(url.host() ?? ""), decorations.links.indices.contains(index) else { return }
+ onOpenLink?(decorations.links[index])
+ }
+
+ private func attributed(_ line: TerminalStyledLine, lineIndex: Int, cursorCell: Int?) -> AttributedString {
+ var out = AttributedString()
+ for segment in MorphTerminalLayout.segments(for: line, cursorCell: cursorCell) {
+ var part = AttributedString(segment.text)
+ let style = segment.style
+ let colors = MorphTerminalPalette.resolve(style, isCursor: segment.isCursor, focused: fieldFocused)
+ var font = Font.system(size: MorphTerminalSurface.fontSize, design: .monospaced)
+ if style.bold { font = font.bold() }
+ if style.italic { font = font.italic() }
+ part.font = font
+ part.foregroundColor = Color(uiColor: colors.fg)
+ if let bg = colors.bg { part.backgroundColor = Color(uiColor: bg) }
+ if style.underline { part.underlineStyle = .single }
+ out.append(part)
+ }
+ if out.characters.isEmpty { out = AttributedString(" ") }
+ decorate(&out, lineIndex: lineIndex)
+ return out
+ }
+
+ /// Underlines the line's links and highlights its search matches, by UTF-16 range.
+ private func decorate(_ out: inout AttributedString, lineIndex: Int) {
+ let plain = String(out.characters)
+ func range(location: Int, length: Int) -> Range? {
+ let utf16 = plain.utf16
+ guard location >= 0, location < utf16.count else { return nil }
+ let lower = utf16.index(utf16.startIndex, offsetBy: location)
+ let upper = utf16.index(lower, offsetBy: min(length, utf16.count - location))
+ guard let start = AttributedString.Index(lower, within: out), let end = AttributedString.Index(upper, within: out) else { return nil }
+ return start.. Void) -> some View {
+ Button(action: action) {
+ Text(title)
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary, monospaced: true)
+ .padding(.horizontal, 10)
+ .frame(minHeight: 28)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(AnymorphColor.bgCard)
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous).strokeBorder(AnymorphColor.strokeLight, lineWidth: 1))
+ )
+ }
+ .buttonStyle(.morphPlain)
+ .disabled(!isRunning)
+ }
+
+ private var inputRow: some View {
+ HStack(spacing: 6) {
+ Text("$")
+ .anymorphText(.callout, weight: .strong, color: AnymorphColor.fgTertiary, monospaced: true)
+ TextField("명령어 입력 (Return으로 실행)", text: $draft)
+ .textFieldStyle(.plain)
+ .font(AnymorphFonts.font(.footnote, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .submitLabel(.send)
+ .focused($fieldFocused)
+ .onSubmit(submit)
+ Button(action: submit) {
+ MorphLucideIcon(.cornerDownRight, size: 13)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(!isRunning)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 10)
+ .background(AnymorphColor.bgGrouped)
+ }
+
+ private func submit() {
+ let line = draft
+ draft = ""
+ onInput(line + "\r")
+ fieldFocused = true
+ }
+}
+
+struct MorphTerminalGrid: Equatable, Hashable {
+ let cols: Int
+ let rows: Int
+}
+
+#endif
diff --git a/apple/Apps/Shared/MorphVoiceDictation.swift b/apple/Apps/Shared/MorphVoiceDictation.swift
new file mode 100644
index 000000000..b62d8b822
--- /dev/null
+++ b/apple/Apps/Shared/MorphVoiceDictation.swift
@@ -0,0 +1,895 @@
+import Foundation
+import Observation
+import MorphCore
+#if canImport(AVFoundation)
+import AVFoundation
+#endif
+
+// MARK: - Composer realtime voice dictation (Azure OpenAI gpt-live-transcribe)
+//
+// Starts microphone capture and the Codex-style live waveform immediately on tap while opening the Azure OpenAI
+// Realtime WebSocket in parallel using a cached 2-hour ephemeral client secret. Audio captured during the
+// ~350 ms socket handshake is buffered in memory and flushed in order the instant the socket connects, so
+// dictation feels instantaneous with zero dropped opening syllables.
+
+@MainActor
+@Observable
+final class MorphVoiceDictator {
+ enum Phase: Equatable, Sendable {
+ case idle
+ case connecting
+ case recording
+ case finalizing
+ }
+
+ typealias SessionResolver = @Sendable (_ forceRefresh: Bool) async throws -> (session: VoiceTranscriptionSession, fromCache: Bool)
+
+ /// Current dictation lifecycle phase.
+ private(set) var phase: Phase = .idle
+ /// Rolling normalized microphone levels (0...1) for the Codex-style waveform bar.
+ private(set) var audioLevels: [Double] = Array(repeating: 0, count: MorphVoiceDictator.barCount)
+ /// Whole seconds elapsed since recording started.
+ private(set) var elapsedSeconds: Int = 0
+ /// What the recognizer heard in this recording so far (without the pre-existing composer prefix).
+ private(set) var liveTranscript = ""
+ /// Why dictation could not start or stopped early. The view shows it and clears it.
+ var errorMessage: String?
+
+ var isActive: Bool { phase != .idle }
+ var isRecording: Bool { phase == .recording }
+ var isConnecting: Bool { phase == .connecting }
+ var isFinalizing: Bool { phase == .finalizing }
+
+ static let barCount = 180
+
+ @ObservationIgnored private var onText: (@MainActor (String) -> Void)?
+ @ObservationIgnored private var sessionResolver: SessionResolver?
+ @ObservationIgnored private var activeKeywords: [String] = []
+ @ObservationIgnored private var activePrompt: String?
+ @ObservationIgnored private var accumulator = RealtimeTranscriptAccumulator()
+ @ObservationIgnored private var levelMeter = VoiceLevelMeter(capacity: MorphVoiceDictator.barCount)
+ /// Bumped on every start, confirm, cancel, and stop so stale callbacks from earlier sessions are dropped.
+ @ObservationIgnored private var session = 0
+ @ObservationIgnored private var elapsedTask: Task?
+ @ObservationIgnored private var finalizeTimeoutTask: Task?
+ @ObservationIgnored private var bytesSinceLastCommit: Int = 0
+ @ObservationIgnored private var secondsSinceLastCommit: Int = 0
+ @ObservationIgnored private var usedCachedSession = false
+ @ObservationIgnored private var hasReceivedSessionCreated = false
+ @ObservationIgnored private var hasRetriedFreshSession = false
+
+ #if canImport(AVFoundation)
+ private nonisolated let pipeline = MorphRealtimeAudioPipeline()
+ #endif
+
+ init() {}
+
+ deinit {
+ #if canImport(AVFoundation)
+ pipeline.teardown()
+ #endif
+ }
+
+ /// Starts realtime dictation (appending after `baseText`), or confirms if already active.
+ func start(
+ baseText: String,
+ keywords: [String] = [],
+ prompt: String? = nil,
+ requestSession: @escaping SessionResolver,
+ onText: @escaping @MainActor (String) -> Void
+ ) {
+ if isActive {
+ confirm()
+ return
+ }
+ errorMessage = nil
+ liveTranscript = ""
+ elapsedSeconds = 0
+ bytesSinceLastCommit = 0
+ secondsSinceLastCommit = 0
+ usedCachedSession = false
+ hasReceivedSessionCreated = false
+ hasRetriedFreshSession = false
+ activeKeywords = keywords
+ activePrompt = prompt
+ sessionResolver = requestSession
+ accumulator = RealtimeTranscriptAccumulator(baseText: baseText)
+ levelMeter.reset()
+ audioLevels = levelMeter.bars
+ self.onText = onText
+ session += 1
+ let current = session
+
+ // Fast path: when mic permission is already granted, open capture and live UI immediately with zero wait.
+ if Self.isMicrophoneAuthorizedSynchronously() {
+ beginCaptureAndConnect(session: current, forceRefresh: false)
+ return
+ }
+
+ phase = .connecting
+ Task { [weak self] in
+ if let permissionFailure = await Self.authorizeMicrophone() {
+ guard let self, self.session == current else { return }
+ self.fail(permissionFailure, preserveTranscript: false)
+ return
+ }
+ guard let self, self.session == current else { return }
+ self.beginCaptureAndConnect(session: current, forceRefresh: false)
+ }
+ }
+
+ /// Finishes recording, commits the final audio turn for punctuation/polish, and keeps the transcript.
+ func confirm() {
+ switch phase {
+ case .idle:
+ return
+ case .connecting:
+ cancel()
+ case .finalizing:
+ finishKeepingTranscript()
+ case .recording:
+ let current = session
+ elapsedTask?.cancel()
+ elapsedTask = nil
+ #if canImport(AVFoundation)
+ pipeline.stopCaptureOnly()
+ #endif
+
+ guard bytesSinceLastCommit > 0 else {
+ finishKeepingTranscript()
+ return
+ }
+
+ phase = .finalizing
+ #if canImport(AVFoundation)
+ pipeline.commitTurn(withTrailingSilenceMs: 240)
+ #endif
+ bytesSinceLastCommit = 0
+ secondsSinceLastCommit = 0
+
+ finalizeTimeoutTask?.cancel()
+ finalizeTimeoutTask = Task { [weak self] in
+ try? await Task.sleep(for: .milliseconds(4000))
+ guard let self, self.session == current, self.phase == .finalizing else { return }
+ self.finishKeepingTranscript()
+ }
+ }
+ }
+
+ /// Cancels recording immediately and restores whatever text was in the composer before dictation started.
+ func cancel() {
+ let base = accumulator.baseText
+ let handler = onText
+ let shouldRestore = phase != .idle
+ teardownState()
+ if shouldRestore {
+ handler?(base)
+ }
+ }
+
+ /// Stops recording immediately (e.g. thread switch or submit), keeping whatever text has already streamed.
+ func stop() {
+ guard phase != .idle else { return }
+ teardownState()
+ }
+
+ // MARK: - Instant Capture + Parallel WebSocket Attach
+
+ #if canImport(AVFoundation)
+ private func beginCaptureAndConnect(session current: Int, forceRefresh: Bool) {
+ guard Self.hasMicrophoneUsageDescription() else {
+ fail("앱에 마이크 권한 설명이 없어 받아쓰기를 시작할 수 없습니다.", preserveTranscript: false)
+ return
+ }
+ do {
+ try pipeline.startCapture(
+ targetSampleRate: 24000.0,
+ onAudioChunk: { [weak self] byteCount, level in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ self?.receiveAudioMetrics(session: current, byteCount: byteCount, level: level)
+ }
+ }
+ }
+ )
+ phase = .recording
+ startElapsedClock(session: current)
+ } catch {
+ pipeline.teardown()
+ fail("실시간 음성 인식을 시작하지 못했습니다. \(error.localizedDescription)", preserveTranscript: false)
+ return
+ }
+
+ connectWebSocket(session: current, forceRefresh: forceRefresh)
+ }
+
+ private func connectWebSocket(session current: Int, forceRefresh: Bool) {
+ guard let resolver = sessionResolver else { return }
+ let keywords = activeKeywords
+ let prompt = activePrompt
+
+ Task { [weak self] in
+ let resolved: (session: VoiceTranscriptionSession, fromCache: Bool)
+ do {
+ resolved = try await resolver(forceRefresh)
+ } catch {
+ guard let self, self.session == current else { return }
+ self.fail(Self.friendlySessionError(error), preserveTranscript: !self.liveTranscript.isEmpty)
+ return
+ }
+
+ guard let self, self.session == current, self.phase == .recording || self.phase == .finalizing else { return }
+ guard let url = URL(string: resolved.session.wsUrl) else {
+ self.fail("음성 인식 서버 주소가 올바르지 않습니다.", preserveTranscript: !self.liveTranscript.isEmpty)
+ return
+ }
+
+ self.usedCachedSession = resolved.fromCache
+ self.hasReceivedSessionCreated = false
+ let sessionUpdateJSON = RealtimeSessionUpdateEncoder.encode(
+ model: resolved.session.model,
+ sampleRate: resolved.session.sampleRate,
+ languages: ["ko", "en"],
+ keywords: keywords,
+ prompt: prompt
+ )
+ self.pipeline.attachWebSocket(
+ wsURL: url,
+ clientSecret: resolved.session.clientSecret,
+ sessionUpdateJSON: sessionUpdateJSON,
+ onEvent: { [weak self] event in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ self?.receiveEvent(session: current, event: event)
+ }
+ }
+ },
+ onDisconnect: { [weak self] message in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ self?.receiveDisconnect(session: current, message: message)
+ }
+ }
+ }
+ )
+ }
+ }
+ #else
+ private func beginCaptureAndConnect(session current: Int, forceRefresh: Bool) {
+ fail("이 기기에서는 실시간 받아쓰기를 지원하지 않습니다.", preserveTranscript: false)
+ }
+ #endif
+
+ private func startElapsedClock(session current: Int) {
+ elapsedTask?.cancel()
+ elapsedTask = Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(1))
+ guard !Task.isCancelled, let self, self.session == current, self.phase == .recording else { break }
+ self.elapsedSeconds += 1
+ self.secondsSinceLastCommit += 1
+ // Safeguard very long continuous recordings so turns commit cleanly without hitting buffer caps.
+ if self.secondsSinceLastCommit >= 80, self.bytesSinceLastCommit > 0 {
+ #if canImport(AVFoundation)
+ self.pipeline.commitTurn(withTrailingSilenceMs: 0)
+ #endif
+ self.bytesSinceLastCommit = 0
+ self.secondsSinceLastCommit = 0
+ }
+ }
+ }
+ }
+
+ private func receiveAudioMetrics(session current: Int, byteCount: Int, level: Double) {
+ guard current == session, phase == .recording else { return }
+ bytesSinceLastCommit += byteCount
+ levelMeter.push(level: level)
+ audioLevels = levelMeter.bars
+ // Soft mid-recording commit during a quiet breath after 50s of speech to keep latency snappy.
+ if secondsSinceLastCommit >= 50, level < 0.05, bytesSinceLastCommit > 0 {
+ #if canImport(AVFoundation)
+ self.pipeline.commitTurn(withTrailingSilenceMs: 0)
+ #endif
+ bytesSinceLastCommit = 0
+ secondsSinceLastCommit = 0
+ }
+ }
+
+ private func receiveEvent(session current: Int, event: RealtimeTranscriptionEvent) {
+ guard current == session, phase == .recording || phase == .finalizing else { return }
+ if case .sessionCreated = event {
+ hasReceivedSessionCreated = true
+ #if canImport(AVFoundation)
+ pipeline.markSessionEstablished()
+ #endif
+ }
+ if let errMessage = accumulator.apply(event) {
+ fail("음성 인식 오류: \(errMessage)", preserveTranscript: !liveTranscript.isEmpty)
+ return
+ }
+ let updated = accumulator.transcript
+ if updated != liveTranscript {
+ liveTranscript = updated
+ onText?(accumulator.composedText)
+ }
+ if case .completed = event, phase == .finalizing, accumulator.pendingItemCount == 0 {
+ finishKeepingTranscript()
+ }
+ }
+
+ private func receiveDisconnect(session current: Int, message: String?) {
+ guard current == session else { return }
+ // If a cached ephemeral secret expired early before handshake completed, refresh once transparently
+ // while keeping every buffered audio chunk intact.
+ #if canImport(AVFoundation)
+ if usedCachedSession, !hasReceivedSessionCreated, !hasRetriedFreshSession,
+ phase == .recording || phase == .finalizing {
+ hasRetriedFreshSession = true
+ usedCachedSession = false
+ pipeline.requeueUnackedAudioForReconnect()
+ connectWebSocket(session: current, forceRefresh: true)
+ return
+ }
+ #endif
+ switch phase {
+ case .idle:
+ return
+ case .finalizing:
+ finishKeepingTranscript()
+ case .connecting, .recording:
+ let reason = (message?.isEmpty == false) ? message! : "실시간 음성 연결이 끊어졌습니다."
+ fail(reason, preserveTranscript: !liveTranscript.isEmpty)
+ }
+ }
+
+ private func finishKeepingTranscript() {
+ let finalText = accumulator.composedText
+ let handler = onText
+ teardownState()
+ handler?(finalText)
+ }
+
+ private func fail(_ message: String, preserveTranscript: Bool) {
+ let restoreText = preserveTranscript ? nil : accumulator.baseText
+ let handler = onText
+ teardownState()
+ if let restoreText {
+ handler?(restoreText)
+ }
+ errorMessage = message
+ }
+
+ private func teardownState() {
+ session += 1
+ phase = .idle
+ elapsedSeconds = 0
+ bytesSinceLastCommit = 0
+ secondsSinceLastCommit = 0
+ usedCachedSession = false
+ hasReceivedSessionCreated = false
+ hasRetriedFreshSession = false
+ elapsedTask?.cancel()
+ elapsedTask = nil
+ finalizeTimeoutTask?.cancel()
+ finalizeTimeoutTask = nil
+ onText = nil
+ sessionResolver = nil
+ levelMeter.reset()
+ audioLevels = levelMeter.bars
+ #if canImport(AVFoundation)
+ pipeline.teardown()
+ #endif
+ }
+
+ private static func friendlySessionError(_ error: Error) -> String {
+ if case let SyncError.httpStatus(code, body) = error {
+ if code == 503 || body?.contains("voice_transcription_not_configured") == true {
+ return "서버에 Azure 실시간 음성 인식이 설정되지 않았습니다."
+ }
+ if code == 401 || code == 403 {
+ return "로그인 세션을 확인한 뒤 음성 인식을 다시 시도해 주세요."
+ }
+ }
+ return "실시간 음성 인식 세션을 열지 못했습니다. \(error.localizedDescription)"
+ }
+
+ // MARK: - Microphone Permission
+
+ nonisolated private static func hasMicrophoneUsageDescription() -> Bool {
+ let info = Bundle.main.infoDictionary ?? [:]
+ return info["NSMicrophoneUsageDescription"] != nil
+ }
+
+ nonisolated private static func isMicrophoneAuthorizedSynchronously() -> Bool {
+ #if canImport(AVFoundation)
+ guard hasMicrophoneUsageDescription() else { return false }
+ #if os(macOS)
+ return AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
+ #else
+ return AVAudioApplication.shared.recordPermission == .granted
+ #endif
+ #else
+ return false
+ #endif
+ }
+
+ nonisolated private static func authorizeMicrophone() async -> String? {
+ #if canImport(AVFoundation)
+ guard hasMicrophoneUsageDescription() else {
+ return "앱에 마이크 권한 설명이 없어 받아쓰기를 시작할 수 없습니다."
+ }
+ let granted = await microphoneAuthorization()
+ guard granted else {
+ #if os(macOS)
+ return "마이크 권한이 꺼져 있습니다. 시스템 설정 > 개인정보 보호 및 보안 > 마이크에서 Morph를 허용해 주세요."
+ #else
+ return "마이크 권한이 꺼져 있습니다. 설정 > Morph에서 마이크 접근을 허용해 주세요."
+ #endif
+ }
+ return nil
+ #else
+ return "이 기기에서는 받아쓰기를 지원하지 않습니다."
+ #endif
+ }
+
+ #if canImport(AVFoundation)
+ nonisolated private static func microphoneAuthorization() async -> Bool {
+ #if os(macOS)
+ switch AVCaptureDevice.authorizationStatus(for: .audio) {
+ case .authorized:
+ return true
+ case .notDetermined:
+ return await AVCaptureDevice.requestAccess(for: .audio)
+ default:
+ return false
+ }
+ #else
+ switch AVAudioApplication.shared.recordPermission {
+ case .granted:
+ return true
+ case .undetermined:
+ return await AVAudioApplication.requestRecordPermission()
+ default:
+ return false
+ }
+ #endif
+ }
+ #endif
+}
+
+#if DEBUG
+@MainActor
+@Observable
+final class MorphVoiceDictationQA {
+ static let shared = MorphVoiceDictationQA()
+ var overrideState: MorphComposerDictation?
+}
+#endif
+
+// MARK: - Off-Main-Actor Instant Capture + Pre-Buffered Realtime WebSocket Pipeline
+
+#if canImport(AVFoundation)
+/// Owns `AVAudioEngine`, 24 kHz mono PCM16 `AVAudioConverter`, a bounded pre-buffer queue, and a shared
+/// persistent `URLSession` (for warm TLS session resumption across consecutive Azure Realtime recordings).
+final class MorphRealtimeAudioPipeline: @unchecked Sendable {
+ enum Failure: LocalizedError {
+ case noInput
+ case converterUnavailable
+
+ var errorDescription: String? {
+ switch self {
+ case .noInput: return "사용할 수 있는 마이크 입력이 없습니다."
+ case .converterUnavailable: return "오디오 포맷 변환기를 초기화하지 못했습니다."
+ }
+ }
+ }
+
+ /// Reused across recordings so TLS session tickets to Azure stay warm (~350ms vs ~950ms cold).
+ private let sharedURLSession: URLSession = {
+ let config = URLSessionConfiguration.default
+ config.waitsForConnectivity = false
+ config.httpMaximumConnectionsPerHost = 2
+ return URLSession(configuration: config)
+ }()
+
+ private let lock = NSLock()
+ private var engine: AVAudioEngine?
+ private var wsTask: URLSessionWebSocketTask?
+ private var chunker: MorphPCMChunker?
+ private var receiveTask: Task?
+ private var targetSampleRate: Double = 24000
+ private var activeGeneration: Int = 0
+ private var wsGeneration: Int = 0
+ private var isCapturing = false
+ private var isSessionEstablished = false
+ private var pendingQueue = RealtimeAudioChunkQueue()
+ /// Copy of chunks transmitted before `session.created`, kept briefly so a stale cached token can retry losslessly.
+ private var unackedPreSessionChunks: [Data] = []
+ private var unackedPreSessionCommitSilenceMs: Int?
+
+ deinit {
+ teardown()
+ sharedURLSession.invalidateAndCancel()
+ }
+
+ /// Starts microphone capture immediately, buffering PCM16 chunks until `attachWebSocket` connects.
+ func startCapture(
+ targetSampleRate: Double,
+ onAudioChunk: @escaping @Sendable (_ byteCount: Int, _ level: Double) -> Void
+ ) throws {
+ teardown()
+ #if os(iOS)
+ let audioSession = AVAudioSession.sharedInstance()
+ try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)
+ try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
+ #endif
+
+ let engine = AVAudioEngine()
+ let input = engine.inputNode
+ let inputFormat = input.outputFormat(forBus: 0)
+ guard inputFormat.sampleRate > 0, inputFormat.channelCount > 0 else {
+ throw Failure.noInput
+ }
+ guard let outputFormat = AVAudioFormat(
+ commonFormat: .pcmFormatInt16,
+ sampleRate: targetSampleRate,
+ channels: 1,
+ interleaved: true
+ ), let converter = AVAudioConverter(from: inputFormat, to: outputFormat) else {
+ throw Failure.converterUnavailable
+ }
+
+ let generation: Int = lock.withLock {
+ activeGeneration += 1
+ wsGeneration += 1
+ self.engine = engine
+ self.targetSampleRate = targetSampleRate
+ self.isCapturing = true
+ self.isSessionEstablished = false
+ self.pendingQueue.reset()
+ self.unackedPreSessionChunks.removeAll(keepingCapacity: false)
+ self.unackedPreSessionCommitSilenceMs = nil
+ return activeGeneration
+ }
+
+ let chunker = MorphPCMChunker(
+ converter: converter,
+ outputFormat: outputFormat,
+ chunkByteSize: Int(targetSampleRate * 2 * 0.08) // ~80ms chunks (~3840 bytes)
+ ) { [weak self] chunk, level in
+ self?.handleCapturedChunk(generation: generation, chunk: chunk, level: level, onAudioChunk: onAudioChunk)
+ }
+ lock.withLock {
+ if activeGeneration == generation {
+ self.chunker = chunker
+ }
+ }
+
+ input.installTap(onBus: 0, bufferSize: 1024, format: inputFormat) { buffer, _ in
+ chunker.process(buffer)
+ }
+ engine.prepare()
+ do {
+ try engine.start()
+ } catch {
+ input.removeTap(onBus: 0)
+ teardown()
+ throw error
+ }
+ }
+
+ /// Opens the Azure Realtime WebSocket, configures dynamic keywords, and immediately flushes any buffered audio.
+ func attachWebSocket(
+ wsURL: URL,
+ clientSecret: String,
+ sessionUpdateJSON: String?,
+ onEvent: @escaping @Sendable (RealtimeTranscriptionEvent) -> Void,
+ onDisconnect: @escaping @Sendable (_ message: String?) -> Void
+ ) {
+ var request = URLRequest(url: wsURL)
+ request.setValue("Bearer \(clientSecret)", forHTTPHeaderField: "Authorization")
+ let wsTask = sharedURLSession.webSocketTask(with: request)
+
+ let drained: (chunks: [Data], commitSilenceMs: Int?)
+ let sampleRate: Double
+ let currentWsGen: Int
+ let previousTask: URLSessionWebSocketTask?
+ let previousReceive: Task?
+
+ let snapshot: (URLSessionWebSocketTask?, Task?, Int, Double, ([Data], Int?)) = lock.withLock {
+ let oldTask = self.wsTask
+ let oldReceive = self.receiveTask
+ self.wsGeneration += 1
+ self.wsTask = wsTask
+ self.isSessionEstablished = false
+ let d = self.pendingQueue.drain()
+ self.unackedPreSessionChunks.append(contentsOf: d.chunks)
+ if let silenceMs = d.commitSilenceMs {
+ self.unackedPreSessionCommitSilenceMs = silenceMs
+ }
+ return (oldTask, oldReceive, self.wsGeneration, self.targetSampleRate, (d.chunks, d.commitSilenceMs))
+ }
+ previousTask = snapshot.0
+ previousReceive = snapshot.1
+ currentWsGen = snapshot.2
+ sampleRate = snapshot.3
+ drained = snapshot.4
+
+ previousReceive?.cancel()
+ previousTask?.cancel(with: .goingAway, reason: nil)
+
+ wsTask.resume()
+ if let sessionUpdateJSON {
+ wsTask.send(.string(sessionUpdateJSON)) { _ in }
+ }
+ for chunk in drained.chunks {
+ Self.sendPCMChunk(chunk, over: wsTask)
+ }
+ if let silenceMs = drained.commitSilenceMs {
+ Self.sendCommit(trailingSilenceMs: silenceMs, sampleRate: sampleRate, over: wsTask)
+ }
+
+ let receiveTask = Task.detached(priority: .userInitiated) { [weak self] in
+ while !Task.isCancelled {
+ do {
+ let message = try await wsTask.receive()
+ guard let self, self.isCurrentWS(currentWsGen) else { return }
+ let payloadData: Data
+ switch message {
+ case .string(let text):
+ payloadData = Data(text.utf8)
+ case .data(let data):
+ payloadData = data
+ @unknown default:
+ continue
+ }
+ let event = RealtimeTranscriptionEvent.parse(data: payloadData)
+ onEvent(event)
+ } catch {
+ guard let self, self.isCurrentWS(currentWsGen) else { return }
+ if !Task.isCancelled {
+ onDisconnect(error.localizedDescription)
+ }
+ return
+ }
+ }
+ }
+ lock.withLock {
+ if self.wsGeneration == currentWsGen {
+ self.receiveTask = receiveTask
+ } else {
+ receiveTask.cancel()
+ }
+ }
+ }
+
+ func markSessionEstablished() {
+ lock.withLock {
+ isSessionEstablished = true
+ unackedPreSessionChunks.removeAll(keepingCapacity: false)
+ unackedPreSessionCommitSilenceMs = nil
+ }
+ }
+
+ /// Moves any chunks sent before `session.created` back to the front of the queue so a fresh secret reconnects cleanly.
+ func requeueUnackedAudioForReconnect() {
+ let old: (URLSessionWebSocketTask?, Task?) = lock.withLock {
+ wsGeneration += 1
+ let prevTask = wsTask
+ let prevReceive = receiveTask
+ wsTask = nil
+ receiveTask = nil
+ isSessionEstablished = false
+
+ let alreadyQueued = pendingQueue.drain()
+ pendingQueue.reset()
+ for chunk in unackedPreSessionChunks {
+ pendingQueue.enqueue(chunk)
+ }
+ for chunk in alreadyQueued.chunks {
+ pendingQueue.enqueue(chunk)
+ }
+ if let silenceMs = alreadyQueued.commitSilenceMs ?? unackedPreSessionCommitSilenceMs {
+ pendingQueue.markCommit(trailingSilenceMs: silenceMs)
+ }
+ unackedPreSessionChunks.removeAll(keepingCapacity: false)
+ unackedPreSessionCommitSilenceMs = nil
+ return (prevTask, prevReceive)
+ }
+ old.1?.cancel()
+ old.0?.cancel(with: .goingAway, reason: nil)
+ }
+
+ /// Stops microphone capture immediately while keeping the WebSocket open for final commit results.
+ func stopCaptureOnly() {
+ let taken: (AVAudioEngine?, MorphPCMChunker?) = lock.withLock {
+ guard isCapturing else { return (nil, nil) }
+ isCapturing = false
+ let current = (engine, chunker)
+ engine = nil
+ chunker = nil
+ return current
+ }
+ if let engineToStop = taken.0 {
+ engineToStop.inputNode.removeTap(onBus: 0)
+ engineToStop.stop()
+ #if os(iOS)
+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ #endif
+ }
+ taken.1?.flush()
+ }
+
+ /// Flushes optional trailing silence and commits the buffered audio turn (or queues the commit if still connecting).
+ func commitTurn(withTrailingSilenceMs silenceMs: Int) {
+ let snapshot: (URLSessionWebSocketTask?, Double) = lock.withLock {
+ if let wsTask {
+ if !isSessionEstablished {
+ unackedPreSessionCommitSilenceMs = silenceMs
+ }
+ return (wsTask, targetSampleRate)
+ }
+ pendingQueue.markCommit(trailingSilenceMs: silenceMs)
+ return (nil, targetSampleRate)
+ }
+ guard let wsTask = snapshot.0 else { return }
+ Self.sendCommit(trailingSilenceMs: silenceMs, sampleRate: snapshot.1, over: wsTask)
+ }
+
+ /// Stops audio capture, closes active WebSocket, and cancels receive tasks while keeping the shared URLSession warm.
+ func teardown() {
+ let parts: (AVAudioEngine?, URLSessionWebSocketTask?, Task?, Bool) = lock.withLock {
+ activeGeneration += 1
+ wsGeneration += 1
+ let taken = (engine, wsTask, receiveTask, isCapturing)
+ engine = nil
+ wsTask = nil
+ chunker = nil
+ receiveTask = nil
+ isCapturing = false
+ isSessionEstablished = false
+ pendingQueue.reset()
+ unackedPreSessionChunks.removeAll(keepingCapacity: false)
+ unackedPreSessionCommitSilenceMs = nil
+ return taken
+ }
+ parts.2?.cancel()
+ if let engine = parts.0 {
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ }
+ if let wsTask = parts.1 {
+ wsTask.cancel(with: .normalClosure, reason: nil)
+ }
+ #if os(iOS)
+ if parts.3 {
+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ }
+ #endif
+ }
+
+ private func handleCapturedChunk(
+ generation: Int,
+ chunk: Data,
+ level: Double,
+ onAudioChunk: @escaping @Sendable (_ byteCount: Int, _ level: Double) -> Void
+ ) {
+ let activeSocket: URLSessionWebSocketTask? = lock.withLock {
+ guard activeGeneration == generation else { return nil }
+ if let wsTask {
+ if !isSessionEstablished {
+ unackedPreSessionChunks.append(chunk)
+ }
+ return wsTask
+ }
+ pendingQueue.enqueue(chunk)
+ return nil
+ }
+ if let activeSocket {
+ Self.sendPCMChunk(chunk, over: activeSocket)
+ }
+ onAudioChunk(chunk.count, level)
+ }
+
+ private func isCurrentWS(_ generation: Int) -> Bool {
+ lock.withLock { wsGeneration == generation }
+ }
+
+ private static func sendPCMChunk(_ chunk: Data, over wsTask: URLSessionWebSocketTask) {
+ let b64 = chunk.base64EncodedString()
+ let json = #"{"type":"input_audio_buffer.append","audio":"\#(b64)"}"#
+ wsTask.send(.string(json)) { _ in }
+ }
+
+ private static func sendCommit(trailingSilenceMs silenceMs: Int, sampleRate: Double, over wsTask: URLSessionWebSocketTask) {
+ if silenceMs > 0 {
+ let silenceBytes = Int(sampleRate * 2.0 * (Double(silenceMs) / 1000.0))
+ if silenceBytes > 0 {
+ let b64 = Data(repeating: 0, count: silenceBytes).base64EncodedString()
+ let appendJSON = #"{"type":"input_audio_buffer.append","audio":"\#(b64)"}"#
+ wsTask.send(.string(appendJSON)) { _ in }
+ }
+ }
+ wsTask.send(.string(#"{"type":"input_audio_buffer.commit"}"#)) { _ in }
+ }
+}
+
+/// Resamples Core Audio buffers to 24 kHz mono PCM16, measures speech RMS level, and emits fixed-duration chunks.
+private final class MorphPCMChunker: @unchecked Sendable {
+ private let converter: AVAudioConverter
+ private let outputFormat: AVAudioFormat
+ private let chunkByteSize: Int
+ private let onChunk: @Sendable (Data, Double) -> Void
+ private let lock = NSLock()
+ private var pending = Data()
+
+ init(
+ converter: AVAudioConverter,
+ outputFormat: AVAudioFormat,
+ chunkByteSize: Int,
+ onChunk: @escaping @Sendable (Data, Double) -> Void
+ ) {
+ self.converter = converter
+ self.outputFormat = outputFormat
+ self.chunkByteSize = max(960, chunkByteSize)
+ self.onChunk = onChunk
+ }
+
+ func process(_ inputBuffer: AVAudioPCMBuffer) {
+ let ratio = outputFormat.sampleRate / inputBuffer.format.sampleRate
+ let outFrames = AVAudioFrameCount(ceil(Double(inputBuffer.frameLength) * ratio)) + 32
+ guard outFrames > 0,
+ let converted = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: outFrames) else {
+ return
+ }
+
+ var provided = false
+ var error: NSError?
+ let status = converter.convert(to: converted, error: &error) { _, outStatus in
+ if provided {
+ outStatus.pointee = .noDataNow
+ return nil
+ }
+ provided = true
+ outStatus.pointee = .haveData
+ return inputBuffer
+ }
+ guard error == nil,
+ status == .haveData || status == .inputRanDry,
+ converted.frameLength > 0,
+ let channelData = converted.int16ChannelData else {
+ return
+ }
+
+ let byteCount = Int(converted.frameLength) * MemoryLayout.size
+ let pcmData = Data(bytes: channelData[0], count: byteCount)
+ let chunk: Data? = lock.withLock {
+ pending.append(pcmData)
+ guard pending.count >= chunkByteSize else { return nil }
+ let ready = pending
+ pending = Data()
+ return ready
+ }
+ if let chunk {
+ emit(chunk)
+ }
+ }
+
+ func flush() {
+ let remaining: Data? = lock.withLock {
+ guard !pending.isEmpty else { return nil }
+ let ready = pending
+ pending = Data()
+ return ready
+ }
+ if let remaining {
+ emit(remaining)
+ }
+ }
+
+ private func emit(_ chunk: Data) {
+ let level = VoiceLevelMeter.normalizedLevel(pcm16Data: chunk)
+ onChunk(chunk, level)
+ }
+}
+#endif
diff --git a/apple/Apps/Shared/MorphWebPreviewView.swift b/apple/Apps/Shared/MorphWebPreviewView.swift
new file mode 100644
index 000000000..118f2f990
--- /dev/null
+++ b/apple/Apps/Shared/MorphWebPreviewView.swift
@@ -0,0 +1,1080 @@
+import SwiftUI
+import WebKit
+import MorphCore
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// The page width the preview lays out at.
+enum MorphPreviewViewport: String, CaseIterable, Identifiable, Hashable {
+ case desktop
+ case tablet
+ case mobile
+
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .desktop: return "Desktop"
+ case .tablet: return "Tablet"
+ case .mobile: return "Mobile"
+ }
+ }
+
+ /// The fixed page width in points, or nil to fill the pane.
+ var width: CGFloat? {
+ switch self {
+ case .desktop: return nil
+ case .tablet: return 768
+ case .mobile: return 390
+ }
+ }
+}
+
+/// Appearance override for the preview web view (system, light, or dark).
+enum MorphPreviewAppearance: String, CaseIterable, Identifiable, Hashable {
+ case system
+ case light
+ case dark
+
+ var id: String { rawValue }
+
+ var next: Self {
+ switch self {
+ case .system: return .light
+ case .light: return .dark
+ case .dark: return .system
+ }
+ }
+
+ var title: String {
+ switch self {
+ case .system: return "시스템"
+ case .light: return "라이트"
+ case .dark: return "다크"
+ }
+ }
+
+ var icon: String {
+ switch self {
+ case .system: return "circle.lefthalf.filled"
+ case .light: return "sun.max"
+ case .dark: return "moon"
+ }
+ }
+}
+
+// MARK: - Model
+
+/// Navigation state of the preview's web view and the commands the toolbar sends to it.
+@MainActor
+@Observable
+final class MorphWebPreviewModel {
+ private(set) var canGoBack = false
+ private(set) var canGoForward = false
+ private(set) var isLoading = false
+ private(set) var currentURL = ""
+ private(set) var loadError: String?
+ var isPickerActive = false
+
+ /// The address last asked for, so a saved address that comes back unchanged does not load the page twice.
+ @ObservationIgnored private(set) var requestedURL = ""
+ @ObservationIgnored private weak var webView: WKWebView?
+ @ObservationIgnored private var pendingURL: URL?
+ @ObservationIgnored private var observations: [NSKeyValueObservation] = []
+
+ static let mobileUserAgent =
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
+
+ func attach(_ webView: WKWebView) {
+ self.webView = webView
+ observations = [
+ webView.observe(\.canGoBack, options: [.initial, .new]) { [weak self] view, _ in
+ MainActor.assumeIsolated { self?.syncNavigation(from: view) }
+ },
+ webView.observe(\.canGoForward, options: [.new]) { [weak self] view, _ in
+ MainActor.assumeIsolated { self?.syncNavigation(from: view) }
+ },
+ webView.observe(\.isLoading, options: [.new]) { [weak self] view, _ in
+ MainActor.assumeIsolated { self?.syncNavigation(from: view) }
+ },
+ webView.observe(\.url, options: [.new]) { [weak self] view, _ in
+ MainActor.assumeIsolated { self?.syncNavigation(from: view) }
+ },
+ ]
+ if let pendingURL {
+ self.pendingURL = nil
+ webView.load(URLRequest(url: pendingURL))
+ }
+ }
+
+ func detach() {
+ observations.forEach { $0.invalidate() }
+ observations = []
+ webView?.stopLoading()
+ webView = nil
+ }
+
+ private func syncNavigation(from view: WKWebView) {
+ canGoBack = view.canGoBack
+ canGoForward = view.canGoForward
+ isLoading = view.isLoading
+ if let url = view.url?.absoluteString, !url.isEmpty, url != "about:blank" {
+ currentURL = url
+ }
+ }
+
+ func load(_ url: URL) {
+ requestedURL = url.absoluteString
+ loadError = nil
+ guard let webView else {
+ pendingURL = url
+ return
+ }
+ webView.load(URLRequest(url: url))
+ }
+
+ func goBack() { webView?.goBack() }
+ func goForward() { webView?.goForward() }
+
+ func reload() {
+ loadError = nil
+ guard let webView else { return }
+ if webView.url == nil, let url = URL(string: requestedURL) {
+ webView.load(URLRequest(url: url))
+ } else {
+ webView.reload()
+ }
+ }
+
+ func setUserAgent(mobile: Bool) {
+ let agent = mobile ? Self.mobileUserAgent : nil
+ guard let webView, webView.customUserAgent != agent else { return }
+ webView.customUserAgent = agent
+ if webView.url != nil { webView.reload() }
+ }
+
+ @ObservationIgnored private var currentAppearance: MorphPreviewAppearance = .system
+
+ func setAppearance(_ appearance: MorphPreviewAppearance) {
+ currentAppearance = appearance
+ guard let webView else { return }
+ #if os(macOS)
+ switch appearance {
+ case .system: webView.appearance = nil
+ case .light: webView.appearance = NSAppearance(named: .aqua)
+ case .dark: webView.appearance = NSAppearance(named: .darkAqua)
+ }
+ #else
+ switch appearance {
+ case .system: webView.overrideUserInterfaceStyle = .unspecified
+ case .light: webView.overrideUserInterfaceStyle = .light
+ case .dark: webView.overrideUserInterfaceStyle = .dark
+ }
+ #endif
+ let schemeValue: String = switch appearance {
+ case .system: ""
+ case .light: "light"
+ case .dark: "dark"
+ }
+ let js = """
+ (function(){
+ var root = document.documentElement;
+ if (!root) return;
+ root.style.colorScheme = '\(schemeValue)';
+ if ('\(schemeValue)' === 'dark') { root.classList.add('dark'); root.dataset.theme = 'dark'; }
+ else if ('\(schemeValue)' === 'light') { root.classList.remove('dark'); root.dataset.theme = 'light'; }
+ })();
+ """
+ webView.evaluateJavaScript(js, completionHandler: nil)
+ }
+
+ func setPicker(_ active: Bool) {
+ isPickerActive = active
+ applyPicker()
+ }
+
+ /// Turns the element picker in the page on or off; a new page starts with it off.
+ func applyPicker() {
+ let flag = isPickerActive ? "true" : "false"
+ webView?.evaluateJavaScript("window.__morphSetPickerActive && window.__morphSetPickerActive(\(flag));", completionHandler: nil)
+ }
+
+ func didFail(_ error: Error) {
+ let nsError = error as NSError
+ // A new navigation that cancels the current one is not a failure.
+ guard nsError.code != NSURLErrorCancelled else { return }
+ loadError = nsError.localizedDescription
+ }
+
+ func didFinish() {
+ loadError = nil
+ if isPickerActive { applyPicker() }
+ if currentAppearance != .system { setAppearance(currentAppearance) }
+ }
+
+ /// A PNG of what the web view shows.
+ func snapshotPNG() async -> Data? {
+ guard let webView else { return nil }
+ return await withCheckedContinuation { continuation in
+ webView.takeSnapshot(with: nil) { image, _ in
+ continuation.resume(returning: image.flatMap(Self.pngData))
+ }
+ }
+ }
+
+ #if os(macOS)
+ nonisolated static func pngData(_ image: NSImage) -> Data? {
+ guard let tiff = image.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return nil }
+ return rep.representation(using: .png, properties: [:])
+ }
+ #else
+ nonisolated static func pngData(_ image: UIImage) -> Data? {
+ image.pngData()
+ }
+ #endif
+}
+
+// MARK: - Page Script
+
+/// What the page reports through the morphPreview message handler.
+enum MorphPreviewScript {
+ static let handlerName = "morphPreview"
+
+ /// Runs before the page's own scripts: forwards console errors and warnings, uncaught errors, rejected promises
+ /// and failed requests, and adds the element picker that `window.__morphSetPickerActive(bool)` turns on and off.
+ static let source = #"""
+ (function () {
+ if (window.__morphPreviewInstalled) { return; }
+ window.__morphPreviewInstalled = true;
+ var handler = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.morphPreview;
+ function post(payload) {
+ try { if (handler) { handler.postMessage(payload); } } catch (e) {}
+ }
+ function stringify(value) {
+ if (value instanceof Error) { return value.stack || (value.name + ': ' + value.message); }
+ if (typeof value === 'string') { return value; }
+ try { return JSON.stringify(value); } catch (e) { return String(value); }
+ }
+ function joinArgs(args) {
+ return Array.prototype.map.call(args, stringify).join(' ').slice(0, 2000);
+ }
+
+ ['error', 'warn'].forEach(function (level) {
+ var original = console[level];
+ console[level] = function () {
+ post({ type: 'console', level: level === 'warn' ? 'warning' : 'error', message: joinArgs(arguments) });
+ return original.apply(console, arguments);
+ };
+ });
+
+ window.addEventListener('error', function (event) {
+ var target = event.target;
+ if (target && target !== window && (target.src || target.href)) {
+ post({ type: 'network', level: 'network', message: 'Failed to load ' + (target.src || target.href), detail: target.tagName ? target.tagName.toLowerCase() : '' });
+ return;
+ }
+ var where = (event.filename || '') + ':' + (event.lineno || 0) + ':' + (event.colno || 0);
+ var stack = event.error && event.error.stack ? '\n' + event.error.stack : '';
+ post({ type: 'error', level: 'error', message: event.message || 'Script error', detail: (where + stack).slice(0, 2000) });
+ }, true);
+
+ window.addEventListener('unhandledrejection', function (event) {
+ post({ type: 'error', level: 'error', message: 'Unhandled promise rejection: ' + stringify(event.reason).slice(0, 2000) });
+ });
+
+ if (window.fetch) {
+ var originalFetch = window.fetch;
+ window.fetch = function (input, init) {
+ var method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
+ var url = typeof input === 'string' ? input : ((input && input.url) || String(input));
+ return originalFetch.apply(this, arguments).then(function (response) {
+ if (response.status >= 400) {
+ post({ type: 'network', level: 'network', message: method + ' ' + url + ' → ' + response.status, detail: response.statusText || '' });
+ }
+ return response;
+ }, function (error) {
+ post({ type: 'network', level: 'network', message: method + ' ' + url + ' → failed', detail: stringify(error).slice(0, 1000) });
+ throw error;
+ });
+ };
+ }
+
+ if (window.XMLHttpRequest) {
+ var proto = window.XMLHttpRequest.prototype;
+ var originalOpen = proto.open;
+ var originalSend = proto.send;
+ proto.open = function (method, url) {
+ this.__morphMethod = String(method || 'GET').toUpperCase();
+ this.__morphURL = String(url);
+ return originalOpen.apply(this, arguments);
+ };
+ proto.send = function () {
+ var xhr = this;
+ xhr.addEventListener('loadend', function () {
+ if (xhr.status >= 400 || xhr.status === 0) {
+ var result = xhr.status === 0 ? 'failed' : String(xhr.status);
+ post({ type: 'network', level: 'network', message: (xhr.__morphMethod || 'GET') + ' ' + (xhr.__morphURL || '') + ' → ' + result, detail: xhr.statusText || '' });
+ }
+ });
+ return originalSend.apply(this, arguments);
+ };
+ }
+
+ var pickerActive = false;
+ var box = null;
+ var tag = null;
+ var current = null;
+
+ function ensureOverlay() {
+ if (box) { return; }
+ box = document.createElement('div');
+ box.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483646;border:1.5px dashed rgba(22,22,22,0.8);background:rgba(164,164,164,0.12);border-radius:3px;box-shadow:0 0 0 1px rgba(250,250,250,0.65);display:none;';
+ tag = document.createElement('div');
+ tag.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483647;font:500 11px/1.5 -apple-system,Inter,sans-serif;color:#FAFAFA;background:#161616;padding:1px 6px;border-radius:4px;white-space:nowrap;display:none;';
+ document.documentElement.appendChild(box);
+ document.documentElement.appendChild(tag);
+ }
+
+ function cssPath(el) {
+ var parts = [];
+ while (el && el.nodeType === 1 && parts.length < 6) {
+ var part = el.nodeName.toLowerCase();
+ if (el.id) {
+ parts.unshift(part + '#' + CSS.escape(el.id));
+ break;
+ }
+ var classes = Array.prototype.slice.call(el.classList || [], 0, 2);
+ if (classes.length) { part += '.' + classes.map(function (c) { return CSS.escape(c); }).join('.'); }
+ var parent = el.parentElement;
+ if (parent) {
+ var same = Array.prototype.filter.call(parent.children, function (s) { return s.nodeName === el.nodeName; });
+ if (same.length > 1) { part += ':nth-of-type(' + (same.indexOf(el) + 1) + ')'; }
+ }
+ parts.unshift(part);
+ el = parent;
+ }
+ return parts.join(' > ');
+ }
+
+ function describe(el) {
+ var rect = el.getBoundingClientRect();
+ var className = typeof el.className === 'string' ? el.className : (el.getAttribute('class') || '');
+ return {
+ type: 'element',
+ url: location.href,
+ selector: cssPath(el),
+ tagName: el.tagName.toLowerCase(),
+ id: el.id || '',
+ className: className,
+ text: (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120),
+ html: (el.outerHTML || '').slice(0, 400),
+ x: Math.round(rect.left),
+ y: Math.round(rect.top),
+ width: Math.round(rect.width),
+ height: Math.round(rect.height)
+ };
+ }
+
+ function highlight(el) {
+ ensureOverlay();
+ var rect = el.getBoundingClientRect();
+ box.style.left = rect.left + 'px';
+ box.style.top = rect.top + 'px';
+ box.style.width = rect.width + 'px';
+ box.style.height = rect.height + 'px';
+ box.style.display = 'block';
+ tag.textContent = el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + ' ' + Math.round(rect.width) + '×' + Math.round(rect.height);
+ tag.style.left = Math.max(0, rect.left) + 'px';
+ tag.style.top = (rect.top > 22 ? rect.top - 20 : rect.bottom + 4) + 'px';
+ tag.style.display = 'block';
+ }
+
+ function setActive(active) {
+ pickerActive = !!active;
+ if (!pickerActive && box) {
+ box.style.display = 'none';
+ tag.style.display = 'none';
+ }
+ if (!pickerActive) { current = null; }
+ if (document.documentElement) { document.documentElement.style.cursor = pickerActive ? 'crosshair' : ''; }
+ }
+
+ document.addEventListener('mouseover', function (event) {
+ if (!pickerActive || event.target === box || event.target === tag || event.target.nodeType !== 1) { return; }
+ current = event.target;
+ highlight(current);
+ }, true);
+
+ function block(event) {
+ if (!pickerActive) { return; }
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ document.addEventListener('mousedown', block, true);
+ document.addEventListener('mouseup', block, true);
+ document.addEventListener('click', function (event) {
+ if (!pickerActive) { return; }
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.stopImmediatePropagation) { event.stopImmediatePropagation(); }
+ var el = current || event.target;
+ setActive(false);
+ if (el && el.nodeType === 1) { post(describe(el)); }
+ }, true);
+ document.addEventListener('keydown', function (event) {
+ if (pickerActive && event.key === 'Escape') {
+ setActive(false);
+ post({ type: 'picker', active: false });
+ }
+ }, true);
+
+ window.__morphSetPickerActive = setActive;
+ })();
+ """#
+}
+
+// MARK: - Web View
+
+#if os(macOS)
+typealias MorphWebViewRepresentableBase = NSViewRepresentable
+#else
+typealias MorphWebViewRepresentableBase = UIViewRepresentable
+#endif
+
+/// A WKWebView with the preview script, reporting navigation to the model and page messages to the callbacks.
+struct MorphPreviewWebView: MorphWebViewRepresentableBase {
+ let model: MorphWebPreviewModel
+ let onMessage: @MainActor ([String: Any]) -> Void
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(model: model)
+ }
+
+ private func makeWebView(coordinator: Coordinator) -> WKWebView {
+ coordinator.onMessage = onMessage
+ let contentController = WKUserContentController()
+ contentController.addUserScript(
+ WKUserScript(source: MorphPreviewScript.source, injectionTime: .atDocumentStart, forMainFrameOnly: true)
+ )
+ // The content controller keeps its handlers alive, so it holds the coordinator weakly.
+ contentController.add(MorphWeakScriptHandler(target: coordinator), name: MorphPreviewScript.handlerName)
+ let configuration = WKWebViewConfiguration()
+ configuration.userContentController = contentController
+ let webView = WKWebView(frame: .zero, configuration: configuration)
+ webView.navigationDelegate = coordinator
+ webView.isInspectable = true
+ #if os(macOS)
+ webView.allowsMagnification = true
+ #endif
+ model.attach(webView)
+ return webView
+ }
+
+ private static func dismantle(_ webView: WKWebView, coordinator: Coordinator) {
+ webView.configuration.userContentController.removeScriptMessageHandler(forName: MorphPreviewScript.handlerName)
+ webView.navigationDelegate = nil
+ coordinator.model.detach()
+ }
+
+ #if os(macOS)
+ func makeNSView(context: Context) -> WKWebView {
+ makeWebView(coordinator: context.coordinator)
+ }
+
+ func updateNSView(_ nsView: WKWebView, context: Context) {
+ context.coordinator.onMessage = onMessage
+ let isEnabled = context.environment.isEnabled
+ if nsView.isHidden != !isEnabled {
+ nsView.isHidden = !isEnabled
+ }
+ if !isEnabled,
+ let window = nsView.window,
+ let responder = window.firstResponder as? NSView,
+ responder.isDescendant(of: nsView) {
+ window.makeFirstResponder(nil)
+ }
+ }
+
+ static func dismantleNSView(_ nsView: WKWebView, coordinator: Coordinator) {
+ dismantle(nsView, coordinator: coordinator)
+ }
+ #else
+ func makeUIView(context: Context) -> WKWebView {
+ makeWebView(coordinator: context.coordinator)
+ }
+
+ func updateUIView(_ uiView: WKWebView, context: Context) {
+ context.coordinator.onMessage = onMessage
+ let isEnabled = context.environment.isEnabled
+ if uiView.isHidden != !isEnabled {
+ uiView.isHidden = !isEnabled
+ }
+ if uiView.isUserInteractionEnabled != isEnabled {
+ uiView.isUserInteractionEnabled = isEnabled
+ }
+ }
+
+ static func dismantleUIView(_ uiView: WKWebView, coordinator: Coordinator) {
+ dismantle(uiView, coordinator: coordinator)
+ }
+ #endif
+
+ @MainActor
+ final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
+ let model: MorphWebPreviewModel
+ var onMessage: (@MainActor ([String: Any]) -> Void)?
+
+ init(model: MorphWebPreviewModel) {
+ self.model = model
+ }
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ guard let body = message.body as? [String: Any] else { return }
+ onMessage?(body)
+ }
+
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
+ model.didFinish()
+ }
+
+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
+ model.didFail(error)
+ }
+
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
+ model.didFail(error)
+ }
+ }
+}
+
+/// Forwards page messages to a handler without the content controller keeping it alive.
+@MainActor
+final class MorphWeakScriptHandler: NSObject, WKScriptMessageHandler {
+ weak var target: WKScriptMessageHandler?
+
+ init(target: WKScriptMessageHandler) {
+ self.target = target
+ }
+
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
+ target?.userContentController(userContentController, didReceive: message)
+ }
+}
+
+// MARK: - Preview Pane
+
+/// The inspector's 프리뷰 tab: the project's dev server in a web view, with navigation, viewport sizes, the dev
+/// script, an element picker and screenshots that go to the composer, and a console and network drawer.
+struct MorphWebPreviewView: View {
+ @Bindable var state: MorphAppState
+ let project: CodeProject?
+ let thread: CodeThread?
+
+ @Environment(\.openURL) private var openURL
+ @State private var model = MorphWebPreviewModel()
+ @State private var urlDraft = ""
+ @State private var viewport: MorphPreviewViewport = .desktop
+ @State private var appearance: MorphPreviewAppearance = .system
+ @State private var isConsoleOpen = false
+ @State private var isCapturing = false
+ @State private var capturedRecently = false
+ @Namespace private var viewportNamespace
+
+ static let defaultURL = "http://localhost:3000"
+ private static let devServerTabId = "preview-dev-server"
+
+ init(state: MorphAppState, project: CodeProject?, thread: CodeThread?) {
+ self.state = state
+ self.project = project
+ self.thread = thread
+ }
+
+ var body: some View {
+ if let project {
+ content(projectId: project.id)
+ } else {
+ Text("프로젝트를 선택하면 프리뷰를 열 수 있습니다.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .padding(14)
+ }
+ }
+
+ private func content(projectId: String) -> some View {
+ VStack(spacing: 0) {
+ navigationBar(projectId: projectId)
+ toolsBar(projectId: projectId)
+ pageArea
+ consoleDrawer(projectId: projectId)
+ }
+ .task(id: projectId) {
+ let initial = resolvedURL(projectId: projectId)
+ urlDraft = initial
+ if let url = Self.normalizedURL(initial) {
+ model.load(url)
+ }
+ }
+ .onChange(of: state.codePreviewURLByProject[projectId]) { _, saved in
+ guard let saved, saved != model.requestedURL, let url = Self.normalizedURL(saved) else { return }
+ urlDraft = url.absoluteString
+ model.load(url)
+ }
+ .onChange(of: state.codeDetectedPreviewURLByProject[projectId]) { _, detected in
+ // A dev server that just printed its address replaces the default until an address is saved.
+ guard let detected, state.codePreviewURLByProject[projectId] == nil, let url = Self.normalizedURL(detected) else { return }
+ urlDraft = url.absoluteString
+ model.load(url)
+ }
+ .onChange(of: model.currentURL) { _, current in
+ if !current.isEmpty { urlDraft = current }
+ }
+ .onChange(of: viewport) { _, next in
+ model.setUserAgent(mobile: next == .mobile)
+ }
+ .onChange(of: appearance) { _, next in
+ model.setAppearance(next)
+ }
+ }
+
+ // MARK: Bars
+
+ private func navigationBar(projectId: String) -> some View {
+ HStack(spacing: 4) {
+ iconButton("chevron.left", help: "뒤로") { model.goBack() }
+ .disabled(!model.canGoBack)
+ iconButton("chevron.right", help: "앞으로") { model.goForward() }
+ .disabled(!model.canGoForward)
+ iconButton(model.isLoading ? "xmark" : "arrow.clockwise", help: "새로고침") { model.reload() }
+
+ AnymorphTextField(Self.defaultURL, text: $urlDraft, appearance: .outlined) {
+ submitURL(projectId: projectId)
+ }
+
+ iconButton("arrow.up.right.square", help: "외부 브라우저에서 열기") {
+ guard let url = Self.normalizedURL(model.currentURL.isEmpty ? urlDraft : model.currentURL) else { return }
+ openURL(url)
+ }
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .overlay(alignment: .bottom) { AnymorphDivider() }
+ }
+
+ private func viewportIcon(_ preset: MorphPreviewViewport) -> String {
+ switch preset {
+ case .desktop: return "desktopcomputer"
+ case .tablet: return "ipad"
+ case .mobile: return "iphone"
+ }
+ }
+
+ private func toolsBar(projectId: String) -> some View {
+ let devRunning = isDevServerRunning(projectId: projectId)
+ return ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 5) {
+ // The segment control's frame and sliding plate, with an icon for each width.
+ HStack(spacing: 2) {
+ ForEach(MorphPreviewViewport.allCases) { preset in
+ let active = viewport == preset
+ Button {
+ guard viewport != preset else { return }
+ viewport = preset
+ } label: {
+ Image(systemName: viewportIcon(preset))
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(active ? AnymorphColor.fgPrimary : AnymorphColor.fgQuaternary)
+ .frame(width: 25, height: 24)
+ .background {
+ if active {
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .fill(AnymorphColor.bgSurface)
+ .matchedGeometryEffect(id: "viewport-plate", in: viewportNamespace)
+ }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+ .help(preset.title)
+ .accessibilityLabel(preset.title)
+ .accessibilityAddTraits(active ? .isSelected : [])
+ }
+ }
+ .animation(AnymorphMotion.fast, value: viewport)
+ .padding(3)
+ .background(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).fill(AnymorphColor.bgBase))
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .fixedSize()
+
+ Button {
+ appearance = appearance.next
+ } label: {
+ Image(systemName: appearance.icon)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundStyle(appearance == .system ? AnymorphColor.fgSecondary : AnymorphColor.fgPrimary)
+ }
+ .anymorphButton(size: .inline, appearance: appearance == .system ? .ghost : .light, iconOnly: true)
+ .help("Appearance: \(appearance.title) (click to switch)")
+ .accessibilityLabel("Appearance \(appearance.title)")
+
+ Button {
+ if devRunning {
+ stopDevServer(projectId: projectId)
+ } else {
+ startDevServer(projectId: projectId)
+ }
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: devRunning ? "stop.fill" : "play.fill")
+ .font(.system(size: 8, weight: .semibold))
+ Text(devRunning ? "Stop Dev" : "Dev")
+ }
+ }
+ .anymorphButton(size: .inline, appearance: .light)
+ .fixedSize()
+ .help(devScript(projectId: projectId).map { "\($0.name): \($0.command)" } ?? "Open terminal if no dev script is configured")
+
+ Button {
+ model.setPicker(!model.isPickerActive)
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "cursorarrow.rays")
+ .font(.system(size: 10.5, weight: .medium))
+ Text("Inspect")
+ }
+ }
+ .anymorphButton(size: .inline, appearance: model.isPickerActive ? .solid : .light)
+ .fixedSize()
+ .help("Pick a page element to reference in the composer (Esc to cancel)")
+ .accessibilityAddTraits(model.isPickerActive ? .isSelected : [])
+
+ Button {
+ captureScreenshot()
+ } label: {
+ if isCapturing {
+ MorphRunningDots(dotSize: 2.0, spacing: 2.0)
+ } else {
+ Image(systemName: capturedRecently ? "checkmark" : "camera")
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(capturedRecently ? AnymorphColor.fgPrimary : AnymorphColor.fgSecondary)
+ }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .disabled(isCapturing)
+ .help("Copy screenshot to clipboard and attach to composer")
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ }
+ .overlay(alignment: .bottom) { AnymorphDivider() }
+ }
+
+ private func iconButton(_ systemName: String, help: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Image(systemName: systemName)
+ .font(.system(size: 11.5, weight: .medium))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ }
+ .anymorphButton(size: .inline, appearance: .ghost, iconOnly: true)
+ .help(help)
+ }
+
+ // MARK: Page
+
+ private var pageArea: some View {
+ ZStack(alignment: .top) {
+ if let width = viewport.width {
+ AnymorphColor.bgGrouped
+ MorphPreviewWebView(model: model, onMessage: handleMessage)
+ .frame(maxWidth: width)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: AnymorphRadius.md, style: .continuous).strokeBorder(AnymorphColor.strokeBase, lineWidth: 1))
+ .padding(10)
+ } else {
+ MorphPreviewWebView(model: model, onMessage: handleMessage)
+ }
+
+ if let error = model.loadError {
+ VStack(spacing: 8) {
+ Text("Unable to load page")
+ .anymorphText(.footnote, weight: .strong, color: AnymorphColor.fgPrimary)
+ Text(error)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .multilineTextAlignment(.center)
+ Text("Make sure your dev server is running.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ Button("Retry") { model.reload() }
+ .anymorphButton(size: .md, appearance: .light)
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(AnymorphColor.bgBase)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ // MARK: Console drawer
+
+ private func consoleDrawer(projectId: String) -> some View {
+ let entries = state.codePreviewConsoleByProject[projectId] ?? []
+ let errors = entries.filter { $0.level == .error }.count
+ let warnings = entries.filter { $0.level == .warning }.count
+ let network = entries.filter { $0.level == .network }.count
+ return VStack(spacing: 0) {
+ AnymorphDivider()
+ HStack(spacing: 6) {
+ Button {
+ withAnimation(AnymorphMotion.fast) { isConsoleOpen.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: isConsoleOpen ? "chevron.down" : "chevron.up")
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundStyle(AnymorphColor.fgQuaternary)
+ Text("Console & Network")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ .lineLimit(1)
+ .fixedSize()
+ if errors > 0 { AnymorphBadge("에러 \(errors)") }
+ if warnings > 0 { AnymorphBadge("경고 \(warnings)") }
+ if network > 0 { AnymorphBadge("네트워크 \(network)") }
+ Spacer(minLength: 4)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.morphPlain)
+
+ if isConsoleOpen {
+ Button("지우기") { state.clearPreviewConsoleEntries(projectId: projectId) }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ .disabled(entries.isEmpty)
+ }
+ Button("Send errors to agent") { sendErrorsToAgent(entries: entries) }
+ .anymorphButton(size: .inline, appearance: .light)
+ .fixedSize()
+ .disabled(errors + network + warnings == 0)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+
+ if isConsoleOpen {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ if entries.isEmpty {
+ Text("No console errors or failed requests recorded.")
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary)
+ .padding(.vertical, 8)
+ }
+ ForEach(entries.reversed()) { entry in
+ consoleRow(entry)
+ AnymorphDivider()
+ }
+ }
+ .padding(.horizontal, 12)
+ }
+ .frame(maxHeight: 200)
+ }
+ }
+ .background(AnymorphColor.bgBase)
+ }
+
+ private func consoleRow(_ entry: CodePreviewConsoleEntry) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(Self.levelLabel(entry.level))
+ .anymorphText(.caption, weight: entry.level == .error ? .strong : .emphasis, color: entry.level == .error ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary, monospaced: true)
+ .frame(width: 38, alignment: .leading)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(entry.message)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(4)
+ if let detail = entry.detail, !detail.isEmpty {
+ Text(detail)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(3)
+ }
+ }
+ .textSelection(.enabled)
+ Spacer(minLength: 0)
+ Text(entry.timestamp, format: .dateTime.hour().minute().second())
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgQuaternary, tabular: true)
+ }
+ .padding(.vertical, 6)
+ }
+
+ static func levelLabel(_ level: CodePreviewConsoleEntry.Level) -> String {
+ switch level {
+ case .error: return "ERR"
+ case .warning: return "WARN"
+ case .network: return "NET"
+ case .log: return "LOG"
+ }
+ }
+
+ // MARK: Actions
+
+ private func resolvedURL(projectId: String) -> String {
+ state.codePreviewURLByProject[projectId] ?? state.codeDetectedPreviewURLByProject[projectId] ?? Self.defaultURL
+ }
+
+ private func submitURL(projectId: String) {
+ guard let url = Self.normalizedURL(urlDraft) else { return }
+ urlDraft = url.absoluteString
+ model.load(url)
+ state.codePreviewURLByProject[projectId] = url.absoluteString
+ }
+
+ /// The address as typed, with a scheme added: http for local hosts and https otherwise.
+ static func normalizedURL(_ raw: String) -> URL? {
+ var text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { return nil }
+ if text.hasPrefix(":") { text = "localhost" + text }
+ if !text.contains("://") {
+ let isLocal = text.hasPrefix("localhost") || text.hasPrefix("127.") || text.hasPrefix("0.0.0.0") || text.hasPrefix("[::1]")
+ text = (isLocal ? "http://" : "https://") + text
+ }
+ text = text.replacingOccurrences(of: "://0.0.0.0", with: "://localhost")
+ text = text.replacingOccurrences(of: "://[::1]", with: "://localhost")
+ return URL(string: text)
+ }
+
+ private func devScript(projectId: String) -> CodeProjectScript? {
+ (state.codeProjectScriptsByProject[projectId] ?? []).first { $0.kind == "dev" }
+ }
+
+ private func devSessionKey(projectId: String) -> String {
+ state.codeTerminalKey(projectId: projectId, threadId: thread?.id) + "#" + Self.devServerTabId
+ }
+
+ private func isDevServerRunning(projectId: String) -> Bool {
+ let hasTab = state.terminalTabs(projectId: projectId, threadId: thread?.id).contains { $0.id == Self.devServerTabId }
+ return hasTab && state.codeTerminalSessions[devSessionKey(projectId: projectId)]?.running == true
+ }
+
+ /// Runs the project's dev script in its own terminal tab, or opens the terminal when the project has none.
+ private func startDevServer(projectId: String) {
+ let threadId = thread?.id
+ guard let script = devScript(projectId: projectId) else {
+ state.codeInspectorSection = .terminal
+ state.showInfo("dev 스크립트가 없어 터미널을 열었습니다. 서버를 직접 실행해 주세요.")
+ return
+ }
+ let scope = state.codeTerminalKey(projectId: projectId, threadId: threadId)
+ let sessionKey = devSessionKey(projectId: projectId)
+ var tabs = state.terminalTabs(projectId: projectId, threadId: threadId)
+ if !tabs.contains(where: { $0.id == Self.devServerTabId }) {
+ tabs.append(CodeTerminalTab(id: Self.devServerTabId, title: "Dev Server", sessionKey: sessionKey))
+ state.codeTerminalTabsByScope[scope] = tabs
+ }
+ Task {
+ await state.ensureCodeTerminalSession(sessionKey: sessionKey, projectId: projectId, threadId: threadId, cols: 120, rows: 30)
+ await state.sendCodeTerminalInput(sessionKey: sessionKey, projectId: projectId, data: script.command + "\r")
+ }
+ }
+
+ private func stopDevServer(projectId: String) {
+ let threadId = thread?.id
+ Task { await state.closeTerminalTab(Self.devServerTabId, projectId: projectId, threadId: threadId) }
+ }
+
+ private func captureScreenshot() {
+ guard !isCapturing else { return }
+ isCapturing = true
+ let url = model.currentURL.isEmpty ? urlDraft : model.currentURL
+ let threadId = thread?.id
+ Task {
+ defer { isCapturing = false }
+ guard let data = await model.snapshotPNG() else {
+ state.showError("프리뷰 스크린샷을 찍지 못했습니다.")
+ return
+ }
+ Self.copyImageToClipboard(data)
+ state.sendPreviewContextToComposer(text: "[프리뷰 스크린샷] \(url)", imageData: data, imageName: "preview.png", threadId: threadId)
+ state.showInfo("스크린샷을 클립보드에 복사하고 입력창에 첨부했습니다.")
+ capturedRecently = true
+ Task {
+ try? await Task.sleep(for: .seconds(1.5))
+ capturedRecently = false
+ }
+ }
+ }
+
+ private static func copyImageToClipboard(_ pngData: Data) {
+ #if os(macOS)
+ let pb = NSPasteboard.general
+ pb.clearContents()
+ pb.setData(pngData, forType: .png)
+ #else
+ if let image = UIImage(data: pngData) {
+ UIPasteboard.general.image = image
+ }
+ #endif
+ }
+
+ private func sendErrorsToAgent(entries: [CodePreviewConsoleEntry]) {
+ let relevant = entries.filter { $0.level != .log }.suffix(20)
+ guard !relevant.isEmpty else { return }
+ let url = model.currentURL.isEmpty ? urlDraft : model.currentURL
+ let lines = relevant.map { entry -> String in
+ var line = "[\(Self.levelLabel(entry.level))] \(entry.message)"
+ if let detail = entry.detail, !detail.isEmpty {
+ line += "\n " + detail.replacingOccurrences(of: "\n", with: "\n ")
+ }
+ return line
+ }
+ let text = """
+ [프리뷰 콘솔] \(url)
+ 프리뷰에서 아래 브라우저 에러와 실패한 요청이 났습니다. 원인을 찾아 고쳐 주세요.
+
+ ```text
+ \(lines.joined(separator: "\n"))
+ ```
+ """
+ state.sendPreviewContextToComposer(text: text, threadId: thread?.id)
+ }
+
+ // MARK: Page messages
+
+ private func handleMessage(_ body: [String: Any]) {
+ guard let project, let type = body["type"] as? String else { return }
+ switch type {
+ case "element":
+ model.isPickerActive = false
+ state.sendPreviewContextToComposer(text: Self.elementContext(body), threadId: thread?.id)
+ case "picker":
+ model.isPickerActive = (body["active"] as? Bool) ?? false
+ default:
+ let message = (body["message"] as? String) ?? ""
+ guard !message.isEmpty else { return }
+ let level: CodePreviewConsoleEntry.Level
+ switch body["level"] as? String {
+ case "error": level = .error
+ case "warning": level = .warning
+ case "network": level = .network
+ default: level = .log
+ }
+ let detail = (body["detail"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ state.recordPreviewConsoleEntry(projectId: project.id, entry: CodePreviewConsoleEntry(level: level, message: message, detail: detail))
+ }
+ }
+
+ /// The picked element as Markdown for the composer.
+ static func elementContext(_ body: [String: Any]) -> String {
+ func string(_ key: String) -> String { (body[key] as? String) ?? "" }
+ func number(_ key: String) -> Int { (body[key] as? NSNumber)?.intValue ?? 0 }
+ var lines = ["[프리뷰 요소] \(string("url"))"]
+ lines.append("- 선택자: `\(string("selector"))`")
+ var identity = "- 태그: `\(string("tagName"))`"
+ if !string("id").isEmpty { identity += ", id: `\(string("id"))`" }
+ if !string("className").isEmpty { identity += ", class: `\(string("className"))`" }
+ lines.append(identity)
+ lines.append("- 위치와 크기: (\(number("x")), \(number("y"))), \(number("width"))×\(number("height"))")
+ if !string("text").isEmpty { lines.append("- 텍스트: \"\(string("text"))\"") }
+ if !string("html").isEmpty {
+ lines.append("")
+ lines.append("```html\n\(string("html"))\n```")
+ }
+ return lines.joined(separator: "\n")
+ }
+}
diff --git a/apple/Apps/Shared/MorphWindowTitlebar.swift b/apple/Apps/Shared/MorphWindowTitlebar.swift
new file mode 100644
index 000000000..80db7039c
--- /dev/null
+++ b/apple/Apps/Shared/MorphWindowTitlebar.swift
@@ -0,0 +1,93 @@
+import MorphCore
+import SwiftUI
+#if os(macOS)
+import AppKit
+#endif
+
+#if os(macOS)
+/// Handles standard macOS window titlebar double-click actions for `.hiddenTitleBar` windows
+/// whose custom SwiftUI header bars sit over the transparent title bar.
+@MainActor
+public enum MorphWindowTitlebar {
+ /// Performs the user's configured macOS titlebar double-click action on `window`.
+ /// Does nothing while the window is in native full-screen mode.
+ public static func performDoubleClick(on window: NSWindow, defaults: UserDefaults = .standard) {
+ guard !window.styleMask.contains(.fullScreen) else { return }
+ switch WindowTitlebarDoubleClickAction.current(defaults: defaults) {
+ case .zoom:
+ guard window.styleMask.contains(.resizable) else { return }
+ window.performZoom(nil)
+ case .minimize:
+ guard window.styleMask.contains(.miniaturizable) else { return }
+ window.performMiniaturize(nil)
+ case .none:
+ break
+ }
+ }
+}
+
+@MainActor
+private final class MorphWeakWindowBox {
+ weak var window: NSWindow?
+}
+
+/// Captures the hosting `NSWindow` without intercepting hit-testing.
+private struct MorphWindowReader: NSViewRepresentable {
+ let box: MorphWeakWindowBox
+
+ final class ReaderNSView: NSView {
+ var box: MorphWeakWindowBox?
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ box?.window = window
+ }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+ }
+
+ func makeNSView(context: Context) -> ReaderNSView {
+ let view = ReaderNSView()
+ view.box = box
+ return view
+ }
+
+ func updateNSView(_ nsView: ReaderNSView, context: Context) {
+ nsView.box = box
+ if let window = nsView.window {
+ box.window = window
+ }
+ }
+}
+
+private struct MorphWindowTitlebarModifier: ViewModifier {
+ @State private var windowBox = MorphWeakWindowBox()
+
+ func body(content: Content) -> some View {
+ content
+ .contentShape(Rectangle())
+ .background { MorphWindowReader(box: windowBox) }
+ .gesture(WindowDragGesture())
+ .simultaneousGesture(
+ TapGesture(count: 2).onEnded {
+ guard let window = windowBox.window else { return }
+ MorphWindowTitlebar.performDoubleClick(on: window)
+ }
+ )
+ }
+}
+#endif
+
+extension View {
+ /// Makes a custom macOS titlebar background or non-interactive title label draggable
+ /// and responsive to macOS's standard titlebar double-click (zoom/fill or minimize).
+ /// No-op on iOS.
+ @ViewBuilder
+ func morphWindowTitlebar() -> some View {
+ #if os(macOS)
+ modifier(MorphWindowTitlebarModifier())
+ #else
+ self
+ #endif
+ }
+}
diff --git a/apple/Apps/Shared/SettingsView.swift b/apple/Apps/Shared/SettingsView.swift
new file mode 100644
index 000000000..83e2af007
--- /dev/null
+++ b/apple/Apps/Shared/SettingsView.swift
@@ -0,0 +1,1674 @@
+import SwiftUI
+import MorphCore
+import AppKit
+@preconcurrency import UserNotifications
+
+/// Two-column macOS Settings dialog for Morph Code (⌘,).
+public struct SettingsView: View {
+ @Bindable var state: MorphAppState
+ @Environment(\.openURL) private var openURL
+ @State private var editingProviderKey: LocalProviderChoice?
+ @State private var escapeKeyMonitor: Any?
+
+ public init(state: MorphAppState) {
+ self.state = state
+ }
+
+ public var body: some View {
+ HStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(MorphSettingsSection.allCases) { section in
+ SettingsNavRow(section: section, isSelected: state.settingsSection == section) {
+ state.settingsSection = section
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 14)
+ .frame(width: 212)
+ .frame(maxHeight: .infinity, alignment: .top)
+ .background(AnymorphColor.bgSidebar)
+ .overlay(alignment: .trailing) {
+ Rectangle().fill(AnymorphColor.strokeLight).frame(width: 1)
+ }
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 24) {
+ Text(state.settingsSection.title)
+ .anymorphText(.title, weight: .strong, color: AnymorphColor.fgPrimary)
+ sectionContent(state.settingsSection)
+ }
+ .padding(.horizontal, 32)
+ .padding(.top, 26)
+ .padding(.bottom, 32)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .id(state.settingsSection)
+ .animation(nil, value: state.settingsSection)
+ .background(AnymorphColor.bgBase)
+ }
+ .overlay(alignment: .topTrailing) {
+ Button {
+ state.isSettingsPresented = false
+ } label: {
+ Image(systemName: "xmark")
+ }
+ .morphRound(diameter: 30)
+ .keyboardShortcut(editingProviderKey != nil ? nil : .cancelAction)
+ .padding(12)
+ .help("Close")
+ .accessibilityLabel("Close Settings")
+ }
+ .focusEffectDisabled()
+ .onKeyPress(.escape) {
+ guard editingProviderKey == nil else { return .ignored }
+ state.isSettingsPresented = false
+ return .handled
+ }
+ .onAppear {
+ if escapeKeyMonitor == nil {
+ escapeKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
+ guard event.keyCode == 53, editingProviderKey == nil else { return event }
+ state.isSettingsPresented = false
+ return nil
+ }
+ }
+ }
+ .onDisappear {
+ if let monitor = escapeKeyMonitor {
+ NSEvent.removeMonitor(monitor)
+ escapeKeyMonitor = nil
+ }
+ }
+ .sheet(item: $editingProviderKey) { choice in
+ ConfigureProviderKeySheet(state: state, provider: choice)
+ }
+ }
+
+ @ViewBuilder
+ private func sectionContent(_ section: MorphSettingsSection) -> some View {
+ switch section {
+ case .general:
+ generalSection
+ case .notifications:
+ notificationsSection
+ case .providers:
+ providersSection
+ case .harness:
+ harnessSection
+ }
+ }
+
+ // MARK: - General
+
+ private var generalSection: some View {
+ VStack(alignment: .leading, spacing: 24) {
+ MorphSettingsGroup("Appearance") {
+ MorphSettingsRow("Theme", detail: "Match macOS or lock light/dark appearance") {
+ EmptyView()
+ } trailing: {
+ AnymorphSegmentControl(
+ items: MorphThemeMode.allCases,
+ selection: $state.themeMode,
+ label: { $0.label }
+ )
+ }
+ }
+
+ MorphSettingsGroup("Morph Code") {
+ MorphSettingsRow("Follow-up Messages", detail: "Steer the active run immediately or queue behind it") {
+ EmptyView()
+ } trailing: {
+ AnymorphSegmentControl(
+ items: CodeFollowUpMode.allCases,
+ selection: $state.codeFollowUpMode,
+ label: { $0.label }
+ )
+ }
+
+ MorphSettingsRow("New Thread Title", detail: state.codeTitleStyle.example) {
+ EmptyView()
+ } trailing: {
+ AnymorphSegmentControl(
+ items: CodeTitleStyle.allCases,
+ selection: $state.codeTitleStyle,
+ label: { $0.label }
+ )
+ }
+
+ if state.codeTitleStyle == .custom {
+ MorphSettingsRow("Title Format", detail: "Keep brackets and separators as-is; the remaining slot fills from your prompt") {
+ EmptyView()
+ } trailing: {
+ AnymorphTextField(
+ "e.g. [Area] Short action title",
+ text: $state.codeTitleFormat
+ )
+ .frame(width: 220)
+ }
+ }
+ }
+
+ MorphSettingsGroup(
+ "Local Daemon",
+ footnote: "Morph Code runs all sessions, Git operations, terminals, and provider calls through the local morphcode daemon on \(MacBridgeAgent.activeListenAddress)."
+ ) {
+ let version = state.localBridgeHealth?.version ?? state.localCodeDaemonVersion
+ MorphSettingsRow(
+ state.localBridgeOnline ? "Connected" : "Offline",
+ detail: version.map { "http://\(MacBridgeAgent.activeListenAddress) · v\($0)" } ?? "http://\(MacBridgeAgent.activeListenAddress)"
+ ) {
+ MorphServiceIcon(state.localBridgeOnline ? "bolt.horizontal.circle" : "bolt.slash")
+ } trailing: {
+ HStack(spacing: 8) {
+ AnymorphBadge(state.localBridgeOnline ? "Online" : "Offline")
+ Button("Restart Daemon") {
+ Task { await state.restartLocalDaemon() }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ }
+ }
+ }
+
+ MorphSettingsGroup("About") {
+ let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "4.0.0"
+ MorphSettingsRow("Morph Code", detail: "Local-first macOS coding client · Version \(appVersion)") {
+ MorphAssistantMark(width: 22)
+ } trailing: {
+ AnymorphBadge("v\(appVersion)")
+ }
+ }
+ }
+ }
+
+ // MARK: - Notifications
+
+ private var notificationsSection: some View {
+ VStack(alignment: .leading, spacing: 24) {
+ MorphSettingsGroup(
+ "Code Notifications",
+ footnote: "Only notifies when you are viewing another thread or Morph Code is in the background. Clicking a notification jumps directly to that thread."
+ ) {
+ MorphSettingsRow("Code Notifications", detail: "Alerts for completed turns, failures, approvals, and questions") {
+ EmptyView()
+ } trailing: {
+ Toggle(
+ "Code Notifications",
+ isOn: Binding(
+ get: { state.codeNotificationsEnabled },
+ set: { enabled in
+ state.codeNotificationsEnabled = enabled
+ if enabled {
+ MorphNotificationManager.shared.requestAuthorizationIfNeeded()
+ }
+ }
+ )
+ )
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ }
+
+ MorphSettingsRow("Turn Completed", detail: "Notify when an agent finishes responding") {
+ EmptyView()
+ } trailing: {
+ Toggle("Turn Completed", isOn: $state.codeNotifyTurnDone)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ .disabled(!state.codeNotificationsEnabled)
+ }
+
+ MorphSettingsRow("Turn Failed", detail: "Notify if a run exits with an error") {
+ EmptyView()
+ } trailing: {
+ Toggle("Turn Failed", isOn: $state.codeNotifyTurnFailed)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ .disabled(!state.codeNotificationsEnabled)
+ }
+
+ MorphSettingsRow("Approvals & Questions", detail: "Notify when a tool run or question needs your input") {
+ EmptyView()
+ } trailing: {
+ Toggle("Approvals & Questions", isOn: $state.codeNotifyAttention)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ .disabled(!state.codeNotificationsEnabled)
+ }
+
+ MorphSettingsRow("Notification Sound", detail: "Play the default alert sound") {
+ EmptyView()
+ } trailing: {
+ Toggle("Notification Sound", isOn: $state.codeNotificationSoundEnabled)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ .disabled(!state.codeNotificationsEnabled)
+ }
+ }
+ }
+ }
+
+ // MARK: - Providers & Models
+
+ private var providersSection: some View {
+ VStack(alignment: .leading, spacing: 24) {
+ MorphSettingsGroup(
+ "Built-In Providers & Local CLIs",
+ footnote: "Morph Code automatically uses your locally installed Claude Code or Codex CLI authentication. You can also configure API keys stored locally in ~/.morph-code/providers.json (0600) or via standard environment variables."
+ ) {
+ Button {
+ Task {
+ await state.loadProviderKeys()
+ await state.loadProviderHarnesses()
+ await state.refreshCodeState()
+ }
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .morphRound(diameter: 26)
+ .help("Refresh provider status")
+ } content: {
+ ForEach(LocalProviderChoice.allCases) { choice in
+ builtinProviderRow(choice)
+ }
+ }
+
+ MorphProviderHarnessesSection(state: state)
+
+ MorphCustomProvidersSection(state: state)
+ }
+ .task {
+ await state.loadProviderKeys()
+ await state.loadProviderHarnesses()
+ await state.loadCustomProviders()
+ await state.refreshCodeState()
+ }
+ }
+
+ private func builtinProviderRow(_ choice: LocalProviderChoice) -> some View {
+ let hasCLI = choice.supportsLocalCLI && (state.nativeCliAvailable[choice.rawValue] == true)
+ let hasKey = state.providerKeyStatus[choice.rawValue] == true
+ let detail: String = {
+ var parts: [String] = []
+ if choice.supportsLocalCLI {
+ parts.append(hasCLI ? "Local \(choice.cliBinaryName) CLI detected" : "\(choice.cliBinaryName) CLI not found")
+ }
+ parts.append(hasKey ? "API key configured" : "Env: \(choice.envKeyName)")
+ return parts.joined(separator: " · ")
+ }()
+
+ return MorphSettingsRow(choice.title, detail: detail) {
+ MorphServiceIcon(brand: choice.brand)
+ } trailing: {
+ HStack(spacing: 8) {
+ if hasCLI || hasKey {
+ AnymorphBadge(hasKey ? "API Key" : "Local CLI")
+ }
+ Button(hasKey ? "Update Key" : "Set API Key") {
+ editingProviderKey = choice
+ }
+ .anymorphButton(size: .inline, appearance: .secondary)
+ if hasKey {
+ Button {
+ Task { await state.clearProviderKey(provider: choice.rawValue) }
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 24)
+ .help("Clear saved API key")
+ }
+ }
+ }
+ }
+
+ // MARK: - Harness & MCP
+
+ private var harnessSection: some View {
+ CodeHarnessSettingsSection(state: state)
+ }
+}
+
+// MARK: - Navigation Row
+
+private struct SettingsNavRow: View {
+ let section: MorphSettingsSection
+ let isSelected: Bool
+ let action: () -> Void
+ @State private var hovered = false
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 10) {
+ Image(systemName: section.systemImage)
+ .font(.system(size: 13, weight: .regular))
+ .foregroundStyle(AnymorphColor.fgSecondary)
+ .frame(width: 18)
+ Text(section.title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 34)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(isSelected ? AnymorphColor.bgSelected : (hovered ? AnymorphColor.bgHover : Color.clear))
+ )
+ .contentShape(RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous))
+ }
+ .buttonStyle(.morphPlain)
+ .onHover { hovered = $0 }
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ }
+}
+
+// MARK: - Add Local Provider Account / Key Sheet
+
+private enum LocalProviderChoice: String, CaseIterable, Identifiable {
+ case claude
+ case codex
+ case deepseek
+
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .claude: return "Claude"
+ case .codex: return "Codex"
+ case .deepseek: return "DeepSeek"
+ }
+ }
+
+ var supportsLocalCLI: Bool {
+ self == .claude || self == .codex
+ }
+
+ var cliBinaryName: String {
+ switch self {
+ case .claude: return "claude"
+ case .codex: return "codex"
+ case .deepseek: return ""
+ }
+ }
+
+ var envKeyName: String {
+ switch self {
+ case .claude: return "ANTHROPIC_API_KEY"
+ case .codex: return "OPENAI_API_KEY"
+ case .deepseek: return "DEEPSEEK_API_KEY"
+ }
+ }
+
+ var brand: MorphBrand {
+ switch self {
+ case .claude: return .claude
+ case .codex: return .openai
+ case .deepseek: return .deepseek
+ }
+ }
+}
+
+private struct ConfigureProviderKeySheet: View {
+ @Bindable var state: MorphAppState
+ let provider: LocalProviderChoice
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var apiKey = ""
+ @State private var baseURL = ""
+ @State private var isBusy = false
+ @State private var errorMessage: String?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 18) {
+ HStack(spacing: 8) {
+ MorphBrandMark(provider.brand, size: 17)
+ Text("Configure \(provider.title)")
+ .anymorphText(.subhead, weight: .strong, color: AnymorphColor.fgPrimary)
+ Spacer()
+ Button {
+ dismiss()
+ } label: {
+ Image(systemName: "xmark")
+ }
+ .morphRound(diameter: 26)
+ }
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text("API Key (\(provider.envKeyName))")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ SecureField("sk-...", text: $apiKey)
+ .textFieldStyle(.plain)
+ .anymorphText(.body)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ .background(AnymorphColor.bgCard)
+ .clipShape(RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous))
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.sm, style: .continuous)
+ .stroke(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ }
+
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Base URL (optional)")
+ .anymorphText(.caption, weight: .emphasis, color: AnymorphColor.fgSecondary)
+ AnymorphTextField("Default official endpoint", text: $baseURL)
+ }
+
+ Text("Stored locally in ~/.morph-code/providers.json with 0600 permissions. Leave empty to use your local CLI login or environment variable.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgSecondary)
+ .fixedSize(horizontal: false, vertical: true)
+
+ if let errorMessage, !errorMessage.isEmpty {
+ Text(errorMessage)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.statusError)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ HStack {
+ Spacer()
+ Button("Cancel") { dismiss() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button(isBusy ? "Saving…" : "Save") {
+ Task { await save() }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(isBusy || (apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
+ }
+ }
+ .padding(22)
+ .frame(width: 460)
+ .background(AnymorphColor.bgBase)
+ .onAppear {
+ baseURL = state.providerBaseURLs[provider.rawValue] ?? ""
+ }
+ }
+
+ private func save() async {
+ isBusy = true
+ errorMessage = nil
+ defer { isBusy = false }
+ let ok = await state.saveProviderKey(
+ provider: provider.rawValue,
+ apiKey: apiKey,
+ baseURL: baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : baseURL
+ )
+ if ok {
+ dismiss()
+ } else {
+ errorMessage = state.notice?.text ?? "Could not save provider settings."
+ }
+ }
+}
+
+// MARK: - Code Harness Settings Section
+
+private struct CodeHarnessSettingsSection: View {
+ @Bindable var state: MorphAppState
+
+ @State private var selectedProjectId: String?
+ @State private var showsMCPForm = false
+ @State private var mcpName = ""
+ @State private var mcpTransport: HarnessMCPTransport = .stdio
+ @State private var mcpCommand = ""
+ @State private var mcpArgs = ""
+ @State private var mcpURL = ""
+ @State private var mcpHeaders = ""
+ @State private var mcpEnv = ""
+
+ @State private var globalAgentsDraft = ""
+ @State private var projectAgentsDraft = ""
+ @State private var isSavingAgents = false
+
+ @State private var skillDraft: HarnessSkillDraft?
+
+ @State private var showsScriptForm = false
+ @State private var scriptName = ""
+ @State private var scriptCommand = ""
+ @State private var scriptKind: HarnessScriptKind = .custom
+ @State private var scriptRunsOnWorktree = false
+
+ @State private var showsHookForm = false
+ @State private var hookEvent: HarnessHookEvent = .preToolUse
+ @State private var hookMatcher = "Bash"
+ @State private var hookCommand = ""
+ @State private var hookScope: HarnessEntryScope = .global
+
+ @State private var showsRuleForm = false
+ @State private var ruleEffect: HarnessRuleEffect = .deny
+ @State private var ruleTool = "Bash"
+ @State private var rulePattern = ""
+ @State private var ruleScope: HarnessEntryScope = .global
+
+ @State private var isCheckingVersions = false
+
+ private var projects: [CodeProject] { state.codeFolderProjects }
+ private var selectedProject: CodeProject? {
+ guard let id = selectedProjectId else { return nil }
+ return projects.first { $0.id == id }
+ }
+ private var servers: [CodeMCPServerConfig] { state.codeHarnessConfig?.mcpServers ?? [] }
+ private var scripts: [CodeProjectScript] {
+ guard let pid = selectedProjectId else { return [] }
+ return state.codeProjectScriptsByProject[pid] ?? []
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ projectGroup
+ if state.isLocalBridgeOutdated {
+ versionGroup
+ }
+ mcpGroup
+ agentsGroup
+ skillsGroup
+ scriptsGroup
+ approvalRulesGroup
+ permissionRulesGroup
+ hooksGroup
+ compactSandboxGroup
+ if !state.isLocalBridgeOutdated {
+ versionGroup
+ }
+ }
+ .task {
+ if selectedProjectId == nil {
+ selectedProjectId = state.selectedCodeThread?.projectId ?? state.codeFolderProjects.first?.id
+ }
+ await reloadProjectScoped()
+ await state.refreshCodeApprovalRules()
+ await state.refreshCodeDaemonHealth()
+ }
+ .onChange(of: selectedProjectId) { _, _ in
+ skillDraft = nil
+ showsScriptForm = false
+ showsHookForm = false
+ showsRuleForm = false
+ Task { await reloadProjectScoped() }
+ }
+ }
+
+ private func reloadProjectScoped() async {
+ let pid = selectedProjectId
+ await state.refreshCodeHarnessConfig(projectId: pid)
+ syncAgentsDrafts()
+ await state.refreshCodeSkills(projectId: pid)
+ if let pid {
+ await state.refreshCodeProjectScripts(projectId: pid)
+ }
+ }
+
+ private func syncAgentsDrafts() {
+ globalAgentsDraft = state.codeHarnessConfig?.agentsMd ?? ""
+ projectAgentsDraft = state.codeHarnessConfig?.projectAgentsMd ?? ""
+ }
+
+ private var projectGroup: some View {
+ MorphSettingsGroup("Target Project", footnote: "Project AGENTS.md, skills, and scripts apply to the selected repository.") {
+ MorphSettingsRow(
+ selectedProject?.name ?? "Global Only",
+ detail: selectedProject?.workspacePath ?? "Select a project to also edit repository-scoped settings"
+ ) {
+ MorphServiceIcon("folder")
+ } trailing: {
+ MorphPopupButton(selectedProject?.name ?? "Global Only", menuWidth: 260, name: "harness-project") {
+ MorphMenuItem("Global Only", icon: .symbol("globe"), isSelected: selectedProjectId == nil) {
+ selectedProjectId = nil
+ }
+ ForEach(projects) { project in
+ MorphMenuItem(
+ project.name,
+ subtitle: project.workspacePath,
+ icon: .symbol("folder"),
+ isSelected: selectedProjectId == project.id,
+ id: project.id
+ ) {
+ selectedProjectId = project.id
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // MARK: MCP Servers
+
+ private var mcpGroup: some View {
+ MorphSettingsGroup(
+ "MCP Servers",
+ footnote: "Configured MCP servers are synced to morphcode, Claude Code, and Codex. Secret header and env values are hidden after saving."
+ ) {
+ Button(showsMCPForm ? "Close" : "Add MCP Server") {
+ withAnimation(AnymorphMotion.base) { showsMCPForm.toggle() }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ } content: {
+ if state.isLoadingCodeHarnessConfig && state.codeHarnessConfig == nil {
+ MorphSettingsRow("Loading…", detail: "Reading harness configuration")
+ } else if servers.isEmpty && !showsMCPForm {
+ MorphSettingsRow("No MCP servers configured", detail: "Add stdio or HTTP MCP servers to expose extra tools to your agents")
+ }
+ ForEach(servers) { server in
+ mcpRow(server)
+ }
+ if showsMCPForm {
+ mcpForm
+ }
+ }
+ }
+
+ private func mcpRow(_ server: CodeMCPServerConfig) -> some View {
+ let target = server.transport == "http"
+ ? (server.url ?? "")
+ : ([server.command ?? ""] + (server.args ?? [])).filter { !$0.isEmpty }.joined(separator: " ")
+ let envKeys = (server.envKeys ?? server.env.map { Array($0.keys) } ?? []).sorted()
+ let headerKeys = (server.headerKeys ?? server.headers.map { Array($0.keys) } ?? []).sorted()
+ let secretKeys = headerKeys + envKeys
+ let isCustom = server.source == nil || server.source == "custom"
+ return MorphSettingsRow(server.name, detail: "\(server.transport) · \(target.isEmpty ? "—" : target)") {
+ MorphServiceIcon(server.transport == "http" ? "network" : "terminal")
+ } trailing: {
+ HStack(spacing: 6) {
+ ForEach(secretKeys.prefix(3), id: \.self) { key in
+ AnymorphBadge(key)
+ }
+ if secretKeys.count > 3 {
+ AnymorphBadge("+\(secretKeys.count - 3)")
+ }
+ if !isCustom, let source = server.source {
+ AnymorphBadge(source)
+ }
+ Toggle(
+ "Enable \(server.name)",
+ isOn: Binding(
+ get: { server.enabled },
+ set: { enabled in
+ var updated = server
+ updated.enabled = enabled
+ saveServers(servers.map { $0.name == server.name ? updated : $0 })
+ }
+ )
+ )
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ if isCustom {
+ Button {
+ saveServers(servers.filter { $0.name != server.name })
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Remove")
+ .accessibilityLabel("Remove \(server.name)")
+ }
+ }
+ }
+ }
+
+ private var mcpForm: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphTextField("Name (e.g. github, postgres)", text: $mcpName)
+ AnymorphSegmentControl(items: HarnessMCPTransport.allCases, selection: $mcpTransport, label: { $0.label })
+ if mcpTransport == .stdio {
+ AnymorphTextField("Command (e.g. npx)", text: $mcpCommand)
+ AnymorphTextField("Arguments (space-separated, e.g. -y @modelcontextprotocol/server-github)", text: $mcpArgs)
+ Text("Environment variables (optional, one KEY=VALUE per line)")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ HarnessCodeEditor(text: $mcpEnv, minHeight: 64, maxHeight: 120)
+ } else {
+ AnymorphTextField("URL (e.g. https://mcp.example.com/mcp)", text: $mcpURL)
+ Text("HTTP headers (optional, one KEY: VALUE per line)")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ HarnessCodeEditor(text: $mcpHeaders, minHeight: 64, maxHeight: 120)
+ }
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("Cancel") { resetMCPForm() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button("Save") { addMCPServer() }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(!canSaveMCPServer)
+ }
+ }
+ .padding(16)
+ }
+
+ private var canSaveMCPServer: Bool {
+ let name = mcpName.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !name.isEmpty, !servers.contains(where: { $0.name == name }) else { return false }
+ switch mcpTransport {
+ case .stdio: return !mcpCommand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ case .http: return URL(string: mcpURL.trimmingCharacters(in: .whitespacesAndNewlines))?.scheme != nil
+ }
+ }
+
+ private func addMCPServer() {
+ let name = mcpName.trimmingCharacters(in: .whitespacesAndNewlines)
+ var env: [String: String] = [:]
+ for line in mcpEnv.split(whereSeparator: \.isNewline) {
+ let parts = line.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
+ guard parts.count == 2, !parts[0].isEmpty else { continue }
+ env[parts[0]] = parts[1]
+ }
+ var headers: [String: String] = [:]
+ for line in mcpHeaders.split(whereSeparator: \.isNewline) {
+ let sep: Character = line.contains(":") ? ":" : "="
+ let parts = line.split(separator: sep, maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
+ guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else { continue }
+ headers[parts[0]] = parts[1]
+ }
+ let server: CodeMCPServerConfig
+ switch mcpTransport {
+ case .stdio:
+ let args = mcpArgs.split(whereSeparator: \.isWhitespace).map(String.init)
+ server = CodeMCPServerConfig(
+ name: name,
+ transport: "stdio",
+ command: mcpCommand.trimmingCharacters(in: .whitespacesAndNewlines),
+ args: args.isEmpty ? nil : args,
+ env: env.isEmpty ? nil : env,
+ envKeys: env.isEmpty ? nil : env.keys.sorted()
+ )
+ case .http:
+ server = CodeMCPServerConfig(
+ name: name,
+ transport: "http",
+ url: mcpURL.trimmingCharacters(in: .whitespacesAndNewlines),
+ headers: headers.isEmpty ? nil : headers,
+ headerKeys: headers.isEmpty ? nil : headers.keys.sorted(),
+ env: env.isEmpty ? nil : env,
+ envKeys: env.isEmpty ? nil : env.keys.sorted()
+ )
+ }
+ saveServers(servers + [server]) { ok in
+ if ok { resetMCPForm() }
+ }
+ }
+
+ private func resetMCPForm() {
+ withAnimation(AnymorphMotion.base) { showsMCPForm = false }
+ mcpName = ""
+ mcpTransport = .stdio
+ mcpCommand = ""
+ mcpArgs = ""
+ mcpURL = ""
+ mcpHeaders = ""
+ mcpEnv = ""
+ }
+
+ private func saveServers(_ list: [CodeMCPServerConfig], completion: ((Bool) -> Void)? = nil) {
+ let pid = selectedProjectId
+ Task {
+ let ok = await state.saveCodeHarnessConfig(projectId: pid, mcpServers: list)
+ completion?(ok)
+ }
+ }
+
+ // MARK: AGENTS.md
+
+ private var agentsGroup: some View {
+ MorphSettingsGroup(
+ "Global & Project AGENTS.md",
+ footnote: "Saved instructions are synced to AGENTS.md and CLAUDE.md for morphcode, Claude Code, and Codex."
+ ) {
+ VStack(alignment: .leading, spacing: 8) {
+ editorCaption("Global AGENTS.md", path: state.codeHarnessConfig?.agentsMdPath)
+ HarnessCodeEditor(text: $globalAgentsDraft, minHeight: 140, maxHeight: 280)
+ }
+ .padding(16)
+ if let project = selectedProject {
+ VStack(alignment: .leading, spacing: 8) {
+ editorCaption("\(project.name) · AGENTS.md / CLAUDE.md", path: state.codeHarnessConfig?.projectAgentsPath)
+ HarnessCodeEditor(text: $projectAgentsDraft, minHeight: 140, maxHeight: 280)
+ }
+ .padding(16)
+ }
+ HStack(spacing: 8) {
+ Text(agentsDirty ? "Unsaved changes" : "Synced")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ Spacer(minLength: 8)
+ Button("Revert") { syncAgentsDrafts() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .disabled(!agentsDirty || isSavingAgents)
+ Button(isSavingAgents ? "Saving…" : "Save & Sync") { saveAgents() }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(!agentsDirty || isSavingAgents)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ }
+ }
+
+ private var agentsDirty: Bool {
+ let config = state.codeHarnessConfig
+ let globalChanged = globalAgentsDraft != (config?.agentsMd ?? "")
+ let projectChanged = selectedProject != nil && projectAgentsDraft != (config?.projectAgentsMd ?? "")
+ return globalChanged || projectChanged
+ }
+
+ private func editorCaption(_ title: String, path: String?) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(title)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 8)
+ if let path, !path.isEmpty {
+ Text(path)
+ .anymorphText(.caption, weight: .base, color: AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.head)
+ }
+ }
+ }
+
+ private func saveAgents() {
+ let config = state.codeHarnessConfig
+ let pid = selectedProjectId
+ let global = globalAgentsDraft != (config?.agentsMd ?? "") ? globalAgentsDraft : nil
+ let project = pid != nil && projectAgentsDraft != (config?.projectAgentsMd ?? "") ? projectAgentsDraft : nil
+ isSavingAgents = true
+ Task {
+ let ok = await state.saveCodeHarnessConfig(projectId: pid, agentsMd: global, projectAgentsMd: project)
+ isSavingAgents = false
+ if ok { syncAgentsDrafts() }
+ }
+ }
+
+ // MARK: Skills
+
+ private var skillsGroup: some View {
+ MorphSettingsGroup("Skills (/skill)", footnote: "Invoke skills from the composer using /name. Project skills appear only in the selected project.") {
+ Button(skillDraft?.isNew == true ? "Close" : "New Skill") {
+ withAnimation(AnymorphMotion.base) {
+ skillDraft = skillDraft?.isNew == true ? nil : HarnessSkillDraft(isProject: selectedProjectId != nil)
+ }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ } content: {
+ if state.codeSkills.isEmpty && skillDraft == nil {
+ MorphSettingsRow("No skills found", detail: "Create a skill to save reusable Markdown instructions as SKILL.md")
+ }
+ if let draft = skillDraft, draft.isNew {
+ skillEditor
+ }
+ ForEach(state.codeSkills) { skill in
+ if let draft = skillDraft, !draft.isNew, draft.originalName == skill.name, draft.source == skill.source {
+ skillEditor
+ } else {
+ skillRow(skill)
+ }
+ }
+ }
+ }
+
+ private func skillRow(_ skill: CodeSkillItem) -> some View {
+ let deletable = ["global", "project", "custom", "user"].contains(skill.source)
+ return MorphSettingsRow("/\(skill.name)", detail: skill.description.isEmpty ? skill.path : skill.description) {
+ EmptyView()
+ } trailing: {
+ HStack(spacing: 6) {
+ AnymorphBadge(skill.source)
+ Button {
+ withAnimation(AnymorphMotion.base) {
+ skillDraft = HarnessSkillDraft(editing: skill)
+ }
+ } label: {
+ Image(systemName: "pencil")
+ }
+ .morphRound(diameter: 26)
+ .help("Edit")
+ if deletable {
+ Button {
+ let projectId = skill.source == "project" ? selectedProjectId : nil
+ Task { _ = await state.deleteCodeSkill(name: skill.name, projectId: projectId) }
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Delete")
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var skillEditor: some View {
+ if let draft = skillDraft {
+ let binding = Binding(
+ get: { skillDraft ?? draft },
+ set: { skillDraft = $0 }
+ )
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphTextField("Name (e.g. review-pr)", text: binding.name)
+ .disabled(!draft.isNew)
+ AnymorphTextField("Description (when to use this skill)", text: binding.description)
+ if draft.isNew, selectedProject != nil {
+ AnymorphSegmentControl(items: HarnessSkillScope.allCases, selection: binding.scope, label: { $0.label })
+ }
+ Text("SKILL.md Body (Markdown)")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ HarnessCodeEditor(text: binding.content, minHeight: 160, maxHeight: 320)
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("Cancel") {
+ withAnimation(AnymorphMotion.base) { skillDraft = nil }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button("Save") { saveSkill() }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(!(skillDraft?.canSave ?? false))
+ }
+ }
+ .padding(16)
+ }
+ }
+
+ private func saveSkill() {
+ guard let draft = skillDraft, draft.canSave else { return }
+ let projectId = draft.scope == .project ? selectedProjectId : nil
+ Task {
+ let ok = await state.saveCodeSkill(
+ name: draft.name.trimmingCharacters(in: .whitespacesAndNewlines),
+ description: draft.description.trimmingCharacters(in: .whitespacesAndNewlines),
+ content: draft.content,
+ projectId: projectId
+ )
+ if ok {
+ withAnimation(AnymorphMotion.base) { skillDraft = nil }
+ }
+ }
+ }
+
+ // MARK: Project Scripts
+
+ private var scriptsGroup: some View {
+ MorphSettingsGroup("Project Scripts", footnote: "Scripts with 'Run on worktree creation' enabled run automatically whenever a new worktree is created.") {
+ if selectedProject != nil {
+ Button(showsScriptForm ? "Close" : "Add Script") {
+ withAnimation(AnymorphMotion.base) { showsScriptForm.toggle() }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ }
+ } content: {
+ if let project = selectedProject {
+ if scripts.isEmpty && !showsScriptForm {
+ MorphSettingsRow("No scripts saved", detail: "Save setup, dev, test, or lint commands for \(project.name)")
+ }
+ ForEach(scripts) { script in
+ scriptRow(script, project: project)
+ }
+ if showsScriptForm {
+ scriptForm(project: project)
+ }
+ } else {
+ MorphSettingsRow("Select a project", detail: "Scripts are stored per project")
+ }
+ }
+ }
+
+ private func scriptRow(_ script: CodeProjectScript, project: CodeProject) -> some View {
+ let detail = [script.kind, script.command, script.runOnWorktree == true ? "Auto-run on worktree" : nil]
+ .compactMap { $0 }
+ .joined(separator: " · ")
+ return MorphSettingsRow(script.name, detail: detail) {
+ MorphServiceIcon(HarnessScriptKind(rawValue: script.kind)?.systemImage ?? "terminal")
+ } trailing: {
+ HStack(spacing: 6) {
+ Button("Run") {
+ let threadId = state.selectedCodeThread.flatMap { $0.projectId == project.id ? $0.id : nil }
+ Task { await state.runCodeProjectScript(projectId: project.id, scriptId: script.id, threadId: threadId) }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button {
+ let remaining = scripts.filter { $0.id != script.id }
+ Task { _ = await state.saveCodeProjectScripts(projectId: project.id, scripts: remaining) }
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Delete")
+ }
+ }
+ }
+
+ private func scriptForm(project: CodeProject) -> some View {
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphTextField("Name (e.g. Test)", text: $scriptName)
+ AnymorphTextField("Command (e.g. npm test)", text: $scriptCommand)
+ AnymorphSegmentControl(items: HarnessScriptKind.allCases, selection: $scriptKind, label: { $0.rawValue })
+ HStack(spacing: 12) {
+ Text("Run on worktree creation")
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ Spacer(minLength: 8)
+ Toggle("Run on worktree creation", isOn: $scriptRunsOnWorktree)
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ }
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("Cancel") { resetScriptForm() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button("Save") {
+ let script = CodeProjectScript(
+ name: scriptName.trimmingCharacters(in: .whitespacesAndNewlines),
+ command: scriptCommand.trimmingCharacters(in: .whitespacesAndNewlines),
+ kind: scriptKind.rawValue,
+ runOnWorktree: scriptRunsOnWorktree ? true : nil
+ )
+ let next = scripts + [script]
+ Task {
+ if await state.saveCodeProjectScripts(projectId: project.id, scripts: next) {
+ resetScriptForm()
+ }
+ }
+ }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(
+ scriptName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ || scriptCommand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ )
+ }
+ }
+ .padding(16)
+ }
+
+ private func resetScriptForm() {
+ withAnimation(AnymorphMotion.base) { showsScriptForm = false }
+ scriptName = ""
+ scriptCommand = ""
+ scriptKind = .custom
+ scriptRunsOnWorktree = false
+ }
+
+ // MARK: Approval Rules
+
+ private var approvalRulesGroup: some View {
+ MorphSettingsGroup(
+ "Auto-Allow Rules",
+ footnote: "Added when you pick 'Always allow this prefix' on an approval card."
+ ) {
+ if state.codeApprovalRules.isEmpty {
+ MorphSettingsRow("No auto-allow rules", detail: "Approve commands with 'Always allow' to add prefix rules here")
+ }
+ ForEach(state.codeApprovalRules) { rule in
+ approvalRuleRow(rule)
+ }
+ }
+ }
+
+ private func approvalRuleRow(_ rule: CodeApprovalRule) -> some View {
+ let scope = rule.projectId.map { id in state.codeProjects.first { $0.id == id }?.name ?? "Project" } ?? "Global"
+ let detail = [scope, rule.actionKind].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
+ return HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(rule.prefix)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Text(detail)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ Spacer(minLength: 8)
+ AnymorphBadge(rule.projectId == nil ? "global" : "project")
+ Button {
+ Task { await state.deleteCodeApprovalRule(id: rule.id) }
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Delete")
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 11)
+ .frame(minHeight: 52)
+ }
+
+ // MARK: Auto-Compact & Sandbox
+
+ private var autoCompactEnabled: Bool {
+ state.codeHarnessConfig?.autoCompactEnabled ?? true
+ }
+
+ private var autoCompactTokens: Int {
+ state.codeHarnessConfig?.effectiveAutoCompactTokens ?? CodeHarnessConfig.defaultAutoCompactTokens
+ }
+
+ private var networkSandbox: HarnessNetworkSandbox {
+ HarnessNetworkSandbox(rawValue: state.codeHarnessConfig?.networkSandbox ?? "") ?? .inherit
+ }
+
+ private var compactSandboxGroup: some View {
+ MorphSettingsGroup(
+ "Auto-Compact & Network Sandbox",
+ footnote: "Synced to morphcode, Claude Code, and Codex configuration."
+ ) {
+ MorphSettingsRow("Auto-Compact Context", detail: "Automatically summarize conversation when context approaches the threshold") {
+ MorphServiceIcon("rectangle.compress.vertical")
+ } trailing: {
+ Toggle(
+ "Auto-Compact Context",
+ isOn: Binding(
+ get: { autoCompactEnabled },
+ set: { enabled in saveHarnessExtras(autoCompactEnabled: enabled) }
+ )
+ )
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ }
+ MorphSettingsRow("Compact Threshold", detail: "Trigger compaction once token usage reaches this limit") {
+ MorphServiceIcon("gauge.with.dots.needle.67percent")
+ } trailing: {
+ MorphPopupButton(CodeHarnessConfig.tokenLimitLabel(autoCompactTokens), disabled: !autoCompactEnabled, menuWidth: 160, name: "harness-compact-threshold") {
+ ForEach(Self.autoCompactTokenLimits, id: \.self) { tokens in
+ MorphMenuItem(CodeHarnessConfig.tokenLimitLabel(tokens), isSelected: tokens == autoCompactTokens, id: "compact-\(tokens)") {
+ saveHarnessExtras(autoCompactTokens: tokens)
+ }
+ }
+ }
+ }
+ MorphSettingsRow("Network Sandbox", detail: networkSandbox.detail) {
+ MorphServiceIcon("network.badge.shield.half.filled")
+ } trailing: {
+ MorphPopupButton(networkSandbox.label, menuWidth: 300, name: "harness-network-sandbox") {
+ ForEach(HarnessNetworkSandbox.allCases) { mode in
+ MorphMenuItem(mode.label, subtitle: mode.detail, isSelected: mode == networkSandbox, id: mode.rawValue) {
+ saveHarnessExtras(networkSandbox: mode.rawValue)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private static let autoCompactTokenLimits = [200_000, 300_000, 400_000, 500_000, 600_000, 800_000, 1_000_000]
+
+ // MARK: Hooks
+
+ private var hooks: [CodeHarnessHook] {
+ state.codeHarnessConfig?.hooks ?? []
+ }
+
+ private var hooksGroup: some View {
+ MorphSettingsGroup(
+ "Hooks (PreToolUse · PostToolUse · Notification · Stop)",
+ footnote: "Shell commands executed before/after tool use, on notifications, or when a turn finishes."
+ ) {
+ Button(showsHookForm ? "Close" : "Add Hook") {
+ withAnimation(AnymorphMotion.base) { showsHookForm.toggle() }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ } content: {
+ if hooks.isEmpty && !showsHookForm {
+ MorphSettingsRow("No hooks configured", detail: "Example: run a formatter after Edit|Write or chime on Stop")
+ }
+ ForEach(hooks) { hook in
+ hookRow(hook)
+ }
+ if showsHookForm {
+ hookForm
+ }
+ }
+ }
+
+ private func hookRow(_ hook: CodeHarnessHook) -> some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 6) {
+ AnymorphBadge(hook.event)
+ if !hook.matcher.isEmpty {
+ Text(hook.matcher)
+ .anymorphText(.footnote, weight: .emphasis, color: AnymorphColor.fgSecondary, monospaced: true)
+ .lineLimit(1)
+ }
+ }
+ Text(hook.command)
+ .anymorphText(.callout, weight: .base, color: hook.enabled ? AnymorphColor.fgPrimary : AnymorphColor.fgTertiary, monospaced: true)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer(minLength: 8)
+ AnymorphBadge(HarnessEntryScope(rawValue: hook.scope)?.label ?? hook.scope)
+ Toggle(
+ "Enable \(hook.command)",
+ isOn: Binding(
+ get: { hook.enabled },
+ set: { enabled in
+ var updated = hook
+ updated.enabled = enabled
+ saveHarnessExtras(hooks: hooks.map { $0.id == hook.id ? updated : $0 })
+ }
+ )
+ )
+ .toggleStyle(AnymorphSwitchStyle())
+ .labelsHidden()
+ Button {
+ saveHarnessExtras(hooks: hooks.filter { $0.id != hook.id })
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Delete")
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 11)
+ .frame(minHeight: 52)
+ }
+
+ private var hookForm: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphSegmentControl(items: HarnessHookEvent.allCases, selection: $hookEvent, label: { $0.rawValue })
+ if hookEvent.usesMatcher {
+ AnymorphTextField("Tool matcher (e.g. Bash, Edit|Write, *)", text: $hookMatcher)
+ }
+ AnymorphTextField("Command (e.g. make fmt)", text: $hookCommand)
+ scopePicker(selection: $hookScope)
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("Cancel") { resetHookForm() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button("Save") { addHook() }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(hookCommand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ .padding(16)
+ }
+
+ private func addHook() {
+ let matcher = hookMatcher.trimmingCharacters(in: .whitespacesAndNewlines)
+ let hook = CodeHarnessHook(
+ event: hookEvent.rawValue,
+ matcher: hookEvent.usesMatcher ? (matcher.isEmpty ? "*" : matcher) : "",
+ command: hookCommand.trimmingCharacters(in: .whitespacesAndNewlines),
+ scope: effectiveScope(hookScope).rawValue
+ )
+ saveHarnessExtras(hooks: hooks + [hook]) { ok in
+ if ok { resetHookForm() }
+ }
+ }
+
+ private func resetHookForm() {
+ withAnimation(AnymorphMotion.base) { showsHookForm = false }
+ hookEvent = .preToolUse
+ hookMatcher = "Bash"
+ hookCommand = ""
+ hookScope = .global
+ }
+
+ // MARK: Permission Rules
+
+ private var permissionRules: [CodeHarnessPermissionRule] {
+ state.codeHarnessConfig?.permissionRules ?? []
+ }
+
+ private var permissionRulesGroup: some View {
+ MorphSettingsGroup(
+ "Permission Rules (Allow · Ask · Deny)",
+ footnote: "Fine-grained tool policies enforced by the local morphcode harness."
+ ) {
+ Button(showsRuleForm ? "Close" : "Add Rule") {
+ withAnimation(AnymorphMotion.base) { showsRuleForm.toggle() }
+ }
+ .anymorphButton(size: .inline, appearance: .ghost)
+ } content: {
+ if permissionRules.isEmpty && !showsRuleForm {
+ MorphSettingsRow("No permission rules", detail: "Example: deny Bash rm -rf or allow WebFetch docs.example.com")
+ }
+ ForEach(permissionRules) { rule in
+ permissionRuleRow(rule)
+ }
+ if showsRuleForm {
+ permissionRuleForm
+ }
+ }
+ }
+
+ private func permissionRuleRow(_ rule: CodeHarnessPermissionRule) -> some View {
+ HStack(spacing: 12) {
+ AnymorphBadge(HarnessRuleEffect(rawValue: rule.effect)?.label ?? rule.effect)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(rule.tool)
+ .anymorphText(.callout, weight: .emphasis, color: AnymorphColor.fgPrimary)
+ .lineLimit(1)
+ Text(rule.pattern.isEmpty ? "All invocations" : rule.pattern)
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary, monospaced: !rule.pattern.isEmpty)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ Spacer(minLength: 8)
+ AnymorphBadge(HarnessEntryScope(rawValue: rule.scope)?.label ?? rule.scope)
+ Button {
+ saveHarnessExtras(permissionRules: permissionRules.filter { $0.id != rule.id })
+ } label: {
+ Image(systemName: "trash")
+ }
+ .morphRound(diameter: 26)
+ .help("Delete")
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 11)
+ .frame(minHeight: 52)
+ }
+
+ private var permissionRuleForm: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ AnymorphSegmentControl(items: HarnessRuleEffect.allCases, selection: $ruleEffect, label: { $0.formLabel })
+ HStack(spacing: 8) {
+ AnymorphTextField("Tool (e.g. Bash)", text: $ruleTool)
+ MorphPopupButton("Pick Tool", menuWidth: 200, name: "harness-rule-tool") {
+ ForEach(Self.permissionRuleTools, id: \.self) { tool in
+ MorphMenuItem(tool, isSelected: tool == ruleTool, id: "rule-tool-\(tool)") {
+ ruleTool = tool
+ }
+ }
+ }
+ }
+ AnymorphTextField(rulePatternPlaceholder, text: $rulePattern)
+ scopePicker(selection: $ruleScope)
+ HStack(spacing: 8) {
+ Spacer(minLength: 0)
+ Button("Cancel") { resetRuleForm() }
+ .anymorphButton(size: .md, appearance: .secondary)
+ Button("Save") { addPermissionRule() }
+ .anymorphButton(size: .md, appearance: .solid)
+ .disabled(ruleTool.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ }
+ .padding(16)
+ }
+
+ private static let permissionRuleTools = ["Bash", "Read", "Write", "Edit", "WebFetch", "MCP"]
+
+ private var rulePatternPlaceholder: String {
+ switch ruleTool.trimmingCharacters(in: .whitespacesAndNewlines) {
+ case "Bash": return "Command prefix (e.g. rm -rf)"
+ case "Read", "Write", "Edit": return "Path glob (e.g. ./secrets/**)"
+ case "WebFetch": return "Domain (e.g. docs.example.com)"
+ case "MCP": return "Server or tool (e.g. github)"
+ default: return "Pattern (empty matches all)"
+ }
+ }
+
+ private func addPermissionRule() {
+ let rule = CodeHarnessPermissionRule(
+ effect: ruleEffect.rawValue,
+ tool: ruleTool.trimmingCharacters(in: .whitespacesAndNewlines),
+ pattern: rulePattern.trimmingCharacters(in: .whitespacesAndNewlines),
+ scope: effectiveScope(ruleScope).rawValue
+ )
+ saveHarnessExtras(permissionRules: permissionRules + [rule]) { ok in
+ if ok { resetRuleForm() }
+ }
+ }
+
+ private func resetRuleForm() {
+ withAnimation(AnymorphMotion.base) { showsRuleForm = false }
+ ruleEffect = .deny
+ ruleTool = "Bash"
+ rulePattern = ""
+ ruleScope = .global
+ }
+
+ // MARK: Shared Helpers
+
+ @ViewBuilder
+ private func scopePicker(selection: Binding) -> some View {
+ if selectedProject != nil {
+ AnymorphSegmentControl(items: HarnessEntryScope.allCases, selection: selection, label: { $0.label })
+ } else {
+ Text("Saved globally because no project is selected.")
+ .anymorphText(.footnote, weight: .base, color: AnymorphColor.fgTertiary)
+ }
+ }
+
+ private func effectiveScope(_ scope: HarnessEntryScope) -> HarnessEntryScope {
+ selectedProjectId == nil ? .global : scope
+ }
+
+ private func saveHarnessExtras(
+ hooks: [CodeHarnessHook]? = nil,
+ permissionRules: [CodeHarnessPermissionRule]? = nil,
+ autoCompactEnabled: Bool? = nil,
+ autoCompactTokens: Int? = nil,
+ networkSandbox: String? = nil,
+ completion: ((Bool) -> Void)? = nil
+ ) {
+ let pid = selectedProjectId
+ Task {
+ let ok = await state.saveCodeHarnessConfig(
+ projectId: pid,
+ hooks: hooks,
+ permissionRules: permissionRules,
+ autoCompactEnabled: autoCompactEnabled,
+ autoCompactTokens: autoCompactTokens,
+ networkSandbox: networkSandbox
+ )
+ completion?(ok)
+ }
+ }
+
+ // MARK: Local Daemon Version
+
+ private var versionGroup: some View {
+ let localVersion = state.localBridgeHealth?.version ?? state.localCodeState?.daemonVersion
+ let minimum = MorphAppState.minimumSupportedDaemonVersion
+ return MorphSettingsGroup(
+ "Daemon Version",
+ footnote: "Recommended minimum morphcode version is v\(minimum)."
+ ) {
+ MorphSettingsRow("Local Daemon (morphcode)", detail: versionDetail(localVersion, health: state.localBridgeHealth)) {
+ MorphServiceIcon("laptopcomputer")
+ } trailing: {
+ AnymorphBadge(compatibilityLabel(localVersion, health: state.localBridgeHealth))
+ }
+ MorphSettingsRow("Protocol", detail: state.localBridgeHealth?.protocolVersion.map { "v\($0)" } ?? "Not checked yet") {
+ MorphServiceIcon("arrow.left.arrow.right")
+ } trailing: {
+ Button(isCheckingVersions ? "Checking…" : "Check Again") {
+ isCheckingVersions = true
+ Task {
+ await state.refreshCodeDaemonHealth()
+ isCheckingVersions = false
+ }
+ }
+ .anymorphButton(size: .md, appearance: .secondary)
+ .disabled(isCheckingVersions)
+ }
+ }
+ }
+
+ private func versionDetail(_ version: String?, health: CodeDaemonHealth?) -> String {
+ guard let version, !version.isEmpty else { return "Not connected" }
+ var parts = ["v\(version)"]
+ if let status = health?.status, !status.isEmpty {
+ parts.append(status)
+ }
+ if let caps = health?.capabilities, !caps.isEmpty {
+ parts.append("\(caps.count) capabilities")
+ }
+ return parts.joined(separator: " · ")
+ }
+
+ private func compatibilityLabel(_ version: String?, health: CodeDaemonHealth?) -> String {
+ guard let version, !version.isEmpty else { return "Unknown" }
+ if version.compare(MorphAppState.minimumSupportedDaemonVersion, options: .numeric) == .orderedAscending {
+ return "Update recommended"
+ }
+ return "Compatible"
+ }
+}
+
+private enum HarnessMCPTransport: String, CaseIterable, Identifiable, Hashable {
+ case stdio
+ case http
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .stdio: return "stdio (Command)"
+ case .http: return "http (URL)"
+ }
+ }
+}
+
+private enum HarnessNetworkSandbox: String, CaseIterable, Identifiable, Hashable {
+ case inherit
+ case restricted
+ case open
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .inherit: return "Default (inherit)"
+ case .restricted: return "Restricted"
+ case .open: return "Open"
+ }
+ }
+
+ var detail: String {
+ switch self {
+ case .inherit: return "Follow each provider's default network settings"
+ case .restricted: return "Block WebFetch/WebSearch and strip outbound proxies"
+ case .open: return "Unrestricted network access"
+ }
+ }
+}
+
+private enum HarnessHookEvent: String, CaseIterable, Identifiable, Hashable {
+ case preToolUse = "PreToolUse"
+ case postToolUse = "PostToolUse"
+ case notification = "Notification"
+ case stop = "Stop"
+
+ var id: String { rawValue }
+
+ var usesMatcher: Bool {
+ self == .preToolUse || self == .postToolUse
+ }
+}
+
+private enum HarnessRuleEffect: String, CaseIterable, Identifiable, Hashable {
+ case allow
+ case ask
+ case deny
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .allow: return "Allow"
+ case .ask: return "Ask"
+ case .deny: return "Deny"
+ }
+ }
+
+ var formLabel: String {
+ switch self {
+ case .allow: return "Allow"
+ case .ask: return "Ask"
+ case .deny: return "Deny"
+ }
+ }
+}
+
+private enum HarnessEntryScope: String, CaseIterable, Identifiable, Hashable {
+ case global
+ case project
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .global: return "Global"
+ case .project: return "Project"
+ }
+ }
+}
+
+private enum HarnessScriptKind: String, CaseIterable, Identifiable, Hashable {
+ case setup
+ case dev
+ case test
+ case lint
+ case custom
+
+ var id: String { rawValue }
+
+ var systemImage: String {
+ switch self {
+ case .setup: return "shippingbox"
+ case .dev: return "play"
+ case .test: return "checkmark.seal"
+ case .lint: return "wand.and.stars"
+ case .custom: return "terminal"
+ }
+ }
+}
+
+private enum HarnessSkillScope: String, CaseIterable, Identifiable, Hashable {
+ case global
+ case project
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .global: return "Global"
+ case .project: return "This Project"
+ }
+ }
+}
+
+private struct HarnessSkillDraft: Equatable {
+ var originalName: String?
+ var source: String?
+ var name = ""
+ var description = ""
+ var content = ""
+ var scope: HarnessSkillScope = .global
+
+ var isNew: Bool { originalName == nil }
+
+ var canSave: Bool {
+ let clean = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !clean.isEmpty, !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }
+ return clean.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" }
+ }
+
+ init(isProject: Bool) {
+ scope = isProject ? .project : .global
+ }
+
+ init(editing skill: CodeSkillItem) {
+ originalName = skill.name
+ source = skill.source
+ name = skill.name
+ description = skill.description
+ content = skill.content ?? ""
+ scope = skill.source == "project" ? .project : .global
+ }
+}
+
+private struct HarnessCodeEditor: View {
+ @Binding var text: String
+ var minHeight: CGFloat = 120
+ var maxHeight: CGFloat = 260
+
+ var body: some View {
+ TextEditor(text: $text)
+ .font(AnymorphFonts.font(.footnote, weight: .base, monospaced: true))
+ .foregroundStyle(AnymorphColor.fgPrimary)
+ .scrollContentBackground(.hidden)
+ .autocorrectionDisabled()
+ .padding(8)
+ .frame(minHeight: minHeight, maxHeight: maxHeight)
+ .background(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .fill(AnymorphColor.bgBase)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: AnymorphRadius.lg, style: .continuous)
+ .strokeBorder(AnymorphColor.strokeBase, lineWidth: 1)
+ )
+ }
+}
diff --git a/apple/Packages/MorphCore/Package.swift b/apple/Packages/MorphCore/Package.swift
new file mode 100644
index 000000000..55bb7ad1f
--- /dev/null
+++ b/apple/Packages/MorphCore/Package.swift
@@ -0,0 +1,27 @@
+// swift-tools-version: 6.0
+import PackageDescription
+
+let package = Package(
+ name: "MorphCore",
+ platforms: [
+ .macOS(.v15)
+ ],
+ products: [
+ .library(
+ name: "MorphCore",
+ targets: ["MorphCore"]
+ )
+ ],
+ targets: [
+ .target(
+ name: "MorphCore",
+ linkerSettings: [
+ .linkedLibrary("sqlite3")
+ ]
+ ),
+ .testTarget(
+ name: "MorphCoreTests",
+ dependencies: ["MorphCore"]
+ )
+ ]
+)
diff --git a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeAccountDisplay.swift b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeAccountDisplay.swift
new file mode 100644
index 000000000..d0952125f
--- /dev/null
+++ b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeAccountDisplay.swift
@@ -0,0 +1,106 @@
+import Foundation
+
+public enum CodeDateParser {
+ public static func parse(_ raw: String) -> Date? {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return nil }
+ let fractional = ISO8601DateFormatter()
+ fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ if let date = fractional.date(from: trimmed) { return date }
+ let standard = ISO8601DateFormatter()
+ standard.formatOptions = [.withInternetDateTime]
+ return standard.date(from: trimmed)
+ }
+}
+
+public extension CodeAccountView {
+ /// Whether the account has 5-hour and 7-day usage windows to read.
+ var hasQuotaWindows: Bool {
+ provider != "deepseek" && provider != "venice"
+ }
+
+ /// Whether routing passes the account over for now: it failed its health check or waits out a cooldown.
+ var isCoolingDown: Bool {
+ !healthy || !(cooldownUntil ?? "").isEmpty
+ }
+
+ /// The plan the way its provider writes it: "max_20x" reads "Max 20x" and "api" reads "API".
+ var planLabel: String {
+ let lowered = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ var spaced = ""
+ var previous: Character?
+ for character in lowered {
+ if character == "_" || character == "-" {
+ spaced.append(" ")
+ } else {
+ if let previous, previous.isLetter, character.isNumber {
+ spaced.append(" ")
+ }
+ spaced.append(character)
+ }
+ previous = character
+ }
+ return spaced.split(separator: " ").map { word in
+ if word == "api" { return "API" }
+ guard let first = word.first, first.isLetter else { return String(word) }
+ return first.uppercased() + word.dropFirst()
+ }
+ .joined(separator: " ")
+ }
+
+ /// When the account's usage windows were last read; nil when unavailable.
+ var quotaMeasuredAt: Date? {
+ quotaUpdatedAt.flatMap(CodeDateParser.parse)
+ }
+
+ /// Compact remaining time until a quota window resets (e.g. "2h 15m", "42m", "3d 4h", "Resetting soon").
+ static func compactResetLabel(for raw: String?, now: Date = Date()) -> String? {
+ guard let raw, !raw.isEmpty, let date = CodeDateParser.parse(raw) else { return nil }
+ let seconds = Int(date.timeIntervalSince(now))
+ if seconds <= 60 { return "Resetting soon" }
+ let totalMinutes = seconds / 60
+ if totalMinutes < 60 {
+ return "\(totalMinutes)m"
+ }
+ let totalHours = totalMinutes / 60
+ let mins = totalMinutes % 60
+ if totalHours < 24 {
+ return mins > 0 ? "\(totalHours)h \(mins)m" : "\(totalHours)h"
+ }
+ let days = totalHours / 24
+ let hours = totalHours % 24
+ return hours > 0 ? "\(days)d \(hours)h" : "\(days)d"
+ }
+
+ /// Remaining time until the 5-hour window resets.
+ func reset5hCountdown(now: Date = Date()) -> String? {
+ Self.compactResetLabel(for: reset5hAt, now: now)
+ }
+
+ /// Remaining time until the 7-day window resets.
+ func reset7dCountdown(now: Date = Date()) -> String? {
+ Self.compactResetLabel(for: reset7dAt, now: now)
+ }
+}
+
+public enum CodeQuotaReading: Equatable, Sendable {
+ case current
+ case stale(Date)
+ case missing
+ case notApplicable
+
+ public static let staleAfter: TimeInterval = 10 * 60
+
+ public static func newest(in accounts: [CodeAccountView]) -> Date? {
+ accounts.lazy.filter(\.hasQuotaWindows).compactMap(\.quotaMeasuredAt).max()
+ }
+
+ public static func of(_ account: CodeAccountView, newest: Date?) -> CodeQuotaReading {
+ guard account.hasQuotaWindows else { return .notApplicable }
+ guard let measured = account.quotaMeasuredAt else { return .missing }
+ if let newest, newest.timeIntervalSince(measured) >= staleAfter {
+ return .stale(measured)
+ }
+ return .current
+ }
+}
diff --git a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeComposerDraft.swift b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeComposerDraft.swift
new file mode 100644
index 000000000..41946eb50
--- /dev/null
+++ b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeComposerDraft.swift
@@ -0,0 +1,36 @@
+import Foundation
+
+/// Canonical draft-storage keys for the Morph Code composer.
+///
+/// The new-thread compose screen shares a single draft across all projects
+/// so text and image/file attachments survive switching projects or visiting
+/// existing threads.
+public enum CodeComposerDraftKey {
+ public static let newThread = "new"
+
+ public static func thread(_ threadId: String) -> String {
+ "thread:\(threadId)"
+ }
+
+ public static func key(forSelectedThreadId threadId: String?) -> String {
+ if let threadId, !threadId.isEmpty {
+ return thread(threadId)
+ }
+ return newThread
+ }
+}
+
+/// Per-screen draft text and attachments preserved across thread switches.
+public struct CodeComposerDraft: Equatable, Sendable {
+ public var text: String
+ public var attachments: [CodeImageAttachment]
+
+ public init(text: String = "", attachments: [CodeImageAttachment] = []) {
+ self.text = text
+ self.attachments = attachments
+ }
+
+ public var isEmpty: Bool {
+ text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && attachments.isEmpty
+ }
+}
diff --git a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeImageInput.swift b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeImageInput.swift
new file mode 100644
index 000000000..035300dc2
--- /dev/null
+++ b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeImageInput.swift
@@ -0,0 +1,189 @@
+import Foundation
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+
+/// An image the composer attaches, in a form every coding engine takes: PNG, JPEG, GIF or WebP, upright, at most
+/// `CodeImageNormalizer.defaultMaxLongEdge` pixels on its long edge and `defaultMaxBytes` in size.
+public struct CodeImagePayload: Sendable, Equatable {
+ public let data: Data
+ public let mimeType: String
+ public let fileExtension: String
+ public let pixelWidth: Int
+ public let pixelHeight: Int
+}
+
+/// Turns whatever image a member pastes, drops or picks into a `CodeImagePayload`.
+///
+/// Claude takes images up to 5 MB of base64 and scales anything over 1568 px down; GPT reads at most 2048 px; Gemini
+/// sends the bytes inline. So an image keeps its own bytes when it is already a PNG, JPEG, GIF or WebP that is
+/// upright, within 2048 px and within 3.75 MB (5 MB once base64-encoded). Anything else (TIFF from the clipboard,
+/// HEIC from an iPhone, a 5K screenshot, a photo stored sideways) is redrawn upright within those bounds: as PNG when
+/// it came from a lossless source, as JPEG when it was a photo or the PNG stays too large.
+public enum CodeImageNormalizer {
+ public enum Failure: Error, Equatable, Sendable {
+ /// The data is not an image this device can decode.
+ case unreadable
+ /// No size and quality brought the image under the byte limit.
+ case tooLarge
+ }
+
+ public static let defaultMaxBytes = 3_750_000
+ public static let defaultMaxLongEdge = 2048
+
+ private static let passthrough: [UTType: (mime: String, ext: String)] = [
+ .png: ("image/png", "png"),
+ .jpeg: ("image/jpeg", "jpg"),
+ .gif: ("image/gif", "gif"),
+ .webP: ("image/webp", "webp"),
+ ]
+
+ /// Photo formats, which are redrawn as JPEG rather than PNG.
+ private static let lossySources: Set = [.jpeg, .heic, .heif, .webP]
+
+ public static func normalize(
+ _ data: Data,
+ maxBytes: Int = defaultMaxBytes,
+ maxLongEdge: Int = defaultMaxLongEdge
+ ) throws -> CodeImagePayload {
+ guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
+ CGImageSourceGetCount(source) > 0,
+ let typeIdentifier = CGImageSourceGetType(source),
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
+ let width = properties[kCGImagePropertyPixelWidth] as? Int,
+ let height = properties[kCGImagePropertyPixelHeight] as? Int,
+ width > 0, height > 0
+ else {
+ throw Failure.unreadable
+ }
+ let type = UTType(typeIdentifier as String)
+ let orientation = (properties[kCGImagePropertyOrientation] as? UInt32)
+ .flatMap(CGImagePropertyOrientation.init(rawValue:)) ?? .up
+
+ if let type, let kind = passthrough[type], orientation == .up,
+ max(width, height) <= maxLongEdge, data.count <= maxBytes {
+ return CodeImagePayload(data: data, mimeType: kind.mime, fileExtension: kind.ext, pixelWidth: width, pixelHeight: height)
+ }
+
+ var longEdge = min(max(width, height), maxLongEdge)
+ let prefersJPEG = type.map(lossySources.contains) ?? false
+ // Each pass shrinks the picture a quarter until it fits; a 2048 px image that still does not fit after the
+ // lowest JPEG quality is noise, and noise at 512 px always fits.
+ while longEdge >= 256 {
+ guard let image = upright(source, maxPixelSize: longEdge) else { throw Failure.unreadable }
+ if !prefersJPEG, let png = encode(image, as: .png), png.count <= maxBytes {
+ return CodeImagePayload(data: png, mimeType: "image/png", fileExtension: "png", pixelWidth: image.width, pixelHeight: image.height)
+ }
+ let flat = flattened(image) ?? image
+ for quality in [0.85, 0.7, 0.55, 0.4] {
+ if let jpeg = encode(flat, as: .jpeg, quality: quality), jpeg.count <= maxBytes {
+ return CodeImagePayload(data: jpeg, mimeType: "image/jpeg", fileExtension: "jpg", pixelWidth: image.width, pixelHeight: image.height)
+ }
+ }
+ longEdge = longEdge * 3 / 4
+ }
+ throw Failure.tooLarge
+ }
+
+ /// A small upright picture of the image for previews, its long edge at most maxPixelSize.
+ public static func thumbnail(_ data: Data, maxPixelSize: Int) -> CGImage? {
+ guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary) else {
+ return nil
+ }
+ return upright(source, maxPixelSize: maxPixelSize)
+ }
+
+ /// The name an attachment goes by: the original name with the extension of what is sent, or `image-`.
+ public static func fileName(
+ original: String?,
+ fileExtension: String,
+ date: Date = Date(),
+ timeZone: TimeZone = .current
+ ) -> String {
+ let trimmed = original?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if !trimmed.isEmpty {
+ let stem = (trimmed as NSString).deletingPathExtension
+ return "\(stem.isEmpty ? trimmed : stem).\(fileExtension)"
+ }
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = timeZone
+ formatter.dateFormat = "yyyyMMdd-HHmmss"
+ return "image-\(formatter.string(from: date)).\(fileExtension)"
+ }
+
+ // MARK: Drawing
+
+ private static func upright(_ source: CGImageSource, maxPixelSize: Int) -> CGImage? {
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceThumbnailMaxPixelSize: max(1, maxPixelSize),
+ ]
+ return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)
+ }
+
+ /// The image on white, for JPEG, which has no transparency.
+ private static func flattened(_ image: CGImage) -> CGImage? {
+ switch image.alphaInfo {
+ case .none, .noneSkipFirst, .noneSkipLast:
+ return image
+ default:
+ break
+ }
+ guard let ctx = CGContext(
+ data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
+ ) else { return nil }
+ let rect = CGRect(x: 0, y: 0, width: image.width, height: image.height)
+ ctx.setFillColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 1))
+ ctx.fill(rect)
+ ctx.draw(image, in: rect)
+ return ctx.makeImage()
+ }
+
+ private static func encode(_ image: CGImage, as type: UTType, quality: Double? = nil) -> Data? {
+ let data = NSMutableData()
+ guard let destination = CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil) else { return nil }
+ var properties: [CFString: Any] = [:]
+ if let quality {
+ properties[kCGImageDestinationLossyCompressionQuality] = quality
+ }
+ CGImageDestinationAddImage(destination, image, properties as CFDictionary)
+ guard CGImageDestinationFinalize(destination) else { return nil }
+ return data as Data
+ }
+}
+
+/// What a paste or a drop onto the composer attaches, from what the pasteboard holds.
+///
+/// Finder puts copied files on the pasteboard with their names as text and their icons as an image: image files
+/// attach, other files paste their names. A screenshot copied to the clipboard, or an image a browser copied with
+/// its address, attaches. Spreadsheet cells and rich text come with a picture of themselves: their text pastes.
+public enum CodeImagePasteDecision: Equatable, Sendable {
+ case imageFiles([URL])
+ case imageData
+ case text
+
+ public static func decide(fileURLs: [URL], hasImageData: Bool, plainText: String?) -> CodeImagePasteDecision {
+ if !fileURLs.isEmpty {
+ let images = fileURLs.filter(isImageFile)
+ return images.isEmpty ? .text : .imageFiles(images)
+ }
+ guard hasImageData else { return .text }
+ let text = plainText?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return text.isEmpty || isLoneURL(text) ? .imageData : .text
+ }
+
+ public static func isImageFile(_ url: URL) -> Bool {
+ guard url.isFileURL, let type = UTType(filenameExtension: url.pathExtension) else { return false }
+ return type.conforms(to: .image)
+ }
+
+ private static func isLoneURL(_ text: String) -> Bool {
+ guard !text.contains(where: \.isWhitespace),
+ let scheme = URL(string: text)?.scheme?.lowercased() else { return false }
+ return ["http", "https", "file", "data"].contains(scheme)
+ }
+}
diff --git a/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift
new file mode 100644
index 000000000..d60557098
--- /dev/null
+++ b/apple/Packages/MorphCore/Sources/MorphCore/Models/CodeModelMenu.swift
@@ -0,0 +1,172 @@
+import Foundation
+
+/// How Morph Code organizes its model picker: Auto at top, then compact capability tiers (`Best`, `Standard`),
+/// optional user-registered custom providers, and remaining models under "More models".
+public enum CodeModelMenu {
+ /// A named group of models (a tier like `Best`/`Standard`, or a provider group).
+ public struct EngineGroup: Identifiable, Equatable, Sendable {
+ public let provider: String
+ public let title: String?
+ public let options: [CodeModelOption]
+
+ public init(provider: String, title: String? = nil, options: [CodeModelOption]) {
+ self.provider = provider
+ self.title = title
+ self.options = options
+ }
+
+ public var id: String { provider }
+
+ /// Why every model in a single-engine group cannot run now. Mixed-provider tier groups show status per item.
+ public var status: String? {
+ let distinctProviders = Set(options.map { $0.provider.lowercased() })
+ guard distinctProviders.count == 1 else { return nil }
+ return options.lazy.compactMap(CodeModelMenu.unavailableReason).first
+ }
+ }
+
+ /// A model menu's rows: Auto, tiered main groups, and the rest under More models.
+ public struct Sections: Equatable, Sendable {
+ public let auto: CodeModelOption?
+ public let main: [EngineGroup]
+ public let more: [EngineGroup]
+ }
+
+ private static let bestOrder: [String] = [
+ "orchestrator",
+ "claude/claude-opus-5-5",
+ "codex/gpt-6.2-astra",
+ ]
+
+ private static let standardOrder: [String] = [
+ "claude/claude-sonnet-5-5",
+ "codex/gpt-6.2-sol",
+ "deepseek/deepseek-v4.1-flash-eco",
+ ]
+
+ /// Curated short descriptions for built-in models.
+ private static let purposes: [String: String] = [
+ "auto": "Automatically picks an available configured engine",
+ "orchestrator": "Decomposes tasks and delegates to parallel workers",
+ "claude/claude-opus-5-5": "Complex debugging and deep reasoning",
+ "claude/claude-sonnet-5-5": "Fast everyday coding and reviews",
+ "claude/claude-fable-5-2": "Architecture and long autonomous runs",
+ "codex/gpt-6.2-astra": "Strong multi-step coding and refactoring",
+ "codex/gpt-6.2-sol": "Fast coding and edits",
+ "deepseek/deepseek-v4.1-flash-eco": "Lightweight edits at low cost",
+ ]
+
+ /// Explicit clean display names for curated models.
+ private static let displayNames: [String: String] = [
+ "deepseek/deepseek-v4.1-flash-eco": "DeepSeek 4.1 Flash Eco",
+ ]
+
+ private static let builtinProviders: Set