diff --git a/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json b/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json new file mode 100644 index 00000000..508fe1dd --- /dev/null +++ b/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "icon.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg b/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg new file mode 100644 index 00000000..f88129ef --- /dev/null +++ b/ios/Hapi/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg @@ -0,0 +1 @@ + diff --git a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift index 9a7cbfcd..dfccfe04 100644 --- a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift +++ b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift @@ -20,6 +20,7 @@ struct UserTextBlockView: View { @Environment(\.hapiTypography) private var typography @Environment(\.hapiTheme) private var theme @Environment(\.openChatMessage) private var openMessage + @State private var confirmRewind = false init(block: UserTextBlock) { self.block = block @@ -111,8 +112,39 @@ struct UserTextBlockView: View { metadata: nil, alignment: .trailing ) + if let interactions, let localId = block.localId { + let actions = interactions.historyActions(forMessageLocalId: localId) + // Forking the whole conversation already lives in the + // toolbar menu; per-message history only needs rewind. + if actions.rewind { + Button { + confirmRewind = true + } label: { + Image(systemName: "clock.arrow.circlepath") + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(interactions.historyActionPending) + .accessibilityLabel(Text("Rewind to here")) + } + } } } + .confirmationDialog( + "Rewind to this message?", + isPresented: $confirmRewind, + titleVisibility: .visible + ) { + Button("Rewind", role: .destructive) { + if let localId = block.localId { + interactions?.rewindConversation(toMessageLocalId: localId) + } + } + Button("Cancel", role: .cancel) {} + } message: { + Text("Later messages will be removed from the active conversation.") + } } } diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index b6608a94..66b6e89c 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -18,6 +18,10 @@ struct ChatHeaderUI: Equatable { var project: String? = nil var model: String? = nil var effort: String? = nil + var backgroundTaskCount: Int = 0 + var serviceTier: String? = nil + var collaborationMode: CodexCollaborationMode? = nil + var isCompacting: Bool = false } /// Presentation state machine for the read-only chat screen (M2f) — the iOS @@ -44,6 +48,10 @@ final class ChatModel { // MARK: Published render state private(set) var blocks: [VisibleChatBlock] = [] + /// Reducer context usage for the composer meter; nil until a usage row + /// appears in the current window. + private(set) var latestUsage: LatestUsage? + private(set) var latestGoal: JSONValue? private(set) var header: ChatHeaderUI /// Workspace root, for path display in tool cards. private(set) var basePath: String? @@ -87,6 +95,17 @@ final class ChatModel { private(set) var supersededSessionId: String? /// Delayed session-pipe notice; stable until the hub handshake arrives. + /// Goal/tasks/subagents/team summary for the collapsible status card. + var statusPanelData: ChatStatusPanelData? { + let detail = hub.sessionStore.detail(for: sessionId) + return ChatStatusPanelData.build( + goal: latestGoal, + tasks: detail?.todos, + blocks: blocks, + teamState: detail?.teamState + ) + } + var isReconnecting: Bool { chat.reconnectNotice.isVisible } // MARK: Export @@ -582,12 +601,15 @@ final class ChatModel { let detail = hub.sessionStore.detail(for: sessionId) let summary = hub.sessionStore.sessions.first { $0.id == sessionId } let machines = hub.machineStore.machines - let visible = await pipeline.run( + let output = await pipeline.runResult( messages: window.messages, agentState: detail?.agentState, hasMoreMessages: window.hasMore, directSendLocalIds: interactor.directSendLocalIds ) + let visible = output.blocks + latestUsage = output.latestUsage + latestGoal = output.latestGoal let sources = Set(visible.flatMap { block -> [String] in guard case .block(let value) = block else { return [] } switch value { @@ -730,7 +752,11 @@ final class ChatModel { thinking: detail?.thinking ?? summary?.thinking ?? false, project: project, model: model, - effort: effort + effort: effort, + backgroundTaskCount: detail?.backgroundTaskCount ?? summary?.backgroundTaskCount ?? 0, + serviceTier: detail?.serviceTier, + collaborationMode: detail?.collaborationMode, + isCompacting: detail?.agentState?.contextCompactionStartedAt != nil ) } diff --git a/ios/Hapi/Features/Chat/ChatStatusPanel.swift b/ios/Hapi/Features/Chat/ChatStatusPanel.swift new file mode 100644 index 00000000..c9233a15 --- /dev/null +++ b/ios/Hapi/Features/Chat/ChatStatusPanel.swift @@ -0,0 +1,461 @@ +import HapiProtocol +import HapiUI +import SwiftUI + +/// Read-only session status derived from the current transcript and session +/// detail. This is the native counterpart of the web `SessionStatusPanel` + +/// `TeamPanel`: goal, todo tasks, running subagents, foreground commands, and +/// team state, folded into one collapsible card. +struct ChatStatusPanelData: Equatable { + struct Goal: Equatable { + var objective: String + var status: String + var timeUsedSeconds: Double + var tokensUsed: Double + var tokenBudget: Double? + } + + struct Task: Identifiable, Equatable { + var id: String + var content: String + var completed: Bool + } + + struct Subagent: Identifiable, Equatable { + var id: String + var title: String + var detail: String? + var state: String + } + + struct Terminal: Identifiable, Equatable { + var id: String + var command: String + var cwd: String? + } + + struct TeamMember: Identifiable, Equatable { + var id: String + var name: String + var agentType: String? + var status: String? + } + + struct TeamTask: Identifiable, Equatable { + var id: String + var title: String + var status: String? + var owner: String? + } + + struct TeamMessage: Identifiable, Equatable { + var id: String + var from: String + var to: String + var summary: String + } + + struct Team: Equatable { + var name: String + var description: String? + var members: [TeamMember] + var tasks: [TeamTask] + var messages: [TeamMessage] + } + + var goal: Goal? + var tasks: [Task] + var subagents: [Subagent] + var terminals: [Terminal] + var team: Team? + + var isEmpty: Bool { + goal == nil && tasks.isEmpty && subagents.isEmpty && terminals.isEmpty && team == nil + } + + static func build( + goal: JSONValue?, + tasks: [TodoItem]?, + blocks: [VisibleChatBlock], + teamState: JSONValue? + ) -> ChatStatusPanelData? { + let data = ChatStatusPanelData( + goal: parseGoal(goal), + tasks: (tasks ?? []).map { + Task(id: $0.id.isEmpty ? $0.content : $0.id, + content: $0.content, + completed: $0.status == .completed) + }, + subagents: subagents(in: blocks), + terminals: terminals(in: blocks), + team: parseTeam(teamState) + ) + return data.isEmpty ? nil : data + } + + // MARK: - Goal + + private static func parseGoal(_ value: JSONValue?) -> Goal? { + guard let object = value?.statusObject, + let objective = object["objective"]?.statusString, + !objective.isEmpty else { return nil } + return Goal( + objective: objective, + status: object["status"]?.statusString ?? "", + timeUsedSeconds: object["timeUsedSeconds"]?.statusNumber ?? 0, + tokensUsed: object["tokensUsed"]?.statusNumber ?? 0, + tokenBudget: object["tokenBudget"]?.statusNumber + ) + } + + // MARK: - Tools + + private static func tools(in blocks: [VisibleChatBlock]) -> [ToolCallBlock] { + var result: [ToolCallBlock] = [] + func collect(_ block: ChatBlock) { + guard case .toolCall(let tool) = block else { return } + result.append(tool) + for child in tool.children { collect(child) } + } + for visible in blocks { + switch visible { + case .block(let block): + collect(block) + case .toolGroup(let group): + for tool in group.tools { collect(.toolCall(tool)) } + } + } + return result + } + + private static func subagents(in blocks: [VisibleChatBlock]) -> [Subagent] { + tools(in: blocks).compactMap { block in + let name = block.tool.name.trimmingCharacters(in: .whitespaces).lowercased() + guard name == "task" || name == "agent" || name == "codexagent" + || name.hasPrefix("task:") || name.hasPrefix("agent:") else { return nil } + guard block.tool.state != .completed else { return nil } + let title = inputString(block.tool.input, ["description", "summary", "title", "prompt", "message"]) + ?? inputString(block.tool.input, ["subagent_type", "agent_type"]) + ?? block.tool.nativeTitle + ?? String(localized: "Agent") + let detail = block.children.last.flatMap { child -> String? in + guard case .toolCall(let tool) = child else { return nil } + return tool.tool.nativeTitle ?? tool.tool.name + } + let state: String + switch block.tool.state { + case .error: state = String(localized: "Error") + case .pending: state = String(localized: "Waiting") + default: state = String(localized: "Running") + } + return Subagent(id: block.id, title: title, detail: detail, state: state) + } + } + + private static func terminals(in blocks: [VisibleChatBlock]) -> [Terminal] { + tools(in: blocks).compactMap { block in + guard block.tool.state == .running else { return nil } + let name = block.tool.name.lowercased() + guard name == "bash" || name == "shell" || name == "command" else { return nil } + guard let command = inputString(block.tool.input, ["command", "cmd"]) else { + return Terminal(id: block.id, command: block.tool.nativeTitle ?? name, cwd: nil) + } + return Terminal( + id: block.id, + command: command, + cwd: inputString(block.tool.input, ["cwd", "workdir", "path"]) + ) + } + } + + private static func inputString(_ value: JSONValue?, _ keys: [String]) -> String? { + guard let object = value?.statusObject else { return nil } + for key in keys { + if let string = object[key]?.statusString, + !string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return string + } + } + return nil + } + + // MARK: - Team + + private static func parseTeam(_ value: JSONValue?) -> Team? { + guard let object = value?.statusObject, + let name = object["teamName"]?.statusString, + !name.isEmpty else { return nil } + let members = (object["members"]?.statusArray ?? []).enumerated().compactMap { (index, item) -> TeamMember? in + guard let member = item.statusObject, let memberName = member["name"]?.statusString else { return nil } + return TeamMember( + id: "\(index)-\(memberName)", + name: memberName, + agentType: member["agentType"]?.statusString, + status: member["status"]?.statusString + ) + } + let tasks = (object["tasks"]?.statusArray ?? []).enumerated().compactMap { (index, item) -> TeamTask? in + guard let task = item.statusObject, let title = task["title"]?.statusString else { return nil } + return TeamTask( + id: task["id"]?.statusString ?? "\(index)", + title: title, + status: task["status"]?.statusString, + owner: task["owner"]?.statusString + ) + } + let messages = (object["messages"]?.statusArray ?? []).suffix(5).enumerated().compactMap { (index, item) -> TeamMessage? in + guard let message = item.statusObject, + let from = message["from"]?.statusString, + let to = message["to"]?.statusString else { return nil } + return TeamMessage( + id: "\(index)-\(from)-\(to)", + from: from, + to: to, + summary: message["summary"]?.statusString ?? "" + ) + } + return Team( + name: name, + description: object["description"]?.statusString, + members: members, + tasks: tasks, + messages: messages + ) + } +} + +struct ChatStatusPanelView: View { + let data: ChatStatusPanelData + + @State private var expanded = false + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + + private var completedTasks: Int { data.tasks.filter(\.completed).count } + + private var summary: String { + var parts: [String] = [] + if !data.tasks.isEmpty { parts.append("\(completedTasks)/\(data.tasks.count)") } + if !data.subagents.isEmpty { parts.append("\(data.subagents.count)") } + if !data.terminals.isEmpty { parts.append("\(data.terminals.count)") } + if let team = data.team { parts.append("\(team.name)") } + return parts.joined(separator: " · ") + } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Button { + withAnimation(.easeInOut(duration: 0.18)) { expanded.toggle() } + } label: { + HStack(spacing: 7) { + Image(systemName: "list.bullet.rectangle") + .font(.system(size: 12, weight: .semibold)) + Text("Session status") + .font(typography.captionFont.weight(.semibold)) + if data.goal != nil { + Text("Goal") + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + } + Spacer(minLength: 6) + if !summary.isEmpty { + Text(summary) + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + .lineLimit(1) + } + Image(systemName: "chevron.down") + .font(.system(size: 9, weight: .semibold)) + .rotationEffect(.degrees(expanded ? 180 : 0)) + } + .foregroundStyle(theme.textSecondary) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if expanded { + ScrollView(.vertical, showsIndicators: false) { + VStack(alignment: .leading, spacing: 12) { + if let goal = data.goal { goalSection(goal) } + if !data.tasks.isEmpty { taskSection } + if !data.subagents.isEmpty { subagentSection } + if !data.terminals.isEmpty { terminalSection } + if let team = data.team { teamSection(team) } + } + .padding(.horizontal, 12) + .padding(.bottom, 10) + } + .frame(maxHeight: 280) + } + } + .background(theme.surface, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .padding(.horizontal, 12) + } + + private func goalSection(_ goal: ChatStatusPanelData.Goal) -> some View { + section("Goal") { + Text(verbatim: goal.objective) + .font(typography.captionFont) + .foregroundStyle(theme.textPrimary) + .lineLimit(3) + HStack(spacing: 6) { + Text(verbatim: goal.status) + if goal.tokenBudget != nil { + Text(verbatim: "\(Int(goal.tokensUsed)) / \(Int(goal.tokenBudget ?? 0))") + } + } + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + } + } + + private var taskSection: some View { + section("Tasks", suffix: "\(completedTasks)/\(data.tasks.count)") { + ForEach(data.tasks.prefix(12)) { task in + HStack(alignment: .top, spacing: 6) { + Image(systemName: task.completed ? "checkmark.square.fill" : "square") + .font(.system(size: 10)) + .foregroundStyle(task.completed ? theme.success : theme.textHint) + Text(verbatim: task.content) + .font(typography.captionFont) + .foregroundStyle(task.completed ? theme.textHint : theme.textPrimary) + .strikethrough(task.completed) + } + } + } + } + + private var subagentSection: some View { + section("Subagents") { + ForEach(data.subagents) { agent in + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 5) { + Circle().fill(subagentColor(agent.state)).frame(width: 5, height: 5) + Text(verbatim: agent.title) + .font(typography.captionFont) + .foregroundStyle(theme.textPrimary) + .lineLimit(1) + Spacer(minLength: 4) + Text(verbatim: agent.state) + .font(typography.captionFont) + .foregroundStyle(subagentColor(agent.state)) + } + if let detail = agent.detail { + Text(verbatim: detail) + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + .lineLimit(1) + .padding(.leading, 10) + } + } + } + } + } + + private var terminalSection: some View { + section("Terminals") { + ForEach(data.terminals) { terminal in + VStack(alignment: .leading, spacing: 1) { + Text(verbatim: terminal.command) + .font(typography.codeFont(size: 11)) + .foregroundStyle(theme.textPrimary) + .lineLimit(1) + if let cwd = terminal.cwd { + Text(verbatim: cwd) + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + .lineLimit(1) + } + } + } + } + } + + private func teamSection(_ team: ChatStatusPanelData.Team) -> some View { + section("Team", suffix: team.name) { + if let description = team.description { + Text(verbatim: description) + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + } + if !team.members.isEmpty { + Text(team.members.map(\.name).joined(separator: " · ")) + .font(typography.captionFont) + .foregroundStyle(theme.textPrimary) + } + ForEach(team.tasks.prefix(8)) { task in + HStack(spacing: 5) { + Circle().fill(teamTaskColor(task.status)).frame(width: 5, height: 5) + Text(verbatim: task.title) + .font(typography.captionFont) + .lineLimit(1) + if let owner = task.owner { + Text(verbatim: owner) + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + } + } + } + ForEach(team.messages) { message in + Text(verbatim: "\(message.from) → \(message.to): \(message.summary)") + .font(typography.captionFont) + .foregroundStyle(theme.textHint) + .lineLimit(1) + } + } + } + + private func section( + _ title: LocalizedStringKey, + suffix: String? = nil, + @ViewBuilder content: () -> Content + ) -> some View { + VStack(alignment: .leading, spacing: 3) { + (Text(title) + (suffix.map { Text(verbatim: " · \($0)") } ?? Text(verbatim: ""))) + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(theme.textHint) + .textCase(.uppercase) + content() + } + } + + private func subagentColor(_ state: String) -> Color { + if state == String(localized: "Error") { return theme.danger } + if state == String(localized: "Waiting") { return theme.warning } + return theme.success + } + + private func teamTaskColor(_ status: String?) -> Color { + switch status { + case "completed": return theme.success + case "in_progress": return theme.accent + case "blocked": return theme.danger + default: return theme.textHint + } + } +} + + +private extension JSONValue { + var statusObject: [String: JSONValue]? { + if case .object(let value) = self { return value } + return nil + } + + var statusArray: [JSONValue]? { + if case .array(let value) = self { return value } + return nil + } + + var statusString: String? { + if case .string(let value) = self { return value } + return nil + } + + var statusNumber: Double? { + if case .number(let value) = self { return value } + return nil + } +} diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index dda69d6d..dc1f49b9 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -97,7 +97,14 @@ struct ChatView: View { reconnectNotice } .safeAreaInset(edge: .top, spacing: 0) { - warningBanner + VStack(spacing: 0) { + if let status = model.statusPanelData { + ChatStatusPanelView(data: status) + .padding(.top, 6) + .padding(.bottom, 2) + } + warningBanner + } } // Toast overlays the thread; applying it before the bottom inset // anchors it just above the composer instead of on top of it. @@ -107,9 +114,7 @@ struct ChatView: View { .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { QueuedMessagesBarView(interactor: model.interactor) - ChatComposerStatusBar(model: model) { - configOpen = true - } + ChatComposerStatusBar(model: model) ChatComposerView( interactor: model.interactor, dictation: model.dictation, diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift index 028379a3..035d3f16 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerStatusBar.swift @@ -1,4 +1,5 @@ import HapiClient +import HapiProtocol import HapiUI import SwiftUI @@ -7,7 +8,6 @@ import SwiftUI /// existing session config sheet; this is a readout, not a second settings UI. struct ChatComposerStatusBar: View { let model: ChatModel - let openSettings: () -> Void @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography @@ -28,15 +28,16 @@ struct ChatComposerStatusBar: View { if let label = config.modelOptions?.first(where: { $0.value == config.model })?.label { return label } - return config.model + return config.model ?? model.header.model } private var effortLabel: String? { - config.effortOptions?.first { $0.value == config.effort }?.label - } - - private var permissionLabel: String? { - config.permissionModes.first { $0.mode == config.permissionMode }?.label + if let effort = config.effort ?? model.header.effort { + return config.effortOptions?.first { $0.value == effort }?.label ?? effort + } + // Codex's default has no wire value; show it without forcing a + // model-catalog request just to render the status strip. + return model.header.flavor == "codex" ? "Default" : nil } var body: some View { @@ -52,14 +53,37 @@ struct ChatComposerStatusBar: View { Spacer(minLength: 8) - if let modelLabel { - pill(modelLabel, icon: "cpu") + if let usage = model.latestUsage { + ContextUsagePill(usage: usage, window: usage.contextWindow) } - if let effortLabel { - pill(effortLabel, icon: "speedometer") + if model.header.isCompacting { + statusChip("Compacting", icon: "archivebox.fill", tint: theme.warning) } - if let permissionLabel { - pill(permissionLabel, icon: "lock.shield") + if model.header.backgroundTaskCount > 0 { + statusChip("\(model.header.backgroundTaskCount)", icon: "gearshape.2.fill") + } + if model.header.serviceTier == "fast" { + statusChip("Fast", icon: "bolt.fill", tint: theme.success) + } + if let mode = model.header.collaborationMode, mode != .default { + statusChip(mode.label, icon: "person.2") + } + if modelLabel != nil || effortLabel != nil { + HStack(spacing: 4) { + if let modelLabel { + Image(systemName: "cpu") + .font(.system(size: 9, weight: .medium)) + Text(modelLabel) + } + if let modelLabel, let effortLabel { + Text(verbatim: "·") + .foregroundStyle(theme.textHint) + } + if let effortLabel { + Text(effortLabel) + } + } + .lineLimit(1) } } .font(typography.captionFont) @@ -70,20 +94,115 @@ struct ChatComposerStatusBar: View { .accessibilityElement(children: .combine) } - private func pill(_ label: String, icon: String) -> some View { - Button(action: openSettings) { + private func statusChip(_ label: String, icon: String, tint: Color? = nil) -> some View { + HStack(spacing: 3) { + Image(systemName: icon) + .font(.system(size: 9, weight: .medium)) + Text(label) + .lineLimit(1) + } + .padding(.horizontal, 6) + .padding(.vertical, 3) + .background(theme.surface, in: Capsule()) + .foregroundStyle(tint ?? theme.textSecondary) + } +} + + +/// Compact context-window meter. The ring and percentage answer “do I need to +/// compact?” without opening the settings sheet. +private struct ContextUsagePill: View { + let usage: LatestUsage + /// Nil when the agent did not report a context window. The meter then + /// shows used tokens without pretending to know a percentage. + let window: Double? + + @Environment(\.hapiTheme) private var theme + + private var validWindow: Double? { + guard let window, window > 0 else { return nil } + return window + } + + private var fraction: Double? { + guard let window = validWindow else { return nil } + return min(1, max(0, usage.contextSize / window)) + } + + private var percent: Int? { + guard let fraction else { return nil } + return Int((fraction * 100).rounded()) + } + + private var tint: Color { + guard let percent else { return theme.accent } + if percent >= 95 { return theme.danger } + if percent >= 80 { return theme.warning } + return theme.accent + } + + private var usedText: String { tokenText(usage.contextSize) } + private var windowText: String { validWindow.map(tokenText) ?? "—" } + private var remainingText: String { + guard let window = validWindow else { return "—" } + return tokenText(max(0, window - usage.contextSize)) + } + + var body: some View { + Menu { + if let percent { + Text("Context \(usedText) / \(windowText)") + Text("Used \(percent)%") + Text("Remaining \(remainingText)") + } else { + Text("Context used \(usedText)") + Text("Window unknown") + } + if usage.cacheRead > 0 { + Text("Cache read \(tokenText(usage.cacheRead))") + } + } label: { HStack(spacing: 3) { - Image(systemName: icon) - .font(.system(size: 9, weight: .medium)) - Text(label) - .lineLimit(1) + if let fraction { + ZStack { + Circle() + .stroke(theme.divider, 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("\(percent ?? 0)%") + .font(.system(size: 9, weight: .semibold)) + .monospacedDigit() + .foregroundStyle(tint) + } else { + Image(systemName: "circle.dotted") + .font(.system(size: 9, weight: .semibold)) + .foregroundStyle(theme.textSecondary) + Text(usedText) + .font(.system(size: 9, weight: .semibold)) + .monospacedDigit() + .foregroundStyle(theme.textSecondary) + } } .padding(.horizontal, 7) .padding(.vertical, 3) .background(theme.surface, in: Capsule()) } - .buttonStyle(.plain) - .foregroundStyle(theme.textSecondary) - .accessibilityHint("Open session settings") + .menuStyle(.borderlessButton) + .accessibilityLabel(Text("Context")) + .accessibilityValue(Text(verbatim: percent.map { "\($0)%" } ?? usedText)) + } + + private func tokenText(_ value: Double) -> String { + if value >= 1_000_000 { + return String(format: "%.1fM", value / 1_000_000) + } + if value >= 1_000 { + return "\(Int((value / 1_000).rounded()))k" + } + return String(Int(value.rounded())) } } diff --git a/ios/Hapi/Features/Chat/MessageChrome.swift b/ios/Hapi/Features/Chat/MessageChrome.swift index 41b24d1d..f3a49fa5 100644 --- a/ios/Hapi/Features/Chat/MessageChrome.swift +++ b/ios/Hapi/Features/Chat/MessageChrome.swift @@ -151,6 +151,15 @@ struct ChatMessageActionRow: View { .buttonStyle(.plain) .accessibilityLabel(copied ? Text("Copied") : Text("Copy")) } + if let copyText, !copyText.isEmpty { + ShareLink(item: copyText) { + Image(systemName: "square.and.arrow.up") + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Share") + } if let metadata, metadata.hasDetails { Menu { if let duration = metadata.durationLabel { diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index fb6a57c1..3f924600 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -9,6 +9,12 @@ import UIKit /// iPhone pushes the chat; iPad and foldable iPhones select a stable detail in /// a native split that collapses to a stack when the window is compact. /// Spawn, notification and row selection share the same opening path. +private struct NewSessionSeed: Identifiable { + let id = UUID() + let machineId: String? + let directory: String +} + struct HomeView: View { let session: HubSession @@ -16,12 +22,15 @@ struct HomeView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @State private var listModel: SessionListModel @State private var showNewSession = false + @State private var newSessionSeed: NewSessionSeed? @State private var showSettings = false @State private var path: [String] = [] @State private var tabletNavigation = SessionNavigationState() /// Transient connection states show only after `connectionRevealDelay`: /// a foreground reconnect usually finishes first (Telegram-style). @State private var connectionStatusRevealed = false + @State private var searchOpen = false + @FocusState private var searchFocused: Bool private let connectionRevealDelay: Duration = .seconds(2) private var usesSplitNavigation: Bool { @@ -49,7 +58,7 @@ struct HomeView: View { @Bindable var model = model Group { if usesSplitNavigation { - SessionSplitView(navigation: tabletNavigation, onNewSession: { showNewSession = true }) { + SessionSplitView(navigation: tabletNavigation, onNewSession: { presentNewSession() }) { sessionList } detail: { sessionId in chat(sessionId) @@ -92,8 +101,12 @@ struct HomeView: View { PairingFlowView(context: .addHub) .macSheetSizing() } - .sheet(isPresented: $showNewSession) { - NewSessionView(session: session) { sessionId in + .sheet(isPresented: $showNewSession, onDismiss: { newSessionSeed = nil }) { + NewSessionView( + session: session, + initialMachineId: newSessionSeed?.machineId, + initialDirectory: newSessionSeed?.directory + ) { sessionId in // Navigate-replace: drop the sheet, push the fresh chat. showNewSession = false openSession(sessionId) @@ -105,13 +118,18 @@ struct HomeView: View { .macSheetSizing() } .focusedSceneValue(\.homeCommands, HomeCommandActions( - newSession: { showNewSession = true }, + newSession: { presentNewSession() }, openSettings: { showSettings = true }, toggleSidebar: usesSplitNavigation ? toggleSidebar : nil, selectAdjacentSession: usesSplitNavigation ? selectAdjacentSession : nil )) } + private func presentNewSession(_ seed: NewSessionSeed? = nil) { + newSessionSeed = seed + showNewSession = true + } + private func toggleSidebar() { tabletNavigation.columnVisibility = tabletNavigation.columnVisibility == .detailOnly ? .all : .detailOnly } @@ -141,7 +159,12 @@ struct HomeView: View { // Native list deselection (e.g. a filter hides the row) is // not an authoritative removal and must not close the chat. set: { if let id = $0 { openSession(id) } } - ) : nil, onOpenSession: openSession) + ) : nil, + onOpenSession: openSession, + onNewSessionInDirectory: { machineId, directory in + presentNewSession(NewSessionSeed(machineId: machineId, directory: directory)) + } + ) } .task(id: session.connectionState == .connected) { connectionStatusRevealed = false @@ -151,10 +174,14 @@ struct HomeView: View { } .modifier(ConnectionSubtitle(message: subtitleCarriesConnectionStatus ? connectionNotice.transientMessage(revealed: connectionStatusRevealed) : nil)) - .searchable(text: $listModel.searchQuery, prompt: Text("Search sessions")) .onChange(of: tabletNavigation.selectedSessionId, initial: true) { _, sessionId in listModel.selectedSessionId = sessionId } + .safeAreaInset(edge: .top, spacing: 0) { + if searchOpen { + searchOverlay + } + } .navigationTitle("Sessions") // Inline: it shares the toolbar row, so the list starts right below // and Pinned/Recent headers carry the structure. @@ -162,6 +189,14 @@ struct HomeView: View { .modifier(SidebarTitleRemoval(isSidebar: showsSideBySide || isFoldedOuterScreen)) .toolbar { ToolbarItem(placement: .topBarLeading) { settingsButton } + ToolbarItem(placement: .topBarTrailing) { + Button { + searchOpen = true + } label: { + Image(systemName: "magnifyingglass") + } + .accessibilityLabel("Search sessions") + } if listModel.showsFilterMenu { // Beside Settings when the system sidebar toggle shares the // trailing edge, so the icons do not bunch up. @@ -169,11 +204,8 @@ struct HomeView: View { SessionFilterMenu(model: listModel) } } - if !showsNewSessionBesideSearch { - ToolbarItem(placement: .topBarTrailing) { newSessionButton } - } + ToolbarItem(placement: .topBarTrailing) { newSessionButton } } - .modifier(NewSessionBesideSearch(isEnabled: showsNewSessionBesideSearch) { newSessionButton }) } private var connectionNotice: SessionConnectionNotice { @@ -193,16 +225,8 @@ struct HomeView: View { return !(showsSideBySide || isFoldedOuterScreen) } - /// iOS 26 bottom search bar, as in Messages: New Session sits beside the - /// field. A side-by-side sidebar keeps search at its top, and older - /// systems keep search under the title. - private var showsNewSessionBesideSearch: Bool { - guard #available(iOS 26.0, *) else { return false } - return !showsSideBySide - } - private var newSessionButton: some View { - Button { showNewSession = true } label: { + Button { presentNewSession() } label: { Label("New Session", systemImage: "plus") .modifier(TouchTarget()) } @@ -217,7 +241,46 @@ struct HomeView: View { .accessibilityIdentifier("home.settings") } + private var searchOverlay: some View { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + TextField("Search sessions", text: $listModel.searchQuery) + .focused($searchFocused) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.search) + if !listModel.searchQuery.isEmpty { + Button { + listModel.searchQuery = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + } + Button("Cancel") { closeSearch() } + .font(.footnote) + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(.regularMaterial, in: Capsule()) + .shadow(radius: 5, y: 2) + .padding(.horizontal, 12) + .padding(.top, 6) + .onAppear { searchFocused = true } + } + + private func closeSearch() { + searchFocused = false + searchOpen = false + listModel.searchQuery = "" + } + private func openSession(_ sessionId: String) { + if searchOpen { + closeSearch() + } if usesSplitNavigation { tabletNavigation.open(sessionId) } else if path.last != sessionId { @@ -274,27 +337,6 @@ private struct SidebarTitleRemoval: ViewModifier { } } -/// Places the system search field in the bottom bar with New Session on its -/// trailing side. The OS branch is static and the toggle lives inside the -/// toolbar, so resizing never replaces the session list's identity. -private struct NewSessionBesideSearch: ViewModifier { - let isEnabled: Bool - @ViewBuilder var newSessionButton: () -> NewSessionButton - - func body(content: Content) -> some View { - if #available(iOS 26.0, *) { - content.toolbar { - if isEnabled { - DefaultToolbarItem(kind: .search, placement: .bottomBar) - ToolbarSpacer(.fixed, placement: .bottomBar) - ToolbarItem(placement: .bottomBar) { newSessionButton() } - } - } - } else { - content - } - } -} /// Home connection status. Transient SSE states are quiet: the iOS 26 nav /// subtitle, else a gray line with a spinner. Only a failed list refresh diff --git a/ios/Hapi/Features/NewSession/NewSessionModel.swift b/ios/Hapi/Features/NewSession/NewSessionModel.swift index 802e09b5..b9f3f844 100644 --- a/ios/Hapi/Features/NewSession/NewSessionModel.swift +++ b/ios/Hapi/Features/NewSession/NewSessionModel.swift @@ -41,6 +41,16 @@ enum CodexModelsState: Equatable { case failed(String) } +/// Machine Claude-models catalog state (web `useClaudeModels`). The picker +/// keeps the static presets while loading/failed and replaces them once the +/// CLI catalog arrives. +enum ClaudeModelsState: Equatable { + case hidden + case loading + case loaded([ClaudeModelSummary]) + case failed(String) +} + /// Discovered model catalog of the selected non-Claude/Codex agent. enum AgentModelsState: Equatable { case hidden @@ -78,11 +88,23 @@ private struct CachedAgentModels { /// `newSessionFormDraft.ts`) so backing out of the sheet loses nothing. /// JSON blobs in `UserDefaults`, keyed per hub (the Android original keys /// app-wide; per-hub matches this app's multi-hub stores). +struct NewSessionLaunchSettings: Codable, Equatable { + var model: String + var effort: String + var modelReasoningEffort: String + var serviceTier: String + var permissionMode: String + var yolo: Bool +} + struct NewSessionPrefsData: Codable, Equatable { var lastMachineId: String? /// Machine id → most-recent-first spawn directories /// (cap `NewSessionLogic.maxRecentPaths`). var recentPaths: [String: [String]] = [:] + var lastAgent: String? + /// Machine + agent → last launch selections. + var launchSettings: [String: NewSessionLaunchSettings]? } struct NewSessionPrefsStore { @@ -134,11 +156,13 @@ struct NewSessionPrefsStore { /// Web reference: `web/src/components/NewSession/index.tsx`. /// /// Option matrix (web create form): -/// - model pickers: claude (static presets), codex (machine catalog; hidden +/// - model pickers: claude (machine CLI catalog, static presets while it +/// loads/fails), codex (machine catalog; hidden /// when the runner lacks the RPC) and the `AgentModelCatalog` flavors — /// agy/cursor/dsh/pi per machine, copilot/grok/kimi/opencode once the /// directory exists. Cursor is a flat list of ACP ids (no variant drill-down). -/// - effort: claude static levels, grok per-model efforts, pi thinking +/// - effort: claude per-model catalog levels (static fallback), grok per-model +/// efforts, pi thinking /// levels; reasoning effort: codex catalog, opencode variants. /// - `startingMode` stays unset → the runner spawns `'remote'` (pty deferred). @MainActor @Observable @@ -168,6 +192,7 @@ final class NewSessionModel { let directoryInput: NewSessionDirectoryModel var suggestions: [String] { directoryInput.suggestions } private(set) var codexModels: CodexModelsState = .hidden + private(set) var claudeModels: ClaudeModelsState = .hidden private(set) var agentModels: AgentModelsState = .hidden /// OpenCode variants keyed `provider/model`; nil until loaded. private(set) var opencodeVariants: [String: [String]]? @@ -183,6 +208,8 @@ final class NewSessionModel { private let session: HubSession private let prefsStore: NewSessionPrefsStore + private let initialMachineId: String? + private let initialDirectory: String? /// Fired once with the new session id — navigate-replace to the chat. private let onCreated: @MainActor (String) -> Void @@ -190,6 +217,9 @@ final class NewSessionModel { @ObservationIgnored private var availabilityTask: Task? @ObservationIgnored private var defaultDirectoryTask: Task? @ObservationIgnored private var codexFetchedForMachine: String? + @ObservationIgnored private var claudeModelsTask: Task? + @ObservationIgnored private var claudeFetchedForMachine: String? + @ObservationIgnored private var claudeModelsCache: [String: [ClaudeModelSummary]] = [:] @ObservationIgnored private var agentModelsTask: Task? @ObservationIgnored private var agentModelsFetched: AgentModelsRequest?? @ObservationIgnored private var agentModelsCache: [AgentModelsRequest: CachedAgentModels] = [:] @@ -197,16 +227,21 @@ final class NewSessionModel { @ObservationIgnored private var suppressSuggestions = false @ObservationIgnored private var spawnInFlight = false @ObservationIgnored private var hasStarted = false + @ObservationIgnored private var loadedDraft = false @ObservationIgnored private var directoryEdited = false @ObservationIgnored private var directoryEditVersion = 0 init( session: HubSession, defaults: UserDefaults = .standard, + initialMachineId: String? = nil, + initialDirectory: String? = nil, onCreated: @escaping @MainActor (String) -> Void ) { self.session = session self.prefsStore = NewSessionPrefsStore(hubUrl: session.hubUrl, defaults: defaults) + self.initialMachineId = initialMachineId + self.initialDirectory = initialDirectory self.onCreated = onCreated self.directoryInput = NewSessionDirectoryModel( requester: session.api, @@ -228,14 +263,32 @@ final class NewSessionModel { hasStarted = true prefsData = prefsStore.readPrefs() let draft = prefsStore.readDraft().map(NewSessionLogic.sanitizeDraft) - form = draft ?? NewSessionForm() - // A saved empty path can be intentional; never replace it on refresh. - directoryEdited = draft != nil + if let initialDirectory, !initialDirectory.isEmpty { + // A directory-header + starts a fresh form at that exact path; + // it must not inherit an unrelated draft. + form = NewSessionForm() + form.machineId = initialMachineId + form.directory = initialDirectory + loadedDraft = false + directoryEdited = true + } else { + loadedDraft = draft != nil + form = draft ?? NewSessionForm() + directoryEdited = draft != nil + } + if !loadedDraft, let raw = prefsData.lastAgent, + AgentFlavor.creatableFlavors.contains(AgentFlavor(rawValue: raw)) { + form.agent = AgentFlavor(rawValue: raw) + } suppressSuggestions = true } reconcileMachineSelection() + if !loadedDraft { + applyPreferredLaunchSettings() + } refreshAgentAvailability() refreshCodexModelsIfNeeded() + refreshClaudeModelsIfNeeded() refreshAgentModelsIfNeeded() scheduleDirectoryWork() @@ -259,8 +312,11 @@ final class NewSessionModel { directoryBrowser.close() availabilityTask?.cancel() codexTask?.cancel() + claudeModelsTask?.cancel() availabilityFetchedForMachine = nil codexFetchedForMachine = nil + claudeFetchedForMachine = nil + claudeModels = .hidden } else { if directoryBrowser.isPresented, directoryBrowser.roots != selectedMachine.map(RemoteDirectoryPath.browseRoots) { @@ -268,6 +324,7 @@ final class NewSessionModel { } refreshAgentAvailability() refreshCodexModelsIfNeeded() + refreshClaudeModelsIfNeeded() } refreshAgentModelsIfNeeded() scheduleDirectoryWork() @@ -359,7 +416,16 @@ final class NewSessionModel { var modelOptions: [NewSessionOption]? { switch (form.agent, codexModels) { case (.claude, _): - return NewSessionCatalogs.claudeModels + let catalog: [ClaudeModelSummary]? = { + if case .loaded(let models) = claudeModels { return models } + return nil + }() + return NewSessionCatalogs.claudeLaunchModelOptions( + catalog: catalog, + selectedModel: form.model, + notListedSuffix: String(localized: "not listed"), + otherModelsLabel: String(localized: "Other models") + ) case (.codex, .loaded(let models)): return [NewSessionOption(value: "auto", label: "Default")] + models.map { NewSessionOption(value: $0.id, label: $0.displayName) } @@ -384,7 +450,9 @@ final class NewSessionModel { } var modelsLoading: Bool { - (form.agent == .codex && codexModels == .loading) || agentModels == .loading + (form.agent == .codex && codexModels == .loading) + || (form.agent == .claude && claudeModels == .loading) + || agentModels == .loading } var modelsError: String? { @@ -405,7 +473,16 @@ final class NewSessionModel { /// Claude effort, grok effort or pi thinking level; nil hides the field. var effortOptions: [NewSessionOption]? { switch form.agent { - case .claude: return NewSessionCatalogs.claudeEfforts + case .claude: + let catalog: [ClaudeModelSummary]? = { + if case .loaded(let models) = claudeModels { return models } + return nil + }() + return NewSessionCatalogs.claudeEffortOptions( + catalog: catalog, + model: form.model, + currentEffort: form.effort + ) case .grok: return AgentModelCatalog.grokEffortOptions(response: loadedAgentModels, model: form.model) case .pi: return AgentModelCatalog.piEffortOptions(response: loadedAgentModels, model: form.model) default: return nil @@ -450,6 +527,13 @@ final class NewSessionModel { return modes.filter { $0 != .auto } } + /// Machine id whose Claude catalog the form needs, or nil for other + /// agents / no selected machine. + var claudeModelsRequest: String? { + guard form.agent == .claude, let machineId = selectedMachine?.id else { return nil } + return machineId + } + /// The discovered-model fetch the form needs now; nil when the flavor /// has no catalog, no machine is selected, or a directory-scoped catalog /// has no existing directory to probe yet. @@ -605,8 +689,11 @@ final class NewSessionModel { form.serviceTier = .standard form.collaborationMode = .default form.copilotAgentMode = .interactive + applyPreferredLaunchSettings() + captureLaunchSettings() persistDraft() refreshCodexModelsIfNeeded() + refreshClaudeModelsIfNeeded() refreshAgentModelsIfNeeded() } @@ -615,27 +702,35 @@ final class NewSessionModel { if form.agent == .codex { form = reconcileCodexSelections(form) } + if form.agent == .claude { + form = reconcileClaudeEffort(form) + } form = reconcileAgentModelSelections(form) + captureLaunchSettings() persistDraft() } func setEffort(_ effort: String) { form.effort = effort + captureLaunchSettings() persistDraft() } func setModelReasoningEffort(_ value: String) { form.modelReasoningEffort = value + captureLaunchSettings() persistDraft() } func setPermissionMode(_ mode: PermissionMode) { form.permissionMode = mode + captureLaunchSettings() persistDraft() } func setYolo(_ enabled: Bool) { form.yolo = enabled + captureLaunchSettings() persistDraft() } @@ -652,6 +747,7 @@ final class NewSessionModel { func setServiceTier(_ tier: ServiceTier) { form.serviceTier = tier + captureLaunchSettings() persistDraft() } @@ -667,7 +763,9 @@ final class NewSessionModel { func retryModels() { codexFetchedForMachine = nil + claudeFetchedForMachine = nil refreshCodexModelsIfNeeded() + refreshClaudeModelsIfNeeded(force: true) refreshAgentModelsIfNeeded(force: true) } @@ -771,6 +869,25 @@ final class NewSessionModel { machineId.flatMap { prefsData.recentPaths[$0] } ?? [] } + /// Recent spawn paths plus directories already used by sessions on this + /// machine (web `useDirectorySuggestions`), so existing projects are + /// visible before the user types anything. + var knownDirectories: [String] { + guard let machineId = form.machineId else { return recentPaths } + let recent = recentPaths(for: machineId) + let recentSet = Set(recent) + let sessionPaths = session.sessionStore.sessions + .filter { $0.metadata?.machineId == machineId } + .flatMap { summary -> [String] in + [summary.metadata?.path, summary.metadata?.worktree?.basePath].compactMap { $0 } + } + .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + let extras = Set(sessionPaths) + .subtracting(recentSet) + .sorted { $0.localizedStandardCompare($1) == .orderedAscending } + return recent + extras + } + private func reconcileMachineSelection() { guard form.machineId == nil else { return } let machines = session.machineStore.machines.filter(\.active) @@ -788,6 +905,9 @@ final class NewSessionModel { suppressSuggestions = true form.machineId = machineId form.model = "auto" + if !loadedDraft { + applyPreferredLaunchSettings() + } if resetDirectory { let machine = session.machineStore.machines.first { $0.id == machineId } directoryEdited = false @@ -944,6 +1064,72 @@ final class NewSessionModel { } } + /// Fetches or reuses the selected machine's Claude model catalog. The + /// form keeps the static presets while this is loading or fails. + func refreshClaudeModelsIfNeeded(force: Bool = false) { + guard form.agent == .claude, let machineId = selectedMachine?.id else { + claudeModelsTask?.cancel() + claudeFetchedForMachine = nil + claudeModels = .hidden + return + } + if !force, let cached = claudeModelsCache[machineId] { + claudeFetchedForMachine = machineId + claudeModels = .loaded(cached) + form = reconcileClaudeEffort(form) + persistDraft() + return + } + if !force, claudeFetchedForMachine == machineId, claudeModels != .hidden { + return + } + claudeFetchedForMachine = machineId + claudeModelsTask?.cancel() + claudeModels = .loading + claudeModelsTask = Task { [weak self] in + guard let self else { return } + let state: ClaudeModelsState + do { + let response = try await self.session.api.machineClaudeModels(machineId: machineId) + state = response.success + ? .loaded(response.availableModels ?? []) + : .failed(response.error ?? String(localized: "Failed to load Claude models")) + } catch is CancellationError { + return + } catch { + state = .failed( + (error as? LocalizedError)?.errorDescription + ?? String(localized: "Failed to load Claude models") + ) + } + guard !Task.isCancelled, + self.form.machineId == machineId, + self.form.agent == .claude + else { return } + self.claudeModels = state + if case .loaded(let models) = state { + self.claudeModelsCache[machineId] = models + self.form = self.reconcileClaudeEffort(self.form) + self.persistDraft() + } + } + } + + private func reconcileClaudeEffort(_ current: NewSessionForm) -> NewSessionForm { + guard case .loaded(let models) = claudeModels else { return current } + guard let options = NewSessionCatalogs.claudeEffortOptions( + catalog: models, + model: current.model, + currentEffort: current.effort + ) else { return current } + if !options.contains(where: { $0.value == current.effort }) { + var next = current + next.effort = "auto" + return next + } + return current + } + /// Fetches (or reuses) the catalog for ``agentModelsRequest``. The view /// calls this whenever the request changes — including when a typed /// directory turns out to exist. @@ -1038,6 +1224,45 @@ final class NewSessionModel { return NewSessionLogic.codexModelAdvertisesFastTier(model: current.model, models: models) } + private func launchSettingsKey(machineId: String, agent: AgentFlavor) -> String { + "\(machineId)|\(agent.rawValue)" + } + + private func applyPreferredLaunchSettings() { + guard let machineId = form.machineId, + let settings = prefsData.launchSettings?[ + launchSettingsKey(machineId: machineId, agent: form.agent) + ] else { return } + form.model = settings.model + form.effort = settings.effort + form.modelReasoningEffort = settings.modelReasoningEffort + if let tier = ServiceTier(rawValue: settings.serviceTier) { + form.serviceTier = tier + } + if let mode = PermissionMode(rawValue: settings.permissionMode), + form.agent.permissionModes.contains(mode) { + form.permissionMode = mode + } + form.yolo = settings.yolo + } + + private func captureLaunchSettings() { + guard let machineId = form.machineId else { return } + prefsData.lastMachineId = machineId + prefsData.lastAgent = form.agent.rawValue + var settings = prefsData.launchSettings ?? [:] + settings[launchSettingsKey(machineId: machineId, agent: form.agent)] = NewSessionLaunchSettings( + model: form.model, + effort: form.effort, + modelReasoningEffort: form.modelReasoningEffort, + serviceTier: form.serviceTier.rawValue, + permissionMode: form.permissionMode.rawValue, + yolo: form.yolo + ) + prefsData.launchSettings = settings + prefsStore.writePrefs(prefsData) + } + private func persistDraft() { prefsStore.writeDraft(form) } diff --git a/ios/Hapi/Features/NewSession/NewSessionView.swift b/ios/Hapi/Features/NewSession/NewSessionView.swift index e65bf9ba..0d137fc7 100644 --- a/ios/Hapi/Features/NewSession/NewSessionView.swift +++ b/ios/Hapi/Features/NewSession/NewSessionView.swift @@ -9,11 +9,22 @@ import SwiftUI /// dismisses the sheet and pushes the chat — navigate-replace). struct NewSessionView: View { @State private var model: NewSessionModel + @State private var modelPickerPresented = false @Environment(\.dismiss) private var dismiss private let session: HubSession - init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { - _model = State(initialValue: NewSessionModel(session: session, onCreated: onCreated)) + init( + session: HubSession, + initialMachineId: String? = nil, + initialDirectory: String? = nil, + onCreated: @escaping @MainActor (String) -> Void + ) { + _model = State(initialValue: NewSessionModel( + session: session, + initialMachineId: initialMachineId, + initialDirectory: initialDirectory, + onCreated: onCreated + )) self.session = session } @@ -54,6 +65,16 @@ struct NewSessionView: View { ) .macSheetSizing() } + .sheet(isPresented: $modelPickerPresented) { + ModelPickerSheet( + options: model.modelOptions ?? [], + selected: model.form.model + ) { value in + model.setModel(value) + modelPickerPresented = false + } + .macSheetSizing() + } .onDisappear { model.stopDirectoryWork() } @@ -150,10 +171,11 @@ struct NewSessionView: View { .buttonStyle(.plain) } - if !model.recentPaths.isEmpty { + let directories = model.knownDirectories + if !directories.isEmpty { ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 8) { - ForEach(model.recentPaths, id: \.self) { path in + LazyHStack(spacing: 8) { + ForEach(directories, id: \.self) { path in FilterChip(label: path, selected: false) { model.pickRecentPath(path) } @@ -329,11 +351,14 @@ struct NewSessionView: View { private var optionsSection: some View { Section("Options") { if let options = model.modelOptions { - optionPicker( - "Model", - options: options, - selection: Binding(get: { model.form.model }, set: { model.setModel($0) }) - ) + Button { + modelPickerPresented = true + } label: { + LabeledContent("Model") { + Text(selectedModelLabel(options)) + .lineLimit(1) + } + } .disabled(model.modelsLoading || model.modelsError != nil) if model.modelsLoading { Text("Loading…") @@ -464,15 +489,30 @@ struct NewSessionView: View { ) } + private func selectedModelLabel(_ options: [NewSessionOption]) -> String { + options.first { $0.value == model.form.model }?.label ?? model.form.model + } + private func optionPicker( _ title: LocalizedStringKey, options: [NewSessionOption], selection: Binding ) -> some View { - Picker(title, selection: selection) { - ForEach(options, id: \.value) { option in + let ungrouped = options.filter { $0.group == nil } + let groupNames = options.compactMap(\.group).reduce(into: [String]()) { names, name in + if !names.contains(name) { names.append(name) } + } + return Picker(title, selection: selection) { + ForEach(ungrouped, id: \.value) { option in Text(option.label).tag(option.value) } + ForEach(groupNames, id: \.self) { group in + Section(group) { + ForEach(options.filter { $0.group == group }, id: \.value) { option in + Text(option.label).tag(option.value) + } + } + } } } @@ -511,3 +551,72 @@ struct NewSessionView: View { return String(localized: "Create") } } + + +private struct ModelPickerSheet: View { + let options: [NewSessionOption] + let selected: String + let onSelect: (String) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + + private var filtered: [NewSessionOption] { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return options } + return options.filter { + $0.label.localizedCaseInsensitiveContains(trimmed) + || $0.value.localizedCaseInsensitiveContains(trimmed) + } + } + + private var groupNames: [String] { + filtered.compactMap(\.group).reduce(into: [String]()) { names, name in + if !names.contains(name) { names.append(name) } + } + } + + var body: some View { + NavigationStack { + List { + ForEach(filtered.filter { $0.group == nil }, id: \.value) { option in + row(option) + } + ForEach(groupNames, id: \.self) { group in + Section(group) { + ForEach(filtered.filter { $0.group == group }, id: \.value) { option in + row(option) + } + } + } + } + .searchable(text: $query, prompt: "Search models") + .navigationTitle("Model") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + } + } + } + + private func row(_ option: NewSessionOption) -> some View { + Button { + onSelect(option.value) + } label: { + HStack(spacing: 10) { + Text(option.label) + .foregroundStyle(.primary) + Spacer(minLength: 8) + if option.value == selected { + Image(systemName: "checkmark") + .font(.body.weight(.semibold)) + .foregroundStyle(.tint) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } +} diff --git a/ios/Hapi/Features/Sessions/AgentFlavorIcon.swift b/ios/Hapi/Features/Sessions/AgentFlavorIcon.swift index b0eea90a..ce0ee6ee 100644 --- a/ios/Hapi/Features/Sessions/AgentFlavorIcon.swift +++ b/ios/Hapi/Features/Sessions/AgentFlavorIcon.swift @@ -19,7 +19,7 @@ struct AgentFlavorIconView: View { /// Flavors with a bundled `AgentIcons/` image set. private static let bundledFlavors: Set = [ - "agy", "claude", "codex", "copilot", "cursor", + "agy", "claude", "codex", "copilot", "cursor", "dsh", "gemini", "grok", "kimi", "opencode", "pi", ] @@ -70,7 +70,7 @@ struct AgentFlavorIconView: View { private struct AgentFlavorIconPreviewGrid: View { private let flavors: [String?] = [ - "agy", "claude", "codex", "copilot", "cursor", + "agy", "claude", "codex", "copilot", "cursor", "dsh", "gemini", "grok", "kimi", "opencode", "pi", "mystery", ] diff --git a/ios/Hapi/Features/Sessions/SessionFilterMenu.swift b/ios/Hapi/Features/Sessions/SessionFilterMenu.swift index 7d1d1f8b..4e11f4d5 100644 --- a/ios/Hapi/Features/Sessions/SessionFilterMenu.swift +++ b/ios/Hapi/Features/Sessions/SessionFilterMenu.swift @@ -69,10 +69,18 @@ struct SessionFilterMenu: View { // Native Menu buttons turn the second Text into a // subtitle; Picker options silently discard it. Text(machine.label) - Text("\(machine.sessionCount, specifier: "%lld") sessions") + if let health = machine.healthLabel { + Text("\(machine.sessionCount, specifier: "%lld") sessions · \(health)") + } else { + Text("\(machine.sessionCount, specifier: "%lld") sessions") + } if model.activeMachineFilter == machine.id { Image(systemName: "checkmark") } } - .accessibilityLabel(Text("\(machine.label), \(machine.sessionCount, specifier: "%lld") sessions")) + .accessibilityLabel(Text( + machine.healthLabel.map { + "\(machine.label), \(machine.sessionCount, specifier: "%lld") sessions, \($0)" + } ?? "\(machine.label), \(machine.sessionCount, specifier: "%lld") sessions" + )) .accessibilityAddTraits(model.activeMachineFilter == machine.id ? .isSelected : []) } } diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index 46ed074b..58a133db 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -39,6 +39,8 @@ struct SessionListSectionUI: Identifiable, Equatable { let id: String let kind: SessionListGroupKind let directoryName: String? + let projectPath: String? + let machineId: String? let machineLabel: String? let rows: [SessionRowUI] let buckets: [SessionListBucketUI] @@ -125,6 +127,8 @@ struct MachineFilterUI: Identifiable, Equatable { let id: String let label: String let sessionCount: Int + /// `CPU 12% · Mem 45%` from the latest health sample, when online. + let healthLabel: String? } /// Transient, per-home filters. Add future dimensions here, not to navigation. @@ -214,12 +218,18 @@ final class SessionListModel { counts[id, default: 0] += 1 } var names: [String: String] = [:] + var healths: [String: String] = [:] for machine in machineStore.machines where counts[machine.id] != nil { guard let metadata = machine.metadata else { continue } let displayName = metadata.displayName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let host = metadata.host.trimmingCharacters(in: .whitespacesAndNewlines) let name = displayName.isEmpty ? host : displayName if !name.isEmpty { names[machine.id] = name } + let parts: [String] = [ + machine.health?.cpuPercent.map { "CPU \(Int($0))%" }, + machine.health?.memoryPercent.map { "Mem \(Int($0))%" }, + ].compactMap { $0 } + if !parts.isEmpty { healths[machine.id] = parts.joined(separator: " · ") } } let nameCounts = Dictionary(grouping: names.values, by: { $0.lowercased() }).mapValues(\.count) return counts @@ -234,7 +244,12 @@ final class SessionListModel { } else { label = String(format: String(localized: "Machine · %@"), String(id.prefix(8))) } - return MachineFilterUI(id: id, label: label, sessionCount: entry.value) + return MachineFilterUI( + id: id, + label: label, + sessionCount: entry.value, + healthLabel: healths[id] + ) } .sorted { lhs, rhs in func rank(_ id: String) -> Int { @@ -403,6 +418,8 @@ final class SessionListModel { id: group.id, kind: group.kind, directoryName: group.displayName, + projectPath: group.projectPath, + machineId: group.machineId, machineLabel: machineLabel, rows: group.sessions.compactMap { rowById[$0.id] }, buckets: group.buckets.map { bucket in diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index 141da452..e39584c3 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -32,6 +32,7 @@ struct SessionListView: View { let model: SessionListModel var selection: Binding? = nil let onOpenSession: (String) -> Void + var onNewSessionInDirectory: ((_ machineId: String?, _ directory: String) -> Void)? = nil @State private var renameTarget: SessionRowUI? @State private var renameText = "" @@ -312,31 +313,51 @@ struct SessionListView: View { } private func sectionHeader(_ section: SessionListSectionUI, collapsed: Bool) -> some View { - Button { - toggle(section) - } label: { - HStack(spacing: 6) { - Image(systemName: "chevron.right") - .font(.system(size: metrics.headerSize * 0.75, weight: .semibold)) - .rotationEffect(.degrees(collapsed ? 0 : 90)) - .frame(width: 10) - sectionIcon(section) - sectionTitle(section) - .font(.system(size: metrics.headerSize, weight: .semibold)) - .lineLimit(1) - Text("(\(section.totalCount))") - .font(.system(size: metrics.headerSize, weight: .regular)) - .monospacedDigit() - Spacer(minLength: 0) + HStack(spacing: 6) { + Button { + toggle(section) + } label: { + HStack(spacing: 6) { + Image(systemName: "chevron.right") + .font(.system(size: metrics.headerSize * 0.75, weight: .semibold)) + .rotationEffect(.degrees(collapsed ? 0 : 90)) + .frame(width: 10) + sectionIcon(section) + sectionTitle(section) + .font(.system(size: metrics.headerSize, weight: .semibold)) + .lineLimit(1) + Text("(\(section.totalCount))") + .font(.system(size: metrics.headerSize, weight: .regular)) + .monospacedDigit() + Spacer(minLength: 0) + } + .foregroundStyle(theme.textSecondary) + .textCase(nil) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(sectionAccessibilityLabel(section))) + + if let onNewSessionInDirectory, + section.kind == .directory, + let path = section.projectPath, + !path.isEmpty, + path != "Other" { + Button { + onNewSessionInDirectory(section.machineId, path) + } label: { + Image(systemName: "plus") + .font(.system(size: metrics.headerSize * 0.8, weight: .semibold)) + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textSecondary) + .accessibilityLabel(Text("New session in this directory")) } - .foregroundStyle(theme.textSecondary) - .textCase(nil) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) } - .buttonStyle(.plain) .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16)) - .accessibilityLabel(Text(sectionAccessibilityLabel(section))) } @ViewBuilder diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index 5a288e31..f43c9864 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -94,6 +94,7 @@ struct SettingsView: View { insightsSection } aboutSection + signOutSection } .navigationTitle("Settings") .navigationBarTitleDisplayMode(.inline) @@ -145,6 +146,11 @@ struct SettingsView: View { dismiss() appModel.showAddHub = true } + } + } + + private var signOutSection: some View { + Section { Button("Sign Out…", role: .destructive) { confirmSignOut = true } diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 2b85090b..885c08aa 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -12055,6 +12055,533 @@ } } }, + "Other models" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Другие модели" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "其他模型" + } + } + } + }, + "not listed" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "не в списке" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未列出" + } + } + } + }, + "Failed to load Claude models" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить модели Claude" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "加载 Claude 模型失败" + } + } + } + }, + "New session in this directory" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Новый сеанс в этой папке" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在此目录新建会话" + } + } + } + }, + "Context used %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использовано контекста %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上下文已用 %@" + } + } + } + }, + "Window unknown" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Окно неизвестно" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "窗口大小未知" + } + } + } + }, + "Context %@ / %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Контекст %@ / %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上下文 %@ / %@" + } + } + } + }, + "Used %lld%%" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использовано %lld%%" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已用 %lld%%" + } + } + } + }, + "Remaining %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Осталось %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "剩余 %@" + } + } + } + }, + "Cache read %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чтение из кэша %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "缓存读取 %@" + } + } + } + }, + "Collapse" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Свернуть" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "收起" + } + } + } + }, + "Show all lines" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все строки" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "显示全部行" + } + } + } + }, + "Wrap lines" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переносить строки" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "自动换行" + } + } + } + }, + "Disable line wrap" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отключить перенос строк" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "关闭自动换行" + } + } + } + }, + "Copy code" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать код" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "复制代码" + } + } + } + }, + "Compacting" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сжатие" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "压缩中" + } + } + } + }, + "Session status" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Статус сеанса" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "会话状态" + } + } + } + }, + "Goal" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Цель" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目标" + } + } + } + }, + "Tasks" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Задачи" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "任务" + } + } + } + }, + "Subagents" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Субагенты" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "子代理" + } + } + } + }, + "Terminals" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Терминалы" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "终端" + } + } + } + }, + "Team" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Команда" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "团队" + } + } + } + }, + "Waiting" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ожидание" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "等待中" + } + } + } + }, + "Fork from here" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ответвить отсюда" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "从此处分叉" + } + } + } + }, + "Rewind to here" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Откатить сюда" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "回退到这里" + } + } + } + }, + "Message actions" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Действия сообщения" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "消息操作" + } + } + } + }, + "Rewind to this message?" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Откатить к этому сообщению?" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "回退到这条消息?" + } + } + } + }, + "Later messages will be removed from the active conversation." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Последующие сообщения будут удалены из активного диалога." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "后面的消息会从当前会话中移除。" + } + } + } + }, + "Context" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Контекст" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上下文" + } + } + } + }, + "Share" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поделиться" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享" + } + } + } + }, + "Search models" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск моделей" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "搜索模型" + } + } + } + }, "Started %@" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiWidgets/AgentFlavorIcon.swift b/ios/HapiWidgets/AgentFlavorIcon.swift index ac492984..7c1dbaf7 100644 --- a/ios/HapiWidgets/AgentFlavorIcon.swift +++ b/ios/HapiWidgets/AgentFlavorIcon.swift @@ -13,7 +13,7 @@ struct AgentFlavorIconView: View { /// Flavors with a bundled `AgentIcons/` image set. private static let bundledFlavors: Set = [ - "agy", "claude", "codex", "copilot", "cursor", + "agy", "claude", "codex", "copilot", "cursor", "dsh", "gemini", "grok", "kimi", "opencode", "pi", ] diff --git a/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json b/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json new file mode 100644 index 00000000..508fe1dd --- /dev/null +++ b/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images" : [ + { + "filename" : "icon.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg b/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg new file mode 100644 index 00000000..f88129ef --- /dev/null +++ b/ios/HapiWidgets/Assets.xcassets/AgentIcons/dsh.imageset/icon.svg @@ -0,0 +1 @@ + diff --git a/ios/HapiWidgets/HapiHomeWidget.swift b/ios/HapiWidgets/HapiHomeWidget.swift index 0902dd47..195cd259 100644 --- a/ios/HapiWidgets/HapiHomeWidget.swift +++ b/ios/HapiWidgets/HapiHomeWidget.swift @@ -384,6 +384,7 @@ private struct InlineAccessory: View { private struct WidgetHeader: View { let snapshot: WidgetSnapshot + var showsRefresh = true var body: some View { HStack(spacing: 5) { @@ -402,7 +403,9 @@ private struct WidgetHeader: View { .fill(.orange) .frame(width: 7, height: 7) } - WidgetRefreshButton() + if showsRefresh { + WidgetRefreshButton() + } } } } @@ -1070,6 +1073,7 @@ private struct HapiFocusWidgetView: View { .font(.system(size: 9.5, weight: .medium)) .foregroundStyle(.secondary) } + WidgetRefreshButton() } .padding(.top, 1) @@ -1077,7 +1081,6 @@ private struct HapiFocusWidgetView: View { mediumMetaLine(session) Spacer(minLength: 6) focusSwitcher(for: session) - WidgetRefreshButton() } .padding(.top, 1) @@ -1121,7 +1124,7 @@ private struct HapiFocusWidgetView: View { .padding(.vertical, 2) .padding(.horizontal, 7) .frame(maxWidth: .infinity, alignment: .leading) - .frame(height: 90, alignment: .topLeading) + .frame(height: 84, alignment: .topLeading) .background { RoundedRectangle(cornerRadius: 8, style: .continuous) .fill(Color.teal.opacity(0.08)) @@ -1136,18 +1139,24 @@ private struct HapiFocusWidgetView: View { let index = sessions.firstIndex { $0.id == session.id } ?? 0 let previous = sessions[(index - 1 + sessions.count) % sessions.count] let next = sessions[(index + 1) % sessions.count] - HStack(spacing: 5) { + HStack(spacing: 3) { Button(intent: HapiFocusSessionIntent(sessionId: previous.id)) { Image(systemName: "chevron.left") - .frame(width: 16, height: 14) + .frame(width: 20, height: 20) .contentShape(Rectangle()) } .buttonStyle(.plain) - Text("\(index + 1)/\(sessions.count)") - .monospacedDigit() + Button(intent: HapiFocusSessionIntent(sessionId: next.id)) { + Text("\(index + 1)/\(sessions.count)") + .monospacedDigit() + .frame(minWidth: 26, minHeight: 20) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Next session") Button(intent: HapiFocusSessionIntent(sessionId: next.id)) { Image(systemName: "chevron.right") - .frame(width: 16, height: 14) + .frame(width: 20, height: 20) .contentShape(Rectangle()) } .buttonStyle(.plain) diff --git a/ios/HapiWidgets/Localizable.xcstrings b/ios/HapiWidgets/Localizable.xcstrings index 12de9160..65120c32 100644 --- a/ios/HapiWidgets/Localizable.xcstrings +++ b/ios/HapiWidgets/Localizable.xcstrings @@ -120,6 +120,23 @@ } } }, + "No active sessions" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет активных сеансов" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "没有活跃会话" + } + } + } + }, "No running sessions" : { "extractionState" : "manual", "localizations" : { @@ -426,6 +443,23 @@ } } }, + "Next session" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Следующий сеанс" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "下一个会话" + } + } + } + }, "Refresh" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift index d9fedc9e..93a9d299 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift @@ -30,6 +30,18 @@ import HapiProtocol /// app-side `ChatModel` is the single caller and awaits each run to /// completion, so runs never interleave in practice; the actor makes that a /// guarantee rather than a convention. +public struct ChatPipelineResult: Sendable { + public let blocks: [VisibleChatBlock] + public let latestUsage: LatestUsage? + public let latestGoal: JSONValue? + + public init(blocks: [VisibleChatBlock], latestUsage: LatestUsage?, latestGoal: JSONValue?) { + self.blocks = blocks + self.latestUsage = latestUsage + self.latestGoal = latestGoal + } +} + public actor ChatPipeline { private struct NormalizeCacheEntry { /// The exact row instance the cached result was computed from. @@ -51,6 +63,23 @@ public actor ChatPipeline { hasMoreMessages: Bool, directSendLocalIds: Set = [] ) -> [VisibleChatBlock] { + runResult( + messages: messages, + agentState: agentState, + hasMoreMessages: hasMoreMessages, + directSendLocalIds: directSendLocalIds + ).blocks + } + + /// Same pipeline with the reducer's latest context usage, used by the + /// composer's context meter. `run` stays the blocks-only API for tests and + /// callers that do not need usage. + public func runResult( + messages: [WindowMessage], + agentState: AgentState?, + hasMoreMessages: Bool, + directSendLocalIds: Set = [] + ) -> ChatPipelineResult { // Composer-owned rows out, except sends the idle agent is about to // consume (`ChatInteractor.directSendLocalIds`); duplicate ids keep // the first occurrence (merge output cannot contain duplicates — @@ -102,7 +131,7 @@ public actor ChatPipeline { if case .toolGroup(let group) = block { return group } return nil } - return visible + return ChatPipelineResult(blocks: visible, latestUsage: reduced.latestUsage, latestGoal: reduced.latestGoal) } private static func filterEmptyReasoning(_ blocks: [ChatBlock]) -> [ChatBlock] { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift index 96ce5e79..2ce85b17 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/MachineEndpoints.swift @@ -81,4 +81,12 @@ extension APIClient { public func machineCodexModels(machineId: String) async throws -> CodexModelsResponse { try await request(.get, "/api/machines/\(encodePathComponent(machineId))/codex-models") } + + /// `GET /api/machines/:id/claude-models` — the Claude CLI's own model + /// list for this machine (RPC envelope — check `success`). The create + /// form falls back to its static presets while loading or when a runner + /// lacks the RPC. + public func machineClaudeModels(machineId: String) async throws -> ClaudeModelsResponse { + try await request(.get, "/api/machines/\(encodePathComponent(machineId))/claude-models") + } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift index 49e44138..bd945637 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/NewSessionCatalogs.swift @@ -4,10 +4,13 @@ import Foundation public struct NewSessionOption: Equatable, Hashable, Sendable { public let value: String public let label: String + /// Optional picker section (the web renders these as ``). + public let group: String? - public init(value: String, label: String) { + public init(value: String, label: String, group: String? = nil) { self.value = value self.label = label + self.group = group } } @@ -32,11 +35,87 @@ public enum NewSessionCatalogs { /// `'auto'` sentinel row, then the `ClaudeEfforts` levels in ascending /// order. public static let claudeEfforts: [NewSessionOption] = - [NewSessionOption(value: "auto", label: "Auto")] + [NewSessionOption(value: "auto", label: "Default")] + ClaudeEfforts.levels.map { NewSessionOption(value: $0, label: ClaudeEfforts.label(for: $0) ?? effortLabel($0)) } + /// Launch model rows for Claude, mirroring the web + /// `getClaudeLaunchModelOptions`: the machine CLI catalog replaces the + /// built-in presets when available; earlier family versions go under the + /// "Other models" section; a saved model the catalog no longer lists stays + /// selectable with a suffix. + public static func claudeLaunchModelOptions( + catalog: [ClaudeModelSummary]?, + selectedModel: String?, + notListedSuffix: String, + otherModelsLabel: String + ) -> [NewSessionOption] { + guard let catalog, !catalog.isEmpty else { return claudeModels } + + var familySeen = Set() + var main: [NewSessionOption] = [] + var other: [NewSessionOption] = [] + for row in catalog where row.value != "default" { + let family = claudeFamily(row.value) + let isMain = familySeen.insert(family).inserted + let option = NewSessionOption( + value: row.value, + label: row.displayName ?? ClaudeModels.label(for: row.value) ?? row.value, + group: isMain ? nil : otherModelsLabel + ) + if isMain { main.append(option) } else { other.append(option) } + } + + let listed = Set((main + other).map(\.value)) + let normalized = (selectedModel?.trimmingCharacters(in: .whitespaces) ?? "") + let selected = normalized.isEmpty || normalized == "auto" || normalized == "default" + ? nil + : normalized + var options = [NewSessionOption(value: "auto", label: "Default")] + if let selected, !listed.contains(selected) { + let base = ClaudeModels.label(for: selected) ?? selected + options.append(NewSessionOption(value: selected, label: "\(base) (\(notListedSuffix))")) + } + options.append(contentsOf: main) + options.append(contentsOf: other) + return options + } + + /// Effort rows for the selected Claude model. Unknown support keeps the + /// static levels; an empty catalog row means only Default is offered. + public static func claudeEffortOptions( + catalog: [ClaudeModelSummary]?, + model: String?, + currentEffort: String? + ) -> [NewSessionOption]? { + guard let catalog, !catalog.isEmpty else { return claudeEfforts } + let normalizedModel = (model?.trimmingCharacters(in: .whitespaces) ?? "") + let lookup = normalizedModel.isEmpty || normalizedModel == "auto" || normalizedModel == "default" + ? "default" + : normalizedModel + guard let levels = catalog.first(where: { $0.value == lookup })?.effortLevels else { + return claudeEfforts + } + let supported = ClaudeEfforts.levels.filter { levels.contains($0) } + var options = [NewSessionOption(value: "auto", label: "Default")] + let normalizedEffort = (currentEffort?.trimmingCharacters(in: .whitespaces).lowercased() ?? "") + if !normalizedEffort.isEmpty, + normalizedEffort != "auto", normalizedEffort != "default", + !supported.contains(normalizedEffort) { + options.append(NewSessionOption(value: normalizedEffort, label: effortLabel(normalizedEffort))) + } + options.append(contentsOf: supported.map { + NewSessionOption(value: $0, label: ClaudeEfforts.label(for: $0) ?? effortLabel($0)) + }) + return options + } + + private static func claudeFamily(_ value: String) -> String { + let trimmed = value.hasPrefix("claude-") ? String(value.dropFirst("claude-".count)) : value + return trimmed.split(whereSeparator: { $0 == "-" || $0 == "[" }).first.map(String.init) ?? trimmed + } + /// Static codex fallback when the model row advertises no efforts /// (the web drops `max` for codex — `EffortField.tsx`). public static let codexReasoningEfforts: [NewSessionOption] = [ diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Chat/Reducer.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Chat/Reducer.swift index b0867955..019b7aed 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Chat/Reducer.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Chat/Reducer.swift @@ -12,6 +12,16 @@ private func calculateContextSize(_ usage: UsageData) -> Double { return (usage.cacheCreationInputTokens ?? 0) + (usage.cacheReadInputTokens ?? 0) + usage.inputTokens } +/// Some Claude-compatible providers emit assistant snapshots with an all-zero +/// usage object after long tool runs. Looking through them prevents the +/// context bar from resetting to 0%. +private func hasContextUsageSignal(_ usage: UsageData) -> Bool { + (usage.contextTokens ?? 0) > 0 + || usage.inputTokens > 0 + || (usage.cacheCreationInputTokens ?? 0) > 0 + || (usage.cacheReadInputTokens ?? 0) > 0 +} + /// Port of `isUsageVisibleInParentContext` — subagent usage must not drive /// the parent thread's context bar. private func isUsageVisibleInParentContext(_ msg: NormalizedMessage) -> Bool { @@ -148,7 +158,9 @@ public func reduceChatBlocks( // Latest usage: the most recent parent-context message with usage data. var latestUsage: LatestUsage? for msg in normalized.reversed() { - if let usage = msg.usage, isUsageVisibleInParentContext(msg) { + if let usage = msg.usage, + isUsageVisibleInParentContext(msg), + hasContextUsageSignal(usage) { latestUsage = LatestUsage( inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift index b60fdab0..72c0dbc1 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AgentState.swift @@ -102,18 +102,22 @@ public struct AgentState: Codable, Equatable, Sendable { public var requests: [String: AgentStateRequest]? /// Resolved requests keyed by request id. public var completedRequests: [String: AgentStateCompletedRequest]? + /// Epoch ms when the agent started compacting its context; nil otherwise. + public var contextCompactionStartedAt: Int? public init( controlledByUser: Bool? = nil, startingMode: SessionStartingMode? = nil, requests: [String: AgentStateRequest]? = nil, completedRequests: [String: AgentStateCompletedRequest]? = nil, - codexPlanProposalId: String? = nil + codexPlanProposalId: String? = nil, + contextCompactionStartedAt: Int? = nil ) { self.controlledByUser = controlledByUser self.startingMode = startingMode self.codexPlanProposalId = codexPlanProposalId self.requests = requests self.completedRequests = completedRequests + self.contextCompactionStartedAt = contextCompactionStartedAt } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift index 57ec6faa..48c28a3c 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift @@ -487,6 +487,41 @@ public struct CodexModelsResponse: Codable, Equatable, Sendable { } } +// MARK: - Claude model catalog + +/// One row of `GET /api/machines/:id/claude-models`. `value` is what +/// `claude --model` accepts; `effortLevels == []` means the model exposes no +/// effort control, while `nil` means the CLI did not report support. +public struct ClaudeModelSummary: Codable, Equatable, Sendable { + public var value: String + public var displayName: String? + public var effortLevels: [String]? + + public init(value: String, displayName: String? = nil, effortLevels: [String]? = nil) { + self.value = value + self.displayName = displayName + self.effortLevels = effortLevels + } +} + +/// Body of `GET /api/machines/:id/claude-models` (RPC envelope — check +/// `success`). A runner without the RPC answers 503 `rpc_target_missing`. +public struct ClaudeModelsResponse: Codable, Equatable, Sendable { + public var success: Bool + public var availableModels: [ClaudeModelSummary]? + public var error: String? + + public init( + success: Bool, + availableModels: [ClaudeModelSummary]? = nil, + error: String? = nil + ) { + self.success = success + self.availableModels = availableModels + self.error = error + } +} + // MARK: - Uploads /// Body of `POST /api/sessions/:id/upload` (RPC envelope). `path` feeds the diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift index 1f224dfa..879b88f7 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Code/CodeBlockView.swift @@ -1,13 +1,13 @@ import SwiftUI -/// Fenced code block: rounded container with a header (language chip + copy -/// button) and horizontally scrollable monospaced body. Highlighting runs off -/// the main thread through the injected `SyntaxHighlighting` engine and is -/// applied when ready; until then (or when the engine declines) the code -/// renders as plain text. +/// Fenced code block: rounded container with a header (language chip, wrap +/// toggle, copy button) and a monospaced body. Long blocks collapse by height +/// and offer a show-all control; line numbers are shown in the default +/// no-wrap mode and hidden when wrapping is enabled. /// -/// Unsupported fence languages the web renders specially (mermaid, math) -/// deliberately fall back to this view per the v1 plan. +/// Highlighting runs off the main thread through the injected +/// `SyntaxHighlighting` engine and is applied when ready; until then (or when +/// the engine declines) the code renders as plain text. public struct CodeBlockView: View { public let language: String? public let code: String @@ -20,6 +20,8 @@ public struct CodeBlockView: View { @State private var highlighted: AttributedString? @State private var showCopied = false + @State private var wrapLines = false + @State private var expanded = false public init(language: String?, code: String) { self.language = language @@ -36,16 +38,30 @@ public struct CodeBlockView: View { "\(displayLanguage)|\(theme.isDark ? "d" : "l")|\(code.count)|\(code.hashValue)" } + private var lineCount: Int { + max(1, code.split(separator: "\n", omittingEmptySubsequences: false).count) + } + + private var isCollapsible: Bool { lineCount > 18 } + + private var isCollapsed: Bool { isCollapsible && !expanded && !wrapLines } + public var body: some View { VStack(alignment: .leading, spacing: 0) { header - ScrollView(.horizontal, showsIndicators: false) { - Text(highlighted ?? AttributedString(code)) - .font(typography.codeFont(size: codeFontSize)) - .lineSpacing(typography.codeLineSpacing) - .foregroundStyle(theme.textPrimary) - .textSelection(.enabled) - .padding(12) + codeBody + if isCollapsible && !wrapLines { + Button { + expanded.toggle() + } label: { + Text(expanded ? "Collapse" : "Show all lines") + .font(typography.captionFont) + .frame(maxWidth: .infinity, minHeight: 34) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(theme.link) + .background(theme.codeHeaderBackground) } } .background(theme.codeBackground) @@ -59,6 +75,44 @@ public struct CodeBlockView: View { } } + @ViewBuilder + private var codeBody: some View { + if wrapLines { + Text(highlighted ?? AttributedString(code)) + .font(typography.codeFont(size: codeFontSize)) + .lineSpacing(typography.codeLineSpacing) + .foregroundStyle(theme.textPrimary) + .textSelection(.enabled) + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } else { + ScrollView(.horizontal, showsIndicators: false) { + HStack(alignment: .top, spacing: 0) { + Text((1...lineCount).map(String.init).joined(separator: "\n")) + .font(typography.codeFont(size: codeFontSize)) + .lineSpacing(typography.codeLineSpacing) + .foregroundStyle(theme.textHint) + .multilineTextAlignment(.trailing) + .padding(.leading, 8) + .padding(.trailing, 7) + .padding(.vertical, 12) + Rectangle() + .fill(theme.divider) + .frame(width: 1) + Text(highlighted ?? AttributedString(code)) + .font(typography.codeFont(size: codeFontSize)) + .lineSpacing(typography.codeLineSpacing) + .foregroundStyle(theme.textPrimary) + .textSelection(.enabled) + .padding(12) + } + } + .frame(maxHeight: isCollapsed ? 250 : nil, alignment: .top) + .clipped() + } + } + private var header: some View { HStack(spacing: 8) { Text(displayLanguage) @@ -66,6 +120,16 @@ public struct CodeBlockView: View { .foregroundStyle(theme.textSecondary) .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 12) + Button { + wrapLines.toggle() + } label: { + Image(systemName: wrapLines ? "text.alignleft" : "arrow.left.and.right") + .font(typography.captionFont) + .frame(minWidth: 40, minHeight: 44) + .foregroundStyle(wrapLines ? theme.link : theme.textSecondary) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(wrapLines ? "Disable line wrap" : "Wrap lines")) Button { // Explicit MainActor hop: keeps the @MainActor pasteboard // call valid regardless of the SDK's Button-action isolation. diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift index 1e78e7bb..516bbf02 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift @@ -252,7 +252,7 @@ struct CatalogTests { NewSessionOption(value: "haiku", label: "Haiku"), ]) #expect(NewSessionCatalogs.claudeEfforts == [ - NewSessionOption(value: "auto", label: "Auto"), + NewSessionOption(value: "auto", label: "Default"), NewSessionOption(value: "low", label: "Low"), NewSessionOption(value: "medium", label: "Medium"), NewSessionOption(value: "high", label: "High"), @@ -268,4 +268,37 @@ struct CatalogTests { ]) #expect(NewSessionCatalogs.effortLabel("xhigh") == "Xhigh") } + + @Test func claudeLaunchOptionsGroupOlderFamiliesAndKeepUnlistedSelection() { + let catalog = [ + ClaudeModelSummary(value: "opus", displayName: "Opus 4.1", effortLevels: ["low", "high"]), + ClaudeModelSummary(value: "claude-opus-4-0", displayName: "Opus 4"), + ClaudeModelSummary(value: "sonnet", displayName: "Sonnet 4.5"), + ] + let options = NewSessionCatalogs.claudeLaunchModelOptions( + catalog: catalog, + selectedModel: "claude-old", + notListedSuffix: "not listed", + otherModelsLabel: "Other models" + ) + + #expect(options.map(\.value) == [ + "auto", "claude-old", "opus", "sonnet", "claude-opus-4-0", + ]) + #expect(options[1].label == "claude-old (not listed)") + #expect(options[4].group == "Other models") + } + + @Test func claudeEffortOptionsUseTheSelectedModelLevels() { + let catalog = [ + ClaudeModelSummary(value: "default", effortLevels: ["low", "medium"]), + ClaudeModelSummary(value: "opus", effortLevels: []), + ] + #expect(NewSessionCatalogs.claudeEffortOptions( + catalog: catalog, model: "auto", currentEffort: "auto" + )?.map(\.value) == ["auto", "low", "medium"]) + #expect(NewSessionCatalogs.claudeEffortOptions( + catalog: catalog, model: "opus", currentEffort: "auto" + )?.map(\.value) == ["auto"]) + } }