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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#if os(macOS)
import AppKit
import SwiftUI
import UniformTypeIdentifiers

/// Native macOS chat window with a sessions sidebar and conversation toolbar.
/// Draft controls belong to the composer; the compact menu-bar panel keeps
/// using `OpenClawChatView` directly.
@MainActor
public struct OpenClawChatWindowShell: View {
    public nonisolated static let assistantTraceDefaultsKey = "openclaw.webchat.showAssistantTrace"
    public nonisolated static let assistantReasoningDefaultsKey = "openclaw.webchat.showAssistantReasoning"
    public nonisolated static let assistantToolActivityDefaultsKey = "openclaw.webchat.showAssistantToolActivity"

    @State private var viewModel: OpenClawChatViewModel
    @Environment(\.colorScheme) private var colorScheme
    /// Keep absent keys available to the app's legacy trace-preference migration.
    @AppStorage(OpenClawChatWindowShell.assistantReasoningDefaultsKey)
    private var storedShowsReasoning: Bool?
    @AppStorage(OpenClawChatWindowShell.assistantToolActivityDefaultsKey)
    private var storedShowsToolActivity: Bool?
    @State private var sessionQuery = ""
    @State private var isConfirmingClearHistory = false
    @State private var isPresentingSessions = false
    @State private var isRenamingSession = false
    @State private var isPresentingNewSessionOptions = false
    @State private var renameSessionTarget: OpenClawChatSessionTarget?
    @State private var renameText = ""
    private let attentionRequests: [OpenClawChatAttentionRequest]
    private let userAccent: Color?
    private let displayOptions: OpenClawChatDisplayOptions
    private let emptyAssistantIntro: String?
    private let emptyAssistantPrompts: [OpenClawChatView.StarterPrompt]
    private let talkControl: OpenClawChatTalkControl?
    private let voiceNoteControl: OpenClawChatVoiceNoteControl?
    private let speech: OpenClawChatSpeechController?
    private let mediaPlaybackAllowed: @MainActor @Sendable () -> Bool

    /// `showsAssistantTrace` remains as a source-compatible convenience that sets both display options.
    public init(
        viewModel: OpenClawChatViewModel,
        userAccent: Color? = nil,
        attentionRequests: [OpenClawChatAttentionRequest] = [],
        displayOptions: OpenClawChatDisplayOptions? = nil,
        showsAssistantTrace: Bool = false,
        emptyAssistantIntro: String? = nil,
        emptyAssistantPrompts: [OpenClawChatView.StarterPrompt] = [],
        talkControl: OpenClawChatTalkControl? = nil,
        voiceNoteControl: OpenClawChatVoiceNoteControl? = nil,
        speech: OpenClawChatSpeechController? = nil,
        mediaPlaybackAllowed: @escaping @MainActor @Sendable () -> Bool = { true })
    {
        _viewModel = State(initialValue: viewModel)
        self.attentionRequests = attentionRequests
        self.userAccent = userAccent
        self.displayOptions = displayOptions ?? .assistantTrace(showsAssistantTrace)
        self.emptyAssistantIntro = emptyAssistantIntro
        self.emptyAssistantPrompts = emptyAssistantPrompts
        self.talkControl = talkControl
        self.voiceNoteControl = voiceNoteControl
        self.speech = speech
        self.mediaPlaybackAllowed = mediaPlaybackAllowed
    }

    public var body: some View {
        NavigationSplitView {
            ChatSessionSidebar(
                viewModel: self.viewModel,
                query: self.$sessionQuery,
                additionalAttentionRequests: self.attentionRequests)
                .navigationSplitViewColumnWidth(min: 220, ideal: 260, max: 360)
        } detail: {
            OpenClawChatView(
                viewModel: self.viewModel,
                drawsBackground: false,
                userAccent: self.userAccent,
                displayOptions: self.displayOptions,
                assistantName: self.viewModel.selectedAgent?.displayName,
                assistantAvatarText: self.viewModel.selectedAgent?.emoji,
                showsAssistantAvatars: false,
                composerChrome: .clean,
                messagePlaceholder: self.viewModel.selectedAgent.map {
                    String(format: String(localized: "Message %@…"), $0.displayName)
                },
                emptyAssistantIntro: self.emptyAssistantIntro,
                emptyAssistantPrompts: self.emptyAssistantPrompts,
                talkControl: self.talkControl,
                voiceNoteControl: self.voiceNoteControl,
                speech: self.speech,
                mediaPlaybackAllowed: self.mediaPlaybackAllowed)
                .environment(\.openClawChatDesktopLayout, true)
                .navigationTitle(self.activeSessionTitle)
                .toolbar { self.detailToolbar }
                .background(self.keyboardShortcutHandlers)
                .background(OpenClawChatTheme.desktopCanvas(in: self.colorScheme))
        }
        .task { await self.viewModel.refreshAgents() }
        .confirmationDialog(
            "Clear this thread's history?",
            isPresented: self.$isConfirmingClearHistory)
        {
            Button(role: .destructive) {
                self.viewModel.requestSessionReset()
            } label: {
                Text("Clear History")
                    .font(OpenClawChatTypography.body)
            }
        } message: {
            Text(verbatim: String(
                format: String(localized: """
                This resets the conversation for %@. The session key stays the same.
                """),
                self.activeSessionTitle))
                .font(OpenClawChatTypography.body)
        }
        .alert(String(localized: "Rename Thread"), isPresented: self.$isRenamingSession) {
                TextField(String(localized: "Thread name"), text: self.$renameText)
                Button(String(localized: "Rename")) {
                    guard let target = self.renameSessionTarget else { return }
                    self.viewModel.renameSession(
                        key: target.sessionKey,
                        label: self.renameText,
                        agentID: target.agentID)
                    self.renameSessionTarget = nil
                }
                Button(String(localized: "Cancel"), role: .cancel) {
                    self.renameSessionTarget = nil
                }
            }
            .sheet(isPresented: self.$isPresentingSessions) {
                ChatSessionsSheet(viewModel: self.viewModel)
            }
            .onChange(of: self.viewModel.pendingRunCount) { previous, current in
                // Run completion changes timestamps/token totals; pull them once
                // per run instead of polling.
                if previous > 0, current == 0 {
                    self.viewModel.refreshSessions(limit: 200)
                }
            }
    }

    /// Key equivalents only fire for installed views; buttons inside a closed
    /// toolbar Menu are not built yet, so the shortcuts live here and the menu
    /// items carry matching labels for discoverability.
    private var keyboardShortcutHandlers: some View {
        Group {
            Button {
                Task { await self.viewModel.startNewSession() }
            } label: {
                Text("New Thread")
                    .font(OpenClawChatTypography.body)
            }
            .keyboardShortcut("n", modifiers: [.command, .shift])
            .focusable(false)

            Button {
                self.viewModel.refresh()
                self.viewModel.refreshSessions(limit: 200)
            } label: {
                Text("Refresh")
                    .font(OpenClawChatTypography.body)
            }
            .keyboardShortcut("r", modifiers: [.command])
            .focusable(false)

            Button {
                self.exportTranscript()
            } label: {
                Text("Export Transcript")
                    .font(OpenClawChatTypography.body)
            }
            .keyboardShortcut("e", modifiers: [.command, .shift])
            .focusable(false)
            .disabled(self.viewModel.messages.isEmpty)

            Button {
                self.isPresentingSessions = true
            } label: {
                Text("Threads")
                    .font(OpenClawChatTypography.body)
            }
            .keyboardShortcut("s", modifiers: [.command, .shift])
            .focusable(false)
        }
        .opacity(0)
        .frame(width: 0, height: 0)
        .accessibilityHidden(true)
    }

    private var activeSessionTitle: String {
        if let entry = self.activeSessionEntry {
            return ChatSessionSidebarModel.displayName(for: entry)
        }
        return ChatSessionSidebarModel.displayName(forKey: self.viewModel.sessionKey)
    }

    private var activeSessionEntry: OpenClawChatSessionEntry? {
        self.viewModel.currentSessionEntry()
    }

    private var activeSessionKey: String {
        self.activeSessionEntry?.key ?? self.viewModel.sessionKey
    }

    @ToolbarContentBuilder
    private var detailToolbar: some ToolbarContent {
        if #available(macOS 26.0, *) {
            ToolbarItem(placement: .principal) {
                self.conversationIdentity
            }
            .sharedBackgroundVisibility(.hidden)
        } else {
            ToolbarItem(placement: .principal) {
                self.conversationIdentity
            }
        }
        ToolbarItem(placement: .primaryAction) {
            self.sessionActionsMenu
        }
    }

    private var conversationIdentity: some View {
        TimelineView(.periodic(from: .now, by: 30)) { context in
            HStack(spacing: 8) {
                if let agent = self.viewModel.selectedAgent {
                    ChatSidebarAgentAvatar(agent: agent, size: 24)
                }
                VStack(alignment: .leading, spacing: 2) {
                    Text(self.activeSessionTitle)
                        .font(OpenClawChatTypography.body(size: 13, weight: .semibold, relativeTo: .headline))
                    HStack(spacing: 6) {
                        if let agent = self.viewModel.selectedAgent {
                            Text(verbatim: agent.displayName)
                        }
                        if let status = self.conversationStatus(at: context.date) {
                            Text(verbatim: "·").accessibilityHidden(true)
                            Label(status.title, systemImage: status.symbol)
                                .labelStyle(.titleAndIcon)
                                .foregroundStyle(status.tint)
                        }
                    }
                    .font(OpenClawChatTypography.caption)
                    .foregroundStyle(.secondary)
                }
                .lineLimit(1)
            }
            .padding(.horizontal, 4)
            .padding(.vertical, 6)
            .accessibilityElement(children: .combine)
            .accessibilityIdentifier("chat-conversation-identity")
        }
    }

    private func conversationStatus(at date: Date) -> (title: String, symbol: String, tint: Color)? {
        if !self.viewModel.healthOK {
            return (String(localized: "Connecting…"), "network", .secondary)
        }
        if self.viewModel.composerModelAvailabilityMessage != nil {
            return (String(localized: "Sign-in needed"), "key", OpenClawChatTheme.warning)
        }
        if self.viewModel.visibleQuestionCards.contains(where: { $0.status(at: date) == .pending }) {
            return (String(localized: "Needs you"), "bubble.left", OpenClawChatTheme.warning)
        }
        let activity = self.activeSessionEntry.flatMap {
            ChatSessionSidebarModel.activity(for: $0, now: date.timeIntervalSince1970 * 1000)
        }
        if activity?.kind == .attention {
            return (String(localized: "Needs you"), "exclamationmark.bubble", OpenClawChatTheme.warning)
        }
        if activity?.kind == .queued {
            return (String(localized: "Queued"), "hourglass", .secondary)
        }
        if self.viewModel.hasBlockingRunActivity {
            return (String(localized: "Working"), "circle.dotted", .secondary)
        }
        guard let activity else { return nil }
        switch activity.kind {
        case .attention:
            return (String(localized: "Needs you"), "exclamationmark.bubble", OpenClawChatTheme.warning)
        case .running:
            return (String(localized: "Working"), "circle.dotted", .secondary)
        case .queued:
            return (String(localized: "Queued"), "hourglass", .secondary)
        case .failed:
            return (String(localized: "Failed"), "exclamationmark.triangle", OpenClawChatTheme.warning)
        case .finished:
            return (String(localized: "Finished"), "checkmark", .secondary)
        case .idle:
            return (String(localized: "Ready"), "circle", .secondary)
        case .unknown:
            return nil
        }
    }

    private var sessionActionsMenu: some View {
        Menu {
            Button {
                Task { await self.viewModel.startNewSession() }
            } label: {
                chatWindowActionLabel("New Thread", systemImage: "square.and.pencil")
            }
            .keyboardShortcut("n", modifiers: [.command, .shift])

            Button {
                self.isPresentingNewSessionOptions = true
            } label: {
                chatWindowActionLabel("New Thread Options…", systemImage: "slider.horizontal.3")
            }

            Button {
                self.viewModel.refresh()
                self.viewModel.refreshSessions(limit: 200)
            } label: {
                chatWindowActionLabel("Refresh", systemImage: "arrow.clockwise")
            }
            .keyboardShortcut("r", modifiers: [.command])

            Button {
                self.isPresentingSessions = true
            } label: {
                chatWindowActionLabel("Threads…", systemImage: "rectangle.stack")
            }
            .keyboardShortcut("s", modifiers: [.command, .shift])

            Divider()

            Button {
                self.renameSessionTarget = self.viewModel.currentSessionTarget
                self.renameText = self.activeSessionEntry?.label ?? self.activeSessionTitle
                self.isRenamingSession = true
            } label: {
                chatWindowActionLabel(
                    LocalizedStringKey(String(localized: "Rename Thread…")),
                    systemImage: "pencil")
            }

            Button {
                let target = self.viewModel.currentSessionTarget
                Task { await self.viewModel.forkSession(key: target.sessionKey, agentID: target.agentID) }
            } label: {
                chatWindowActionLabel(
                    LocalizedStringKey(
                        self.activeSessionEntry?.hasActiveRun == true
                            ? String(localized: "Fork from last completed message")
                            : String(localized: "Fork")),
                    systemImage: "arrow.triangle.branch")
            }

            Button {
                self.viewModel.setSessionPinned(
                    key: self.activeSessionKey,
                    pinned: self.activeSessionEntry?.pinned != true,
                    agentID: self.viewModel.currentSessionTarget.agentID)
            } label: {
                chatWindowActionLabel(
                    LocalizedStringKey(self.activeSessionEntry?.pinned == true
                        ? String(localized: "Unpin")
                        : String(localized: "Pin")),
                    systemImage: self.activeSessionEntry?.pinned == true ? "pin.slash" : "pin")
            }

            Button {
                self.viewModel.setSessionUnread(
                    key: self.activeSessionKey,
                    unread: self.activeSessionEntry?.unread != true,
                    agentID: self.viewModel.currentSessionTarget.agentID)
            } label: {
                chatWindowActionLabel(
                    LocalizedStringKey(self.activeSessionEntry?.unread == true
                        ? String(localized: "Mark Read")
                        : String(localized: "Mark Unread")),
                    systemImage: self.activeSessionEntry?.unread == true ? "envelope.open" : "envelope.badge")
            }

            if self.activeSessionEntry.map({
                ChatSessionSidebarModel.canArchiveSession(
                    $0,
                    mainSessionKey: self.viewModel.selectedAgentMainSessionKey)
            }) == true {
                Button {
                    if let activeSessionEntry = self.activeSessionEntry {
                        self.viewModel.setSessionArchived(
                            activeSessionEntry,
                            archived: !activeSessionEntry.isArchived)
                    }
                } label: {
                    chatWindowActionLabel(
                        LocalizedStringKey(self.activeSessionEntry?.isArchived == true
                            ? String(localized: "Restore")
                            : String(localized: "Archive")),
                        systemImage: self.activeSessionEntry?.isArchived == true
                            ? "tray.and.arrow.up"
                            : "archivebox")
                }
            }

            OpenClawSessionColorMenu(color: self.activeSessionEntry?.color) { color in
                let target = self.viewModel.currentSessionTarget
                Task {
                    await self.viewModel.setSessionColor(
                        key: target.sessionKey,
                        color: color,
                        agentID: target.agentID)
                }
            }

            Divider()

            Button {
                self.copyToPasteboard(self.viewModel.sessionKey)
            } label: {
                chatWindowActionLabel("Copy Session Key", systemImage: "doc.on.doc")
            }

            Button {
                self.exportTranscript()
            } label: {
                chatWindowActionLabel("Export Transcript…", systemImage: "square.and.arrow.up")
            }
            .keyboardShortcut("e", modifiers: [.command, .shift])
            .disabled(self.viewModel.messages.isEmpty)

            Toggle(isOn: Binding(
                get: { self.displayOptions.contains(.reasoning) },
                set: { self.storedShowsReasoning = $0 }))
            {
                chatWindowActionLabel(
                    "Show Reasoning",
                    systemImage: "brain.head.profile")
            }

            Toggle(isOn: Binding(
                get: { self.displayOptions.contains(.toolActivity) },
                set: { self.storedShowsToolActivity = $0 }))
            {
                chatWindowActionLabel(
                    "Show Tool Activity",
                    systemImage: "hammer")
            }

            Divider()

            Button {
                self.viewModel.requestSessionCompact()
            } label: {
                chatWindowActionLabel("Compact Thread", systemImage: "arrow.down.right.and.arrow.up.left")
            }
            .disabled(self.viewModel.hasBlockingRunActivity)

            Button(role: .destructive) {
                self.isConfirmingClearHistory = true
            } label: {
                chatWindowActionLabel("Clear History…", systemImage: "trash")
            }
        } label: {
            chatWindowActionLabel("Thread", systemImage: "ellipsis.circle")
        }
        .popover(isPresented: self.$isPresentingNewSessionOptions) {
            ChatNewSessionOptionsPopover(viewModel: self.viewModel) {
                self.isPresentingNewSessionOptions = false
            }
        }
        .menuIndicator(.hidden)
        .help("Thread actions")
    }

    private func copyToPasteboard(_ string: String) {
        NSPasteboard.general.clearContents()
        NSPasteboard.general.setString(string, forType: .string)
    }

    private func exportTranscript() {
        let markdown = self.viewModel.exportTranscriptMarkdown()
        let panel = NSSavePanel()
        panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]
        panel.nameFieldStringValue = ChatTranscriptExporter.filename(
            sessionTitle: self.activeSessionTitle,
            sessionKey: self.viewModel.sessionKey)
        panel.begin { response in
            guard response == .OK, let url = panel.url else { return }
            try? markdown.write(to: url, atomically: true, encoding: .utf8)
        }
    }
}

func chatWindowActionLabel(_ title: LocalizedStringKey, systemImage: String) -> some View {
    Label {
        Text(title)
            .font(OpenClawChatTypography.body(size: 13, weight: .regular, relativeTo: .body))
    } icon: {
        Image(systemName: systemImage)
    }
}
#endif