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
112 changes: 112 additions & 0 deletions app/src/androidTest/java/dev/threadline/TranscriptScreenTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.autofill.ContentDataType
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
Expand Down Expand Up @@ -64,6 +65,7 @@ import dev.threadline.core.shell.CommandSubmissionResult
import dev.threadline.core.shell.CompletedCommand
import dev.threadline.core.shell.LifecyclePhase
import dev.threadline.core.shell.StructuredShellState
import dev.threadline.core.session.ReplySubmissionResult
import dev.threadline.core.terminal.TerminalKey
import dev.threadline.core.terminal.TerminalModifiers
import dev.threadline.core.transcript.CommandOutput
Expand All @@ -80,6 +82,116 @@ class TranscriptScreenTest {
@get:Rule
val composeRule = createAndroidComposeRule<ComponentActivity>()

@Test
fun runningReplySendsToItsCommandWithoutChangingTheComposerDraft() {
val replies = mutableListOf<Pair<CommandId, String>>()
composeRule.setContent {
MaterialTheme {
TranscriptSurface(
structuredShell = runningShell(),
transcript = CommandTranscriptState(
turns = listOf(turn(status = CommandStatus.RUNNING)),
),
onSubmit = { CommandSubmissionResult.Rejected(CommandSubmissionRejection.NOT_READY) },
onReply = { id, value ->
replies += id to value.concatToString()
ReplySubmissionResult.SENT
},
onStop = {},
onDisconnect = {},
)
}
}

composeRule.onNodeWithTag(TranscriptTags.COMPOSER).performTextInput("draft command")
composeRule.onNodeWithTag(TranscriptTags.REPLY).assertIsDisplayed().performClick()
composeRule.onNodeWithText("The remote program can echo or print this reply. " +
"It may appear in the transcript and saved history.").assertIsDisplayed()
composeRule.onNodeWithTag(TranscriptTags.REPLY_FIELD).performTextInput("yes")
composeRule.onNodeWithTag(TranscriptTags.REPLY_SEND).performClick()

composeRule.runOnIdle {
assertEquals(listOf(CommandId("command-42") to "yes"), replies)
}
assertComposerText("draft command")
composeRule.onNodeWithText("Reply to running command").assertDoesNotExist()
}

@Test
fun maskedReplyIsNotRestoredAndCancelSendsNothing() {
val replies = mutableListOf<String>()
val restorationTester = StateRestorationTester(composeRule)
restorationTester.setContent {
MaterialTheme {
TranscriptSurface(
structuredShell = runningShell(),
transcript = CommandTranscriptState(
turns = listOf(turn(status = CommandStatus.RUNNING)),
),
onSubmit = { CommandSubmissionResult.Rejected(CommandSubmissionRejection.NOT_READY) },
onReply = { _, value ->
replies += value.concatToString()
ReplySubmissionResult.SENT
},
onStop = {},
onDisconnect = {},
)
}
}

composeRule.onNodeWithTag(TranscriptTags.REPLY).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_MASKED).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_FIELD)
.assert(SemanticsMatcher.expectValue(
SemanticsProperties.ContentDataType,
ContentDataType.None,
))
.performTextInput("fixture-secret")
composeRule.onNodeWithTag(TranscriptTags.REPLY_FIELD)
.assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.Password))
composeRule.onNodeWithText("Cancel").performClick()
composeRule.runOnIdle { assertTrue(replies.isEmpty()) }

composeRule.onNodeWithTag(TranscriptTags.REPLY).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_MASKED).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_SEND).performClick()
composeRule.runOnIdle { assertEquals(listOf(""), replies) }

composeRule.onNodeWithTag(TranscriptTags.REPLY).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_MASKED).performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_FIELD).performTextInput("not-restored")
restorationTester.emulateSavedInstanceStateRestore()
composeRule.onNodeWithText("Reply to running command").assertDoesNotExist()
composeRule.onNodeWithText("not-restored").assertDoesNotExist()
}

@Test
fun replyControlsRemainReachableAtTwoHundredPercentFontScale() {
composeRule.setContent {
val density = LocalDensity.current
CompositionLocalProvider(LocalDensity provides Density(density.density, 2f)) {
MaterialTheme {
TranscriptSurface(
structuredShell = runningShell(),
transcript = CommandTranscriptState(
turns = listOf(turn(status = CommandStatus.RUNNING)),
),
onSubmit = {
CommandSubmissionResult.Rejected(CommandSubmissionRejection.NOT_READY)
},
onStop = {},
onDisconnect = {},
)
}
}
}

composeRule.onNodeWithTag(TranscriptTags.REPLY).assertIsDisplayed().performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_MASKED).assertIsDisplayed().performClick()
composeRule.onNodeWithTag(TranscriptTags.REPLY_FIELD).assertIsDisplayed()
composeRule.onNodeWithTag(TranscriptTags.REPLY_SEND).assertIsDisplayed()
}

@Test
fun composerSubmitsExactMultilineCommandAndClearsAfterAcceptance() {
var submitted: String? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,109 @@ import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class AndroidStructuredShellIntegrationTest {
@Test
fun repliesReachRunningCommandAndOnlyRemoteEchoEntersSavedOutput() = runBlocking {
val arguments = InstrumentationRegistry.getArguments()
val password = arguments.getString(PASSWORD_ARGUMENT)
assumeTrue("No fixture password supplied", !password.isNullOrEmpty())
val targetContext = InstrumentationRegistry.getInstrumentation().targetContext
val legacyPreferences = targetContext.getSharedPreferences(
"android_reply_known_hosts",
Context.MODE_PRIVATE,
)
legacyPreferences.edit().clear().commit()
val database = Room.inMemoryDatabaseBuilder(
targetContext,
ThreadlineDatabase::class.java,
).build()
val transcriptHistoryStore = RoomTranscriptHistoryStore(database.transcriptArchives())
val manager = SessionManager(
adapter = ConnectBotSshClientAdapter(
HostKeyAlgorithmPolicy.overrideWhenEd25519Unavailable(
AndroidSshCryptoProvider.install(),
),
),
knownHostStore = RoomKnownHostStore(database.knownHosts(), legacyPreferences),
terminal = NoOpTerminal,
transcriptArchiveSink = transcriptHistoryStore,
)
val profile = HostProfile(
displayName = "Reply fixture",
endpoint = HostEndpoint(
arguments.getString(HOST_ARGUMENT) ?: DEFAULT_HOST,
arguments.getString(PORT_ARGUMENT)?.toIntOrNull() ?: DEFAULT_PORT,
),
username = arguments.getString(USER_ARGUMENT) ?: DEFAULT_USER,
)

try {
assertTrue(manager.prepareConnection(ConnectionRequest(
profile,
SessionCredential.Password.from(requireNotNull(password).toCharArray()),
)))
assertTrue(manager.connectPrepared())
withTimeout(CONNECTION_TIMEOUT_MILLIS) {
manager.state.filterIsInstance<SessionState.AwaitingHostKey>().first()
}
assertTrue(manager.resolveHostKey(HostKeyDecision.ACCEPT_AND_SAVE))
withTimeout(CONNECTION_TIMEOUT_MILLIS) {
manager.structuredState.filterIsInstance<StructuredShellState.Ready>().first()
}

val ordinary = accepted(manager.submitCommand(
"stty -echo; read -r -p 'Continue? ' reply; stty echo; test -n \"\$reply\"",
))
awaitTranscriptOutput(manager, ordinary.commandId, "Continue? ")
assertEquals(ReplySubmissionResult.SENT,
manager.sendReply(ordinary.commandId, "yes".toCharArray()))
assertEquals(0, awaitCompletion(manager, ordinary.commandId).exitStatus)

val masked = accepted(manager.submitCommand(
"stty -echo; read -r -p 'Secret? ' reply; stty echo; test -n \"\$reply\"",
))
awaitTranscriptOutput(manager, masked.commandId, "Secret? ")
assertEquals(ReplySubmissionResult.SENT,
manager.sendReply(masked.commandId, "fixture-secret".toCharArray()))
assertEquals(0, awaitCompletion(manager, masked.commandId).exitStatus)
assertTrue(!manager.transcriptState.value.turns.first { it.id == masked.commandId }
.output.plainText.contains("fixture-secret"))

val echoed = accepted(manager.submitCommand(
"read -r -p 'Password: ' reply; test -n \"\$reply\"",
))
awaitTranscriptOutput(manager, echoed.commandId, "Password: ")
assertEquals(ReplySubmissionResult.SENT,
manager.sendReply(echoed.commandId, "fixture-echo".toCharArray()))
assertEquals(0, awaitCompletion(manager, echoed.commandId).exitStatus)
assertTrue(manager.transcriptState.value.turns.first { it.id == echoed.commandId }
.output.plainText.contains("fixture-echo"))

manager.disconnect()
withTimeout(CONNECTION_TIMEOUT_MILLIS) {
manager.state.first { it is SessionState.Disconnected }
}
val savedId = withTimeout(CONNECTION_TIMEOUT_MILLIS) {
transcriptHistoryStore.sessions.first { it.isNotEmpty() }.single().id
}
val saved = transcriptHistoryStore.load(savedId).turns.map { it.turn }
assertTrue(saved.first { it.id == masked.commandId }.let {
!it.command.contains("fixture-secret") &&
!it.output.plainText.contains("fixture-secret")
})
assertTrue(saved.first { it.id == echoed.commandId }
.output.plainText.contains("fixture-echo"))
} finally {
if (manager.state.value !is SessionState.Disconnected) {
manager.disconnect()
withTimeout(CONNECTION_TIMEOUT_MILLIS) {
manager.state.first { it is SessionState.Disconnected }
}
}
database.close()
legacyPreferences.edit().clear().commit()
}
}

@Test
fun encryptedImportedKeyAuthenticatesAfterDatabaseReopen() = runBlocking {
val arguments = InstrumentationRegistry.getArguments()
Expand Down Expand Up @@ -471,6 +574,19 @@ class AndroidStructuredShellIntegrationTest {
assertEquals(0, completed.exitStatus)
}

private suspend fun awaitTranscriptOutput(
manager: SessionManager,
commandId: CommandId,
text: String,
) {
withTimeout(COMMAND_TIMEOUT_MILLIS) {
manager.transcriptState.first { transcript ->
transcript.turns.firstOrNull { it.id == commandId }
?.output?.plainText?.contains(text) == true
}
}
}

private suspend fun assertSuccessful(
manager: SessionManager,
command: String,
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/dev/threadline/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ private fun ThreadlineApp() {
onSubmit = manager::submitCommand,
onSubmitIsolated = manager::submitIsolatedCommand,
onControlC = manager::sendControlC,
onReply = manager::sendReply,
onDisconnect = manager::disconnect,
onOpenHome = { showConnectedSession = false },
onOpenDiagnostics = openDiagnostics,
Expand Down
Loading
Loading