fix(swift-ios): make composer state durable
This commit is contained in:
9 files changed
+371
-15
No files matched your search
@@ -206,7 +206,7 @@ struct FeatureComposerUserInputPanel: View {
|
||||
|
||||
TextField(
|
||||
"Write custom answer",
|
||||
text: answerBinding(for: question.id),
|
||||
text: answerBinding(for: question),
|
||||
axis: .vertical
|
||||
)
|
||||
.font(T3Typography.composer)
|
||||
@@ -364,13 +364,21 @@ struct FeatureComposerUserInputPanel: View {
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
|
||||
private func answerBinding(for questionID: String) -> Binding<String> {
|
||||
private func answerBinding(for question: FeatureInputQuestion) -> Binding<String> {
|
||||
Binding(
|
||||
get: {
|
||||
guard case let .text(value)? = answers[questionID] else { return "" }
|
||||
return value
|
||||
FeatureComposerCustomAnswer.text(
|
||||
in: answers[question.id],
|
||||
for: question
|
||||
)
|
||||
},
|
||||
set: { answers[questionID] = .text($0) }
|
||||
set: {
|
||||
answers[question.id] = FeatureComposerCustomAnswer.replacingText(
|
||||
in: answers[question.id],
|
||||
with: $0,
|
||||
for: question
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -421,6 +429,39 @@ struct FeatureComposerUserInputPanel: View {
|
||||
}
|
||||
}
|
||||
|
||||
enum FeatureComposerCustomAnswer {
|
||||
static func text(
|
||||
in answer: FeatureInputAnswer?,
|
||||
for question: FeatureInputQuestion
|
||||
) -> String {
|
||||
let optionLabels = Set(question.options.map(\.label))
|
||||
switch answer {
|
||||
case let .text(value):
|
||||
return optionLabels.contains(value) ? "" : value
|
||||
case let .selections(values):
|
||||
return values.first(where: { !optionLabels.contains($0) }) ?? ""
|
||||
case nil:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
static func replacingText(
|
||||
in answer: FeatureInputAnswer?,
|
||||
with text: String,
|
||||
for question: FeatureInputQuestion
|
||||
) -> FeatureInputAnswer {
|
||||
guard question.allowsMultiple else { return .text(text) }
|
||||
let optionLabels = Set(question.options.map(\.label))
|
||||
let selectedOptions: [String]
|
||||
if case let .selections(values) = answer {
|
||||
selectedOptions = values.filter(optionLabels.contains)
|
||||
} else {
|
||||
selectedOptions = []
|
||||
}
|
||||
return .selections(text.isEmpty ? selectedOptions : selectedOptions + [text])
|
||||
}
|
||||
}
|
||||
|
||||
enum FeatureComposerQuestionReconciliation {
|
||||
static func index(
|
||||
current: Int,
|
||||
|
||||
@@ -593,6 +593,8 @@ public final class FeatureRootModel {
|
||||
|| snapshot.environments != value.environments
|
||||
|| snapshot.projects != value.projects
|
||||
|| snapshot.providers != value.providers
|
||||
|| snapshot.providersByEnvironment != value.providersByEnvironment
|
||||
|| snapshot.preferencesByEnvironment != value.preferencesByEnvironment
|
||||
|| snapshot.threads != value.threads {
|
||||
homePresentationRevision &+= 1
|
||||
}
|
||||
@@ -1048,12 +1050,16 @@ public final class FeatureRootModel {
|
||||
|| (environment.isActive && snapshot.connection.state == .connected)
|
||||
}
|
||||
|
||||
private static func shouldQueue(
|
||||
static func shouldQueue(
|
||||
_ error: any Error,
|
||||
environmentID: String,
|
||||
snapshot: FeatureSnapshot
|
||||
) -> Bool {
|
||||
if error is CancellationError || error is URLError { return true }
|
||||
if let rpcError = error as? RPCError,
|
||||
case .responseTimedOut = rpcError {
|
||||
return true
|
||||
}
|
||||
if let environment = snapshot.environments.first(where: { $0.id == environmentID }) {
|
||||
let disconnected = environment.connectionState != .connected
|
||||
&& !(environment.isActive && snapshot.connection.state == .connected)
|
||||
|
||||
@@ -27,6 +27,7 @@ public struct NewThreadView: View {
|
||||
@State private var restoredDraftProjectID: String?
|
||||
@State private var draftRestoreContext: NewTaskDraftRestoreContext?
|
||||
@State private var draftSaveTask: Task<Void, Never>?
|
||||
@State private var immediateDraftSaveTasks: [String: Task<Void, Never>] = [:]
|
||||
@State private var submittedSuccessfully = false
|
||||
@FocusState private var promptFocused: Bool
|
||||
|
||||
@@ -447,9 +448,14 @@ public struct NewThreadView: View {
|
||||
}
|
||||
promptFocused = false
|
||||
isSubmitting = true
|
||||
draftSaveTask?.cancel()
|
||||
let pendingDraftSaveTask = draftSaveTask
|
||||
pendingDraftSaveTask?.cancel()
|
||||
draftSaveTask = nil
|
||||
let draftKey = currentDraftKey
|
||||
let draftSnapshot = composerDraft
|
||||
let immediateDraftSaveTask = draftKey.flatMap {
|
||||
immediateDraftSaveTasks.removeValue(forKey: $0)
|
||||
}
|
||||
let request = NewTaskRequest(
|
||||
projectID: project.id,
|
||||
prompt: trimmedPrompt,
|
||||
@@ -468,14 +474,20 @@ public struct NewThreadView: View {
|
||||
attachments: attachments
|
||||
)
|
||||
|
||||
Task {
|
||||
Task { @MainActor in
|
||||
await NewTaskDraftWriteFence.cancelAndWait(pendingDraftSaveTask)
|
||||
await NewTaskDraftWriteFence.cancelAndWait(immediateDraftSaveTask)
|
||||
if let draftKey {
|
||||
try? await draftStore.setDraft(draftSnapshot, for: draftKey)
|
||||
}
|
||||
if let thread = await submit(request) {
|
||||
submittedSuccessfully = true
|
||||
draftSaveTask?.cancel()
|
||||
let trailingDraftSaveTask = draftSaveTask
|
||||
draftSaveTask = nil
|
||||
await NewTaskDraftWriteFence.cancelAndWait(trailingDraftSaveTask)
|
||||
if let draftKey {
|
||||
let trailingSave = immediateDraftSaveTasks.removeValue(forKey: draftKey)
|
||||
await NewTaskDraftWriteFence.cancelAndWait(trailingSave)
|
||||
try? await draftStore.removeDraft(for: draftKey)
|
||||
}
|
||||
onCreated(thread)
|
||||
@@ -594,6 +606,13 @@ public struct NewThreadView: View {
|
||||
return
|
||||
}
|
||||
let key = FeatureComposerDraftStore.newTaskKey(project: project)
|
||||
let pendingImmediateSave = immediateDraftSaveTasks[key]
|
||||
await NewTaskDraftWriteFence.wait(pendingImmediateSave)
|
||||
guard !Task.isCancelled,
|
||||
projectID == requestedProjectID,
|
||||
draftRestoreContext?.projectID == requestedProjectID else {
|
||||
return
|
||||
}
|
||||
let saved = try? await draftStore.draft(for: key)
|
||||
guard !Task.isCancelled,
|
||||
projectID == requestedProjectID,
|
||||
@@ -666,13 +685,17 @@ public struct NewThreadView: View {
|
||||
|
||||
private func scheduleDraftSave() {
|
||||
guard restoredDraftProjectID == projectID,
|
||||
!isSubmitting,
|
||||
!submittedSuccessfully,
|
||||
let key = currentDraftKey else {
|
||||
return
|
||||
}
|
||||
draftSaveTask?.cancel()
|
||||
let pendingDraftSaveTask = draftSaveTask
|
||||
pendingDraftSaveTask?.cancel()
|
||||
draftSaveTask = nil
|
||||
let snapshot = composerDraft
|
||||
draftSaveTask = Task {
|
||||
await NewTaskDraftWriteFence.wait(pendingDraftSaveTask)
|
||||
do {
|
||||
try await Task.sleep(for: .milliseconds(220))
|
||||
try Task.checkCancellation()
|
||||
@@ -690,23 +713,31 @@ public struct NewThreadView: View {
|
||||
let key = currentDraftKey else {
|
||||
return
|
||||
}
|
||||
draftSaveTask?.cancel()
|
||||
let pendingDraftSaveTask = draftSaveTask
|
||||
pendingDraftSaveTask?.cancel()
|
||||
draftSaveTask = nil
|
||||
let snapshot = composerDraft
|
||||
let restoreContext = draftRestoreContext
|
||||
let draftProjectID = projectID
|
||||
let needsRestoreMerge = restoredDraftProjectID != draftProjectID
|
||||
draftSaveTask = nil
|
||||
Task {
|
||||
let previousSave = immediateDraftSaveTasks[key]
|
||||
previousSave?.cancel()
|
||||
let task = Task { @MainActor in
|
||||
await NewTaskDraftWriteFence.wait(pendingDraftSaveTask)
|
||||
await NewTaskDraftWriteFence.wait(previousSave)
|
||||
guard !Task.isCancelled else { return }
|
||||
if needsRestoreMerge,
|
||||
let restoreContext,
|
||||
restoreContext.projectID == draftProjectID {
|
||||
let saved = try? await draftStore.draft(for: key)
|
||||
guard !Task.isCancelled else { return }
|
||||
let merged = restoreContext.merging(saved: saved, current: snapshot)
|
||||
try? await draftStore.setDraft(merged, for: key)
|
||||
} else {
|
||||
try? await draftStore.setDraft(snapshot, for: key)
|
||||
}
|
||||
}
|
||||
immediateDraftSaveTasks[key] = task
|
||||
}
|
||||
|
||||
private static func branchSort(
|
||||
@@ -720,6 +751,17 @@ public struct NewThreadView: View {
|
||||
}
|
||||
}
|
||||
|
||||
enum NewTaskDraftWriteFence {
|
||||
static func wait(_ task: Task<Void, Never>?) async {
|
||||
await task?.value
|
||||
}
|
||||
|
||||
static func cancelAndWait(_ task: Task<Void, Never>?) async {
|
||||
task?.cancel()
|
||||
await task?.value
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures the clean target-project state before its persisted draft is read.
|
||||
/// Async restore results can then merge live typing without ever borrowing state
|
||||
/// from the project that was previously selected.
|
||||
|
||||
@@ -82,6 +82,7 @@ public struct AddProjectView: View {
|
||||
.padding(.horizontal, 18)
|
||||
.padding(.top, 14)
|
||||
.padding(.bottom, 32)
|
||||
.disabled(isSubmitting)
|
||||
}
|
||||
.scrollDismissesKeyboard(.interactively)
|
||||
} else {
|
||||
|
||||
@@ -99,6 +99,7 @@ public struct ProviderModelPicker: View {
|
||||
}
|
||||
|
||||
private func materializeSelection() {
|
||||
guard !normalizedProviders.isEmpty else { return }
|
||||
let resolved = ProviderModelSelectionResolver.materialized(
|
||||
selection,
|
||||
in: normalizedProviders
|
||||
@@ -401,7 +402,15 @@ enum ProviderModelSelectionResolver {
|
||||
_ selection: FeatureSelection?,
|
||||
in providers: [FeatureProvider]
|
||||
) -> FeatureSelection? {
|
||||
if let validated = DailyUXModelOptions.validated(selection, in: providers) {
|
||||
guard !providers.isEmpty else { return selection }
|
||||
if var validated = DailyUXModelOptions.validated(selection, in: providers),
|
||||
let model = providers
|
||||
.first(where: { $0.id == validated.providerID })?
|
||||
.models.first(where: { $0.id == validated.modelID }) {
|
||||
validated.options = ProviderModelConfiguration.materializedOptions(
|
||||
for: model,
|
||||
preserving: validated.options
|
||||
)
|
||||
return validated
|
||||
}
|
||||
let currentProviders = providers.compactMap { provider -> FeatureProvider? in
|
||||
@@ -429,6 +438,22 @@ enum ProviderModelCatalogNormalizer {
|
||||
existing.requiresNewThreadForModelChange =
|
||||
existing.requiresNewThreadForModelChange
|
||||
|| provider.requiresNewThreadForModelChange
|
||||
if existing.name.isEmpty {
|
||||
existing.name = provider.name
|
||||
}
|
||||
if existing.driver.isEmpty {
|
||||
existing.driver = provider.driver
|
||||
}
|
||||
existing.slashCommands = mergingMetadata(
|
||||
existing.slashCommands,
|
||||
provider.slashCommands,
|
||||
id: \.id
|
||||
)
|
||||
existing.skills = mergingMetadata(
|
||||
existing.skills,
|
||||
provider.skills,
|
||||
id: \.id
|
||||
)
|
||||
providersByID[provider.id] = existing
|
||||
} else {
|
||||
var normalized = provider
|
||||
@@ -451,6 +476,18 @@ enum ProviderModelCatalogNormalizer {
|
||||
return order.compactMap { providersByID[$0] }
|
||||
}
|
||||
|
||||
private static func mergingMetadata<Value>(
|
||||
_ first: [Value]?,
|
||||
_ second: [Value]?,
|
||||
id: KeyPath<Value, String>
|
||||
) -> [Value]? {
|
||||
guard first != nil || second != nil else { return nil }
|
||||
var seen = Set<String>()
|
||||
return ((first ?? []) + (second ?? [])).filter {
|
||||
seen.insert($0[keyPath: id]).inserted
|
||||
}
|
||||
}
|
||||
|
||||
private static func isImplicitModel(_ model: FeatureModel) -> Bool {
|
||||
let tokens = [model.id, model.name].flatMap {
|
||||
$0.lowercased()
|
||||
@@ -537,7 +574,10 @@ private struct ModelConfigurationView: View {
|
||||
self.onConfirm = onConfirm
|
||||
if currentSelection?.providerID == option.provider.id,
|
||||
currentSelection?.modelID == option.model.id {
|
||||
_optionSelections = State(initialValue: currentSelection?.options ?? [])
|
||||
_optionSelections = State(initialValue: ProviderModelConfiguration.materializedOptions(
|
||||
for: option.model,
|
||||
preserving: currentSelection?.options ?? []
|
||||
))
|
||||
} else {
|
||||
_optionSelections = State(initialValue: DailyUXModelOptions.defaults(for: option.model))
|
||||
}
|
||||
@@ -648,6 +688,18 @@ private struct ModelConfigurationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
enum ProviderModelConfiguration {
|
||||
static func materializedOptions(
|
||||
for model: FeatureModel,
|
||||
preserving selections: [FeatureModelOptionSelection]
|
||||
) -> [FeatureModelOptionSelection] {
|
||||
let selectedIDs = Set(selections.map(\.id))
|
||||
return selections + DailyUXModelOptions.defaults(for: model).filter {
|
||||
!selectedIDs.contains($0.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ModelOptionLabel: View {
|
||||
let option: DailyUXModelOption
|
||||
let isSelected: Bool
|
||||
|
||||
@@ -194,4 +194,28 @@ struct ComposerDraftStoreTests {
|
||||
#expect(merged.selection == liveSelection)
|
||||
#expect(merged.workspace == fallbackWorkspace)
|
||||
}
|
||||
|
||||
@Test func successfulSubmissionFenceWaitsForCancelledDraftWrites() async {
|
||||
let started = AsyncStream<Void>.makeStream()
|
||||
let release = AsyncStream<Void>.makeStream()
|
||||
let events = AsyncStream<String>.makeStream()
|
||||
let pendingWrite = Task {
|
||||
started.continuation.yield()
|
||||
for await _ in release.stream { break }
|
||||
events.continuation.yield("write finished")
|
||||
}
|
||||
var startedIterator = started.stream.makeAsyncIterator()
|
||||
_ = await startedIterator.next()
|
||||
|
||||
let fencedRemoval = Task {
|
||||
await NewTaskDraftWriteFence.cancelAndWait(pendingWrite)
|
||||
events.continuation.yield("draft removed")
|
||||
}
|
||||
release.continuation.yield()
|
||||
await fencedRemoval.value
|
||||
|
||||
var eventIterator = events.stream.makeAsyncIterator()
|
||||
#expect(await eventIterator.next() == "write finished")
|
||||
#expect(await eventIterator.next() == "draft removed")
|
||||
}
|
||||
}
|
||||
@@ -264,6 +264,89 @@ struct DailyUXModelPickerTests {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func selectionWaitsForTheProviderCatalogBeforeMaterializing() {
|
||||
let saved = FeatureSelection(
|
||||
providerID: "claude",
|
||||
modelID: "claude-opus-5"
|
||||
)
|
||||
|
||||
#expect(ProviderModelSelectionResolver.materialized(saved, in: []) == saved)
|
||||
#expect(ProviderModelSelectionResolver.materialized(nil, in: []) == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func configurationMaterializesDisplayedDefaultsWithoutOverwritingSelections() {
|
||||
let model = FeatureModel(
|
||||
id: "gpt-5.6-sol",
|
||||
name: "Sol",
|
||||
options: [
|
||||
.init(
|
||||
id: "effort",
|
||||
label: "Effort",
|
||||
kind: .select,
|
||||
choices: [
|
||||
.init(id: "high", label: "High", isDefault: true),
|
||||
]
|
||||
),
|
||||
.init(
|
||||
id: "fast",
|
||||
label: "Fast",
|
||||
kind: .boolean,
|
||||
defaultValue: .boolean(true)
|
||||
),
|
||||
]
|
||||
)
|
||||
let existing = [
|
||||
FeatureModelOptionSelection(id: "effort", value: .string("custom")),
|
||||
]
|
||||
|
||||
#expect(
|
||||
ProviderModelConfiguration.materializedOptions(
|
||||
for: model,
|
||||
preserving: existing
|
||||
) == [
|
||||
.init(id: "effort", value: .string("custom")),
|
||||
.init(id: "fast", value: .boolean(true)),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func concreteSelectionIncludesTheOptionDefaultsShownByThePicker() {
|
||||
let providers = [
|
||||
FeatureProvider(
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
models: [
|
||||
.init(
|
||||
id: "gpt-5.6-sol",
|
||||
name: "Sol",
|
||||
options: [
|
||||
.init(
|
||||
id: "effort",
|
||||
label: "Effort",
|
||||
kind: .select,
|
||||
choices: [
|
||||
.init(id: "high", label: "High", isDefault: true),
|
||||
]
|
||||
),
|
||||
]
|
||||
),
|
||||
]
|
||||
),
|
||||
]
|
||||
|
||||
#expect(
|
||||
ProviderModelSelectionResolver.materialized(
|
||||
.init(providerID: "codex", modelID: "gpt-5.6-sol"),
|
||||
in: providers
|
||||
)?.options == [
|
||||
.init(id: "effort", value: .string("high")),
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func duplicateCatalogEntriesCollapseAndImplicitModelsDisappear() {
|
||||
let normalized = ProviderModelCatalogNormalizer.normalized([
|
||||
@@ -291,6 +374,31 @@ struct DailyUXModelPickerTests {
|
||||
#expect(normalized[0].models.map(\.name) == ["Opus", "Sonnet"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func duplicateProvidersMergeComposerCommandsAndSkills() {
|
||||
let normalized = ProviderModelCatalogNormalizer.normalized([
|
||||
FeatureProvider(
|
||||
id: "claude",
|
||||
name: "Claude",
|
||||
models: [.init(id: "opus", name: "Opus")],
|
||||
slashCommands: [.init(name: "review")],
|
||||
skills: [.init(name: "deploy")]
|
||||
),
|
||||
FeatureProvider(
|
||||
id: "claude",
|
||||
name: "Claude",
|
||||
driver: "claudeAgent",
|
||||
models: [.init(id: "sonnet", name: "Sonnet")],
|
||||
slashCommands: [.init(name: "review"), .init(name: "compact")],
|
||||
skills: [.init(name: "deploy"), .init(name: "fix-ci")]
|
||||
),
|
||||
])
|
||||
|
||||
#expect(normalized[0].driver == "claudeAgent")
|
||||
#expect(normalized[0].slashCommands?.map(\.name) == ["review", "compact"])
|
||||
#expect(normalized[0].skills?.map(\.name) == ["deploy", "fix-ci"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func favoritesAndRecentsDoNotRepeatInProviderSections() {
|
||||
let providers = [
|
||||
|
||||
@@ -423,6 +423,58 @@ struct FeatureRootModelTests {
|
||||
#expect(model.homePresentationRevision == 4)
|
||||
}
|
||||
|
||||
@Test
|
||||
func environmentScopedCatalogAndPreferencesInvalidateHomePresentation() async {
|
||||
let client = FeatureClientStub()
|
||||
let model = testRootModel(client: client)
|
||||
client.snapshot = FeatureSnapshot(
|
||||
providersByEnvironment: [
|
||||
"studio": [
|
||||
.init(
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
models: [.init(id: "gpt-5.6-sol", name: "Sol")]
|
||||
),
|
||||
],
|
||||
]
|
||||
)
|
||||
|
||||
await model.reload()
|
||||
let catalogRevision = model.homePresentationRevision
|
||||
#expect(catalogRevision == 1)
|
||||
|
||||
client.snapshot.preferencesByEnvironment = [
|
||||
"studio": .init(defaultWorkspaceMode: .worktree),
|
||||
]
|
||||
await model.reload()
|
||||
|
||||
#expect(model.homePresentationRevision == catalogRevision + 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func responseTimeoutKeepsDurableSubmissionQueued() {
|
||||
let snapshot = FeatureSnapshot(
|
||||
connection: .init(state: .connected),
|
||||
environments: [
|
||||
.init(
|
||||
id: "studio",
|
||||
name: "Studio",
|
||||
endpoint: "https://studio.example",
|
||||
isActive: true,
|
||||
connectionState: .connected
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
#expect(
|
||||
FeatureRootModel.shouldQueue(
|
||||
RPCError.responseTimedOut,
|
||||
environmentID: "studio",
|
||||
snapshot: snapshot
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func detailEventsIgnoreDuplicatesAndAdvancePerThreadRevision() async {
|
||||
let client = FeatureClientStub()
|
||||
|
||||
@@ -61,4 +61,34 @@ struct UserInputAnswerTests {
|
||||
#expect(FeatureInputAnswer.text(" ").normalized == nil)
|
||||
#expect(FeatureInputAnswer.selections([]).normalized == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func testMultiSelectCustomTextStaysInTheSelectionArray() {
|
||||
let question = FeatureInputQuestion(
|
||||
id: "surfaces",
|
||||
header: "Surfaces",
|
||||
question: "Where should this ship?",
|
||||
options: [
|
||||
.init(label: "Server", detail: "Backend"),
|
||||
.init(label: "Web", detail: "Browser"),
|
||||
],
|
||||
allowsMultiple: true
|
||||
)
|
||||
let selected = FeatureInputAnswer.selections(["Server"])
|
||||
let withCustom = FeatureComposerCustomAnswer.replacingText(
|
||||
in: selected,
|
||||
with: "CLI",
|
||||
for: question
|
||||
)
|
||||
|
||||
#expect(withCustom == .selections(["Server", "CLI"]))
|
||||
#expect(FeatureComposerCustomAnswer.text(in: withCustom, for: question) == "CLI")
|
||||
#expect(
|
||||
FeatureComposerCustomAnswer.replacingText(
|
||||
in: withCustom,
|
||||
with: "",
|
||||
for: question
|
||||
) == .selections(["Server"])
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user