Files
t3code/apps/swift-ios/Features/Workspace/NewThreadView.swift
T

515 lines
18 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
public struct NewThreadView: View {
@SwiftUI.Environment(\.dismiss) private var dismiss
@Bindable var model: FeatureRootModel
let submit: (NewTaskRequest) async -> FeatureThread?
let onCreated: (FeatureThread) -> Void
@State private var projectID = ""
@State private var prompt = ""
@State private var selection: FeatureSelection?
@State private var attachments: [FeatureDraftAttachment] = []
@State private var workspaceMode: FeatureWorkspaceMode = .local
@State private var branches: [FeatureWorkspaceBranch] = []
@State private var selectedBranch: FeatureWorkspaceBranch?
@State private var startFromOrigin = true
@State private var branchesLoading = false
@State private var branchLoadFailed = false
@State private var showingBranchPicker = false
@State private var isSubmitting = false
@State private var submissionFailed = false
@FocusState private var promptFocused: Bool
public init(
model: FeatureRootModel,
submit: @escaping (NewTaskRequest) async -> FeatureThread?,
onCreated: @escaping (FeatureThread) -> Void
) {
self.model = model
self.submit = submit
self.onCreated = onCreated
}
public var body: some View {
ZStack {
T3Colors.background.ignoresSafeArea()
VStack(spacing: 0) {
topBar
hero
.padding(.top, 82)
Spacer(minLength: 140)
}
}
.safeAreaInset(edge: .bottom, spacing: 0) {
VStack(spacing: 0) {
workspaceControls
FeatureComposerView(
text: $prompt,
selection: $selection,
attachments: $attachments,
providers: creationProviders,
threadSelection: nil,
isSending: isSubmitting,
isWorking: false,
focused: $promptFocused,
onSend: startTask,
onStop: {},
forceExpanded: true
)
}
.background(T3Colors.background)
}
.onAppear {
if projectID.isEmpty {
projectID = creationProjects.first?.id ?? ""
}
if selection == nil {
selection = initialSelection
}
}
.onChange(of: projectID) {
selection = initialSelection
resetWorkspaceSelection()
}
.task(id: projectID) { await loadBranches() }
.sheet(isPresented: $showingBranchPicker) {
NewTaskBranchPicker(
branches: branches,
selection: selectedBranch,
isLoading: branchesLoading,
loadFailed: branchLoadFailed,
onSelect: { branch in
selectedBranch = branch
showingBranchPicker = false
},
onRefresh: { Task { await loadBranches(refresh: true) } }
)
}
.alert("Couldn’t start task", isPresented: $submissionFailed) {
Button("OK") {}
} message: {
Text("Check your connection and try again.")
}
.interactiveDismissDisabled(isSubmitting)
.presentationDetents([.large])
.presentationDragIndicator(.visible)
.preferredColorScheme(.dark)
}
private var topBar: some View {
HStack {
Button("Cancel") { dismiss() }
.font(.body)
.foregroundStyle(T3Colors.textSecondary)
.disabled(isSubmitting)
Spacer()
}
.padding(.horizontal, 16)
.frame(height: 48)
}
private var hero: some View {
VStack(spacing: 10) {
Text("What should we build")
HStack(spacing: 0) {
Text("in")
Menu {
ForEach(creationProjects) { project in
Button {
projectID = project.id
} label: {
if project.id == projectID {
Label(project.name, systemImage: "checkmark")
} else {
Text(project.name)
}
}
}
} label: {
Text(selectedProject?.name ?? "a project")
.foregroundStyle(T3Colors.textPrimary)
.overlay(alignment: .bottom) {
DottedUnderline()
.stroke(
T3Colors.textPrimary.opacity(0.58),
style: StrokeStyle(lineWidth: 1, dash: [2, 3])
)
.frame(height: 1)
.offset(y: 3)
}
}
.buttonStyle(.plain)
.padding(.leading, 5)
Text("?")
}
}
.font(T3Typography.threadHeading1.weight(.regular))
.tracking(-0.35)
.foregroundStyle(T3Colors.textPrimary)
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.overlay(alignment: .bottom) {
HStack(spacing: 6) {
Image(systemName: "server.rack")
.font(.system(size: 11, weight: .medium))
Text("on \(environmentName)")
}
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textTertiary)
.offset(y: 31)
}
.accessibilityElement(children: .contain)
}
private var selectedProject: FeatureProject? {
creationProjects.first { $0.id == projectID }
}
private var workspaceControls: some View {
HStack(spacing: 14) {
Menu {
Button {
setWorkspaceMode(.local)
} label: {
Label(
FeatureWorkspaceMode.local.title,
systemImage: workspaceMode == .local ? "checkmark" : "folder"
)
}
Button {
setWorkspaceMode(.worktree)
} label: {
Label(
FeatureWorkspaceMode.worktree.title,
systemImage: workspaceMode == .worktree
? "checkmark"
: "arrow.triangle.branch"
)
}
} label: {
workspaceControlLabel(
workspaceMode.title,
systemImage: workspaceMode.systemImage,
showsChevron: true
)
}
.disabled(isSubmitting)
if workspaceMode == .worktree {
Button {
showingBranchPicker = true
} label: {
workspaceControlLabel(
selectedBranch?.name
?? (branchesLoading ? "Loading branches" : "Choose branch"),
systemImage: "arrow.triangle.branch",
showsChevron: true
)
}
.buttonStyle(.plain)
.disabled(isSubmitting)
.accessibilityLabel("Base branch")
.accessibilityValue(selectedBranch?.name ?? "Not selected")
Button {
startFromOrigin.toggle()
} label: {
Label(
"Latest origin",
systemImage: startFromOrigin ? "checkmark.circle.fill" : "circle"
)
.lineLimit(1)
}
.buttonStyle(.plain)
.foregroundStyle(
startFromOrigin ? T3Colors.textSecondary : T3Colors.textTertiary
)
.disabled(isSubmitting)
.accessibilityValue(startFromOrigin ? "On" : "Off")
} else if let selectedBranch {
Label(selectedBranch.name, systemImage: "arrow.triangle.branch")
.lineLimit(1)
.foregroundStyle(T3Colors.textTertiary)
.accessibilityLabel("Current branch, \(selectedBranch.name)")
}
Spacer(minLength: 0)
}
.font(T3Typography.supporting)
.padding(.horizontal, 18)
.frame(minHeight: 38)
.animation(.snappy(duration: 0.18), value: workspaceMode)
}
private func workspaceControlLabel(
_ title: String,
systemImage: String,
showsChevron: Bool
) -> some View {
HStack(spacing: 5) {
Image(systemName: systemImage)
.font(.system(size: 12, weight: .medium))
Text(title)
.lineLimit(1)
if showsChevron {
Image(systemName: "chevron.down")
.font(.system(size: 8, weight: .bold))
}
}
.foregroundStyle(T3Colors.textSecondary)
.contentShape(Rectangle())
}
private var creationProjects: [FeatureProject] {
DailyUXCreationContext.projects(in: model.snapshot)
}
private var environmentName: String {
if let environmentID = selectedProject?.environmentID,
let environment = model.snapshot.environments.first(where: { $0.id == environmentID }) {
return environment.name
}
return model.snapshot.connection.environmentName ?? "this server"
}
private var initialSelection: FeatureSelection? {
DailyUXCreationContext.initialSelection(
for: selectedProject,
in: model.snapshot
)
}
/// Provider catalogues are active-device-only. For a passive project, keep
/// its own default selectable without leaking models from another machine.
private var creationProviders: [FeatureProvider] {
DailyUXCreationContext.providers(for: selectedProject, in: model.snapshot)
}
private var canSubmit: Bool {
!isSubmitting
&& !projectID.isEmpty
&& (!trimmedPrompt.isEmpty || !attachments.isEmpty)
&& (attachments.isEmpty || imagesAllowed)
&& (workspaceMode != .worktree || selectedBranch != nil)
}
private var trimmedPrompt: String {
prompt.trimmingCharacters(in: .whitespacesAndNewlines)
}
private var imagesAllowed: Bool {
DailyUXModelOptions.supportsImages(
selection: selection,
providers: creationProviders
)
}
private func startTask() {
guard canSubmit else { return }
promptFocused = false
isSubmitting = true
let request = NewTaskRequest(
projectID: projectID,
prompt: trimmedPrompt,
selection: selection,
runtimeMode: .fullAccess,
interactionMode: .standard,
workspaceMode: workspaceMode,
branch: selectedBranch?.name,
worktreePath: workspaceMode == .local
? NewTaskWorkspaceDefaults.normalizedWorktreePath(
for: selectedBranch,
projectPath: selectedProject?.path ?? ""
)
: nil,
startFromOrigin: startFromOrigin,
attachments: attachments
)
Task {
if let thread = await submit(request) {
onCreated(thread)
} else {
isSubmitting = false
submissionFailed = true
promptFocused = true
}
}
}
private func resetWorkspaceSelection() {
branches = []
selectedBranch = nil
branchLoadFailed = false
}
private func setWorkspaceMode(_ mode: FeatureWorkspaceMode) {
workspaceMode = mode
selectedBranch = switch mode {
case .local: NewTaskWorkspaceDefaults.localBranch(in: branches)
case .worktree: NewTaskWorkspaceDefaults.worktreeBase(in: branches)
}
}
@MainActor
private func loadBranches(refresh: Bool = false) async {
let requestedProjectID = projectID
guard !requestedProjectID.isEmpty else { return }
branchesLoading = true
branchLoadFailed = false
do {
let loaded = try await model.workspaceBranches(
projectID: requestedProjectID,
refresh: refresh
)
guard !Task.isCancelled, projectID == requestedProjectID else { return }
branches = loaded.sorted(by: Self.branchSort)
if let selectedBranch,
let updated = branches.first(where: { $0.id == selectedBranch.id }) {
self.selectedBranch = updated
} else {
self.selectedBranch = switch workspaceMode {
case .local: NewTaskWorkspaceDefaults.localBranch(in: branches)
case .worktree: NewTaskWorkspaceDefaults.worktreeBase(in: branches)
}
}
} catch is CancellationError {
return
} catch {
guard projectID == requestedProjectID else { return }
branchLoadFailed = true
}
guard projectID == requestedProjectID else { return }
branchesLoading = false
}
private static func branchSort(
_ lhs: FeatureWorkspaceBranch,
_ rhs: FeatureWorkspaceBranch
) -> Bool {
let lhsRank = lhs.isCurrent ? 0 : lhs.isDefault ? 1 : lhs.isRemote ? 3 : 2
let rhsRank = rhs.isCurrent ? 0 : rhs.isDefault ? 1 : rhs.isRemote ? 3 : 2
if lhsRank != rhsRank { return lhsRank < rhsRank }
return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending
}
}
private struct DottedUnderline: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.minX, y: rect.midY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
return path
}
}
private struct NewTaskBranchPicker: View {
@SwiftUI.Environment(\.dismiss) private var dismiss
let branches: [FeatureWorkspaceBranch]
let selection: FeatureWorkspaceBranch?
let isLoading: Bool
let loadFailed: Bool
let onSelect: (FeatureWorkspaceBranch) -> Void
let onRefresh: () -> Void
@State private var query = ""
var body: some View {
NavigationStack {
Group {
if isLoading, branches.isEmpty {
ProgressView("Loading branches")
.foregroundStyle(T3Colors.textSecondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if filteredBranches.isEmpty {
ContentUnavailableView {
Label(
loadFailed ? "Branches unavailable" : "No branches found",
systemImage: loadFailed
? "exclamationmark.triangle"
: "arrow.triangle.branch"
)
} description: {
Text(
loadFailed
? "Check the connection and try again."
: "Try a different search."
)
} actions: {
if loadFailed {
Button("Try again", action: onRefresh)
}
}
} else {
List(filteredBranches) { branch in
Button {
onSelect(branch)
} label: {
HStack(spacing: 12) {
Image(systemName: "arrow.triangle.branch")
.foregroundStyle(T3Colors.textTertiary)
Text(branch.name)
.foregroundStyle(T3Colors.textPrimary)
.lineLimit(1)
Spacer(minLength: 10)
if let badge = branch.badge {
Text(badge)
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textTertiary)
}
if branch.id == selection?.id {
Image(systemName: "checkmark")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(T3Colors.accent)
}
}
.frame(minHeight: 34)
}
.buttonStyle(.plain)
.listRowBackground(T3Colors.background)
}
.listStyle(.plain)
.refreshable { onRefresh() }
}
}
.background(T3Colors.background)
.navigationTitle("Base branch")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $query, prompt: "Search branches")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .primaryAction) {
Button(action: onRefresh) {
Image(systemName: "arrow.clockwise")
}
.disabled(isLoading)
.accessibilityLabel("Refresh branches")
}
}
}
.presentationDetents([.medium, .large])
.presentationBackground(T3Colors.background)
.preferredColorScheme(.dark)
}
private var filteredBranches: [FeatureWorkspaceBranch] {
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return branches }
return branches.filter {
$0.name.localizedCaseInsensitiveContains(trimmed)
}
}
}