diff --git a/agent/PhoneBox.Agent.Tests/AuditRegressionTests.cs b/agent/PhoneBox.Agent.Tests/AuditRegressionTests.cs
index 2fd1c76..170e594 100644
--- a/agent/PhoneBox.Agent.Tests/AuditRegressionTests.cs
+++ b/agent/PhoneBox.Agent.Tests/AuditRegressionTests.cs
@@ -109,6 +109,23 @@ public void TheRestTimeStillHoldsWhenTheConditionReallyEndsAndComesBack()
Assert.False(push.Snapshot().ContainsKey("onair"));
}
+ [Fact]
+ public void AnAppInFrontRuleFollowsTheForegroundApp()
+ {
+ var (engine, push, write) = Rules();
+ write("""{"id":"focus","name":"Focus","when":"app-in-front","match":"code","then":"goto","page":"work","whileActive":true}""");
+ engine.FrontProbe = () => "Visual Studio Code";
+ engine.Evaluate();
+ Assert.Contains(push.Since(0), e => e.Kind == "goto");
+ Assert.Contains("focus", engine.Active());
+ engine.FrontProbe = () => "Safari";
+ engine.Evaluate();
+ Thread.Sleep(RuleEngine.ReleaseSec * 1000 + 300);
+ engine.Evaluate();
+ Assert.Contains(push.Since(0), e => e.Kind == "back");
+ Assert.DoesNotContain("focus", engine.Active());
+ }
+
[Theory]
[InlineData("on", true)]
[InlineData("off", false)]
diff --git a/agent/PhoneBox.Agent/Config.cs b/agent/PhoneBox.Agent/Config.cs
index 9a53e70..b8a86fa 100644
--- a/agent/PhoneBox.Agent/Config.cs
+++ b/agent/PhoneBox.Agent/Config.cs
@@ -230,7 +230,7 @@ public sealed class RuleConfig
public string Id { get; set; } = "";
public string Name { get; set; } = "";
public bool Enabled { get; set; } = true;
- /// session-waiting, session-busy, media-playing, process-running, mic-in-use, camera-in-use, obs-live, calendar-event, cpu-above, idle, time, push.
+ /// session-waiting, session-busy, media-playing, process-running, app-in-front, mic-in-use, camera-in-use, obs-live, calendar-event, cpu-above, idle, time, push.
public string When { get; set; } = "session-waiting";
/// App / process names ("zoom|Teams"), a time window ("22:00-07:00") or a push key, depending on .
public string? Match { get; set; }
@@ -263,7 +263,7 @@ public sealed class RuleConfig
public string? Op { get; set; }
public string? Arg { get; set; }
- public static readonly string[] Triggers = ["session-waiting", "session-busy", "media-playing", "process-running", "mic-in-use", "camera-in-use", "obs-live", "calendar-event",
+ public static readonly string[] Triggers = ["session-waiting", "session-busy", "media-playing", "process-running", "app-in-front", "mic-in-use", "camera-in-use", "obs-live", "calendar-event",
"cpu-above", "idle", "time", "push", "quota-above", "review-requested", "ci-failed", "battery-low", "ping-high", "always"];
public static readonly string[] Actions = ["goto", "notify", "push", "shortcut"];
}
diff --git a/agent/PhoneBox.Agent/RuleEngine.cs b/agent/PhoneBox.Agent/RuleEngine.cs
index 73721d3..755d5d7 100644
--- a/agent/PhoneBox.Agent/RuleEngine.cs
+++ b/agent/PhoneBox.Agent/RuleEngine.cs
@@ -1,4 +1,7 @@
using System.Diagnostics;
+#if WINDOWS
+using System.Runtime.InteropServices;
+#endif
using System.Text.Json;
namespace PhoneBox.Agent;
@@ -199,6 +202,12 @@ private void Undo(RuleConfig r)
.FirstOrDefault(n => procs.Contains(n) || procs.Any(p => p.Length >= 15 && n.StartsWith(p, StringComparison.OrdinalIgnoreCase)));
return hit is null ? (false, "") : (true, hit);
}
+ case "app-in-front":
+ {
+ var front = FrontApp();
+ var hit = front is not null && names.Any(n => front.Contains(n, StringComparison.OrdinalIgnoreCase));
+ return hit ? (true, front!) : (false, "");
+ }
case "mic-in-use":
case "camera-in-use":
{
@@ -343,4 +352,45 @@ private double IdleSeconds()
_idleAt = Environment.TickCount64;
return _idle = Idle.Seconds();
}
+
+ /// For tests: a fake front-app reader instead of the OS probes.
+ internal Func? FrontProbe;
+
+ private string? _front;
+ private long _frontAt;
+
+ /// The name of the app that owns the foreground window, or null when it cannot be told.
+ private string? FrontApp()
+ {
+ if (FrontProbe is not null) return FrontProbe();
+ if (_frontAt != 0 && Environment.TickCount64 - _frontAt < 1500) return _front;
+ // timed from the end of the probe: osascript or xdotool can take up to 2 s, and every app-in-front rule in
+ // the same pass must reuse that answer instead of starting its own probe
+ _front = FrontAppOs();
+ _frontAt = Environment.TickCount64;
+ return _front;
+ }
+
+#if WINDOWS
+ private static string? FrontAppOs()
+ {
+ var hwnd = GetForegroundWindow();
+ if (hwnd == 0 || GetWindowThreadProcessId(hwnd, out var pid) == 0) return null;
+ try { using var p = Process.GetProcessById((int)pid); return p.ProcessName; } catch { return null; }
+ }
+
+ [DllImport("user32.dll")] private static extern nint GetForegroundWindow();
+ [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint hwnd, out uint processId);
+#else
+ private static string? FrontAppOs()
+ {
+ // macOS: System Events, same Accessibility permission as sending keys. Linux: xdotool on X11 only;
+ // under Wayland there is no desktop-wide frontmost-app query, so the rule simply stays off.
+ if (OperatingSystem.IsMacOS())
+ return Sh.Run("osascript", "-e", "tell application \"System Events\" to get name of first process whose frontmost is true")?.Trim() is { Length: > 0 } app ? app : null;
+ if (Environment.GetEnvironmentVariable("WAYLAND_DISPLAY") is null)
+ return Sh.Run("xdotool", "getactivewindow", "getwindowclassname")?.Trim() is { Length: > 0 } cls ? cls : null;
+ return null;
+ }
+#endif
}
diff --git a/agent/PhoneBox.Agent/settings.html b/agent/PhoneBox.Agent/settings.html
index bd9831b..58ceacc 100644
--- a/agent/PhoneBox.Agent/settings.html
+++ b/agent/PhoneBox.Agent/settings.html
@@ -1626,6 +1626,7 @@ Advanced
'session-busy': { label: 'an AI session is working', match: 'any project (or: api|docs, codex)' },
'media-playing': { label: 'music or video plays', match: 'any app (or: Spotify|Music)' },
'process-running': { label: 'an app is running', match: 'zoom|Teams|obs64' },
+ 'app-in-front': { label: 'an app is in front', match: 'Code|obs64|Safari' },
'mic-in-use': { label: 'the microphone is in use', match: 'any app (or: Zoom|Teams)' },
'camera-in-use': { label: 'the camera is in use', match: 'any app (or: Zoom|Teams)' },
'calendar-event': { label: 'a calendar event is on', match: 'any event (or: meeting|call)' },
diff --git a/docs/GUIDE.md b/docs/GUIDE.md
index 70e80a3..7f58660 100644
--- a/docs/GUIDE.md
+++ b/docs/GUIDE.md
@@ -193,6 +193,7 @@ for senders that cannot set headers). That key opens only the webhook endpoints,
| an AI session needs you / is working (optionally for some projects) | show a page |
| music or video plays (optionally in some apps: `Spotify\|Music`) | show a notification (`{detail}` = what happened) |
| an app is running (`zoom\|Teams\|obs64`) | push a value (e.g. `onair`, shown by a Pushed value widget) |
+| an app is in front (`Code\|obs64\|Safari` — needs Accessibility on macOS, `xdotool` on Linux; not on Wayland) | |
| the microphone / the camera is in use (Windows, Linux) | |
| a calendar event is on (optionally by title) | |
| OBS is recording or streaming | |