Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .memory/tool-approval-scopes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Tool approval scopes — 2026-09-27

- Branch `feature/approval-scopes`, based on `origin/main` at `a9baa4aa3`. Plan: `docs/plans/tool-approval-scopes-plan.md`.
- Shared types and helpers live in `renderer/shared/tool-approval-scope.ts`. The rule book and its persistence are in `main/services/tool-approval-rules.ts` (a DataStore `tool-approval-rules.json`), and the singleton is in `tool-approval-rules-main.ts`.
- `llm-client.ts` computes `toolApprovalRuleTarget(...)` for non-Bot `APPROVAL_TOOL_NAMES` calls in Ask workspaces.
- A remembered match (chat or always) skips the prompt.
- Otherwise it offers `SCOPED_APPROVAL_OFFER` and, after an allow, grants the scope read from `approvals.takeDecisionPayload`.
- The coordinator (`tool-approval.ts`) only stores a scope that is offered, non-once and allowed.
- IPC:
- `chat:approve` options carry `scope`.
- `chat:listApprovalRules`, `chat:revokeApprovalRule` and `chat:revokeAllApprovalRules` back the Settings section `approvals`.
- `remote:respondApprovalFromHost` takes an optional 5th `scope`.
- Remote contract revision 17:
- `PendingApproval.scopes` is present only when `canAllow`.
- The respond body has an optional `scope` that must be allowed and offered, otherwise 400 `invalid_request`. The response echoes it.
- The OpenAPI request schema encodes "scope requires allow" with if/then.
- iOS `AidenApprovalScope` and Android `AidenApprovalScope` decode raw strings tolerantly and set scopes only for allowable action approvals. Android sends `AidenApprovalRequest.of(decision, scope)`.
- Tests:
- `tool-approval-rules.test.ts` (new)
- `tool-approval.test.ts`
- `aiden-remote-streams.test.ts`
- `aiden-remote-router.test.ts`
- `aiden-remote-protocol.test.ts` (Ajv)
- `remote-approval.test.ts`
- `tool-approval-settings.test.tsx` (new, render)
- iOS `AidenChatTests` and `AidenRemoteClientTests`
- Android `AidenChatTest`

## Review follow-up

Remembered file targets preserve leading/trailing whitespace, so distinct filesystem names cannot share approval authority. Regression covers persisted matching; all 7 rule-book tests pass.

- Follow-up review: reject raw parent-path segments before normalization; command rules permit tab/newline/carriage-return whitespace but reject other ASCII controls before trimming. Regression covers leading and embedded control characters and parent segments.

Independent review also identified Windows backslash parent segments; raw parent validation now covers both separator forms and mixed separators, with regression coverage.
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,33 @@ fun AidenChatDetailScreen(
) {
Text(if (isAutomation) "Cancel" else "Deny", fontWeight = FontWeight.SemiBold)
}
val broaderScopes = approval.scopes.filter { it != AidenApprovalScope.ONCE }
if (approval.canAllow && broaderScopes.isNotEmpty()) {
var scopeMenuOpen by remember(approval.id) { mutableStateOf(false) }
Spacer(modifier = Modifier.width(6.dp))
Box {
IconButton(
onClick = { scopeMenuOpen = true },
enabled = connectionState == AidenConnectionState.CONNECTED && !isRespondingToApproval && !isStopping
) {
Icon(Icons.Default.MoreVert, contentDescription = "More allow options")
}
DropdownMenu(
expanded = scopeMenuOpen,
onDismissRequest = { scopeMenuOpen = false }
) {
broaderScopes.forEach { scope ->
DropdownMenuItem(
text = { Text(AidenApprovalPresentation.scopeTitle(scope)) },
onClick = {
scopeMenuOpen = false
viewModel.respondToApproval(AidenApprovalDecision.ALLOW, approval.id, scope)
}
)
}
}
}
}
if (approval.canAllow) {
Spacer(modifier = Modifier.width(10.dp))
Button(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1812,7 +1812,11 @@ class AidenChatViewModel(
cancelTurn()
}

fun respondToApproval(decision: AidenApprovalDecision, approvalId: String) {
fun respondToApproval(
decision: AidenApprovalDecision,
approvalId: String,
scope: AidenApprovalScope = AidenApprovalScope.ONCE
) {
if (isReadOnlyPresentation || coordinator.connectionState.value != AidenConnectionState.CONNECTED ||
_isRespondingToApproval.value || _isStopping.value) return
val approval = _pendingApproval.value ?: return
Expand Down Expand Up @@ -1850,7 +1854,12 @@ class AidenChatViewModel(

viewModelScope.launch {
try {
val response = client.respondToApproval(approval.id, decision)
// Only a scope the Mac offered for this exact approval is sent.
val requestedScope = scope.takeIf {
decision == AidenApprovalDecision.ALLOW && it != AidenApprovalScope.ONCE &&
approval.scopes.contains(it)
}
val response = client.respondToApproval(approval.id, decision, scope = requestedScope)
if (activeClient() !== client || activeStreamId != streamId ||
_streamState.value?.isTerminal == true) return@launch
if (response.approvalId != approval.id || response.decision != decision) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -874,7 +874,10 @@ data class AidenStreamPendingApproval(
val toolCallId: String,
val toolName: String,
@Serializable(with = InstantIso8601Serializer::class) val expiresAt: Instant,
val canAllow: Boolean
val canAllow: Boolean,
/** Contract revision 17. Raw names so an unknown future scope never fails
* decoding; [AidenApprovalScope.offered] keeps the known ones. */
val scopes: List<String>? = null
)

@Serializable
Expand Down Expand Up @@ -1008,10 +1011,47 @@ enum class AidenApprovalDecision {
@SerialName("deny") DENY
}

/** Contract revision 17 allow scopes. ONCE authorizes one call; CHAT and
* ALWAYS let the Mac remember the exact same tool and target for this chat or,
* until revoked in desktop Settings, for the workspace. */
@Serializable
enum class AidenApprovalScope(val wireName: String) {
@SerialName("once") ONCE("once"),
@SerialName("chat") CHAT("chat"),
@SerialName("always") ALWAYS("always");

companion object {
/** Known offered scopes in canonical order; anything not broader than
* a one-time allow collapses to `[ONCE]`. */
fun offered(raw: List<String>?): List<AidenApprovalScope> {
val known = raw.orEmpty().toSet()
val broader = entries.filter { it != ONCE && known.contains(it.wireName) }
return if (broader.isEmpty()) listOf(ONCE) else listOf(ONCE) + broader
}
}
}

/** POST /approvals/{id}/respond body. `scope` is dropped for a one-time allow
* or any deny so pre-revision-17 hosts see the original body shape. */
@Serializable
data class AidenApprovalRequest(
val decision: AidenApprovalDecision,
val scope: AidenApprovalScope? = null
) {
companion object {
fun of(decision: AidenApprovalDecision, scope: AidenApprovalScope?): AidenApprovalRequest =
AidenApprovalRequest(
decision = decision,
scope = scope?.takeIf { decision == AidenApprovalDecision.ALLOW && it != AidenApprovalScope.ONCE }
)
}
}

@Serializable
data class AidenApprovalResponse(
val approvalId: String,
val decision: AidenApprovalDecision,
val scope: AidenApprovalScope? = null,
@Serializable(with = InstantIso8601Serializer::class) val resolvedAt: Instant
)

Expand All @@ -1023,7 +1063,8 @@ data class AidenPendingApproval(
val canRespond: Boolean,
val hasRequiredWriteCapability: Boolean,
val hostCanAllow: Boolean,
val canAllow: Boolean
val canAllow: Boolean,
val scopes: List<AidenApprovalScope> = listOf(AidenApprovalScope.ONCE)
)

data class AidenApprovalCapabilities(
Expand Down Expand Up @@ -1051,6 +1092,12 @@ object AidenApprovalPresentation {
else -> "Approval Required"
}

fun scopeTitle(scope: AidenApprovalScope): String = when (scope) {
AidenApprovalScope.ONCE -> "Allow once"
AidenApprovalScope.CHAT -> "Allow for this chat"
AidenApprovalScope.ALWAYS -> "Always allow"
}

fun requiresDesktopConfirmation(approval: AidenPendingApproval): Boolean =
isAutomation(approval.toolName) && approval.canRespond &&
approval.hasRequiredWriteCapability && !approval.hostCanAllow
Expand All @@ -1069,6 +1116,7 @@ object AidenPendingApprovalResolution {
}
val hasRequiredWriteCapability =
!AidenApprovalPresentation.isAutomation(approval.toolName) || capabilities.canWriteSchedules
val canAllow = approval.canAllow && capabilities.canRespond && hasRequiredWriteCapability
return AidenPendingApproval(
id = approval.approvalId,
summary = approval.summary,
Expand All @@ -1077,7 +1125,12 @@ object AidenPendingApprovalResolution {
canRespond = capabilities.canRespond,
hasRequiredWriteCapability = hasRequiredWriteCapability,
hostCanAllow = approval.canAllow,
canAllow = approval.canAllow && capabilities.canRespond && hasRequiredWriteCapability
canAllow = canAllow,
scopes = if (canAllow && !AidenApprovalPresentation.isAutomation(approval.toolName)) {
AidenApprovalScope.offered(approval.scopes)
} else {
listOf(AidenApprovalScope.ONCE)
}
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -944,12 +944,13 @@ class AidenRemoteClient(
suspend fun respondToApproval(
id: String,
decision: AidenApprovalDecision,
scope: AidenApprovalScope? = null,
idempotencyKey: UUID = UUID.randomUUID()
): AidenApprovalResponse = executeRequest(
"/approvals/$id/respond",
method = "POST",
retryConnectionFailure = false,
bodyJson = json.encodeToString(ApprovalRequest(decision = decision)),
bodyJson = json.encodeToString(AidenApprovalRequest.of(decision, scope)),
idempotencyKey = idempotencyKey
) { bytes ->
json.decodeFromString(String(bytes, Charsets.UTF_8))
Expand All @@ -960,7 +961,7 @@ class AidenRemoteClient(
approvalId: String,
decision: AidenApprovalDecision,
idempotencyKey: UUID = UUID.randomUUID()
): AidenApprovalResponse = respondToApproval(approvalId, decision, idempotencyKey)
): AidenApprovalResponse = respondToApproval(approvalId, decision, idempotencyKey = idempotencyKey)

/** Authoritative pending-question snapshot for one stream. Returns
* `{question: null}` when no prompt is pending. */
Expand Down Expand Up @@ -1926,9 +1927,6 @@ class AidenRemoteClient(
val confirmedForeground: Boolean = true
)

@Serializable
private data class ApprovalRequest(val decision: AidenApprovalDecision)

@Serializable
private data class ScheduledTaskListResponse(val tasks: List<AidenScheduledTask>)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ class AidenBotContractTest {
fun testCheckedInSharedFixtureDecodesEveryBotProjectionDirectly() {
val fixture = loadSharedContractFixture()

assertEquals(16, fixture.contractRevision)
assertEquals(17, fixture.contractRevision)
assertEquals(listOf(true, false), fixture.workspaces.map { it.memoryEnabled })
assertEquals(true, fixture.memorySettings?.enabled)
assertEquals(AidenRemoteProtocol.VERSION, fixture.protocolVersion)
Expand Down
48 changes: 48 additions & 0 deletions android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1526,6 +1526,54 @@ class AidenChatTest {
assertNull(AidenPendingApprovalResolution.resolve(valid.copy(expiresAt = now), "stream-1", "chat-1", now = now))
}

@Test
fun testApprovalScopesAreOfferedOnlyWhenThisDeviceCanAllowAnAction() {
val now = Instant.ofEpochSecond(10_000)
val wire = wireJson.decodeFromString<AidenStreamPendingApproval>(
"""
{"approvalId":"approval-1","streamId":"stream-1","chatId":"chat-1","summary":"npm test",
"toolCallId":"tool-1","toolName":"run_command","expiresAt":"1970-01-01T02:47:40.000Z",
"canAllow":true,"scopes":["always","future-scope","once","chat"]}
""".trimIndent()
)

val allowed = AidenPendingApprovalResolution.resolve(wire, "stream-1", "chat-1", now = now)
// Unknown names are ignored and the order is canonical, once first.
assertEquals(
listOf(AidenApprovalScope.ONCE, AidenApprovalScope.CHAT, AidenApprovalScope.ALWAYS),
allowed?.scopes
)
val reviewOnly = AidenPendingApprovalResolution.resolve(
wire, "stream-1", "chat-1",
capabilities = AidenApprovalCapabilities(canRespond = false, canWriteSchedules = true),
now = now
)
assertEquals(listOf(AidenApprovalScope.ONCE), reviewOnly?.scopes)
assertEquals(
listOf(AidenApprovalScope.ONCE),
AidenPendingApprovalResolution.resolve(wire.copy(scopes = null), "stream-1", "chat-1", now = now)?.scopes
)
}

@Test
fun testApprovalRequestSendsScopeOnlyForBroaderAllows() {
val remembered = wireJson.encodeToString(
AidenApprovalRequest.of(AidenApprovalDecision.ALLOW, AidenApprovalScope.CHAT)
)
assertEquals("chat", Json.parseToJsonElement(remembered).jsonObject["scope"]?.jsonPrimitive?.content)
for (body in listOf(
AidenApprovalRequest.of(AidenApprovalDecision.ALLOW, AidenApprovalScope.ONCE),
AidenApprovalRequest.of(AidenApprovalDecision.DENY, AidenApprovalScope.ALWAYS),
AidenApprovalRequest.of(AidenApprovalDecision.ALLOW, null)
)) {
assertEquals(setOf("decision"), Json.parseToJsonElement(wireJson.encodeToString(body)).jsonObject.keys)
}
val echoed = wireJson.decodeFromString<AidenApprovalResponse>(
"""{"approvalId":"approval-1","decision":"allow","scope":"always","resolvedAt":"2026-08-19T07:00:00.000Z"}"""
)
assertEquals(AidenApprovalScope.ALWAYS, echoed.scope)
}

@Test
fun testAutomationApprovalPresentationPreservesHostOnlyConfirmation() {
val approval = AidenPendingApproval(
Expand Down
5 changes: 3 additions & 2 deletions android/app/src/test/resources/contract.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"contractRevision": 16,
"contractRevision": 17,
"protocolVersion": 1,
"generated": false,
"notice": "Synthetic fixtures only. Values are not credentials and contain no machine-local paths.",
Expand Down Expand Up @@ -159,7 +159,8 @@
"toolCallId": "tool_fixture_01",
"toolName": "write",
"expiresAt": "2026-08-18T19:06:08.000Z",
"canAllow": true
"canAllow": true,
"scopes": ["once", "chat", "always"]
}
},
"streamInput": {
Expand Down
10 changes: 9 additions & 1 deletion docs/aiden-remote-api-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,15 @@ Selection nonces are a separate type. Workspace creation atomically revalidates
authenticated device's `schedule:write` grant. A device that can respond to
approvals but lacks that mutation grant still receives the bounded approval
with `canAllow: false` and may deny it; an attempted allow fails closed.
- `GET /streams/{streamId}/approval`: current bounded approval snapshot, or `null` after resolution.
Contract revision 17 adds an optional `scope` (`once` | `chat` | `always`)
that is valid only with `allow` and only when the pending approval listed it
in `scopes`; anything else is `invalid_request`, and the response echoes the
chosen scope. `chat` and `always` remember only the same tool with the exact
trimmed command or exact normalized workspace-relative path, in the same
workspace; `chat` lasts for that chat until the Mac app quits and `always`
persists on the Mac until revoked in Settings → Tool approvals. Omitting
`scope` means `once`, so revision 16 clients are unchanged.
- `GET /streams/{streamId}/approval`: current bounded approval snapshot, or `null` after resolution. Since revision 17 an allowable snapshot may carry `scopes` (starting with `once`, at least two entries); it is omitted when only a one-time allow is possible or `canAllow` is false. Scopes are offered only for plain parent workspace `write_file`, `edit_file`, and `run_command` calls in an Ask workspace, never for Bot turns, privileged or structured approvals, or schedule/automation tools.
- `GET /streams/{streamId}/question`: current bounded question-prompt snapshot, or `null` after resolution. Requires `chat:read` and is advertised only when `/server.features` contains `chat-question-prompts-v1`; any authenticated device may read its own stream's snapshot, while a response still requires the `questions:respond` grant. The snapshot carries `promptId`, `streamId`, `chatId`, `toolCallId`, the bounded `questions` array (1–4 questions, each with `question`, `header`, `multiSelect`, and 2–4 `options` of `label`/`description`), and `expiresAt`. `expiresAt` is the agent's own answer deadline, never more than five minutes after the prompt reached the stream; when it passes, the host tells the agent to proceed with its best judgement and the prompt resolves as expired. Clients should present an answer given after that point as an ordinary follow-up message. Question text is assistant-authored and already bounded by the host grammar; no host-only data is projected.
- `POST /questions/{promptId}/respond`: resolve one pending prompt owned by the authenticated device. Requires `questions:respond` and an `Idempotency-Key`. The exact body is `{ "cancelled": boolean, "answers": [...] }` where `cancelled: true` dismisses the entire prompt and each answer addresses one question index as `{ "questionIndex": n, "kind": "option" | "custom" | "multi", ... }`—`option` carries one selected `answer` label, `custom` carries free `answer` text (bounded to the shared custom-answer limit), and `multi` carries a unique `selected` label array for `multiSelect` questions. The host semantically validates answers against the stored prompt before settlement: wrong indices, unselectable options, single answers on multi-select questions, or malformed kinds return `invalid_request`. Success returns `{ "promptId", "resolvedAt" }`. A second response for a settled prompt returns `question_already_resolved`; an expired, cancelled, or terminated prompt returns `question_expired`. The idempotency ledger replays the original outcome for a repeated request UUID and rejects conflicting payload reuse. The stream leaves its waiting state and resumes generation once the host consumes the answer.

Expand Down
Loading
Loading