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
36 changes: 36 additions & 0 deletions docs/wiki/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,39 @@ Use bounded, redacted logs and a clear export preview. Track state changes, outp
attempts and failures without retaining conversation content. Distinguish idle,
unknown, stale and unreachable. Retention duration and completion display timeout
remain concept-review decisions.

## Implemented application defaults

`spn settings show` displays the effective saved defaults and the settings path.
Use **Settings → Preferences** in the interactive shell, or:

```powershell
spn settings set --phone iphone --brightness 60 --shell powershell
spn settings set --profile personal --model dot
spn settings set --auto --no-profile
spn settings set --brightness 80 --dry-run
spn settings show --json
spn settings reset
```

Replace `iphone` with a saved alias; `default` follows the designated default phone.
Use `--device <absolute-path>` for a preferred USB/SD output. Explicit command
output flags override the saved output. Otherwise the saved output wins over USB
discovery. A missing or failing preferred output produces an error; it never
redirects delivery to another device. `--auto` restores USB/default-phone discovery.

Defaults are Auto output, 100% brightness, built-in state programs and the platform
export shell (PowerShell on Windows, Bash elsewhere). State sends and the host
use the selected profile/model and brightness; animation preview/apply use the
saved brightness/model unless explicitly overridden. Global brightness scales a
profile's own brightness. `state` and `host run/start` accept `--brightness`,
`--profile`, `--no-profile` and `--model` overrides. A preferred profile requires
an explicit model, so phone delivery does not need USB model detection. Restart
the host after changing its defaults.

The versioned `settings.json` lives next to the protected phone store, under
`SIDEPULSE_NET_HOME` when specified. It contains aliases/paths and ordinary
preferences, never push tokens or command history. Reading defaults and previewing
settings do not create files or open the credential vault. Invalid or newer-schema
settings are preserved with a recovery message. `settings reset` explicitly replaces
settings with defaults; phone links, profiles and integration configurations remain.
8 changes: 5 additions & 3 deletions docs/wiki/Scripting-and-Menus.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ In a terminal, `spn` opens a persistent session. Bare groups `animations`,
Up/Down select, Enter continues, Escape goes back one section. Escape at Home
stays in the session; choose Quit to leave. `/` opens a searchable action palette.
Commands and recoverable failures return to their section. Ctrl+C cancels a
running command; when idle it exits. The detached host keeps running.
running command or a form; on Home it exits. The detached host keeps running.
Fully specified commands always
execute directly. The legacy `host --phone default` shorthand remains supported.

Send state retains its output choice and Preview mode until the session ends.
Send state saves its preferred output across launches and retains Preview mode until the session ends.
Choose a state and press Enter to send; there is no repeated target or Run/Copy
dialog. Change output lists mounted devices and saved phones; Auto selects one
USB device, otherwise the default/sole saved phone. Preview never sends.
Saved application-wide UI preferences and first-run installation are still planned.
Settings → Preferences saves output, brightness, profile/model and export shell;
see [[Configuration]]. Home shows these defaults, host status and the last action.
Esc/Ctrl+C cancels forms while retaining text for retry; Ctrl+U clears text.

Advanced guided actions display a single-line script command before running. Review offers
Run, Copy command, Choose shell and Back. Simple arguments remain unquoted.
Expand Down
15 changes: 15 additions & 0 deletions docs/wiki/Terminal-Experience.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,18 @@ spn doctor
These commands are proposals, not installation instructions. Reserve `--quiet`,
`--json`, `--no-color` and `--non-interactive`. Redirected stdout must not start
an interactive dashboard. Hook commands never prompt and keep stdout empty.

## Implemented preferences and Home

The persistent shell now keeps preferred output, brightness, animation profile/LED
model and export shell across launches. **Settings → Preferences** edits these
values; [[Configuration]] documents the equivalent scripting commands. Preview mode
remains a session choice. Home displays these defaults, a bounded host-status query
and the last action in the current session, inside the same menu panel.

Esc returns from menus, including the searchable `/` action palette. Esc or Ctrl+C
cancels shell forms and retains text for retry; Ctrl+U clears the current input.
Ctrl+C during an executing command requests cancellation, and Ctrl+C on Home exits.
Only successful settings saves change the preferred output. Errors leave the shell
open. This does not complete the proposed live dashboard, persistent activity history,
all specialized editor controls or real Windows Terminal acceptance.
46 changes: 44 additions & 2 deletions scripts/cli_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,46 @@ def run(*args, input=None):
assert not disconnected.stdout and not disconnected.stderr
with tempfile.TemporaryDirectory(prefix='SidePulse test ü ') as directory:
child_env['SIDEPULSE_NET_HOME'] = str(Path(directory) / 'config')
settings_path = Path(child_env['SIDEPULSE_NET_HOME']) / 'settings.json'
initial = json.loads(run('settings', '--json').stdout)
assert initial['preferences']['Brightness'] == 100 and not settings_path.exists()
run('settings', 'set', '--brightness', '42', '--shell', 'bash', '--dry-run')
assert not settings_path.exists(), 'Settings preview wrote configuration'
run('settings', 'set', '--brightness', '42', '--shell', 'bash')
persisted = json.loads(run('settings', 'show', '--json').stdout)['preferences']
assert persisted['Brightness'] == 42 and persisted['Shell'] == 'bash'
dimmed = json.loads(run('state', 'working', '--dry-run', '--json').stdout)
assert dimmed['program'].startswith('brightness 107\n')
explicit = json.loads(run('state', 'working', '--brightness', '10', '--dry-run', '--json').stdout)
assert explicit['program'].startswith('brightness 26\n')
run('profiles', 'set', 'personal', '--state', 'working', '--pattern', 'solid-green', '--brightness', '80')
run('settings', 'set', '--profile', 'personal', '--model', 'dot')
profiled = json.loads(run('state', 'working', '--dry-run', '--json').stdout)
assert '#00ff66' in profiled['program'].lower()
built_in = json.loads(run('state', 'working', '--no-profile', '--dry-run', '--json').stdout)
assert '#00e5ff' in built_in['program'].lower()
run('settings', 'set', '--no-profile')
target_default = Path(directory) / 'preferred'
target_override = Path(directory) / 'override'
for target_dir in (target_default, target_override):
target_dir.mkdir()
(target_dir / 'LEDS.LED').write_text('off')
run('settings', 'set', '--device', str(target_default))
run('state', 'done')
assert '#00ff66' in (target_default / 'LEDS.LED').read_text()
run('state', 'waiting', '--device', str(target_override))
assert '#ff9900' in (target_override / 'LEDS.LED').read_text()
assert '#00ff66' in (target_default / 'LEDS.LED').read_text()
run('settings', 'set', '--device', str(Path(directory) / 'missing'))
failed = subprocess.run([exe, 'state', 'error'], capture_output=True, env=child_env, timeout=10)
assert failed.returncode != 0, 'Missing preferred output silently switched targets'
before = settings_path.read_bytes()
run('state', 'done', '--dry-run')
assert before == settings_path.read_bytes()
settings_path.write_text('{broken')
failed = subprocess.run([exe, 'settings', 'show'], capture_output=True, env=child_env, timeout=10)
assert failed.returncode != 0 and settings_path.read_text() == '{broken'
run('settings', 'reset')
checks = json.loads(run('doctor', '--json').stdout)
assert all(check['Status'] != 'error' for check in checks)
if os.name == 'nt' or os.environ.get('SIDEPULSE_NATIVE_VAULT_TESTS') == '1':
Expand Down Expand Up @@ -54,8 +94,9 @@ def run(*args, input=None):
assert 'exit 0' in hooks['preToolUse'][0]['bash']
refused = subprocess.run([exe, 'hook-config', '--exe', exe, '--output', str(config)], capture_output=True)
assert refused.returncode != 0
run('settings', 'set', '--device', directory, '--brightness', '42')
with open(Path(directory) / 'host.log', 'w') as log:
host = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log)
host = subprocess.Popen([exe, 'host', '--plain'], stdout=log, stderr=log, env=child_env)
try:
# Repeated idempotent input accommodates host startup without a timing-only assertion.
for attempt in range(30):
Expand All @@ -69,6 +110,7 @@ def run(*args, input=None):
assert result.returncode == 0
assert not result.stdout and not result.stderr
if '#00e5ff' in target.read_text():
assert target.read_text().startswith('brightness 107\n')
break
time.sleep(0.1)
else:
Expand All @@ -87,7 +129,7 @@ def run(*args, input=None):
host.terminate()
host.wait(timeout=10)
# A forcibly terminated host must be restartable without manual socket cleanup.
restarted = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log)
restarted = subprocess.Popen([exe, 'host', '--plain'], stdout=log, stderr=log, env=child_env)
try:
for attempt in range(30):
assert restarted.poll() is None, 'Restarted host exited: ' + (Path(directory) / 'host.log').read_text()
Expand Down
41 changes: 41 additions & 0 deletions scripts/terminal_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ def until(self, text):
needle = text.encode('utf-8')
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
if needle in self.output:
self.output = self.output[self.output.index(needle) + len(needle):]
return
if select.select([self.master], [], [], 0.1)[0]:
try:
data = os.read(self.master, 65536)
Expand Down Expand Up @@ -113,6 +116,44 @@ def finish(self):
if menu.process.poll() is None:
menu.process.kill()

settings = Terminal([])
try:
settings.until('Last action:')
settings.until('Quit')
settings.send(b'\x1b[B' * 4 + b'\r')
settings.until('Preferences')
settings.send(b'\r')
settings.until('Show settings')
settings.send(b'\x1b[B' * 2 + b'\r')
settings.until('input retained')
settings.send(b'\x15' + b'42\x03')
settings.until('Show settings')
settings.send(b'\r')
settings.until('input retained')
settings.send(b'\r')
settings.until('Show settings')
settings.send(b'\x1b')
settings.until('Diagnostics')
settings.send(b'\x1b')
settings.until('Brightness: 42%')
settings.until('Quit')
settings.send(b'\x1b[B' * 2 + b'\r')
settings.finish()
finally:
if settings.process.poll() is None:
settings.process.kill()
import json
assert json.loads((root / 'config' / 'settings.json').read_text())['Brightness'] == 42
restarted = Terminal([])
try:
restarted.until('Brightness: 42%')
restarted.until('Quit')
restarted.send(b'\x03')
restarted.finish()
finally:
if restarted.process.poll() is None:
restarted.process.kill()

file = root / 'custom.LED'
editor = Terminal(['animations', 'edit', '--file', str(file), '--model', 'dot'])
try:
Expand Down
13 changes: 7 additions & 6 deletions src/SidePulse.Cli/Animations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public class PatternSettings : CommandSettings
{
[CommandArgument(0, "[NAME]")] public string? Name { get; init; }
[CommandOption("--file <PATH>")] public string? File { get; init; }
[CommandOption("--model <MODEL>")] public DeviceModel Model { get; init; } = DeviceModel.Dot;
[CommandOption("--brightness <PERCENT>")] public int? Brightness { get; init; }
[CommandOption("--model <MODEL>")] public DeviceModel Model { get; init; } = PreferenceStore.Default.Read().Model ?? DeviceModel.Dot;
[CommandOption("--brightness <PERCENT>")] public int? Brightness { get; init; } = PreferenceStore.Default.Read().Brightness is var value && value != 100 ? value : null;
[CommandOption("--json")] public bool Json { get; init; }
public override ValidationResult Validate()
{
Expand Down Expand Up @@ -154,11 +154,12 @@ public sealed class PatternApplyCommand : AsyncCommand<PatternApplySettings>
{
public override async Task<int> ExecuteAsync(CommandContext context, PatternApplySettings settings, CancellationToken cancellationToken)
{
var model = settings.Model ?? AnimationLibrary.DetectModel(settings.Device);
var preferences = PreferenceStore.Default.Read();
var model = settings.Model ?? preferences.Model ?? AnimationLibrary.DetectModel(settings.Device ?? preferences.Device);
var raw = settings.File is { } file ? new LedProgram(await System.IO.File.ReadAllTextAsync(file, cancellationToken)) : AnimationLibrary.Default.Get(settings.Name!, model);
var program = AnimationLibrary.WithBrightness(raw, settings.Brightness);
var program = AnimationLibrary.WithBrightness(raw, settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness));
Animation.Parse(program, model);
await Delivery.Send(settings, program, cancellationToken); Delivery.Receipt(settings, program);
await Delivery.Send(settings, program, cancellationToken, preferences); Delivery.Receipt(settings, program);
return 0;
}
}
Expand Down Expand Up @@ -214,7 +215,7 @@ public override int Execute(CommandContext context, ProfileSettings settings, Ca
if (!AnimationLibrary.Default.List().Any(p => p.Name == settings.Pattern)) throw new ArgumentException("Pattern was not found. Import it first.");
AnimationProfile profile;
try { profile = AnimationLibrary.Default.LoadProfile(settings.Name); }
catch (FileNotFoundException) { profile = new([]); }
catch (IOException ex) when (ex is FileNotFoundException or DirectoryNotFoundException) { profile = new([]); }
profile.States[settings.State.Value] = settings.Pattern;
profile = profile with { Brightness = settings.Brightness ?? profile.Brightness };
var path = AnimationLibrary.Default.SaveProfile(settings.Name, profile, true);
Expand Down
16 changes: 12 additions & 4 deletions src/SidePulse.Cli/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ public override ValidationResult Validate() => new[] { Device, TokenEnvironment,

public static class Delivery
{
public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken)
public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken, Preferences? preferences = null)
{
if (settings.DryRun) return;
var target = OutputTarget.Resolve(settings.Device, settings.Phone, settings.TokenEnvironment,
var target = (preferences ?? PreferenceStore.Default.Read()).ResolveOutput(settings.Device, settings.Phone, settings.TokenEnvironment,
DeviceTransport.Discover, () => File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []);
if (target.Transport == OutputTransport.Phone)
{
Expand All @@ -95,21 +95,29 @@ public static void Receipt(TargetSettings settings, LedProgram program)

public sealed class StateSettings : TargetSettings
{
[CommandOption("--brightness <PERCENT>")] public int? Brightness { get; init; }
[CommandOption("--profile <NAME>")] public string? Profile { get; init; }
[CommandOption("--no-profile")] public bool NoProfile { get; init; }
[CommandOption("--model <MODEL>")] public DeviceModel? Model { get; init; }
[CommandArgument(0, "<STATE>")]
public AgentState State { get; init; }
public override ValidationResult Validate()
{
var target = base.Validate();
if (!target.Successful) return target;
if (Brightness is < 0 or > 100 || Model is { } model && !Enum.IsDefined(model)) return ValidationResult.Error("Choose brightness 0..100 and model dot or pro.");
return Enum.IsDefined(State) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent state.");
}
}
public sealed class StateCommand : AsyncCommand<StateSettings>
{
public override async Task<int> ExecuteAsync(CommandContext context, StateSettings settings, CancellationToken cancellationToken)
{
var program = LedProgram.ForState(settings.State);
await Delivery.Send(settings, program, cancellationToken);
if (settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose --profile or --no-profile.");
var preferences = PreferenceStore.Default.Read();
var profile = settings.NoProfile ? null : settings.Profile ?? preferences.Profile;
var program = AnimationLibrary.WithBrightness(AnimationLibrary.ResolveProfile(profile, settings.Model ?? preferences.Model, settings.Device ?? preferences.Device)[settings.State], settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness));
await Delivery.Send(settings, program, cancellationToken, preferences);
Delivery.Receipt(settings, program);
return 0;
}
Expand Down
9 changes: 7 additions & 2 deletions src/SidePulse.Cli/Hooks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ public override async Task<int> ExecuteAsync(CommandContext context, HookSetting
}
public sealed class HostSettings : TargetSettings
{
[CommandOption("--no-profile")] public bool NoProfile { get; init; }
[CommandOption("--brightness <PERCENT>")] public int? Brightness { get; init; }
[CommandOption("--profile <NAME>")]
public string? Profile { get; init; }
[CommandOption("--model <MODEL>")]
Expand All @@ -117,7 +119,10 @@ public sealed class HostCommand : AsyncCommand<HostSettings>
{
public override async Task<int> ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken)
{
var patterns = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device);
if (settings.NoProfile && settings.Profile is not null) throw new ArgumentException("Choose --profile or --no-profile.");
var preferences = PreferenceStore.Default.Read();
var patterns = AnimationLibrary.ResolveProfile(settings.NoProfile ? null : settings.Profile ?? preferences.Profile, settings.Model ?? preferences.Model, settings.Device ?? preferences.Device)
.ToDictionary(item => item.Key, item => AnimationLibrary.WithBrightness(item.Value, settings.Brightness ?? (preferences.Brightness == 100 ? null : preferences.Brightness)));
if (settings.Background) HostLogs.Detach();
using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); };
Expand All @@ -134,7 +139,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, HostSetting
{
await foreach (var program in outputs.Reader.ReadAllAsync(shutdown.Token))
{
try { await Delivery.Send(settings, program, shutdown.Token); }
try { await Delivery.Send(settings, program, shutdown.Token, preferences); }
catch (Exception ex) when (ex is IOException or ArgumentException or OperationCanceledException)
{
Console.Error.WriteLine("Output unavailable; check the device, token environment variable or network.");
Expand Down
Loading
Loading