Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 伙伴任务卡与凭证销毁不再杀死进程 (#4612)
Chris Zhangd1fd9c91e74a
diff --git a/apps/mobile/app/companions/direct/[threadId].tsx b/apps/mobile/app/companions/direct/[threadId].tsxindex 33ee4e07d7..14da102c90 100644--- a/apps/mobile/app/companions/direct/[threadId].tsx+++ b/apps/mobile/app/companions/direct/[threadId].tsx@@ -30,7 +30,7 @@ export default function CompanionDirectMessages() {<SimpleStackHeader title={thread ? `${thread.botAName} · ${thread.botBName}` : t('devices.companions.messages')} subtitle={t('devices.companions.readOnly')} onBack={() => goBackGuarded(router)} /><ScrollView contentContainerStyle={styles.content}>{!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text> : null}- {thread?.messages.map((message) => <Text selectable key={message.id} style={styles.message}>{`${message.senderBotName}\n${message.content}`}</Text>)}+ {(Array.isArray(thread?.messages) ? thread.messages : []).map((message) => <Text selectable key={message.id} style={styles.message}>{`${message.senderBotName}\n${message.content}`}</Text>)}{!thread && online ? <Text style={styles.note}>{error || value?.ok === false ? t('devices.companions.actionFailed') : t('devices.resources.loading')}</Text> : null}{error || value?.ok === false ? <MainWindowActionButton action={{ label: t('devices.resources.retry'), onPress: refresh }} /> : null}</ScrollView>diff --git a/apps/mobile/modules/cindy-remote-credentials/android/build.gradle b/apps/mobile/modules/cindy-remote-credentials/android/build.gradleindex 8064d0f8ed..044926b0cb 100644--- a/apps/mobile/modules/cindy-remote-credentials/android/build.gradle+++ b/apps/mobile/modules/cindy-remote-credentials/android/build.gradle@@ -20,6 +20,7 @@ dependencies {dependencies {testImplementation 'org.json:json:20240303'+ testImplementation 'junit:junit:4.13.2'}// A test-only JVM peer used by Swift's opt-in two-process interoperability test.// The file contains class paths, never fixture keys or application credentials.diff --git a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CindyRemoteCredentialsModule.kt b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CindyRemoteCredentialsModule.ktindex 1944e0ec0f..9cb3030521 100644--- a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CindyRemoteCredentialsModule.kt+++ b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CindyRemoteCredentialsModule.kt@@ -40,7 +40,15 @@ class CindyRemoteCredentialsModule : Module() {AsyncFunction("close") Coroutine { handle: String -> guarded { client.close(handle) } }AsyncFunction("reset") Coroutine { -> guarded { client.reset() } }OnActivityEntersForeground { clientValue?.foreground = true }- OnActivityEntersBackground { clientValue?.foreground = false; clientValue?.close() }- OnDestroy { android.os.Handler(android.os.Looper.getMainLooper()).post { clientValue?.destroy(); clientValue = null } }+ OnActivityEntersBackground {+ clientValue?.foreground = false+ runCredentialTeardown { clientValue?.close() }+ }+ OnDestroy {+ android.os.Handler(android.os.Looper.getMainLooper()).post {+ runCredentialTeardown { clientValue?.destroy() }+ clientValue = null+ }+ }}}diff --git a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CredentialDirectory.kt b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CredentialDirectory.ktindex 15978db617..7c83efb1dc 100644--- a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CredentialDirectory.kt+++ b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/CredentialDirectory.kt@@ -34,11 +34,17 @@ internal class CredentialInstallation(context: Context) {val temporary = File.createTempFile("installation-", ".tmp", root)try {FileOutputStream(temporary).use { it.write(uuid().toByteArray()); it.fd.sync() }- try { Os.link(temporary.path, marker.path) }- catch (error: ErrnoException) { if (error.errno != OsConstants.EEXIST) throw error }- } finally { temporary.delete() }+ publishMarkerAtomically(+ publishHardLink = { Os.link(temporary.path, marker.path) },+ publishExclusive = { publishExclusiveMarker(temporary, marker) },+ errnoOf = { (it as? ErrnoException)?.errno },+ )+ } catch (error: CredentialFailure) { throw error }+ catch (_: Exception) { throw CredentialFailure("CREDENTIAL_UNAVAILABLE") }+ finally { temporary.delete() }}- val attributes = Os.lstat(marker.path)+ val attributes = try { Os.lstat(marker.path) }+ catch (_: ErrnoException) { throw CredentialFailure("CREDENTIAL_UNAVAILABLE") }requireCredential(OsConstants.S_ISREG(attributes.st_mode) && attributes.st_uid == android.os.Process.myUid() &&attributes.st_size == 36L, "CREDENTIAL_INVALID_IDENTITY")id = marker.readText(); requireCredential(validId(id), "CREDENTIAL_INVALID_IDENTITY")@@ -57,6 +63,31 @@ internal class CredentialInstallation(context: Context) {}}+/** Appear the already-complete temp as `marker` or adopt a winner. Never create an empty dest. */+private fun publishExclusiveMarker(temporary: File, marker: File) {+ val lock = File(requireNotNull(marker.parentFile), ".installation.publish")+ if (!acquireExclusivePublishLock(lock, marker)) {+ if (marker.exists()) return+ throw CredentialFailure("CREDENTIAL_UNAVAILABLE")+ }+ try {+ if (marker.exists()) return+ Os.rename(temporary.path, marker.path)+ } catch (error: ErrnoException) {+ if (error.errno == OsConstants.EEXIST || marker.exists()) return+ throw error+ } finally {+ lock.delete()+ }+}++private fun acquireExclusivePublishLock(lock: File, marker: File): Boolean {+ if (lock.mkdir()) return true+ if (marker.exists()) return false+ if (System.currentTimeMillis() - lock.lastModified() < 10_000L || !lock.delete()) return false+ return lock.mkdir()+}+internal class CredentialDirectory(private val realm: String, private val member: String) {private val origin = when (realm) {"global" -> "https://device-link.cindy.app"diff --git a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/InstallationMarkerPublish.kt b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/InstallationMarkerPublish.ktnew file mode 100644index 0000000000..d1eae96d6d--- /dev/null+++ b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/InstallationMarkerPublish.kt@@ -0,0 +1,64 @@+package app.cindy.credentials++/** Linux/Android errno values used by installation marker publish. */+internal object InstallationErrno {+ const val EPERM = 1+ const val EACCES = 13+ const val EEXIST = 17+ const val EXDEV = 18+ const val ENOSYS = 38+ const val ENOTSUP = 95+}++private val linkFallbackErrnos = setOf(+ InstallationErrno.EPERM,+ InstallationErrno.EACCES,+ InstallationErrno.EXDEV,+ InstallationErrno.ENOSYS,+ InstallationErrno.ENOTSUP,+)++/**+ * Publish a fully written marker. Prefer an exclusive hard link; if the+ * filesystem refuses the link, fall back to exclusive rename of that complete+ * file. Any other failure becomes CREDENTIAL_UNAVAILABLE so teardown cannot+ * abort the process.+ */+internal fun publishMarkerAtomically(+ publishHardLink: () -> Unit,+ publishExclusive: () -> Unit,+ errnoOf: (Throwable) -> Int?,+) {+ try {+ publishHardLink()+ } catch (error: Throwable) {+ val errno = errnoOf(error) ?: throw CredentialFailure("CREDENTIAL_UNAVAILABLE")+ if (errno == InstallationErrno.EEXIST) return+ if (errno !in linkFallbackErrnos) throw CredentialFailure("CREDENTIAL_UNAVAILABLE")+ try {+ publishExclusive()+ } catch (fallback: Throwable) {+ if (errnoOf(fallback) != InstallationErrno.EEXIST) {+ throw CredentialFailure("CREDENTIAL_UNAVAILABLE")+ }+ }+ }+}++internal fun cancelInitializedVault(initialized: Boolean, cancel: () -> Unit) {+ if (initialized) cancel()+}++internal fun runIsolated(action: () -> Unit) {+ try {+ action()+ } catch (_: Exception) {+ }+}++internal fun runCredentialTeardown(action: () -> Unit) {+ try {+ action()+ } catch (_: Exception) {+ }+}diff --git a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/MobileCredentialClient.kt b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/MobileCredentialClient.ktindex 51e5c31694..0cf33cacdd 100644--- a/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/MobileCredentialClient.kt+++ b/apps/mobile/modules/cindy-remote-credentials/android/src/main/java/app/cindy/credentials/MobileCredentialClient.kt@@ -31,7 +31,8 @@ internal class MobileCredentialClient(context: Context, activity: () -> Fragmentfun close() { toSave?.ciphertext?.fill(0); toSave = null; attempt = null; commands.clear(); abandoned.clear(); channel.close() }}private val installation by lazy { CredentialInstallation(context) }- private val vault by lazy { CredentialVault(context, installation, activity) }+ private val vaultHolder = lazy { CredentialVault(context, installation, activity) }+ private val vault by vaultHolderprivate val configureLock = Mutex()private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)private var owner: Owner? = null@@ -195,11 +196,15 @@ internal class MobileCredentialClient(context: Context, activity: () -> Fragment}fun close(handle: String) { if (session?.handle == handle) close() }fun close() {- val state = session; epoch++; session = null; state?.close(); monitor?.cancel(); monitor = null- vault.cancel(); if (state != null) invalidated(state.handle)- }- fun reset() { close(); owner = null; token = ""; key = null; identity = null }- fun destroy() { reset(); scope.cancel() }+ val state = session; epoch++; session = null+ runIsolated { state?.close() }+ runIsolated { monitor?.cancel() }+ monitor = null+ runIsolated { cancelInitializedVault(vaultHolder.isInitialized()) { vault.cancel() } }+ if (state != null) runIsolated { invalidated(state.handle) }+ }+ fun reset() { try { close() } finally { owner = null; token = ""; key = null; identity = null } }+ fun destroy() { try { reset() } finally { scope.cancel() } }private fun current(handle: String): Session {val state = sessionrequireCredential(state != null && state.handle == handle, "CREDENTIAL_INVALID_IDENTITY")diff --git a/apps/mobile/modules/cindy-remote-credentials/android/src/test/java/app/cindy/credentials/InstallationMarkerPublishTest.kt b/apps/mobile/modules/cindy-remote-credentials/android/src/test/java/app/cindy/credentials/InstallationMarkerPublishTest.ktnew file mode 100644index 0000000000..b954d02651--- /dev/null+++ b/apps/mobile/modules/cindy-remote-credentials/android/src/test/java/app/cindy/credentials/InstallationMarkerPublishTest.kt@@ -0,0 +1,99 @@+package app.cindy.credentials++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test++class InstallationMarkerPublishTest {+ private class LinkError(val errno: Int) : Exception()++ private fun errnoOf(error: Throwable): Int? = (error as? LinkError)?.errno++ @Test+ fun hardLinkSuccessDoesNotCallExclusive() {+ var exclusive = false+ publishMarkerAtomically(+ publishHardLink = {},+ publishExclusive = { exclusive = true },+ errnoOf = ::errnoOf,+ )+ assertFalse(exclusive)+ }++ @Test+ fun existingMarkerIsAdopted() {+ var exclusive = false+ publishMarkerAtomically(+ publishHardLink = { throw LinkError(InstallationErrno.EEXIST) },+ publishExclusive = { exclusive = true },+ errnoOf = ::errnoOf,+ )+ assertFalse(exclusive)+ }++ @Test+ fun accessDeniedFallsBackToExclusiveCreate() {+ var exclusive = false+ publishMarkerAtomically(+ publishHardLink = { throw LinkError(InstallationErrno.EACCES) },+ publishExclusive = { exclusive = true },+ errnoOf = ::errnoOf,+ )+ assertTrue(exclusive)+ }++ @Test+ fun exclusiveRaceIsAdopted() {+ publishMarkerAtomically(+ publishHardLink = { throw LinkError(InstallationErrno.EXDEV) },+ publishExclusive = { throw LinkError(InstallationErrno.EEXIST) },+ errnoOf = ::errnoOf,+ )+ }++ @Test+ fun otherLinkFailuresStayUnavailable() {+ try {+ publishMarkerAtomically(+ publishHardLink = { throw LinkError(21) },+ publishExclusive = { fail("exclusive must not run") },+ errnoOf = ::errnoOf,+ )+ fail("expected CredentialFailure")+ } catch (error: CredentialFailure) {+ assertEquals("CREDENTIAL_UNAVAILABLE", error.fixedCode)+ }+ }++ @Test+ fun closeDoesNotInitializeAVault() {+ var cancelled = false+ cancelInitializedVault(false) { cancelled = true }+ assertFalse(cancelled)+ cancelInitializedVault(true) { cancelled = true }+ assertTrue(cancelled)+ }++ @Test+ fun lazyHolderReportsUninitializedWithoutRunningTheInitializer() {+ val holder = lazy { throw AssertionError("vault must stay uninitialized") }+ val unused by holder+ cancelInitializedVault(holder.isInitialized()) { unused.toString() }+ assertFalse(holder.isInitialized())+ }++ @Test+ fun teardownSwallowsInitializationFailure() {+ runCredentialTeardown { throw CredentialFailure("CREDENTIAL_UNAVAILABLE") }+ }++ @Test+ fun isolatedCleanupContinuesAfterAStepFails() {+ var second = false+ runIsolated { throw CredentialFailure("CREDENTIAL_UNAVAILABLE") }+ runIsolated { second = true }+ assertTrue(second)+ }+}diff --git a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsxindex 9c630ca79f..8b99bcd095 100644--- a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx+++ b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx@@ -18,7 +18,17 @@ vi.mock('react-native', () => ({currentState: 'active',addEventListener: () => ({ remove() {} }),},- View: ({ children }: any) => createElement('div', {}, children),+ View: ({ children, onLayout }: any) => {+ useEffect(() => {+ if (!onLayout) return;+ const event = { nativeEvent: { layout: { width: 128, height: 32, x: 0, y: 0 } } as+ | { layout: { width: number; height: number; x: number; y: number } }+ | null };+ onLayout(event);+ event.nativeEvent = null;+ });+ return createElement('div', {}, children);+ },Pressable: ({ children, onPress, disabled }: any) =>createElement('button',@@ -118,6 +128,38 @@ afterEach(async () => {node.remove();vi.useRealTimers();});+it('survives recycled layout events when measuring equal-width task actions', async () => {+ await render();+ expect(node.textContent).toContain('devices.companions.openTask');+ expect(node.textContent).toContain('devices.companions.stopTask');+});++it('keeps the task card when the host omits delegations or sends a broken status', async () => {+ h.invoke.mockResolvedValue({ ok: true });+ await render();+ expect(node.textContent).toContain('devices.companions.status.unknown');+ expect(node.textContent).not.toContain('devices.companions.stopTask');+ h.invoke.mockResolvedValue({+ ok: true,+ delegations: [{ id: 'job', status: 'not-a-status', title: 'Report', childSessionId: 'child' }],+ });+ await render();+ expect(node.textContent).toContain('devices.companions.status.unknown');+ expect(node.textContent).toContain('devices.companions.openTask');+});++it('isolates a broken private-chat card so the session can keep rendering', async () => {+ const broken = {+ ...message,+ key: 'broken-direct',+ companion: { kind: 'direct', meta: null },+ } as unknown as NormalizedRemoteMessage;+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ await act(async () => root.render(createElement(CompanionMessageCard, { message: broken })));+ consoleError.mockRestore();+ expect(node.textContent).toBe('devices.companions.actionFailed');+});+it('reads, opens and stops the task on its source computer, then disables stop offline', async () => {await render();expect(h.invoke).toHaveBeenCalledWith('home', 'maker:bot-delegations:list', ['parent']);diff --git a/apps/mobile/src/session/CompanionMessageCard.tsx b/apps/mobile/src/session/CompanionMessageCard.tsxindex 73121f3bf0..676a41c343 100644--- a/apps/mobile/src/session/CompanionMessageCard.tsx+++ b/apps/mobile/src/session/CompanionMessageCard.tsx@@ -1,6 +1,6 @@-import { useEffect, useState } from 'react';+import { Component, useEffect, useState, type ReactNode } from 'react';import { useLocalSearchParams, useRouter } from 'expo-router';-import { Linking, Pressable, StyleSheet, View } from 'react-native';+import { Linking, Pressable, StyleSheet, View, type LayoutChangeEvent } from 'react-native';import {FileText,GitPullRequest,@@ -18,9 +18,10 @@ import {type PrStatusResult,} from '@cindy/maker-shared';import { useTranslation } from 'react-i18next';-import type {- BotDelegationListResult,- BotDelegationCancelResult,+import {+ BOT_DELEGATION_STATUSES,+ type BotDelegationListResult,+ type BotDelegationCancelResult,} from '@cindy/maker-shared/botDelegation';import type { BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';import { Text } from '@/components/AppText';@@ -31,7 +32,39 @@ import { spacing, radius, typeScale, iconSize } from '@/theme/tokens';import type { NormalizedRemoteMessage } from './messageNormalize';import { useRemoteCompanionQuery } from './useRemoteCompanionQuery';+class CompanionRenderBoundary extends Component<+ { children: ReactNode; fallback: ReactNode; resetKey: string },+ { failed: boolean; resetKey: string }+> {+ state = { failed: false, resetKey: this.props.resetKey };+ static getDerivedStateFromError() {+ return { failed: true };+ }+ static getDerivedStateFromProps(+ props: { resetKey: string },+ state: { failed: boolean; resetKey: string },+ ) {+ return props.resetKey === state.resetKey ? null : { failed: false, resetKey: props.resetKey };+ }+ render() {+ return this.state.failed ? this.props.fallback : this.props.children;+ }+}+export function CompanionMessageCard({ message }: { message: NormalizedRemoteMessage }) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ return (+ <CompanionRenderBoundary+ fallback={<Text style={styles.note}>{t('devices.companions.actionFailed')}</Text>}+ resetKey={message.key}+ >+ <CompanionMessageCardContent message={message} />+ </CompanionRenderBoundary>+ );+}++function CompanionMessageCardContent({ message }: { message: NormalizedRemoteMessage }) {const { t } = useTranslation();const router = useRouter();const params = useLocalSearchParams<{ deviceId?: string }>();@@ -99,7 +132,14 @@ function CompanionTaskCard({'maker:bot-delegations:list',[parentSessionId],);- const row = value?.ok ? value.delegations.find((item) => item.id === meta.delegationId) : null;+ const row =+ value?.ok && Array.isArray(value.delegations)+ ? (value.delegations.find((item) => item.id === meta.delegationId) ?? null)+ : null;+ const status =+ row && (BOT_DELEGATION_STATUSES as readonly string[]).includes(row.status)+ ? row.status+ : 'unknown';const [pending, setPending] = useState(false);const [actionFailed, setActionFailed] = useState(false);const [showPrs, setShowPrs] = useState(false);@@ -206,6 +246,12 @@ function CompanionTaskCard({setPending(false);}};+ const rememberActionWidth = (event: LayoutChangeEvent) => {+ const width = event.nativeEvent?.layout?.width;+ if (typeof width !== 'number' || !Number.isFinite(width)) return;+ const measuredWidth = Math.ceil(width);+ setActionWidth((current) => Math.max(current, measuredWidth));+ };return (<View style={styles.card} testID="companion.taskCard"><View style={styles.header}>@@ -219,15 +265,15 @@ function CompanionTaskCard({(row?.status === 'failed' || row?.status === 'timed-out') && styles.error,]}>- {t(`devices.companions.status.${row?.status || 'unknown'}`)}+ {t(`devices.companions.status.${status}`)}</Text></View><View style={styles.metadata}>{duration ? <Text style={styles.note}>{duration}</Text> : null}- {(row?.artifacts?.length ?? 0) > 0 ? (+ {Array.isArray(row?.artifacts) && row.artifacts.length > 0 ? (<Text style={styles.note}>{t('devices.companions.artifactCount', {- count: row!.artifacts.length,+ count: row.artifacts.length,})}</Text>) : null}@@ -269,11 +315,7 @@ function CompanionTaskCard({>{({ pressed }) => (<View- onLayout={(event) =>- setActionWidth((width) =>- Math.max(width, Math.ceil(event.nativeEvent.layout.width)),- )- }+ onLayout={rememberActionWidth}style={[styles.action,{ minWidth: actionWidth },@@ -303,11 +345,7 @@ function CompanionTaskCard({>{({ pressed }) => (<View- onLayout={(event) =>- setActionWidth((width) =>- Math.max(width, Math.ceil(event.nativeEvent.layout.width)),- )- }+ onLayout={rememberActionWidth}style={[styles.action,{ minWidth: actionWidth },@@ -329,11 +367,7 @@ function CompanionTaskCard({>{({ pressed }) => (<View- onLayout={(event) =>- setActionWidth((width) =>- Math.max(width, Math.ceil(event.nativeEvent.layout.width)),- )- }+ onLayout={rememberActionWidth}style={[styles.action,{ minWidth: actionWidth },diff --git a/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationMarker.swift b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationMarker.swiftindex 6093728f2c..490c880b72 100644--- a/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationMarker.swift+++ b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationMarker.swift@@ -23,7 +23,15 @@ public enum InstallationMarker {guard bytes.withUnsafeBytes({ write(descriptor, $0.baseAddress, $0.count) }) == bytes.count,fsync(descriptor) == 0 else { throw CredentialError.unavailable }if link(temporary.path, file.path) == 0 { return id }- guard errno == EEXIST else { throw CredentialError.unavailable }+ let rejected = errno+ switch InstallationPublish.decide(errno: rejected) {+ case .adoptedExisting:+ break+ case .createExclusive:+ if try publishExclusiveMarker(from: temporary, to: file) { return id }+ case .unavailable:+ throw CredentialError.unavailable+ }}let existing = open(file.path, O_RDONLY | O_NOFOLLOW)guard existing >= 0 else { throw CredentialError.unavailable }@@ -38,4 +46,11 @@ public enum InstallationMarker {return id} catch { throw CredentialError.unavailable }}++ /// Exclusive rename of the already-complete temporary file. Returns false when another writer won.+ private static func publishExclusiveMarker(from temporary: URL, to file: URL) throws -> Bool {+ if renamex_np(temporary.path, file.path, UInt32(RENAME_EXCL)) == 0 { return true }+ guard errno == EEXIST else { throw CredentialError.unavailable }+ return false+ }}diff --git a/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationPublish.swift b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationPublish.swiftnew file mode 100644index 0000000000..3ed2f59789--- /dev/null+++ b/packages/remote-credentials-native/Sources/CindyRemoteCredentials/InstallationPublish.swift@@ -0,0 +1,19 @@+import Darwin++enum InstallationPublish {+ enum Decision {+ case adoptedExisting+ /// Exclusive rename of a complete temporary file onto the marker path.+ case createExclusive+ case unavailable+ }++ static func decide(errno code: Int32) -> Decision {+ if code == EEXIST { return .adoptedExisting }+ if code == EACCES || code == EPERM || code == EXDEV || code == ENOSYS+ || code == ENOTSUP || code == EOPNOTSUPP {+ return .createExclusive+ }+ return .unavailable+ }+}diff --git a/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/InstallationMarkerTests.swift b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/InstallationMarkerTests.swiftindex 62327f3efa..016ff67429 100644--- a/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/InstallationMarkerTests.swift+++ b/packages/remote-credentials-native/Tests/CindyRemoteCredentialsTests/InstallationMarkerTests.swift@@ -1,3 +1,4 @@+import Darwinimport XCTest@testable import CindyRemoteCredentials@@ -49,4 +50,31 @@ final class InstallationMarkerTests: XCTestCase {try FileManager.default.createSymbolicLink(at: file, withDestinationURL: target)XCTAssertThrowsError(try InstallationMarker.loadOrCreate(directory: directory))}++ func testLinkRefusalUsesExclusiveCreateOrExistingMarker() {+ XCTAssertEqual(InstallationPublish.decide(errno: EEXIST), .adoptedExisting)+ XCTAssertEqual(InstallationPublish.decide(errno: EACCES), .createExclusive)+ XCTAssertEqual(InstallationPublish.decide(errno: EPERM), .createExclusive)+ XCTAssertEqual(InstallationPublish.decide(errno: EXDEV), .createExclusive)+ XCTAssertEqual(InstallationPublish.decide(errno: ENOSYS), .createExclusive)+ XCTAssertEqual(InstallationPublish.decide(errno: ENOTSUP), .createExclusive)+ XCTAssertEqual(InstallationPublish.decide(errno: EIO), .unavailable)+ }++ func testExclusiveRenamePublishesACompleteFileAndDoesNotReplaceAWinner() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("cindy-rename-excl-" + UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let dest = directory.appendingPathComponent("installation-id")+ let first = directory.appendingPathComponent("first")+ let second = directory.appendingPathComponent("second")+ let winner = Data(UUID().uuidString.lowercased().utf8)+ try winner.write(to: first)+ try Data(UUID().uuidString.lowercased().utf8).write(to: second)+ XCTAssertEqual(renamex_np(first.path, dest.path, UInt32(RENAME_EXCL)), 0)+ XCTAssertEqual(try Data(contentsOf: dest), winner)+ XCTAssertNotEqual(renamex_np(second.path, dest.path, UInt32(RENAME_EXCL)), 0)+ XCTAssertEqual(errno, EEXIST)+ XCTAssertEqual(try Data(contentsOf: dest), winner)+ }}