Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(apps): keep names as written when they go into a sentence

leepokai9de8ee04558b
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
index 77f8f433..c8b547d6 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -436,7 +436,7 @@ internal val Entry.botReactions: Map<String, List<String>> get() =
members.joinToString(" · ") { it.name }.takeIf { bot.name != members.joinToString(", ") { it.name } },
bot.description.ifEmpty { null }) else listOfNotNull(
if (bot.managedWorkspace) "${backendName(state, bot.backend)} · ${tr("Personal workspace")}"
- else tr("{agent} in {path}").replace("{agent}", backendName(state, bot.backend)).replace("{path}", bot.cwd),
+ else fill(tr("{agent} in {path}"), "agent" to backendName(state, bot.backend), "path" to bot.cwd),
bot.description.ifEmpty { null })
for (line in lines) Text(line, style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
Text(if (bot.kind == "group") "Everyone answers in turn. @mention a bot to ask just that one."
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt
index e4115071..82db745c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt
@@ -21,6 +21,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.codync.android.core.InstalledConnector
import com.codync.android.core.MarketConnector
+import com.codync.android.core.fill
import com.codync.android.design.*
import java.io.IOException
import kotlinx.coroutines.CancellationException
@@ -86,7 +87,7 @@ import kotlinx.coroutines.launch
val onComputer = tr("On {name} ({kind})")
ChoiceList(optionId, item.options.map {
Triple(it.id, if (it.kind == "remote") hosted.replace("{name}", item.title)
- else onComputer.replace("{name}", state.hostName).replace("{kind}", it.kind), null)
+ else fill(onComputer, "name" to state.hostName, "kind" to it.kind), null)
},
{ optionId = it; values = emptyMap() })
}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Fill.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Fill.kt
new file mode 100644
index 00000000..d8d1bdc8
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Fill.kt
@@ -0,0 +1,9 @@
+package com.codync.android.core
+
+private val PLACEHOLDER = Regex("""\{(\w+)\}""")
+
+/** Fills a template's `{key}`s in one pass: a device named "{code}" stays as written. */
+fun fill(template: String, vararg values: Pair<String, String>): String {
+ val named = values.toMap()
+ return PLACEHOLDER.replace(template) { named[it.groupValues[1]] ?: it.value }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
index c0b2cb61..8452ee3a 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
@@ -48,15 +48,14 @@ data class NetworkInfo(
// `lead@*` (only from the command line) reads "lead on any computer": never wider than it is.
rule.fromComputer == ANY -> tr("{bot} on any computer").replace("{bot}", rule.fromAgent)
rule.fromAgent == ANY -> tr("any bot on {computer}").replace("{computer}", rule.fromComputer)
- else -> tr("{bot} on {computer}").replace("{bot}", agentName(rule.fromComputer, rule.fromAgent))
- .replace("{computer}", rule.fromComputer)
+ else -> fill(tr("{bot} on {computer}"), "bot" to agentName(rule.fromComputer, rule.fromAgent), "computer" to rule.fromComputer)
}
val to = if (rule.toAgent == ANY) tr("any bot here") else computers.firstOrNull { it.me }?.let { me ->
me.agents.firstOrNull { it.id == rule.toAgent }?.name
} ?: rule.toAgent
// An access this app doesn't know reads as deny, never wider than it is.
val access = if (rule.access == "allow") "Allow: {from} → {to}" else "Deny: {from} → {to}"
- return tr(access).replace("{from}", from).replace("{to}", to)
+ return fill(tr(access), "from" to from, "to" to to)
}
private fun agentName(computer: String, agent: String): String =
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/FillTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/FillTest.kt
new file mode 100644
index 00000000..ac811c53
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/FillTest.kt
@@ -0,0 +1,11 @@
+package com.codync.android.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class FillTest {
+ @Test fun `what it puts in stays as written`() {
+ assertEquals("Build {other} \$1 and Reviewer", fill("{name} and {other}", "name" to "Build {other} \$1", "other" to "Reviewer"))
+ assertEquals("Build and {missing}", fill("{name} and {missing}", "name" to "Build"))
+ }
+}
diff --git a/apps/desktop/src/renderer/lib/account-copy.ts b/apps/desktop/src/renderer/lib/account-copy.ts
index 9ceb6255..c1419a51 100644
--- a/apps/desktop/src/renderer/lib/account-copy.ts
+++ b/apps/desktop/src/renderer/lib/account-copy.ts
@@ -1,13 +1,11 @@
/** What the interface says when a computer joins or leaves an account (docs/plans/require-sign-in.md, phase 2). */
+import { fill } from './fill.ts'
type Tr = (text: string) => string
/** "123 456" for a 6-digit code. */
export const spacedCode = (code: string) => (code.length === 6 ? `${code.slice(0, 3)} ${code.slice(3)}` : code)
-/** Fills `{key}` in one pass: a device named "{code}" stays as written. */
-const fill = (text: string, values: Record<string, string>) => text.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match)
-
/** A signed-in phone scanned a computer in no account: letting it in brings the computer into the phone's account. */
export function pairingAskText(tr: Tr, request: { deviceName: string; email?: string | null; code: string }) {
// A no-break space: the code never wraps apart.
diff --git a/apps/desktop/src/renderer/lib/fill.test.ts b/apps/desktop/src/renderer/lib/fill.test.ts
new file mode 100644
index 00000000..713e73d7
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/fill.test.ts
@@ -0,0 +1,8 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { fill } from './fill.ts'
+
+test('what fill puts in stays as written', () => {
+ assert.equal(fill('{name} and {other}', { name: 'Build {other} $&', other: 'Reviewer' }), 'Build {other} $& and Reviewer')
+ assert.equal(fill('{name} and {missing}', { name: 'Build' }), 'Build and {missing}')
+})
diff --git a/apps/desktop/src/renderer/lib/fill.ts b/apps/desktop/src/renderer/lib/fill.ts
new file mode 100644
index 00000000..c081d3d9
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/fill.ts
@@ -0,0 +1,3 @@
+/** Fills a template's `{key}`s in one pass: a device named "{code}" stays as written. */
+export const fill = (template: string, values: Record<string, string>) =>
+ template.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match)
diff --git a/apps/desktop/src/renderer/lib/network-copy.ts b/apps/desktop/src/renderer/lib/network-copy.ts
index fccbbc5d..35438a00 100644
--- a/apps/desktop/src/renderer/lib/network-copy.ts
+++ b/apps/desktop/src/renderer/lib/network-copy.ts
@@ -1,6 +1,7 @@
/** What the Network section says about this computer's networks (codync-network). */
import type { Network, NetworkComputer, NetworkRole, NetworkRule } from '@shared/network'
+import { fill } from './fill.ts'
/** How computers reach each other without a direct path. */
export type ConnectorChoice = 'public' | 'private' | 'relay'
@@ -44,14 +45,14 @@ export function ruleLine(rule: NetworkRule, net: Network, tr: (s: string) => str
rule.fromComputer === ANY
? rule.fromAgent === ANY
? tr('any bot on any computer')
- : tr('{bot} on any computer').replaceAll('{bot}', bot)
+ : fill(tr('{bot} on any computer'), { bot })
: rule.fromAgent === ANY
- ? tr('any bot on {computer}').replaceAll('{computer}', rule.fromComputer)
- : tr('{bot} on {computer}').replaceAll('{bot}', bot).replaceAll('{computer}', rule.fromComputer)
+ ? fill(tr('any bot on {computer}'), { computer: rule.fromComputer })
+ : fill(tr('{bot} on {computer}'), { bot, computer: rule.fromComputer })
const me = net.computers.find((c) => c.me)
const to = rule.toAgent === ANY ? tr('any bot here') : agentName(me, rule.toAgent)
const template = rule.access === 'allow' ? 'Allow: {from} → {to}' : 'Deny: {from} → {to}'
- return tr(template).replaceAll('{from}', from).replaceAll('{to}', to)
+ return fill(tr(template), { from, to })
}
/** The rules with `i` moved by `by` (−1 up, +1 down); unchanged at either end. */
diff --git a/apps/desktop/src/renderer/views/ComputerRosterSection.tsx b/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
index 29a8599a..7947820c 100644
--- a/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
+++ b/apps/desktop/src/renderer/views/ComputerRosterSection.tsx
@@ -3,6 +3,7 @@ import { IconButton } from '../components/Controls'
import { Icon } from '../components/Icon'
import type { pointerDrag } from '../lib/pointer-drag'
import { useTr } from '../lib/use-language'
+import { fill } from '../lib/fill.ts'
import { useSlide } from '../lib/slide'
import type { BotStore } from '../store/bot-store'
import { ComputerBadge } from './ComputerBadge'
@@ -33,7 +34,7 @@ export function ComputerRosterSection({ store, compact, collapsed, previous, nex
<section ref={section} className={`computer-roster-section ${lifted ? 'lifted' : ''}`} aria-label={store.hostName} data-computer-section={id}>
<div className="computer-roster-heading">
<button className="computer-roster-toggle" aria-expanded={!collapsed} data-computer-heading={id}
- aria-label={`${store.hostName}, ${store.connectionLabel}`} title={tr('{name} · {other}. Drag to reorder.').replaceAll('{name}', () => store.hostName).replaceAll('{other}', () => store.connectionLabel)}
+ aria-label={`${store.hostName}, ${store.connectionLabel}`} title={fill(tr('{name} · {other}. Drag to reorder.'), { name: store.hostName, other: store.connectionLabel })}
onClick={toggle}
{...drag}
onKeyDown={(event) => {
diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsx
index eb9c8ca5..98fda2da 100644
--- a/apps/desktop/src/renderer/views/call/CallView.tsx
+++ b/apps/desktop/src/renderer/views/call/CallView.tsx
@@ -22,6 +22,7 @@ import { OpenAIRealtimeEngine } from './OpenAIRealtimeEngine'
import { countVoiceUsage, fromBase64, onDeviceAvailable, onDeviceUnavailableReason, providerName, transcribeOnHost, VoiceEngine, VoiceSettings, voiceSettingsClosed, type VoicePhase, type VoiceProvider } from './voice'
import { useTr } from '../../lib/use-language'
import { trNow } from '../../lib/l10n.ts'
+import { fill } from '../../lib/fill.ts'
import './call.css'
/** What the call bar says for `phase`. */
@@ -223,7 +224,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
// A cloud engine that can't start or drops mid-call hands over to on-device voice.
if (phase === 'failed' && session.provider && onDeviceAvailable()) {
countCloudMinutes()
- setNotice(tr("{name} isn't available ({reason}). Using on-device voice.").replaceAll('{name}', providerName(session.provider)).replaceAll('{reason}', () => tr(String(session.failure))))
+ setNotice(fill(tr("{name} isn't available ({reason}). Using on-device voice."), { name: providerName(session.provider), reason: tr(String(session.failure)) }))
begin(null)
}
}, [session, phase])
diff --git a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
index 0ecd09f6..558bf1e4 100644
--- a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
@@ -9,6 +9,7 @@ import { Text } from '../../components/Text'
import { ThinkingOrb } from '../../components/ThinkingOrb'
import { useStore } from '../../store/context'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
import { errorText, market, type AgentAuth, type AuthMethod } from './market-models'
import { ErrorText, Field, ScreenHeader, SlideStack, WebLink, filled } from './pieces'
import { AgentBrings } from './AgentBrings'
@@ -281,7 +282,7 @@ function AgentKeysForm({ backend, method, saved, back, done }: {
</CardSection>
<VStack gap={6} className="agent-keys-notes">
{method.description ? <span>{method.description}</span> : null}
- <span>{tr('Saved on {name} only and given to {other} when it starts.').replaceAll('{name}', () => store.hostName).replaceAll('{other}', () => backend.name)}</span>
+ <span>{fill(tr('Saved on {name} only and given to {other} when it starts.'), { name: store.hostName, other: backend.name })}</span>
{method.link && URL.canParse(method.link) ? <WebLink title="Get a key" url={method.link} /> : null}
</VStack>
</VStack>
diff --git a/apps/desktop/src/renderer/views/marketplace/ComposioViews.tsx b/apps/desktop/src/renderer/views/marketplace/ComposioViews.tsx
index 903b1477..a5c20436 100644
--- a/apps/desktop/src/renderer/views/marketplace/ComposioViews.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/ComposioViews.tsx
@@ -11,6 +11,7 @@ import {
} from './market-models'
import { AppLogo, ErrorText, Field, filled } from './pieces'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
/**
@@ -67,7 +68,7 @@ export function ComposioConnectSheet({ app, requestId, done }: { app: ComposioAp
return
}
if (state.status === 'failed' || state.status === 'expired') {
- setError(tr("Signing in to {name} didn't work ({status}). Close and try again.").replaceAll('{name}', () => app.name).replaceAll('{status}', () => String(state.status)))
+ setError(fill(tr("Signing in to {name} didn't work ({status}). Close and try again."), { name: app.name, status: String(state.status) }))
return
}
}
@@ -93,7 +94,7 @@ export function ComposioConnectSheet({ app, requestId, done }: { app: ComposioAp
if (requestId) await market.finishConnectionRequest(client, requestId, { connectorId: `composio-${app.slug}` })
markConnected()
} else {
- setError(tr('{name} says the connection is {status}.').replaceAll('{name}', () => app.name).replaceAll('{status}', () => String(state.status)))
+ setError(fill(tr('{name} says the connection is {status}.'), { name: app.name, status: String(state.status) }))
}
} catch (e) {
setError(errorText(e))
diff --git a/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx b/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
index a7a675bd..12a94651 100644
--- a/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
@@ -10,6 +10,7 @@ import { ErrorText, Field, WebLink } from './pieces'
import { usePlugins } from './plugins'
import { signInCode } from './sign-in-code'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
/** A sign-in with a code (GitHub): the code to paste on its page, before the page opens. */
export function SignInCodeDialog() {
@@ -106,7 +107,7 @@ export function InstallConnectorSheet({ item, requestId, addsAtOnce = true, done
id: o.id,
label: o.kind === 'remote'
? tr('Hosted by {name}').replaceAll('{name}', item.title)
- : tr('On {name} ({kind})').replaceAll('{name}', store.hostName).replaceAll('{kind}', o.kind),
+ : fill(tr('On {name} ({kind})'), { name: store.hostName, kind: o.kind }),
}))}
/>
</CardSection>
diff --git a/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx b/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
index 439110c5..a6a7a2e0 100644
--- a/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
+++ b/apps/desktop/src/renderer/views/settings/ApprovalSheet.tsx
@@ -9,6 +9,7 @@ import { useApp } from '../../store/context'
import { deviceIcon, errorText } from './parts'
import { spacedCode } from '../../lib/account-copy'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
/**
@@ -43,7 +44,7 @@ export function ApprovalSheet({ approval }: { approval: Approval }) {
<Icon name={deviceIcon(request.platform)} size={40} weight="light" color="var(--secondary)" />
<VStack align="center" gap={4}>
<Text as="div" size="title3" weight="semibold" className="settings-centered">
- {tr('{name} wants to use {other}').replaceAll('{other}', () => approval.store.hostName).replaceAll('{name}', () => request.deviceName)}
+ {fill(tr('{name} wants to use {other}'), { name: request.deviceName, other: approval.store.hostName })}
</Text>
{request.email ? <Text as="div" size="callout" tone="secondary">{tr('Signed in as {email}').split('{email}').join(request.email)}</Text> : null}
</VStack>
diff --git a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
index 1d152f8a..551d597d 100644
--- a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
+++ b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
@@ -5,6 +5,7 @@ import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { connectorChoices, connectorFor, expiryTime, type ConnectorChoice } from '../../lib/network-copy'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
import type { Network, RecoveryCode } from '@shared/network'
import type { BotStore } from '../../store/bot-store'
import { network } from '../../store/network'
@@ -98,9 +99,7 @@ export function RecoveryCodeSheet({ recovery: { code, network: networkName, comp
<IconButton title="Copy recovery code" icon="doc.on.doc" onClick={() => window.codync.app.copy(code)} />
</HStack>
<Text size="callout" tone="secondary">
- {tr("It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.")
- .replaceAll('{network}', networkName)
- .replaceAll('{name}', computer)}
+ {fill(tr("It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer."), { network: networkName, name: computer })}
</Text>
<HStack justify="end">
<Button onClick={done}>I saved it</Button>
@@ -139,7 +138,7 @@ export function InviteSheet({ store, net }: { store: BotStore; net: Network }) {
<IconButton title="Copy invite" icon="doc.on.doc" onClick={() => window.codync.app.copy(invite.invite)} />
</HStack>
<Text size="callout" tone="secondary">
- {tr('One use. Works until {time} while {name} stays on.').replaceAll('{time}', expiryTime(invite.expiresAt)).replaceAll('{name}', net.computer)}
+ {fill(tr('One use. Works until {time} while {name} stays on.'), { time: expiryTime(invite.expiresAt), name: net.computer })}
</Text>
<Text size="callout" tone="secondary">{tr('On the other computer, choose Join with invite under Network.')}</Text>
</>
diff --git a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
index eb1a3f45..caeba98b 100644
--- a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
+++ b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
@@ -13,6 +13,7 @@ import { errorText, liveClient } from './parts'
import * as voice from './voice-settings'
import type { VoiceModels, VoiceProvider } from './voice-settings'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
/**
@@ -245,7 +246,7 @@ function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider:
</div>
) : !canEditKey ? (
<VStack gap={4} className="settings-row">
- <Text>{tr('No {name} key on {other}').replaceAll('{name}', () => info.name).replaceAll('{other}', () => store.hostName)}</Text>
+ <Text>{fill(tr('No {name} key on {other}'), { name: info.name, other: store.hostName })}</Text>
<Text size="footnote" tone="secondary">{tr('Add it in Codync on {name}: Settings → Voice chat, or connect to that computer over SSH.').replaceAll('{name}', () => store.hostName)}</Text>
</VStack>
) : (
diff --git a/apps/desktop/src/renderer/views/thread/BotConversation.tsx b/apps/desktop/src/renderer/views/thread/BotConversation.tsx
index 58e7ca52..ad2ab7ce 100644
--- a/apps/desktop/src/renderer/views/thread/BotConversation.tsx
+++ b/apps/desktop/src/renderer/views/thread/BotConversation.tsx
@@ -11,6 +11,7 @@ import { MarkdownText } from './Markdown'
import './bot-conversation.css'
import { useFetched } from '../../lib/use-fetched'
import { useTr } from '../../lib/use-language'
+import { fill } from '../../lib/fill.ts'
/** The compact chat row for bot-to-bot messages with one peer: who, never what. Opens the conversation. */
@@ -54,7 +55,7 @@ function BotPair({ botId, peer }: { botId: string; peer: Peer }) {
</HStack>
)
return (
- <HStack as="span" gap={8} aria-label={tr('{name} and {other}').replaceAll('{name}', () => name(botId)).replaceAll('{other}', () => name(peer.id))}>
+ <HStack as="span" gap={8} aria-label={fill(tr('{name} and {other}'), { name: name(botId), other: name(peer.id) })}>
{label(botId)}
<Icon name="arrow.left.arrow.right" size={11} color="var(--tertiary)" />
{label(peer.id)}
diff --git a/apps/desktop/src/renderer/views/thread/PermissionCard.tsx b/apps/desktop/src/renderer/views/thread/PermissionCard.tsx
index 60a26e28..b51609fa 100644
--- a/apps/desktop/src/renderer/views/thread/PermissionCard.tsx
+++ b/apps/desktop/src/renderer/views/thread/PermissionCard.tsx
@@ -7,6 +7,7 @@ import { Text } from '../../components/Text'
import './permission-card.css'
import { useTr } from '../../lib/use-language'
import { trNow } from '../../lib/l10n.ts'
+import { fill } from '../../lib/fill.ts'
/** What the agent wants, from the tool's kind (also the notch island's headline). */
@@ -69,7 +70,7 @@ export function PermissionCard({ entry, hostName, answering, respond }: { entry:
</Text>
<HStack gap={6}>
<Icon name="desktopcomputer" size={10} color="var(--tertiary)" />
- <Text size="caption" tone="tertiary">{tr('Runs on {name}{path}').replaceAll('{name}', () => hostName).replaceAll('{path}', () => cwd)}</Text>
+ <Text size="caption" tone="tertiary">{fill(tr('Runs on {name}{path}'), { name: hostName, path: cwd })}</Text>
</HStack>
{hasDetail ? (
<Disclosure expanded={expanded} onToggle={() => setExpanded((e) => !e)} label={<Text size="caption" weight="medium" tone="secondary">{tr(`Details`)}</Text>}>
diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
index ee7e05e2..b6eaea76 100644
--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx
+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
@@ -21,6 +21,7 @@ import { WorkingTransition } from './WorkingTransition'
import { RoutineNotice } from './RoutineNotice'
import { Composer } from './Composer'
import { QueuedMessages } from './QueuedMessages'
+import { fill } from '../../lib/fill.ts'
import { outsideQueue } from './queued-messages'
import { ChatSidePanel } from './ChatSidePanel'
import { DetailsPanel, type DetailsTab } from './DetailsPanel'
@@ -452,7 +453,7 @@ function IntroCard({ bot }: { bot: Bot }) {
const tr = useTr()
const where = bot.managedWorkspace
? `${store.backendName(bot.backend)} · ${tr('Personal workspace')}`
- : tr('{agent} in {path}').replace('{agent}', store.backendName(bot.backend)).replace('{path}', bot.cwd)
+ : fill(tr('{agent} in {path}'), { agent: store.backendName(bot.backend), path: bot.cwd })
return (
<div className="intro-card">
<BotAvatar bot={bot} size={72} />
diff --git a/apps/ios/Kit/Sources/CodyncKit/L10n.swift b/apps/ios/Kit/Sources/CodyncKit/L10n.swift
index 0ffd6b0d..9c3adf1a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/L10n.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/L10n.swift
@@ -131,6 +131,11 @@ public enum L10n {
}
}
+ /// Fills a template's `{key}`s in one pass: a device named "{code}" stays as written.
+ public static func fill(_ template: String, _ values: [String: String]) -> String {
+ template.replacing(/\{(\w+)\}/) { match in values[String(match.1)] ?? String(match.0) }
+ }
+
public static func tr(
_ key: String,
preference: AppLanguage = AppLanguage.preference(),
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
index 52d00c5d..85be8011 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
@@ -35,12 +35,10 @@ public struct NetworkView: Codable, Hashable, Sendable {
? L10n.tr("{bot} on any computer").replacingOccurrences(of: "{bot}", with: rule.fromAgent)
: rule.fromAgent == Rule.any
? L10n.tr("any bot on {computer}").replacingOccurrences(of: "{computer}", with: rule.fromComputer)
- : L10n.tr("{bot} on {computer}")
- .replacingOccurrences(of: "{bot}", with: named(rule.fromAgent, agents(false, rule.fromComputer)))
- .replacingOccurrences(of: "{computer}", with: rule.fromComputer)
+ : L10n.fill(L10n.tr("{bot} on {computer}"), ["bot": named(rule.fromAgent, agents(false, rule.fromComputer)), "computer": rule.fromComputer])
let to = rule.toAgent == Rule.any ? L10n.tr("any bot here") : named(rule.toAgent, agents(true, nil))
let template = rule.access == .allow ? "Allow: {from} → {to}" : "Deny: {from} → {to}"
- return L10n.tr(template).replacingOccurrences(of: "{from}", with: from).replacingOccurrences(of: "{to}", with: to)
+ return L10n.fill(L10n.tr(template), ["from": from, "to": to])
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
index 879f0559..54380b91 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
@@ -68,7 +68,7 @@ struct InstallConnectorSheet: View {
ChoiceList(selection: $optionId, options: item.options.map { o in
(id: o.id, label: o.kind == "remote"
? L10n.tr("Hosted by {name}").replacingOccurrences(of: "{name}", with: item.title)
- : L10n.tr("On {name} ({kind})").replacingOccurrences(of: "{name}", with: model.hostName).replacingOccurrences(of: "{kind}", with: o.kind),
+ : L10n.fill(L10n.tr("On {name} ({kind})"), ["name": model.hostName, "kind": o.kind]),
detail: nil)
})
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
index d496c053..52bb497f 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -292,9 +292,7 @@ struct IntroCard: View {
Text(bot.name).font(.title2.weight(.semibold)).foregroundStyle(Palette.text)
Text(bot.managedWorkspace
? "\(model.backendName(bot.backend)) · \(L10n.tr("Personal workspace"))"
- : L10n.tr("{agent} in {path}")
- .replacingOccurrences(of: "{agent}", with: model.backendName(bot.backend))
- .replacingOccurrences(of: "{path}", with: bot.cwd))
+ : L10n.fill(L10n.tr("{agent} in {path}"), ["agent": model.backendName(bot.backend), "path": bot.cwd]))
.font(.subheadline)
.foregroundStyle(Palette.secondary)
.multilineTextAlignment(.center)
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AppLanguageTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AppLanguageTests.swift
index 14733161..f0ac0af8 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AppLanguageTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AppLanguageTests.swift
@@ -5,6 +5,11 @@ import Testing
@testable import CodyncKit
struct AppLanguageTests {
+ @Test func whatFillPutsInStaysAsWritten() {
+ #expect(L10n.fill("{name} and {other}", ["name": "Build {other}", "other": "Reviewer"]) == "Build {other} and Reviewer")
+ #expect(L10n.fill("{name} and {missing}", ["name": "Build"]) == "Build and {missing}")
+ }
+
@Test func theLanguageChoiceIsReadFromTheStoreItWasWrittenTo() {
let name = "AppLanguageTests.\(UUID().uuidString)"
let suite = UserDefaults(suiteName: name)!
diff --git a/host/src/tui/app/roster.rs b/host/src/tui/app/roster.rs
index 455a0f12..a92425a3 100644
--- a/host/src/tui/app/roster.rs
+++ b/host/src/tui/app/roster.rs
@@ -7,7 +7,7 @@ use std::collections::HashSet;
use icu_normalizer::DecomposingNormalizerBorrowed;
use serde_json::json;
-use super::super::l10n::tr;
+use super::super::l10n::{fill, tr};
use super::super::manage::{Submit, section_fields};
use super::{After, App, Bot, Click, Overlay};
@@ -272,7 +272,7 @@ impl App {
}
let supported = crate::compat::at_least(&self.host_version, since);
if !supported {
- let why = tr(why).replace("{host}", &self.host).replace("{version}", since);
+ let why = fill(&tr(why), &[("host", &self.host), ("version", since)]);
self.flash(&why);
}
supported
diff --git a/host/src/tui/l10n.rs b/host/src/tui/l10n.rs
index 6fdc7ac0..c5d0e785 100644
--- a/host/src/tui/l10n.rs
+++ b/host/src/tui/l10n.rs
@@ -248,6 +248,12 @@ fn compact_time_in(time: &str, table: &HashMap<String, String>) -> Option<String
Some(spoken)
}
+/// Fills a template's `{key}`s in one pass: a device named "{code}" stays as written.
+pub(in crate::tui) fn fill(template: &str, values: &[(&str, &str)]) -> String {
+ let values = values.iter().map(|(key, value)| (format!("{{{key}}}"), (*value).to_owned())).collect();
+ substitute(template, &values)
+}
+
/// An exact chrome phrase. Chat text that is not one of those phrases stays as written.
pub(in crate::tui) fn tr(text: &str) -> Cow<'_, str> {
match active_phrases() {
diff --git a/host/src/tui/l10n_tests.rs b/host/src/tui/l10n_tests.rs
index cf24d065..6057dc3e 100644
--- a/host/src/tui/l10n_tests.rs
+++ b/host/src/tui/l10n_tests.rs
@@ -1,6 +1,15 @@
-use super::{AppLanguage, HANS, PREFERENCE, language_title, resolved_language, tr, translate, translate_with};
+use super::{AppLanguage, HANS, PREFERENCE, fill, language_title, resolved_language, tr, translate, translate_with};
use crate::LockExt;
+#[test]
+fn what_fill_puts_in_stays_as_written() {
+ assert_eq!(
+ fill("{name} and {other}", &[("name", "Build {other}"), ("other", "Reviewer")]),
+ "Build {other} and Reviewer"
+ );
+ assert_eq!(fill("{name} and {missing} {", &[("name", "Build")]), "Build and {missing} {");
+}
+
#[test]
fn brazilian_portuguese_round_trips_its_saved_identifier() {
assert_eq!(AppLanguage::parse("pt-BR").stored(), "pt-BR");
diff --git a/host/src/tui/manage/market.rs b/host/src/tui/manage/market.rs
index ccab5991..a53db518 100644
--- a/host/src/tui/manage/market.rs
+++ b/host/src/tui/manage/market.rs
@@ -4,7 +4,7 @@ use crossterm::event::{KeyCode, KeyEvent};
use serde_json::{Value, json};
use super::super::app::{After, App, Confirm, ConfirmAct, Editor, Overlay, fuzzy};
-use super::super::l10n::tr;
+use super::super::l10n::{fill, tr};
use super::{Fields, Input, Market, Reply, Row, Submit, TABS, Tab, ctrl, s};
/// Registry rows kept loaded under the cursor on Connectors, about the list's height.
@@ -240,7 +240,7 @@ impl App {
if o["kind"] == "remote" {
tr("Hosted by {name}").replace("{name}", &title)
} else {
- tr("On {name} ({kind})").replace("{name}", &host).replace("{kind}", &s(o, "kind"))
+ fill(&tr("On {name} ({kind})"), &[("name", &host), ("kind", &s(o, "kind"))])
}
})
.collect();
diff --git a/host/src/tui/manage/network_rules.rs b/host/src/tui/manage/network_rules.rs
index 6a3c8ddd..4a68b019 100644
--- a/host/src/tui/manage/network_rules.rs
+++ b/host/src/tui/manage/network_rules.rs
@@ -5,7 +5,7 @@ use crossterm::event::{KeyCode, KeyEvent};
use serde_json::{Value, json};
use super::super::app::{App, cycle};
-use super::super::l10n::tr;
+use super::super::l10n::{fill, tr};
use super::network::{NetReply, NetworkSheet, Step};
const ANY: &str = "*";
@@ -86,7 +86,7 @@ impl NetworkSheet {
.iter()
.find(|c| c["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(computer)));
let name = on.and_then(|c| agent_name(c, agent)).unwrap_or(agent);
- tr("{bot} on {computer}").replace("{bot}", name).replace("{computer}", computer)
+ fill(&tr("{bot} on {computer}"), &[("bot", name), ("computer", computer)])
}
};
let to = match s(rule, "toAgent").as_str() {
@@ -94,7 +94,7 @@ impl NetworkSheet {
id => self.me().and_then(|me| agent_name(me, id)).unwrap_or(id).to_owned(),
};
let template = if rule["access"] == "deny" { "Deny: {from} → {to}" } else { "Allow: {from} → {to}" };
- tr(template).replace("{from}", &from).replace("{to}", &to)
+ fill(&tr(template), &[("from", &from), ("to", &to)])
}
}
diff --git a/host/src/tui/view/network.rs b/host/src/tui/view/network.rs
index f6519045..025f0c18 100644
--- a/host/src/tui/view/network.rs
+++ b/host/src/tui/view/network.rs
@@ -7,7 +7,7 @@ use ratatui::text::Span;
use serde_json::Value;
use super::super::app::Editor;
-use super::super::l10n::tr;
+use super::super::l10n::{fill, tr};
use super::super::manage::{CONNECTORS, NetworkSheet, Recovery, Setup, SetupField, Step};
use super::super::md;
use super::buffer::{centered, frame_box, hline, put, put_line, restyle, rput};
@@ -56,7 +56,7 @@ fn recovery(buf: &mut Buffer, body: Rect, r: &Recovery) -> &'static str {
let note = tr(
"It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.",
);
- wrapped(buf, body, &mut y, &note.replace("{network}", &r.network).replace("{name}", &r.computer), t.secondary);
+ wrapped(buf, body, &mut y, &fill(&note, &[("network", &r.network), ("name", &r.computer)]), t.secondary);
"y copy · s I saved it"
}
@@ -70,9 +70,10 @@ fn invite_step(buf: &mut Buffer, body: Rect, n: &NetworkSheet, invite: Option<&(
Some((code, until)) => {
wrapped(buf, body, &mut y, code, t.bold);
y += 1;
- let note = tr("One use. Works until {time} while {name} stays on.")
- .replace("{time}", &clock(*until))
- .replace("{name}", &n.computer());
+ let note = fill(
+ &tr("One use. Works until {time} while {name} stays on."),
+ &[("time", &clock(*until)), ("name", &n.computer())],
+ );
line(buf, body, &mut y, &note, t.secondary);
line(buf, body, &mut y, &tr("On the other computer, choose Join with invite under Network."), t.secondary);
}
diff --git a/host/src/tui/view/pair.rs b/host/src/tui/view/pair.rs
index 644b9dbb..3bd04d87 100644
--- a/host/src/tui/view/pair.rs
+++ b/host/src/tui/view/pair.rs
@@ -9,7 +9,7 @@ use ratatui::text::{Line, Span};
use serde_json::Value;
use super::super::app::{App, PairCode};
-use super::super::l10n::tr;
+use super::super::l10n::{fill, tr};
use super::super::md::{width as w, wrap};
use super::buffer::{centered, frame_box, put, put_line, u};
use super::style::theme;
@@ -46,11 +46,10 @@ fn ask(buf: &mut Buffer, area: Rect, request: &Value) {
Some((a, b)) if code.len() == 6 => format!("{a}\u{a0}{b}"),
_ => code.to_owned(),
};
- // The name last: whatever it says stays as written.
- let text = tr("{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.")
- .replace("{email}", &email)
- .replace("{code}", &code)
- .replace("{name}", name);
+ let text = fill(
+ &tr("{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}."),
+ &[("email", &email), ("code", &code), ("name", name)],
+ );
let lines = note(text, 52, t.text.patch(t.panel));
let r = centered(area, 56, u(lines.len() + 5));
let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));