Skip to content

Commit 9e302fb

Browse files
authored
fix: secret requests preserve native answers and live requester authority (#132122)
* docs: allow isolated browsers for development proof * fix(android): refresh approval when the operator connects last * fix(secrets): preserve protected requests across clients and run lifecycles * fix(secrets): preserve native prompts and durable channel delivery * perf(cli): keep meeting metadata off runtime imports Preserve command metadata and execution behavior while removing the broad meeting runtime from cold CLI discovery. Keep engine-private codec helpers internal and remove the unused, unshipped node-caller wrapper; no SDK budget or stable API changes. * refactor(agents): remove unused reply registry type re-exports * test(secrets): use typed gateway and deferred fixtures * fix(secrets): return authoritative current policy after protected entry * fix(auth): preserve resolved references in model discovery Prepare canonical per-invocation credentials while preserving synchronous catalog callbacks and marker-only generated config. Isolate unavailable selected profiles before HTTP instead of making anonymous requests. * fix(agents): explain protected command credential injection Share compact inherited-sentinel guidance across prompts and tool descriptions: no secret templates, overrides or printing. Preserve host and run-snapshot limits, and clarify primary-session availability in docs. Verified six intended prompt regressions before the wording change. * fix(ollama): separate discovery credentials from catalog configuration * test(agents): mock the active-run projection owner in abort coverage * fix(auth): preserve opaque config references through discovery Carry source SecretRef provenance to model discovery and keep resolved credentials separate from configuration markers, including marker-shaped values. Preserve selected-owner unavailability and existing credential precedence. * fix(agents): explain literal exec environment overrides Clarify that environment override values are literal and omission inherits the prepared environment. This prevents the protected-credential workflow from implying shell expansion; execution semantics stay unchanged. * fix(agents): keep healthy turns available with unrelated cold secrets Reuse the matching config-prepared Gateway owner state instead of repeating broad strict secret resolution. Preserve selected-provider, foreign-config, standalone, and channel/account enforcement, including authored-reference provenance before config projection. Reproduced both entry failures and the source-projection gap before repair; focused regressions, types, lint, import cycles, and independent review pass. Refs #131306. * fix(secrets): publish recovered credentials to model owners Refresh canonical model publication at secret activation and fence superseded publication and rollback. Carry authored SecretRef provenance into catalog workers so resolved key and header bytes remain opaque and writable catalog metadata remains safe. Clarify current entry policy after human edits. Retire real-worker test fixtures at their lifecycle boundary and replace timing-based overlap checks with the existing barrier. Focused regressions, type/lint guards, and isolated P1 review pass. The full local worker suite recorded 14 passes and four 120-second timeouts; unchanged clean-Linux and final live proof remain required before merge. * fix(secrets): show effective hosts before credential replacement Normalize the host list at question creation so web and native cards show what they will save. Preserve explicit empty proposals and human clears; concurrent store writes cannot introduce undisplayed destinations. Keep generic store-update semantics unchanged and cover replacement, new-entry, and concurrent-write cases through the real question handlers. * fix(memory): keep provider readiness out of startup migrations Remove the read-only provider diagnostic that blocked Gateway startup before auth-profile SecretRefs could activate. Keep genuine state migrations, Doctor health guidance, and the runtime guard against replacing an existing semantic index with FTS-only data. Retire the unused migration wrapper and preserve the managed-local readiness collector at its health owner. Cover stored and missing refs through migration and activation while retaining semantic index rows. * fix(auth): preserve resolved secret provenance in model availability Classify provider credentials from the matching authored SecretRef instead of reinterpreting resolved bytes as environment markers, placeholders, or profile names. Share that boundary with runtime auth planning and inline cooldown ownership while retaining profile locks, order, and snapshot matching. The live masked-entry flow recovered authenticated discovery but left the model unavailable. Add failing-before/passing-after Gateway and shared chat-catalog regressions, plus source-ownership and cooldown controls. Focused siblings pass 402 tests; the final changed-file gate and independent review are clean. Refs #131306, #132122. * fix(agents): compact exec parameter descriptions Keep literal environment overrides, inheritance, and every runtime constraint while reducing combined field descriptions from 603 to 523 characters. Preserve the existing 550-character budget and assertions; no schema or runtime change. The exact failing CI assertion reproduces locally. Both schema suites, lint, formatting, prompt snapshots, and independent review pass after the wording fix. Refs #132122 (secret-request repair). * test(secrets): align plugin fixture and tighten SDK counts Load the real Ollama plugin through the SDK-owned, manifest-validating source loader instead of the legacy core test-utils resolver and an import assertion. Keep every credential-ownership and writable-plan assertion unchanged. Regenerate the two lower SDK defaults from collectPluginSdkSurfaceReport: 4357 -> 4355 public exports and 2593 -> 2592 callable exports. Preserve all budget checks, wildcard limits, and source-count equality assertions. The exact import-boundary assertion, 28 plugin/planner cases, 10 SDK-report cases, affected types/lint/format and fresh independent review pass. Refs #132122 (secret-request repair). * fix(codex): preserve startup exits through bounded cleanup Keep natural startup exits and their bounded diagnostics distinct from registration refusals and cleanup-induced exits. Reuse transport-owned containment and exit budgets so a refused npm launcher cannot leave its native child or inherited pipes alive. Preserve synchronous registration before initialize, cancellation authority, retry counts, fingerprint checks, and the existing shutdown deadlines. Add real-process regressions for both exit orderings, shared and isolated startup, live refusals, launcher descendants, and bounded pipe draining. Found while validating the secret-request repair in #132122. The original 12-file CI envelope passes all 278 tests with Node 24 and two workers.
1 parent 043fa17 commit 9e302fb

177 files changed

Lines changed: 9163 additions & 2468 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ Review invariants; full doctrine: `docs/gateway/audit.md`.
189189
- Proof routing: source trust first, required environment second. Trusted development tests, changed gates, typecheck/lint, builds, and full suites run locally with scope proportional to the touched contract. Use Crabbox/Testbox only when the environment is part of the proof: clean-machine, install/package, Docker, E2E, live, desktop, cross-OS, CI parity, or explicit operator-requested remote work. Do not use it merely as generic compute offload. Lease/procedure mechanics: `$crabbox`.
190190
- Untrusted (contributor/fork) source: never run its scripts, tests, checks, wrappers, config, or package hooks locally, regardless of proof size, and never fall back to local. Use secretless fork CI or the sanitized direct AWS Crabbox procedure in `$crabbox`, never a credential-hydrated Testbox. Maintainer approval of credentialed execution after review makes it trusted; an explicit owner/maintainer instruction to land named, reviewed PRs is that approval — do not ask twice.
191191
- Visual proof: use a real isolated browser/desktop on the current host when capable; otherwise use Crabbox. Set up like a user, then screenshot-verify. No harness/bypass/shortcut unless explicitly asked.
192+
- Isolated browsers are pre-approved for development, testing, and sanitized screenshots/recordings; never ask again. Use the signed-in profile only when the flow needs its existing login.
192193
- Captured screenshots/videos are proof only after the agent has looked at them: open every capture, confirm the asserted state is actually visible in frame, and re-shoot when it is not. An uninspected capture is not verification and must not be attached as evidence.
193194
- UI-visible change (Control UI, native app, or user-visible chat/session behavior): before/after screenshots or a short video are mandatory PR evidence, captured from a real running surface and sanitized. Exception: channel-visible chat behavior may satisfy the real-behavior-proof gate via the mock-gateway harness verdict (ClawSweeper section) when it covers the changed path; live proof is stronger. UI proof infeasible: state the exact blocker in the PR.
194195
- Gateway-behavior change provable in the Control UI (session lifecycle, steering/queue, subagent flows, delivery states): prove on a live dev gateway — isolated `OPENCLAW_STATE_DIR`, own port, never the operator's gateway — and attach a video of the flow. Default recorder: Playwright `recordVideo` against the dashboard URL; keep the driving script's waits on asserted UI states, not sleeps.

‎apps/.i18n/native-source.json‎

Lines changed: 20 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1434,6 +1434,8 @@ class NodeRuntime private constructor(
14341434
operatorConnected = true
14351435
operatorStatusText = "Connected"
14361436
}
1437+
// Bootstrap can connect the node before operator access is ready.
1438+
refreshNodesDevices()
14371439
// Method and scope snapshots are synchronous above; refresh only after both so
14381440
// this route cannot inherit readiness from the connection it replaced.
14391441
systemAgentChatController.refresh(startIfNeeded = false)
@@ -1810,11 +1812,10 @@ class NodeRuntime private constructor(
18101812
}
18111813
notificationOutbox.onConnected()
18121814
publishNodePresenceAliveBeacon(NodePresenceAliveBeacon.Trigger.Connect)
1815+
refreshNodesDevices()
18131816
val endpoint = connectedEndpoint
18141817
val auth = activeGatewayAuth
1815-
if (operatorConnected) {
1816-
scope.launch { refreshNodesDevicesFromGateway() }
1817-
} else if (endpoint != null && auth != null) {
1818+
if (!operatorConnected && endpoint != null && auth != null) {
18181819
maybeStartOperatorSessionAfterNodeConnect(endpoint, auth)
18191820
}
18201821
},
@@ -1830,9 +1831,7 @@ class NodeRuntime private constructor(
18301831
updateStatus {
18311832
nodeConnectionProblem = gatewayConnectionProblem(error, pauseReconnect)
18321833
}
1833-
if (operatorConnected && nodeConnectFailureNeedsApprovalRefresh(error)) {
1834-
scope.launch { refreshNodesDevicesFromGateway() }
1835-
}
1834+
if (nodeConnectFailureNeedsApprovalRefresh(error)) refreshNodesDevices()
18361835
},
18371836
onEvent = ::handleNodeGatewayEvent,
18381837
onInvoke = { req ->

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatController.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3529,10 +3529,12 @@ class ChatController internal constructor(
35293529
) {
35303530
val gatewayId = currentCacheScope()?.gatewayId
35313531
var claimedOwner: Any? = null
3532+
var allowedHosts: List<String>? = null
35323533
updateQuestions { prompts ->
35333534
prompts.map { prompt ->
35343535
if (prompt.promptOwner === expected.promptOwner && prompt.status() == ChatQuestionStatus.Pending) {
35353536
claimedOwner = prompt.promptOwner
3537+
allowedHosts = prompt.draft.secretStoreAllowedHosts(prompt.record.questions)
35363538
prompt.copy(submitting = true, skipping = cancel, errorText = null)
35373539
} else {
35383540
prompt
@@ -3551,6 +3553,7 @@ class ChatController internal constructor(
35513553
if (cancel) {
35523554
put("cancel", JsonPrimitive(true))
35533555
} else {
3556+
allowedHosts?.let { put("secretStoreAllowedHosts", JsonArray(it.map(::JsonPrimitive))) }
35543557
put(
35553558
"answers",
35563559
buildJsonObject {

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatQuestion.kt‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,13 @@ data class ChatQuestionPrompt(
4646
data class ChatQuestionDraft(
4747
val selectedOptions: Map<String, Set<String>> = emptyMap(),
4848
val otherText: Map<String, String> = emptyMap(),
49+
val secretStoreAllowedHostsText: String? = null,
4950
) {
51+
fun secretStoreAllowedHosts(questions: List<Question>): List<String>? {
52+
val store = questions.firstOrNull()?.secretStore?.takeIf { it.kind == "secret" } ?: return null
53+
return secretStoreAllowedHostsText?.split(Regex("[,\\s]+"))?.filter { it.isNotEmpty() } ?: store.allowedHosts.orEmpty()
54+
}
55+
5056
fun toggle(
5157
question: Question,
5258
label: String,
@@ -72,7 +78,7 @@ data class ChatQuestionDraft(
7278
value: String,
7379
): ChatQuestionDraft {
7480
if (question.options.isNotEmpty() && question.isOther != true) return this
75-
val clearOptions = question.multiSelect != true && value.isNotBlank()
81+
val clearOptions = question.multiSelect != true && (if (question.isSecret == true) value.isNotEmpty() else value.isNotBlank())
7682
return copy(
7783
selectedOptions = if (clearOptions) selectedOptions + (question.questionId to emptySet()) else selectedOptions,
7884
otherText = otherText + (question.questionId to value),
@@ -84,7 +90,8 @@ data class ChatQuestionDraft(
8490
for (question in questions) {
8591
val selected = selectedOptions[question.questionId].orEmpty()
8692
val values = question.options.mapNotNull { option -> option.label.takeIf { it in selected } }.toMutableList()
87-
otherText[question.questionId]?.trim()?.takeIf { it.isNotEmpty() }?.let(values::add)
93+
val text = otherText[question.questionId]?.let { if (question.isSecret == true) it else it.trim() }
94+
text?.takeIf { it.isNotEmpty() }?.let(values::add)
8895
if (values.isEmpty()) return null
8996
result[question.questionId] = values
9097
}

‎apps/android/app/src/main/java/ai/openclaw/app/ui/chat/ChatQuestionCard.kt‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
3737
import androidx.compose.ui.text.input.VisualTransformation
3838
import androidx.compose.ui.unit.dp
3939
import kotlinx.coroutines.delay
40+
import java.text.DateFormat
41+
import java.util.Date
4042

4143
@Composable
4244
internal fun ChatQuestionCard(
@@ -72,6 +74,14 @@ internal fun ChatQuestionCard(
7274
verticalArrangement = Arrangement.spacedBy(14.dp),
7375
) {
7476
prompt.record.questions.forEach { question ->
77+
if (question.secretStore != null) {
78+
SecretStoreConsent(
79+
prompt = prompt,
80+
question = question,
81+
enabled = pending,
82+
onDraftChanged = { update -> onDraftChanged(prompt, update) },
83+
)
84+
}
7585
QuestionSection(
7686
question = question,
7787
draft = draft,
@@ -91,6 +101,61 @@ internal fun ChatQuestionCard(
91101
}
92102
}
93103

104+
@Composable
105+
private fun SecretStoreConsent(
106+
prompt: ChatQuestionPrompt,
107+
question: Question,
108+
enabled: Boolean,
109+
onDraftChanged: ((ChatQuestionDraft) -> ChatQuestionDraft) -> Unit,
110+
) {
111+
val store = question.secretStore ?: return
112+
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
113+
Text(
114+
text = nativeString("Requested by \$agent • \$session", prompt.record.agentId ?: nativeString("Unknown"), prompt.record.sessionKey ?: nativeString("Unknown")),
115+
style = ClawTheme.type.caption,
116+
color = ClawTheme.colors.textMuted,
117+
)
118+
Text(
119+
text = nativeString("Stores \$name as \$kind", store.name, if (store.kind == "secret") nativeString("Protected secret") else nativeString("Agent-readable environment")),
120+
style = ClawTheme.type.body,
121+
color = ClawTheme.colors.text,
122+
)
123+
store.reason?.takeIf { it.isNotEmpty() }?.let {
124+
Text(text = it, style = ClawTheme.type.body, color = ClawTheme.colors.text)
125+
}
126+
question.secretStoreExisting?.let { existing ->
127+
val updated = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(existing.updatedAtMs))
128+
Text(
129+
text = nativeString("Replaces \$name — last updated \$updated", store.name, updated),
130+
style = ClawTheme.type.caption,
131+
fontWeight = FontWeight.SemiBold,
132+
color = ClawTheme.colors.danger,
133+
)
134+
existing.updatedBy?.let {
135+
Text(text = nativeString("Updated by \$name", it), style = ClawTheme.type.caption, color = ClawTheme.colors.textMuted)
136+
}
137+
}
138+
if (store.kind == "secret") {
139+
OutlinedTextField(
140+
value = prompt.draft.secretStoreAllowedHostsText ?: store.allowedHosts.orEmpty().joinToString(", "),
141+
onValueChange = { value -> onDraftChanged { it.copy(secretStoreAllowedHostsText = value) } },
142+
modifier = Modifier.fillMaxWidth(),
143+
enabled = enabled,
144+
label = { Text(nativeString("Allowed HTTPS hosts"), style = ClawTheme.type.body) },
145+
placeholder = { Text(nativeString("api.example.com, uploads.example.com"), style = ClawTheme.type.body) },
146+
textStyle = ClawTheme.type.body,
147+
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
148+
maxLines = 4,
149+
)
150+
Text(
151+
text = nativeString("Exact hostnames only, separated by commas or spaces. Leave empty for config SecretRefs without proxy use."),
152+
style = ClawTheme.type.caption,
153+
color = ClawTheme.colors.textMuted,
154+
)
155+
}
156+
}
157+
}
158+
94159
@Composable
95160
private fun ChatQuestionSummary(
96161
prompt: ChatQuestionPrompt,

‎apps/android/app/src/test/java/ai/openclaw/app/GatewayBootstrapAuthTest.kt‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import ai.openclaw.app.gateway.DeviceIdentityStore
88
import ai.openclaw.app.gateway.GatewayConnectOptions
99
import ai.openclaw.app.gateway.GatewayEndpoint
1010
import ai.openclaw.app.gateway.GatewayErrorDetails
11+
import ai.openclaw.app.gateway.GatewayHelloSummary
1112
import ai.openclaw.app.gateway.GatewayRegistryEntry
1213
import ai.openclaw.app.gateway.GatewayRegistryEntryKind
1314
import ai.openclaw.app.gateway.GatewaySession
@@ -19,6 +20,7 @@ import ai.openclaw.app.node.InvokeDispatcher
1920
import ai.openclaw.app.protocol.OpenClawCameraCommand
2021
import ai.openclaw.app.protocol.OpenClawLocationCommand
2122
import ai.openclaw.app.protocol.OpenClawTalkCommand
23+
import ai.openclaw.app.ui.canFinishOnboarding
2224
import ai.openclaw.app.voice.MicCaptureManager
2325
import ai.openclaw.app.voice.TalkModeManager
2426
import android.Manifest
@@ -34,13 +36,15 @@ import kotlinx.coroutines.cancelAndJoin
3436
import kotlinx.coroutines.currentCoroutineContext
3537
import kotlinx.coroutines.delay
3638
import kotlinx.coroutines.flow.MutableStateFlow
39+
import kotlinx.coroutines.flow.first
3740
import kotlinx.coroutines.job
3841
import kotlinx.coroutines.joinAll
3942
import kotlinx.coroutines.runBlocking
4043
import kotlinx.coroutines.sync.Mutex
4144
import kotlinx.coroutines.test.resetMain
4245
import kotlinx.coroutines.test.setMain
4346
import kotlinx.coroutines.withTimeout
47+
import kotlinx.coroutines.withTimeoutOrNull
4448
import kotlinx.coroutines.yield
4549
import kotlinx.serialization.json.Json
4650
import kotlinx.serialization.json.JsonObject
@@ -168,6 +172,93 @@ class GatewayBootstrapAuthTest {
168172
)
169173
}
170174

175+
@Test
176+
fun nodeFirstBootstrapBecomesReadyWhenOperatorConnects() {
177+
assertReadyAfterBothSessionsConnect(nodeFirst = true)
178+
}
179+
180+
@Test
181+
fun operatorFirstConnectionRefreshesApprovalWhenNodeConnects() {
182+
assertReadyAfterBothSessionsConnect(nodeFirst = false)
183+
}
184+
185+
private fun assertReadyAfterBothSessionsConnect(nodeFirst: Boolean) =
186+
runBlocking {
187+
val (app, prefs, runtime) = gatewayFixture()
188+
val runtimeJob = requireNotNull(readField<CoroutineScope>(runtime, "scope").coroutineContext[Job])
189+
try {
190+
// Stop startup collectors before callbacks register a gateway, but keep the scope live
191+
// so the real ready callbacks can launch their refreshes without opening sockets.
192+
withTimeout(10_000) {
193+
val startupJobs = runtimeJob.children.toList()
194+
startupJobs.forEach { it.cancel() }
195+
startupJobs.forEach { it.join() }
196+
}
197+
writeField(runtime, "connectedEndpoint", GatewayEndpoint.manual("127.0.0.1", 18789))
198+
val deviceId = DeviceIdentityStore.withPrefs(app, prefs).loadOrCreate().deviceId
199+
val initialNodeListRead = CompletableDeferred<Job>()
200+
runtime.gatewayDataRequestOverrideForTests = { _, method, _ ->
201+
when (method) {
202+
"node.list" ->
203+
if (runtime.nodeConnected.value) {
204+
"""{"nodes":[{"nodeId":"$deviceId","paired":true,"connected":true,"approvalState":"approved"}]}"""
205+
} else {
206+
initialNodeListRead.complete(requireNotNull(currentCoroutineContext()[Job]))
207+
"""{"nodes":[]}"""
208+
}
209+
else -> "{}"
210+
}
211+
}
212+
val hello =
213+
GatewayHelloSummary(
214+
serverName = "Test gateway",
215+
remoteAddress = "127.0.0.1:18789",
216+
serverVersion = null,
217+
mainSessionKey = null,
218+
updateAvailable = null,
219+
authScopes = listOf("operator.read"),
220+
methods = setOf("node.list"),
221+
)
222+
223+
fun connectSession(fieldName: String) {
224+
val session = readField<GatewaySession>(runtime, fieldName)
225+
readField<(GatewayHelloSummary) -> Unit>(session, "onConnected")(hello)
226+
}
227+
228+
fun ready(): Boolean =
229+
canFinishOnboarding(
230+
isConnected = runtime.gatewayConnectionDisplay.value.isConnected,
231+
isNodeConnected = runtime.nodeConnected.value,
232+
nodeCapabilityApproval = runtime.nodeCapabilityApproval.value,
233+
)
234+
235+
connectSession(if (nodeFirst) "nodeSession" else "operatorSession")
236+
withTimeout(10_000) {
237+
if (nodeFirst) {
238+
// Finish the offline node refresh before operator success can make it usable.
239+
runtimeJob.children.toList().forEach { it.join() }
240+
} else {
241+
// Settle the empty read before node success can hide a missing node-ready refresh.
242+
initialNodeListRead.await().join()
243+
}
244+
}
245+
assertEquals(GatewayNodeCapabilityApproval.Loading, runtime.nodeCapabilityApproval.value)
246+
assertFalse(ready())
247+
assertFalse(runtime.nodesDevicesRefreshing.value)
248+
249+
connectSession(if (nodeFirst) "operatorSession" else "nodeSession")
250+
withTimeoutOrNull(10_000) {
251+
runtime.nodeCapabilityApproval.first { it == GatewayNodeCapabilityApproval.Approved }
252+
}
253+
254+
assertEquals(GatewayNodeCapabilityApproval.Approved, runtime.nodeCapabilityApproval.value)
255+
assertTrue(ready())
256+
} finally {
257+
runtime.disconnect()
258+
runtimeJob.cancelAndJoin()
259+
}
260+
}
261+
171262
@Test
172263
fun standaloneStatusPreservesLiveOperatorConnection() {
173264
val runtime = createTestRuntime(RuntimeEnvironment.getApplication())

‎apps/android/app/src/test/java/ai/openclaw/app/chat/ChatQuestionTest.kt‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import kotlinx.coroutines.test.advanceUntilIdle
1919
import kotlinx.coroutines.test.runCurrent
2020
import kotlinx.coroutines.test.runTest
2121
import kotlinx.serialization.encodeToString
22+
import kotlinx.serialization.json.jsonArray
2223
import kotlinx.serialization.json.jsonObject
2324
import kotlinx.serialization.json.jsonPrimitive
2425
import org.junit.Assert.assertEquals
@@ -53,6 +54,66 @@ class ChatQuestionTest {
5354
assertEquals(mapOf("meal" to listOf("Pizza", "Tacos", "Salad")), draft.answers(listOf(question)))
5455
}
5556

57+
@Test
58+
fun secretDraftPreservesBytesWhileNormalAnswersTrim() {
59+
for (isSecret in listOf(false, true)) {
60+
val textQuestion = question.copy(options = emptyList(), isSecret = isSecret)
61+
for (value in listOf(" synthetic-value \t\n", " ", "")) {
62+
val normalized = if (isSecret) value else value.trim()
63+
val expected = if (normalized.isEmpty()) null else mapOf("meal" to listOf(normalized))
64+
assertEquals(expected, ChatQuestionDraft().setOther(textQuestion, value).answers(listOf(textQuestion)))
65+
}
66+
}
67+
}
68+
69+
@Test
70+
fun credentialSubmissionSendsEditedHostsAndRetainsOnlyStoredMarker() =
71+
runTest {
72+
val secret = question.copy(options = emptyList(), isSecret = true, secretStore = QuestionSecretStore("TASK_TOKEN", "secret", listOf("api.example.test")))
73+
val pending = record().copy(questions = listOf(secret))
74+
for (hosts in listOf(null, "uploads.example.test,\n api.example.test", "")) {
75+
var request: String? = null
76+
val controller =
77+
createScriptedChatController {
78+
respond("question.list", json.encodeToString(QuestionListResult(listOf(pending))))
79+
respond("question.resolve") { params ->
80+
request = params
81+
"""{"status":"answered","answers":{"answers":{"meal":["stored"]}}}"""
82+
}
83+
}
84+
controller.handleGatewayEvent("question.requested", json.encodeToString(pending))
85+
runCurrent()
86+
controller.updateQuestionDraft(controller.onlyQuestion) {
87+
it.setOther(secret, " synthetic-value ").copy(secretStoreAllowedHostsText = hosts)
88+
}
89+
controller.resolveQuestion(controller.onlyQuestion, checkNotNull(controller.onlyQuestion.draft.answers(pending.questions)))
90+
runCurrent()
91+
val params = json.parseToJsonElement(checkNotNull(request)).jsonObject
92+
val expectedHosts =
93+
when (hosts) {
94+
null -> listOf("api.example.test")
95+
"" -> emptyList()
96+
else -> listOf("uploads.example.test", "api.example.test")
97+
}
98+
assertEquals(expectedHosts, params.getValue("secretStoreAllowedHosts").jsonArray.map { it.jsonPrimitive.content })
99+
assertEquals(
100+
" synthetic-value ",
101+
params
102+
.getValue("answers")
103+
.jsonObject
104+
.getValue("answers")
105+
.jsonObject
106+
.getValue("meal")
107+
.jsonArray
108+
.single()
109+
.jsonPrimitive.content,
110+
)
111+
assertEquals(QuestionAnswers(mapOf("meal" to listOf("stored"))), controller.onlyQuestion.record.answers)
112+
assertEquals(ChatQuestionDraft(), controller.onlyQuestion.draft)
113+
assertEquals("Answered", terminalQuestionAnswer(controller.onlyQuestion, secret, ChatQuestionStatus.Answered))
114+
}
115+
}
116+
56117
@Test
57118
fun statusDistinguishesLocalRemoteAndExpiry() {
58119
val record = record(status = "pending", expiresAtMs = 2_000)

0 commit comments

Comments
 (0)