A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Share to Coucou: the rule for the shared text and the one-shot draft
Claudeba5ba90e8a3d
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ShareDraft.kt b/android/app/src/main/kotlin/com/coucou/android/core/ShareDraft.ktnew file mode 100644index 00000000..bb2d2ca8--- /dev/null+++ b/android/app/src/main/kotlin/com/coucou/android/core/ShareDraft.kt@@ -0,0 +1,80 @@+package com.coucou.android.core++import com.coucou.android.link.Protocol++/**+ * "Share to Coucou": text shared from another app lands in the chat box as a draft, never sent by itself. This is the pure part: how the shared+ * text is cleaned, what to do for the state the chat is in, and the one-shot slot that carries the draft from the share target to the chat screen+ * inside the process. Other apps can start the share target, so the text is only ever treated as typed text: it is cut to the chat's limit, stripped+ * of control characters, and it goes into the box where the user reads it and taps send (or not).+ */+class ShareDraft(private val clock: () -> Long = System::currentTimeMillis) {+ private var text: String? = null+ private var at = 0L++ /** Keeps the cleaned [raw] as the draft (the last share wins); a blank or missing text keeps nothing. */+ @Synchronized+ fun offer(raw: String?) {+ text = clean(raw)+ at = clock()+ }++ /** The draft once, if it is fresh; null for everything else (nothing shared, already taken, too old). */+ @Synchronized+ fun take(): String? {+ val t = text ?: return null+ val fresh = clock() - at <= TTL_MS+ text = null+ return if (fresh) t else null+ }++ /** True while a fresh draft waits: the main screen then opens on Chat, where it is put in the box. */+ @Synchronized+ fun pending(): Boolean = text != null && clock() - at <= TTL_MS++ enum class Outcome { KEEP_AND_OPEN_CHAT, NOTHING_TO_SHARE, NOT_PAIRED, CHAT_UNAVAILABLE }++ companion object {+ /** A share is opened a few seconds after the tap, but the link may need a moment to come back first. */+ const val TTL_MS = 120_000L++ /** More than this is cut before it is even looked at, so a huge share costs nothing. */+ const val MAX_INPUT = 100_000++ /** The shared text as a draft: line breaks unified, control characters dropped, trimmed, cut to the chat limit; null when nothing is left. */+ fun clean(raw: String?): String? {+ raw ?: return null+ val sb = StringBuilder()+ var i = 0+ val s = raw.take(MAX_INPUT)+ while (i < s.length) {+ val ch = s[i]+ when {+ ch == '\r' -> { sb.append('\n'); if (i + 1 < s.length && s[i + 1] == '\n') i++ }+ ch == '\n' || ch == '\t' -> sb.append(ch)+ ch.isISOControl() || ch == ' ' || ch == ' ' || ch == '' || ch == '' || ch == '' -> {}+ else -> sb.append(ch)+ }+ i+++ }+ val t = sb.toString().trim()+ if (t.isEmpty()) return null+ return t.take(Protocol.CHAT_MAX_TEXT).trimEnd()+ }++ /**+ * What the share target does. A computer that is paired but not reachable yet keeps the draft and opens the chat (it explains itself and+ * receives the draft when the link is back); a chat the computer does not offer says so and keeps nothing.+ */+ fun decide(hasText: Boolean, state: ChatTabState): Outcome = when {+ !hasText -> Outcome.NOTHING_TO_SHARE+ state == ChatTabState.NOT_PAIRED -> Outcome.NOT_PAIRED+ state == ChatTabState.CHAT_OFF || state == ChatTabState.NO_MODELS -> Outcome.CHAT_UNAVAILABLE+ else -> Outcome.KEEP_AND_OPEN_CHAT+ }++ /** How a draft is put in a box that may already hold text: after it, on a new line. Cut to the chat limit. */+ fun into(existing: String, draft: String): String =+ (if (existing.isBlank()) draft else existing.trimEnd() + "\n" + draft).take(Protocol.CHAT_MAX_TEXT)+ }+}diff --git a/android/app/src/test/kotlin/com/coucou/android/ShareDraftTest.kt b/android/app/src/test/kotlin/com/coucou/android/ShareDraftTest.ktnew file mode 100644index 00000000..d5e94670--- /dev/null+++ b/android/app/src/test/kotlin/com/coucou/android/ShareDraftTest.kt@@ -0,0 +1,136 @@+package com.coucou.android++import com.coucou.android.core.ChatTabState+import com.coucou.android.core.ShareDraft+import com.coucou.android.core.ShareDraft.Outcome+import com.coucou.android.link.Protocol+import java.io.File+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class ShareDraftTest {+ private var now = 1_000L+ private val draft = ShareDraft { now }+ private val d get() = draft++ @Test fun sharedTextBecomesADraftOnce() {+ draft.offer("Explain this stack trace")+ assertTrue(draft.pending())+ assertEquals("Explain this stack trace", draft.take())+ assertNull("only once", draft.take())+ assertFalse(draft.pending())+ }++ @Test fun aStaleDraftIsDropped() {+ draft.offer("hello")+ now += ShareDraft.TTL_MS + 1+ assertNull(draft.take())+ }++ @Test fun theLastShareWins() {+ draft.offer("one")+ draft.offer("two")+ assertEquals("two", draft.take())+ }++ @Test fun blankOrMissingTextKeepsNothing() {+ draft.offer(" \n\t ")+ assertNull(draft.take())+ draft.offer(null)+ assertNull(draft.take())+ assertNull(ShareDraft.clean(""))+ assertNull(ShareDraft.clean("\u0000\u0007\u001B"))+ }++ @Test fun controlCharactersAndDirectionTricksAreDropped() {+ assertEquals("ab", ShareDraft.clean("a\u0000b"))+ assertEquals("abc", ShareDraft.clean("a\u001B[31mbc".replace("[31m", "")))+ assertEquals("ab", ShareDraft.clean("ab"))+ assertEquals("ab", ShareDraft.clean("ab"))+ // Tabs and line breaks stay; Windows and old Mac line ends become one \n.+ assertEquals("a\tb\nc\nd\ne", ShareDraft.clean("a\tb\r\nc\rd\ne"))+ }++ @Test fun theTextIsTrimmedAndCutToTheChatLimit() {+ assertEquals("hi", ShareDraft.clean(" hi \n"))+ val long = "x".repeat(Protocol.CHAT_MAX_TEXT + 500)+ assertEquals(Protocol.CHAT_MAX_TEXT, ShareDraft.clean(long)!!.length)+ // A huge share is cut before anything else touches it.+ assertEquals(Protocol.CHAT_MAX_TEXT, ShareDraft.clean("y".repeat(5_000_000))!!.length)+ }++ @Test fun markupIsKeptAsPlainText() {+ // Nothing is interpreted: a script tag or a link is only characters in a box the user reads.+ assertEquals("<b>hi</b> https://example.com/?a=1&b=2", ShareDraft.clean("<b>hi</b> https://example.com/?a=1&b=2"))+ }++ @Test fun whatToDoForEachStateOfTheChat() {+ assertEquals(Outcome.NOTHING_TO_SHARE, ShareDraft.decide(false, ChatTabState.READY))+ assertEquals(Outcome.NOT_PAIRED, ShareDraft.decide(true, ChatTabState.NOT_PAIRED))+ assertEquals(Outcome.KEEP_AND_OPEN_CHAT, ShareDraft.decide(true, ChatTabState.NOT_CONNECTED))+ assertEquals(Outcome.CHAT_UNAVAILABLE, ShareDraft.decide(true, ChatTabState.CHAT_OFF))+ assertEquals(Outcome.CHAT_UNAVAILABLE, ShareDraft.decide(true, ChatTabState.NO_MODELS))+ assertEquals(Outcome.KEEP_AND_OPEN_CHAT, ShareDraft.decide(true, ChatTabState.READY))+ }++ @Test fun aDraftGoesAfterWhatIsAlreadyInTheBox() {+ assertEquals("draft", ShareDraft.into("", "draft"))+ assertEquals("draft", ShareDraft.into(" ", "draft"))+ assertEquals("typed\ndraft", ShareDraft.into("typed ", "draft"))+ assertEquals(Protocol.CHAT_MAX_TEXT, ShareDraft.into("a".repeat(Protocol.CHAT_MAX_TEXT), "more").length)+ }++ // ── The share target (source guards: Android classes only compile in CI) ──────────────────────++ private val main = "src/main/kotlin/com/coucou/android/"+ private val activity = File(main + "app/ShareActivity.kt").readText()+ private val manifest = File("src/main/AndroidManifest.xml").readText()++ @Test fun theShareTargetTakesPlainTextOnly() {+ val block = manifest.substringAfter("""android:name=".app.ShareActivity"""").substringBefore("</activity>")+ assertTrue(block.contains("""android:exported="true""""))+ assertEquals(listOf("android.intent.action.SEND"), Regex("""<action android:name="([^"]+)"""").findAll(block).map { it.groupValues[1] }.toList())+ assertEquals(listOf("text/plain"), Regex("""android:mimeType="([^"]+)"""").findAll(block).map { it.groupValues[1] }.toList())+ assertFalse(block.contains("SEND_MULTIPLE"))+ assertFalse(manifest.contains("EXTRA_STREAM") || activity.contains("EXTRA_STREAM") || activity.contains("ClipData") || activity.contains("getParcelable"))+ }++ @Test fun theShareTargetNeverSendsAndNeverTrustsTheExtra() {+ assertTrue(activity.contains("runCatching { shared.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString() }"))+ assertTrue(activity.contains("ShareDraft.clean("))+ assertTrue(activity.contains("model.offerShare(clean)"))+ for (word in listOf("chatSend", "sendBroadcast", "approve", "unpair", "Log.", "launch.request")) assertFalse(word, activity.contains(word))+ // The text is not logged, shown in a notification or put on the intent it opens the app with.+ assertFalse(activity.contains("putExtra"))+ assertFalse(activity.contains("Notification"))+ }++ @Test fun theMainScreenOpensOnChatWhileADraftWaits() {+ val src = File(main + "MainActivity.kt").readText()+ assertTrue(src.contains("if (model.shareDraft.pending()) screen = Screen.CHAT"))+ // It never reads the share from the intent it is started with.+ assertFalse(src.contains("EXTRA_TEXT"))+ d.offer("hi")+ assertTrue(d.pending())+ now += ShareDraft.TTL_MS + 1+ assertFalse("a stale draft does not pull the app to Chat", d.pending())+ }++ @Test fun theChatBoxReceivesTheDraftAndTheUserSends() {+ val chat = File(main + "ui/ChatScreen.kt").readText()+ assertTrue(chat.contains("model.shareDraft.take()"))+ assertTrue(chat.contains("text = ShareDraft.into(text, it)"))+ // Putting the draft in the box is all it does here; sending stays behind the send button.+ assertEquals(1, Regex("""model\.chatSend\(""").findAll(chat).count())+ assertFalse(File(main + "app/AppModel.kt").readText().substringAfter("fun offerShare").substringBefore("}").contains("chatSend"))+ }++ @Test fun everyLanguageTranslatesTheShareTexts() {+ for (f in File("../i18n/translations").listFiles()!!.filter { it.extension == "json" }) {+ for (k in listOf("share_label", "share_not_paired", "share_chat_off")) assertTrue("${f.name} lacks $k", f.readText().contains("\"$k\""))+ }+ }+}